GLOBALGRID2050 / EXPLORE CODE

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

Pilot Dark and 2 more files

A JavaScript file in the theme folder of Cosmic that maps the Renewable Energy Planning Database (REPD) register, substations and 66kV, using SHA-256.

700 lines of JavaScript and Python and CSS from cosmic, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1143 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. Inject storage · cosmic / tools/explore/theme/inject.py lines 1–265
  2. Pilot Dark render · cosmic / tools/explore/theme/pilot-dark.css lines 1–25
  3. Pilot Dark geodesy · cosmic / tools/explore/theme/pilot-dark.js lines 1–410

Inject

A Python command-line tool in the theme folder of Cosmic that reads pilot places, build graph and play, using SHA-256.

storagecosmic / tools/explore/theme/inject.py · lines 1–265 of 265 · Entry point · pattern build_index (shared by 3 files)

What it does
It loads pilot places, build graph and play. Defines 11 functions or classes, including _ver, copy_assets, pilot_modules, pilot_module_html, bust. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
README: "`inject.py` copies `play.css` and `play.js` to `/theme/`."
Inputs & outputs
In: JSON file pilot-places.json; JSON file places.json; JSON file build_graph.json; JSON file play-index.json; command-line arguments.
Downstream impact
Used directly by 5 files: Extras (cosmic); Test Pilot Dark (cosmic); Test Pilot Lightning (cosmic); Test Pilot Static (cosmic); and 1 more. Reached from 4 other entry points, including CI Chess Workflow (cosmic); Ship (cosmic); Test Extras (cosmic).
What it achieves
It copies assets (`copy_assets`), syncs pilot (`sync_pilot`) and builds index (`build_index`). Post-build step: add the Explore Code play layer to every built HTML page. It accepts `--site`, `--quiet` and `--no-ide`.
Why it matters
Run by Extras. Checked by 4 tests, including Test Pilot Dark.
Application
cosmic · tools/explore/theme · Python CLI
Uses
__future__, argparse, hashlib, json, os, re, shutil, sys
Used by
run by Extras (script call), run by Test Pilot Dark (script call), run by Test Pilot Lightning (script call), run by Test Pilot Static (script call), imported by Test Theme (import)
Produces
copy_assets, pilot_modules, pilot_module_html, sync_pilot, build_index, page_tags, inject_html, run, main
Defines here
_ver, copy_assets, pilot_modules, pilot_module_html, bust, sync_pilot, build_index, page_tags, inject_html, run, main
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/inject.py:1-265 · blob 75fc3e2885b872d466f14d3e642f838363d867b3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Post-build step: add the Explore Code play layer to every built HTML page.

    python tools/explore/theme/inject.py --site <out>/explore-code

What it does, and nothing more:
  1. copies theme/play.css and theme/play.js (and theme/ide.css / ide.js when they exist) to <site>/theme/,
     and, when theme/pilot.html exists, the Pilot page files to <site>/pilot/ (index.html, pilot.css, pilot.js, places.json);
  2. writes <site>/theme/play-index.json, a compact view of <site>/build_graph.json (no new facts);
  3. adds, just before </head> of every *.html page, one <link> and one deferred <script> for play
     (and for ide on s/*.html section pages), each tagged data-ec-theme="...".

Idempotent: earlier tags carrying data-ec-theme are removed before the new ones go in, so a second run
gives byte-identical files. The page body, its text, ids and anchors are never touched. No external hosts.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import shutil
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
TAG_RE = re.compile(r'<(?:link|script)\b[^>]*\bdata-ec-theme="[^"]*"[^>]*>(?:</script>)?')
HEAD_END = '</head>'
IDE_GLOB = re.compile(r'^s/[^/]+\.html$')  # pages that also get the IDE layer (owned by bonus agent B)
# The Pilot page (owned by bonus agent B, HOTBAR-36): byte copies when the sources exist.
PILOT_FILES = (('pilot.css', 'pilot/pilot.css'), ('pilot.js', 'pilot/pilot.js'), ('pilot-places.json', 'pilot/places.json'))
PILOT_PAGE = ('pilot.html', 'pilot/index.html')
# Pilot-200 modules (W10 CAPSTAN-41): every theme/pilot-<name>.js / .css is copied to pilot/ and tagged into the page
# at the markers below, in contract order (CONTRACT.md section 1: plain tags, no defer). Absent modules get no tag.
PILOT_MODULE_ORDER = ('estate', 'goto', 'modes', 'ukpn', 'grid', 'repd', 'vicinity', 'lightning', 'nav', 'lidar', 'dark', 'darkfx', 'ticker', 'subfind')
PILOT_MODULE_RE = re.compile(r'^pilot-([a-z0-9]+)\.(js|css)$')
PILOT_CSS_MARK, PILOT_JS_MARK = '<!--pilot-module-css-->', '<!--pilot-module-js-->'
DRONE_ALIAS = ('drone/index.html', '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Drone View</title>'
               '<meta http-equiv="refresh" content="0; url=../pilot/index.html"><link rel="canonical" href="../pilot/index.html"></head>'
               '<body><p><a href="../pilot/index.html">Open Drone View</a></p><script>location.replace("../pilot/index.html"+location.search+location.hash)</script></body></html>')


def _ver(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()[:10]


def copy_assets(site: Path, ide: bool = True) -> dict[str, str]:
    """Copy theme assets into <site>/theme/ and return {name: version}."""
    out = site / 'theme'
    out.mkdir(parents=True, exist_ok=True)
    vers = {}
    for name in ('play.css', 'play.js') + (('ide.css', 'ide.js') if ide else ()):
        src = HERE / name
        if src.is_file():
            dst = out / name
            if not dst.exists() or dst.read_bytes() != src.read_bytes():
                shutil.copyfile(src, dst)
            vers[name] = _ver(src)
    return vers


def pilot_modules(here: Path = HERE) -> list[tuple[str, str]]:
    """[(name, ext)] of shipped Pilot modules, contract order first, then any others by name."""
    found = {}
    for f in here.iterdir():
        m = PILOT_MODULE_RE.match(f.name)
        if m and f.is_file():
            found.setdefault(m.group(1), set()).add(m.group(2))
    rank = {n: i for i, n in enumerate(PILOT_MODULE_ORDER)}
    names = sorted(found, key=lambda n: (rank.get(n, len(rank)), n))
    return [(n, e) for n in names for e in ('css', 'js') if e in found[n]]


def pilot_module_html(page: str, here: Path = HERE) -> str:
    """Cache-bust the module tags written literally in pilot.html (so Explore Code's build sees the edges), drop a
    tag whose file is missing, and add after the markers only modules found on disk but not tagged. Also versions
    pilot.css / pilot.js."""
    mods = pilot_modules(here)
    have = {(n, e) for n, e in mods}
    tag_re = re.compile(r'<link rel="stylesheet" href="pilot-([a-z0-9]+)\.css">|<script src="pilot-([a-z0-9]+)\.js"></script>\n?')
    tagged = set()

    def bust(m):
        n, e = (m.group(1), 'css') if m.group(1) else (m.group(2), 'js')
        if (n, e) not in have:
            return ''
        tagged.add((n, e))
        v = _ver(here / f'pilot-{n}.{e}')
        return (f'<link rel="stylesheet" href="pilot-{n}.css?v={v}">' if e == 'css'
                else f'<script src="pilot-{n}.js?v={v}"></script>' + ('\n' if m.group(0).endswith('\n') else ''))
    page = tag_re.sub(bust, page)
    css = ''.join(f'<link rel="stylesheet" href="pilot-{n}.css?v={_ver(here / f"pilot-{n}.css")}">' for n, e in mods if e == 'css' and (n, e) not in tagged)
    js = ''.join(f'<script src="pilot-{n}.js?v={_ver(here / f"pilot-{n}.js")}"></script>' for n, e in mods if e == 'js' and (n, e) not in tagged)
    if css:
        page = page.replace(PILOT_CSS_MARK, PILOT_CSS_MARK + css, 1)
    if js:
        page = page.replace(PILOT_JS_MARK, PILOT_JS_MARK + js, 1)
    for core in ('pilot.css', 'pilot.js'):
        if (here / core).is_file():
            page = re.sub(r'((?:href|src)=")' + re.escape(core) + '"', r'\g<1>' + core + '?v=' + _ver(here / core) + '"', page, count=1)
    return page


def sync_pilot(site: Path, vers: dict[str, str]) -> None:
    """Copy the Pilot page files; the page itself gets the same play tags as every other page."""
    src_page = HERE / PILOT_PAGE[0]
    if not src_page.is_file():
        return
    files = list(PILOT_FILES) + [(f'pilot-{n}.{e}', f'pilot/pilot-{n}.{e}') for n, e in pilot_modules(HERE)]
    for src_name, dst_rel in files:
        src = HERE / src_name
        if src.is_file():
            dst = site / dst_rel
            dst.parent.mkdir(parents=True, exist_ok=True)
            if not dst.exists() or dst.read_bytes() != src.read_bytes():
                shutil.copyfile(src, dst)
    dst = site / PILOT_PAGE[1]
    dst.parent.mkdir(parents=True, exist_ok=True)
    new = inject_html(pilot_module_html(src_page.read_text(encoding='utf-8'), HERE), page_tags(PILOT_PAGE[1], '../', vers))
    if not dst.exists() or dst.read_text(encoding='utf-8') != new:
        dst.write_text(new, encoding='utf-8')


def build_index(site: Path) -> dict | None:
    """A compact, read-only digest of build_graph.json for the game layer. Every value is copied from it."""
    gp = site / 'build_graph.json'
    if not gp.is_file():
        return None
    g = json.loads(gp.read_text(encoding='utf-8'))
    roles = [r['id'] for r in g.get('roles', [])]
    role_ix = {r: i for i, r in enumerate(roles)}
    topics = g.get('topics', [])
    topic_ix = {t['id']: i for i, t in enumerate(topics)}
    sections = sorted(g.get('sections', []), key=lambda s: s['section'])
    sec_topic = {s['section']: s.get('topic') for s in sections}
    patterns: list[str] = []
    pat_ix: dict[str, int] = {}
    urls: list[str] = []
    url_ix: dict[str, int] = {}
    langs: list[str] = []
    lang_ix: dict[str, int] = {}
    files = []
    role_by_topic = [[0] * len(roles) for _ in topics]
    pat_files: dict[int, list[int]] = {}
    for f in g.get('files', []):
        p = f.get('pattern') or ''
        pi = -1
        if p:
            if p not in pat_ix:
                pat_ix[p] = len(patterns)
                patterns.append(p)
            pi = pat_ix[p]
        u = f.get('published') or ''
        ui = -1
        if u.startswith('https://'):
            if u not in url_ix:
                url_ix[u] = len(urls)
                urls.append(u)
            ui = url_ix[u]
        lang = f.get('lang') or ''
        if lang not in lang_ix:
            lang_ix[lang] = len(langs)
            langs.append(lang)
        crs = 1 if (f.get('data_contracts') or {}).get('crs') else 0
        ri = role_ix.get(f.get('role'), -1)
        t = sec_topic.get(f.get('section'))
        if t in topic_ix and ri >= 0:
            role_by_topic[topic_ix[t]][ri] += 1
        # [id, section, block, pattern, crs, published, role, lang, title, repo]
        files.append([f['id'], f.get('section', 0), f.get('block', 0), pi, crs, ui, ri, lang_ix[lang],
                      f.get('title', ''), f.get('repo', '')])
        if pi >= 0:
            pat_files.setdefault(pi, []).append(f['id'])
    by_id = {r[0]: r for r in files}
    hunts = []
    for pi, ids in pat_files.items():
        secs = {by_id[i][1] for i in ids}
        if 3 <= len(ids) <= 8 and len(secs) >= 2:
            hunts.append(pi)
    hunts.sort(key=lambda i: patterns[i])
    return {
        'schema': 'explore-play-index-v1',
        'source': 'build_graph.json',
        'cut': g.get('cut', ''),
        'roles': [[r['id'], r.get('title', ''), r.get('colour', '')] for r in g.get('roles', [])],
        'topics': [[t['id'], t.get('title', ''), t.get('sections', 0), role_by_topic[i]] for i, t in enumerate(topics)],
        'sections': [[s['section'], s.get('url', ''), topic_ix.get(s.get('topic'), -1), s.get('title', '')] for s in sections],
        'files': files,
        'patterns': patterns,
        'urls': urls,
        'langs': langs,
        'hunts': hunts,
    }


def page_tags(rel: str, root: str, vers: dict[str, str]) -> str:
    tags = []
    if 'play.css' in vers:
        tags.append(f'<link rel="stylesheet" href="{root}theme/play.css?v={vers["play.css"]}" data-ec-theme="play">')
    if IDE_GLOB.match(rel) and 'ide.css' in vers:
        tags.append(f'<link rel="stylesheet" href="{root}theme/ide.css?v={vers["ide.css"]}" data-ec-theme="ide">')
    if 'play.js' in vers:
        tags.append(f'<script defer src="{root}theme/play.js?v={vers["play.js"]}" data-ec-theme="play"></script>')
    if IDE_GLOB.match(rel) and 'ide.js' in vers:
        tags.append(f'<script defer src="{root}theme/ide.js?v={vers["ide.js"]}" data-ec-theme="ide"></script>')
    return ''.join(tags)


def inject_html(html: str, tags: str) -> str:
    head_end = html.find(HEAD_END)
    if head_end < 0:
        return html
    head = TAG_RE.sub('', html[:head_end])
    return head + tags + html[head_end:]


def run(site: Path, quiet: bool = False, ide: bool = True) -> dict:
    site = site.resolve()
    if not (site / 'index.html').is_file():
        raise SystemExit(f'not an explore-code site (no index.html): {site}')
    vers = copy_assets(site, ide)
    if ide:
        sync_pilot(site, vers)
    idx = build_index(site)
    if idx is not None:
        data = json.dumps(idx, ensure_ascii=False, separators=(',', ':'))
        ip = site / 'theme' / 'play-index.json'
        if not ip.exists() or ip.read_text(encoding='utf-8') != data:
            ip.write_text(data, encoding='utf-8')
    changed = total = 0
    for p in sorted(site.rglob('*.html')):
        rel = p.relative_to(site).as_posix()
        if rel.startswith('theme/') or rel == DRONE_ALIAS[0]:
            continue
        total += 1
        depth = rel.count('/')
        root = '../' * depth
        old = p.read_text(encoding='utf-8')
        new = inject_html(old, page_tags(rel, root, vers))
        if new != old:
            p.write_text(new, encoding='utf-8')
            changed += 1
    if ide and (site / 'pilot' / 'index.html').is_file():   # Drone View: a short link to the Pilot page
        a = site / DRONE_ALIAS[0]
        if not a.exists() or a.read_text(encoding='utf-8') != DRONE_ALIAS[1]:
            a.parent.mkdir(parents=True, exist_ok=True); a.write_text(DRONE_ALIAS[1], encoding='utf-8')
    stats = {'pages': total, 'changed': changed, 'assets': sorted(vers), 'index': idx is not None}
    if not quiet:
        print(json.dumps(stats))
    return stats


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--site', required=True, type=Path, help='the built explore-code folder')
    ap.add_argument('--quiet', action='store_true')
    ap.add_argument('--no-ide', action='store_true', help='leave out theme/ide.* and the Pilot page even when present')
    a = ap.parse_args(argv)
    run(a.site, a.quiet, not a.no_ide)
    return 0


if __name__ == '__main__':
    sys.exit(main())

Pilot Dark

A style sheet in the theme folder of Cosmic.

rendercosmic / tools/explore/theme/pilot-dark.css · lines 1–25 of 25 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
Pilot module "dark" (DARK GRID 1 / UMBRA-63).
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · style sheet
Uses
none found
Used by
loaded by Pilot (stylesheet)
Produces
none declared
Defines here
none
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-dark.css:1-25 · blob 7068251896caa1445b40d172263f39b23efef8c3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Pilot module "dark" (DARK GRID 1 / UMBRA-63). The DARK pill copies GridAtlas's phone dock pills exactly
   (gridatlas@f944f8dc atlas/modules/g204-compact-dock.js #g203-native-dock: 44 px tall, font 600 11px/1 system-ui,
   background #081820ed, text #e4f7f7, 1px #367078 border, radius 6px, a trailing " •" when active as "SATNAV •");
   the radius chips copy its mobile tray chips (atlas/parts/202609012045-sld-sandbox-body.js: #0a1a1d, 1px #2f6f75,
   radius 3px, #8fb3b8; pressed #5fbdc2 / #bfe9ee / rgba(0,255,255,0.08)) in the dock's font. */
.p-dark-row { display: flex; flex-wrap: wrap; gap: 4px; justify-content: center; max-width: calc(100vw - 16px); pointer-events: auto; }
.p-dark-btn, .p-dark-chip {
  box-sizing: border-box; height: 44px; min-height: 44px; min-width: 44px; margin: 0; padding: 0 3px;
  font: 600 11px/1 system-ui, sans-serif; white-space: nowrap; letter-spacing: normal; cursor: pointer;
  touch-action: manipulation; -webkit-tap-highlight-color: transparent;
}
.p-dark-btn {
  width: 68px; display: inline-flex; align-items: center; justify-content: center; text-align: center;
  background: #081820ed; color: #e4f7f7; border: 1px solid #367078; border-radius: 6px; box-shadow: none;
}
.p-dark-btn[aria-pressed="true"] { border-color: #5fbdc2; }
.p-dark-chip {
  padding: 0 8px; background: #0a1a1d; border: 1px solid #2f6f75; border-radius: 3px; color: #8fb3b8; text-transform: uppercase;
}
.p-dark-chip[aria-pressed="true"] { border-color: #5fbdc2; color: #bfe9ee; background: rgba(0, 255, 255, 0.08); }
.p-dark-btn:focus-visible, .p-dark-chip:focus-visible { outline: 2px solid white; outline-offset: 2px; }
.p-dark-status { font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; color: #bfe9ee; overflow-wrap: anywhere; }
.p-dark-status b { color: #e4f7f7; letter-spacing: .06em; }
.p-dark-cav { color: #6f9499; }
@media (prefers-reduced-motion: reduce) { .p-dark-btn, .p-dark-chip { transition: none; } }

Pilot Dark

A JavaScript file in the theme folder of Cosmic that maps the Renewable Energy Planning Database (REPD) register, substations and 66kV, using SHA-256.

geodesycosmic / tools/explore/theme/pilot-dark.js · lines 1–410 of 487 · Entry point · pattern refreshNear (shared by 2 files)

What it does
It maps the REPD register, substations and 66kV. Defines 39 functions or classes, including bandOf, colOf, wOf, grid, finite. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: the REPD register, substations, 66kV, 11kV.
Inputs & outputs
In: browser storage (getItem). Out: interactive map; canvas drawing. Voltage levels named: 66kV, 11kV.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It wires grid (`wireGrid`), refreshes halos (`refreshHalos`) and refreshes near (`refreshNear`). Pilot module "dark" (DARK GRID 1 / UMBRA-63): DARK GRID view for Drone View. Its code works with 66 kV and 11 kV. It responds to click and keydown events.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · script
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
none found
Used by
loaded by Pilot (script src)
Produces
bandOf, colOf, wOf, grid, finite, reduced, effR, focusCentre, dxy, fade, ingest, pack
Defines here
bandOf, colOf, wOf, grid, finite, reduced, effR, focusCentre, dxy, fade, ingest, pack, add, eachSeg, gridOn, heightAt, wireGrid, sprite, hexA, ringPath, ask, visible, refreshHalos, geo, nearestLine, fmtD, refreshNear, dist, finish, focusObject
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-dark.js:1-410 · blob a6dd228dee452314d90281fcaa6445490a7cd07a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unknown
/* Pilot module "dark" (DARK GRID 1 / UMBRA-63): DARK GRID view for Drone View. Optional; builds only on the PILOT
   contract v1 (addLayer, hud, hash, on/emit, data.fetchJSON, ground, geo). It is an OVERLAY over whichever ground
   mode is on (MAP / SAT / STREET from pilot-modes.js), not a mode of its own, so those buttons keep working.
   - Ground: 'dim' = the imagery or map is desaturated and multiplied down to near black, so relief still reads
     faintly as ground; 'wire' = an opaque near-black ground with a faint terrain wireframe draped on PILOT.ground.
   - Grid: the existing layers (pilot-grid lines + substations, pilot-ukpn, pilot-repd) still draw and still own
     taps and cards. DARK adds, under them, a band-coloured line with a soft glow (weight by voltage) and point
     halos, and over everything a focus vignette: assets fade out past the focus radius (1 / 2 / 5 / 10 km), which
     follows the camera and widens with speed and height (FAST mode) so the ground never becomes a pinhole.
   - HUD: one status line, the nearest grid asset (substation, line or UKPN secondary) with distance and bearing,
     straight-line only (PILOT.geo, R_ATLAS), never a route.
   - Entry: a DARK button styled as GridAtlas's phone dock pills (SATNAV / GRID / SUBS / LAYERS); one tap toggles;
     state in the URL hash (#dark=<km>, &darkg=wire). Key K toggles too.
   - No animation of any kind here (prefers-reduced-motion is respected by construction); effects live in
     pilot-darkfx.js (DARK GRID 2 / NOCTILUCENT-27), which talks to this module only through events:
     'dark:state', 'dark:focus', 'dark:query' (see /tmp/vk/neural/outbox/UMBRA-63.md).

   Provenance (pinned, verbatim where marked):
   BANDS: Ventusltd/gridatlas@f944f8dcbc09cd09c0895f0126682ec241cd576f atlas/releases/202608300453-atlas-v9/index.html
     GRID_CONFIG lines 146-151 (file sha256 87a3aaf463843ce33ed5c151096395715cbc80f2575bcb7208f271e94d2ec467):
     colour and width per voltage band, values copied exactly. Below 66 kV GridAtlas has no line band; the UKPN
     layer colour #35e6bb (pilot-ukpn.js, "GridAtlas layer colour") is used for 33 / 11 kV secondaries.
   BUTTON: Ventusltd/gridatlas@f944f8dc atlas/modules/g204-compact-dock.js (#g203-native-dock pills: 44 px, font 600
     11px/1 system-ui, #081820ed / #e4f7f7 / 1px #367078 / radius 6px, "SATNAV •" active dot) and
     atlas/parts/202609012045-sld-sandbox-body.js mobile tray chips (aria-pressed colours).
   WIREFRAME: Ventusltd/graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152
     web/versions/202609262227-site-world/world/layers/ground-grid.mjs (file sha256
     eff6bebb995cd463b493bef05e458ab70b34ae511c4b398b21e89fde51201b22): DETAIL (line 20), grid() (lines 58-94) and
     finite (line 144) VERBATIM, only the leading `export ` keyword removed; test_pilot_dark.py checks the bytes.
   MIT notice for the WIREFRAME block (graphics-engines-open-source LICENSE, reproduced as required):
   Copyright (c) 2026 VENTUS LTD
   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/
(function () {
  'use strict';
  if (!window.PILOT) return;
  var P = window.PILOT, D = document, W = window;
  P.module('dark', { version: '1', owner: 'DARK GRID 1 / UMBRA-63' });

  // ---- S01 GridAtlas voltage bands (pinned above). w = GridAtlas line-width px.
  var BANDS = {
    '400': { col: '#0054ff', w: 2.5 }, '275': { col: '#ff0000', w: 2.0 }, '220': { col: '#ff9900', w: 1.8 },
    '132': { col: '#00cc00', w: 1.5 }, '66': { col: '#b200ff', w: 1.2 }, subs: { col: '#ffffff' }
  };
  var LOW_COL = '#35e6bb';   // < 66 kV (UKPN secondaries), see provenance
  var REPD_COL = '#ffd27a';  // generation sites: a neutral warm halo (REPD is not a voltage band)
  function bandOf(kv) {
    kv = +kv || 0;
    return kv >= 400 ? '400' : kv >= 275 ? '275' : kv >= 220 ? '220' : kv >= 132 ? '132' : kv >= 66 ? '66' : null;
  }
  function colOf(kv) { var b = bandOf(kv); return b ? BANDS[b].col : LOW_COL; }
  function wOf(kv) { var b = bandOf(kv); return b ? BANDS[b].w : 1; }
  var RADII = [1, 2, 5, 10];   // km, chosen in the UI

  // ---- S02 vendored wireframe (verbatim; see provenance)
  // >>> site-world ground-grid begin
const DETAIL = { radius: 100, step: 2 }; // near the viewer, no segment is longer than 2 m
function grid(cx, cy, { spacing, radius }, heightAt, { origin = [0, 0, 0], near = null, sample = null } = {}) {
  const h = sample || ((x, y) => finite(heightAt(x, y)));
  const n = Math.round(radius / spacing), pieces = spacing > DETAIL.step ? Math.ceil(spacing / DETAIL.step) : 1;
  const [ox, oy, oz] = origin, r2 = DETAIL.radius * DETAIL.radius;
  // How many pieces the segment from b0 to b0 + spacing along a line at offset a is cut into.
  const split = pieces > 1 && near
    ? (ax, ay, bx, by) => { const dx = (ax + bx) / 2 - near[0], dy = (ay + by) / 2 - near[1]; return dx * dx + dy * dy <= r2 ? pieces : 1; }
    : () => 1;
  let count = 0;
  for (let i = -n; i <= n; i++) {
    const a = i * spacing;
    for (let j = -n; j < n; j++) {
      const b0 = j * spacing, b1 = b0 + spacing;
      count += split(cx + a, cy + b0, cx + a, cy + b1) + split(cx + b0, cy + a, cx + b1, cy + a);
    }
  }
  const out = new Float32Array(count * 6);
  let w = 0;
  for (let i = -n; i <= n; i++) {
    const a = i * spacing;
    for (let dir = 0; dir < 2; dir++) { // 0: north-south line at x = cx + a; 1: east-west line at y = cy + a
      let px = dir ? cx - n * spacing : cx + a, py = dir ? cy + a : cy - n * spacing, pz = h(px, py, oz);
      for (let j = -n; j < n; j++) {
        const b0 = j * spacing, b1 = b0 + spacing;
        const x0 = dir ? cx + b0 : cx + a, y0 = dir ? cy + a : cy + b0, x1 = dir ? cx + b1 : cx + a, y1 = dir ? cy + a : cy + b1;
        const k = split(x0, y0, x1, y1);
        for (let p = 0; p < k; p++) {
          const qx = x0 + (x1 - x0) * (p + 1) / k, qy = y0 + (y1 - y0) * (p + 1) / k, qz = h(qx, qy, pz); // whole metres stay whole
          out[w++] = px - ox; out[w++] = py - oy; out[w++] = pz - oz;
          out[w++] = qx - ox; out[w++] = qy - oy; out[w++] = qz - oz;
          px = qx; py = qy; pz = qz;
        }
      }
    }
  }
  return out;
}
const finite = h => (Number.isFinite(h) ? h : 0);
  // <<< site-world ground-grid end

  // ---- S03 state
  var S = {
    on: false, km: 2, ground: 'dim', fx: null,
    c: { lat: 0, lon: 0 }, R: 2000, lastState: null, near: null, nearT: 0, haloT: 0, focusT: 0,
    halos: { subs: [], ukpn: [], repd: [] }, gridOn: null, gridOnT: 0, msGround: 0, msGrid: 0, msMask: 0
  };
  var RAD = Math.PI / 180, M_LAT = 111320;
  function reduced() { return !!(P.reduced || (W.matchMedia && W.matchMedia('(prefers-reduced-motion: reduce)').matches)); }

  // Effective radius: the chosen focus, widened with speed (about 8 s of flight) and height so FAST stays readable.
  function effR(c) {
    var base = S.km * 1000, spd = (P.cam && P.cam.speed) || 0, agl = (c && c.agl) || 0;
    return Math.min(40000, Math.max(base, spd * 8, agl * 1.6));
  }
  // Focus centre follows the camera: the ground point it looks at, at most 0.6 R ahead (so the camera stays inside).
  function focusCentre(c, R) {
    var pitch = c.pitch || 0, ahead = pitch < -0.03 ? Math.max(0, c.agl) / Math.tan(-pitch) : R;
    ahead = Math.min(ahead, R * 0.6);
    var h = (c.hdg || 0) * RAD, lat = c.lat + Math.cos(h) * ahead / M_LAT, lon = c.lon + Math.sin(h) * ahead / (M_LAT * Math.cos(c.lat * RAD));
    return { lat: lat, lon: lon };
  }
  // Cheap local metres around the focus centre (screening visuals only; readouts use PILOT.geo).
  function dxy(lat, lon) { return [(lon - S.c.lon) * M_LAT * Math.cos(S.c.lat * RAD), (lat - S.c.lat) * M_LAT]; }
  function fade(d, R) { return d <= R ? 1 : d >= R * 1.35 ? 0 : 1 - (d - R) / (R * 0.35); }

  // ---- S04 grid line data: the grid layer's own memoised GeoJSON (no second download), only kinds it loaded
  var LINE_KINDS = ['400', '275', '220', '132', '66'];
  var ready = {}, LN = {}, CELL = 20;   // 0.05 degree cells
  P.on('grid:ready', function (d) { if (d && LINE_KINDS.indexOf(String(d.kind)) >= 0) { ready[d.kind] = 1; if (S.on) ingest(String(d.kind)); } });
  function ingest(k) {
    if (LN[k] || P.offline || !P.data || !P.data.fetchJSON) return;
    var gl = P.layer && P.layer('grid'), url = gl && typeof gl.src === 'function' ? gl.src(k) : null;
    if (!url) return;
    LN[k] = { pending: true };
    P.data.fetchJSON(url).then(function (gj) { LN[k] = pack(gj); }, function () { delete LN[k]; });
  }
  function pack(gj) {
    var ll = [], idx = new Map(), n = 0;
    function add(a, b) {
      if (!a || !b || !isFinite(a[0]) || !isFinite(b[0])) return;
      ll.push(a[1], a[0], b[1], b[0]);
      var key = Math.floor((a[1] + b[1]) / 2 * CELL) + ':' + Math.floor((a[0] + b[0]) / 2 * CELL), l = idx.get(key);
      if (!l) idx.set(key, l = []); l.push(n++);
    }
    (gj && gj.features || []).forEach(function (f) {
      var g = f && f.geometry; if (!g) return;
      var parts = g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : [];
      parts.forEach(function (c) { for (var i = 1; i < (c || []).length; i++) add(c[i - 1], c[i]); });
    });
    return { ll: new Float64Array(ll), idx: idx, n: n };
  }
  function eachSeg(k, R, fn) {   // segments of kind k whose midpoint cell lies within R (+ one cell) of the focus
    var L = LN[k]; if (!L || !L.idx) return;
    var dLat = R * 1.4 / M_LAT, dLon = R * 1.4 / (M_LAT * Math.cos(S.c.lat * RAD));
    var r0 = Math.floor((S.c.lat - dLat) * CELL), r1 = Math.floor((S.c.lat + dLat) * CELL);
    var c0 = Math.floor((S.c.lon - dLon) * CELL), c1 = Math.floor((S.c.lon + dLon) * CELL);
    if ((r1 - r0 + 1) * (c1 - c0 + 1) > 4000) return;   // far too wide (never at 40 km cap)
    for (var r = r0; r <= r1; r++) for (var c = c0; c <= c1; c++) {
      var a = L.idx.get(r + ':' + c); if (!a) continue;
      for (var i = 0; i < a.length; i++) fn(L.ll, a[i] * 4);
    }
  }
  // Respect the user's pilot-grid voltage toggles (it stores them in localStorage 'p-grid-on').
  function gridOn(k) {
    var now = Date.now();
    if (now - S.gridOnT > 1000) { S.gridOnT = now; try { S.gridOn = JSON.parse(localStorage.getItem('p-grid-on') || 'null'); } catch (e) { S.gridOn = null; } }
    if (!S.gridOn) return k === '400' || k === '275';
    return !!S.gridOn[k];
  }

  // ---- S05 layer: ground (order 1)
  var wire = { key: '', pos: null, ox: 0, oy: 0 };
  function heightAt(x, y) { var ll = P.toLatLon(x, y); return P.ground(ll[0], ll[1]); }
  function wireGrid(v, R) {
    var lod = v.lod || 0, n = lod >= 2 ? 10 : 14;                  // lines each side of the centre: phone budget
    var spacing = Math.max(25, Math.round(R * 1.3 / n / 25) * 25);
    var radius = spacing * n, cxy = P.fromLatLon(S.c.lat, S.c.lon);
    var cx = Math.round(cxy[0] / spacing) * spacing, cy = Math.round(cxy[1] / spacing) * spacing;
    var key = cx + ',' + cy + ',' + spacing + ',' + n;
    if (key !== wire.key) {
      wire.key = key; wire.ox = cx; wire.oy = cy;
      wire.pos = grid(cx, cy, { spacing: spacing, radius: radius }, heightAt, { origin: [cx, cy, 0] });
    }
    return wire;
  }
  var groundLayer = {
    id: 'dark-ground', title: 'DARK GRID ground', order: 1, visible: false,
    draw: function (g, v) {
      var t0 = performance.now();
      if (S.ground === 'wire') {
        g.fillStyle = '#020507'; g.fillRect(0, 0, v.w, v.h);
        var wr = wireGrid(v, S.R), p = wr.pos, ox = wr.ox, oy = wr.oy;
        g.beginPath();
        for (var i = 0; i < p.length; i += 6) {
          var a = v.projectXYZ(p[i] + ox, p[i + 1] + oy, p[i + 2]), b = v.projectXYZ(p[i + 3] + ox, p[i + 4] + oy, p[i + 5]);
          if (!a || !b) continue;
          if ((a.x < 0 && b.x < 0) || (a.x > v.w && b.x > v.w) || (a.y > v.h && b.y > v.h) || (a.y < 0 && b.y < 0)) continue;
          g.moveTo(a.x, a.y); g.lineTo(b.x, b.y);
        }
        g.strokeStyle = 'rgba(156,219,255,0.20)'; g.lineWidth = 1; g.stroke();   // site-world MAJOR colour #9cdbff, quieter
      } else {
        if ((v.lod || 0) < 2) { g.globalCompositeOperation = 'saturation'; g.fillStyle = '#808080'; g.fillRect(0, 0, v.w, v.h); }
        g.globalCompositeOperation = 'multiply'; g.fillStyle = 'rgb(46,56,64)'; g.fillRect(0, 0, v.w, v.h);
        g.globalCompositeOperation = 'source-over'; g.fillStyle = 'rgba(2,6,10,0.35)'; g.fillRect(0, 0, v.w, v.h);
      }
      S.msGround = S.msGround * 0.9 + (performance.now() - t0) * 0.1;
    }
  };

  // ---- S06 layer: band-coloured glow lines (order 31), under pilot-grid's substations, above its own lines
  var SEG_CAP = [5000, 3500, 2200, 1400];
  var gridLayer = {
    id: 'dark-grid', title: 'DARK GRID voltage glow', order: 31, visible: false,
    draw: function (g, v) {
      var t0 = performance.now(), gl = P.layer && P.layer('grid');
      if (gl && gl.visible === false) return;
      var R = S.R, cap = SEG_CAP[Math.min(3, v.lod || 0)], used = 0;
      g.lineCap = 'round'; g.lineJoin = 'round';
      for (var ki = 0; ki < LINE_KINDS.length; ki++) {
        var k = LINE_KINDS[ki]; if (!LN[k] || !LN[k].idx || !gridOn(k)) continue;
        var B = [[], [], []];   // fade buckets: inside, edge, outer edge
        eachSeg(k, R, function (ll, o) {
          if (used >= cap) return;
          var m = dxy((ll[o] + ll[o + 2]) / 2, (ll[o + 1] + ll[o + 3]) / 2), d = Math.sqrt(m[0] * m[0] + m[1] * m[1]), f = fade(d, R);
          if (f <= 0) return;
          var a = v.project(ll[o], ll[o + 1], null), b = v.project(ll[o + 2], ll[o + 3], null);
          if (!a || !b) return;
          if ((a.x < -40 && b.x < -40) || (a.x > v.w + 40 && b.x > v.w + 40) || (a.y < -40 && b.y < -40) || (a.y > v.h + 40 && b.y > v.h + 40)) return;
          used++; B[f >= 0.999 ? 0 : f > 0.5 ? 1 : 2].push(a.x, a.y, b.x, b.y);
        });
        var w = BANDS[k].w * 1.2, col = BANDS[k].col, AL = [1, 0.6, 0.25];
        for (var bi = 0; bi < 3; bi++) {
          var s = B[bi]; if (!s.length) continue;
          g.beginPath(); for (var j = 0; j < s.length; j += 4) { g.moveTo(s[j], s[j + 1]); g.lineTo(s[j + 2], s[j + 3]); }
          g.strokeStyle = col;
          g.globalAlpha = 0.10 * AL[bi]; g.lineWidth = w * 6; g.stroke();     // soft glow: two wide, faint strokes
          g.globalAlpha = 0.22 * AL[bi]; g.lineWidth = w * 3; g.stroke();     // (no shadowBlur: phone budget)
          g.globalAlpha = AL[bi]; g.lineWidth = w; g.stroke();
        }
        g.globalAlpha = 1;
      }
      S.msGrid = S.msGrid * 0.9 + (performance.now() - t0) * 0.1;
    }
  };

  // ---- S07 layer: point halos for substations, UKPN secondaries and REPD sites (order 49)
  var sprites = {};
  function sprite(col) {
    if (sprites[col]) return sprites[col];
    var c = D.createElement('canvas'); c.width = c.height = 48;
    var x = c.getContext('2d'), gr = x.createRadialGradient(24, 24, 0, 24, 24, 24);
    gr.addColorStop(0, col); gr.addColorStop(0.18, col); gr.addColorStop(0.4, hexA(col, 0.35)); gr.addColorStop(1, hexA(col, 0));
    x.fillStyle = gr; x.fillRect(0, 0, 48, 48);
    return (sprites[col] = c);
  }
  function hexA(h, a) { var n = parseInt(h.slice(1), 16); return 'rgba(' + (n >> 16) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')'; }
  var haloLayer = {
    id: 'dark-halo', title: 'DARK GRID asset halos', order: 49, visible: false,
    draw: function (g, v) {
      var R = S.R, lists = [['subs', 'grid-subs'], ['ukpn', 'ukpn'], ['repd', 'repd']], drawn = 0, max = (v.lod || 0) >= 2 ? 120 : 260;
      for (var li = 0; li < lists.length; li++) {
        var L = P.layer && P.layer(lists[li][1]); if (!L || L.visible === false) continue;
        var arr = S.halos[lists[li][0]];
        for (var i = 0; i < arr.length && drawn < max; i++) {
          var o = arr[i], m = dxy(o.lat, o.lon), f = fade(Math.sqrt(m[0] * m[0] + m[1] * m[1]), R); if (f <= 0) continue;
          var p = v.project(o.lat, o.lon, null); if (!p || p.x < -30 || p.y < -30 || p.x > v.w + 30 || p.y > v.h + 30) continue;
          var r = Math.max(6, Math.min(22, (o.big ? 9000 : 5000) / Math.max(200, p.d) * 3));
          g.globalAlpha = f; g.drawImage(sprite(o.col), p.x - r, p.y - r, r * 2, r * 2); drawn++;
        }
      }
      g.globalAlpha = 1;
    }
  };

  // ---- S08 layer: focus vignette (order 85): everything past the radius fades to the dark
  var RINGS = [[1.0, 0.28], [1.12, 0.28], [1.25, 0.3], [1.4, 0.45]];
  function ringPath(g, v, r, zg) {
    var cxy = P.fromLatLon(S.c.lat, S.c.lon), cam = P.cam || { yaw: 0 }, N = 40;
    for (var i = 0; i <= N; i++) {
      var t = i / N * 2 * Math.PI, x = cxy[0] + Math.sin(t) * r, y = cxy[1] + Math.cos(t) * r, p = v.projectXYZ(x, y, zg), sx, sy;
      if (p) { sx = p.x; sy = p.y; }
      else {   // behind the camera: that part of the circle encloses the ground under and behind the viewer
        var side = Math.sin(t - cam.yaw); sx = side > 0.2 ? v.w * 4 : side < -0.2 ? -v.w * 3 : v.w / 2; sy = v.h * 4;
      }
      if (i) g.lineTo(sx, sy); else g.moveTo(sx, sy);
    }
    g.closePath();
  }
  var maskLayer = {
    id: 'dark-mask', title: 'DARK GRID focus', order: 85, visible: false,
    draw: function (g, v) {
      var t0 = performance.now(), zg = P.ground(S.c.lat, S.c.lon);
      for (var i = 0; i < RINGS.length; i++) {
        g.beginPath(); g.rect(-10, -10, v.w + 20, v.h + 20); ringPath(g, v, S.R * RINGS[i][0], zg);
        g.fillStyle = 'rgba(1,3,6,' + RINGS[i][1] + ')'; g.fill('evenodd');
      }
      // the focus edge itself: one faint hairline so the radius reads without a label
      g.beginPath(); ringPath(g, v, S.R, zg); g.strokeStyle = 'rgba(120,200,220,0.22)'; g.lineWidth = 1; g.stroke();
      S.msMask = S.msMask * 0.9 + (performance.now() - t0) * 0.1;
    }
  };
  var LAYERS = [groundLayer, gridLayer, haloLayer, maskLayer];
  LAYERS.forEach(function (l) { P.addLayer(l); });

  // ---- S09 per frame: focus, halos (1/s), nearest readout (2/s), events for pilot-darkfx.js
  function ask(kind, lat, lon, n, rM, cb) {
    var done = false;
    try { P.emit(kind + ':query', { lat: lat, lon: lon, n: n, radiusM: rM, maxM: rM, reply: function (list, meta) { if (done) return; done = true; cb(Array.isArray(list) ? list : [], meta || {}); } }); }
    catch (e) { /* a module failed: leave the list as it was */ }
  }
  function visible(id) { var l = P.layer && P.layer(id); return !!(l && l.visible !== false); }
  function refreshHalos() {
    var c = S.c, rM = S.R * 1.35;
    if (visible('grid-subs')) ask('grid', c.lat, c.lon, 150, rM, function (l) { S.halos.subs = l.map(function (o) { return { lat: o.lat, lon: o.lon, col: colOf(o.kv), big: (+o.kv || 0) >= 132, name: o.name, kv: o.kv }; }); });
    else S.halos.subs = [];
    if (visible('ukpn')) ask('ukpn', c.lat, c.lon, 200, rM, function (l) { S.halos.ukpn = l.map(function (o) { return { lat: o.lat, lon: o.lon, col: colOf(o.voltage), id: o.id, kv: o.voltage }; }); });
    else S.halos.ukpn = [];
    if (visible('repd')) ask('repd', c.lat, c.lon, 100, rM, function (l) { S.halos.repd = l.map(function (o) { return { lat: o.lat, lon: o.lon, col: REPD_COL, name: o.name }; }); });
    else S.halos.repd = [];
  }
  var geo = function () { return P.geo || (P.estate && P.estate.geo) || null; };
  function nearestLine(lat, lon, R) {
    var G = geo(), best = null;
    LINE_KINDS.forEach(function (k) {
      if (!LN[k] || !LN[k].idx || !gridOn(k)) return;
      eachSeg(k, R, function (ll, o) {
        var km;
        if (G && G.distanceToSegmentKm) km = G.distanceToSegmentKm(lon, lat, ll[o + 1], ll[o], ll[o + 3], ll[o + 2]).km;
        else return;
        if (!best || km < best.km) best = { km: km, kv: +k, lat: (ll[o] + ll[o + 2]) / 2, lon: (ll[o + 1] + ll[o + 3]) / 2 };
      });
    });
    return best;
  }
  var HDG = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
  function fmtD(m) { if (m == null || !isFinite(m)) return 'unknown'; return m < 1000 ? Math.round(m) + ' m' : (m / 1000).toFixed(m < 10000 ? 1 : 0) + ' km'; }   // unknown, never zero
  function refreshNear() {
    var c = P.camLL ? P.camLL() : null; if (!c) return;
    var cands = [], pending = 0, G = geo();
    function dist(lat, lon) { return P.dist ? P.dist(c.lat, c.lon, lat, lon) : null; }   // no geodesy: unknown, not 0 m
    function finish() {
      if (pending > 0) return;
      var ln = nearestLine(c.lat, c.lon, S.R);
      if (ln) cands.push({ name: ln.kv + ' kV line', kind: 'line', kv: ln.kv, d: ln.km * 1000, lat: ln.lat, lon: ln.lon });
      cands = cands.filter(function (x) { return x.d != null && isFinite(x.d); });
      cands.sort(function (a, b) { return a.d - b.d; });
      S.near = cands[0] || null; renderStatus();
    }
    pending++; ask('grid', c.lat, c.lon, 1, 0, function (l) { var o = l[0]; if (o) cands.push({ name: o.name, kind: 'substation', kv: o.kv, d: o.d != null ? o.d : dist(o.lat, o.lon), lat: o.lat, lon: o.lon }); pending--; finish(); });
    if (visible('ukpn')) { pending++; ask('ukpn', c.lat, c.lon, 1, 0, function (l) { var o = l[0]; if (o) cands.push({ name: 'UKPN secondary ' + (o.id || ''), kind: 'ukpn', kv: o.voltage, d: o.m != null ? o.m : dist(o.lat, o.lon), lat: o.lat, lon: o.lon }); pending--; finish(); }); }
    if (!pending) finish();
    void G;
  }
  function focusObject() {
    var lines = [], R = S.R;
    LINE_KINDS.forEach(function (k) {
      if (!LN[k] || !LN[k].idx || !gridOn(k)) return;
      var ll = [];
      eachSeg(k, R, function (a, o) { var m = dxy((a[o] + a[o + 2]) / 2, (a[o + 1] + a[o + 3]) / 2); if (m[0] * m[0] + m[1] * m[1] <= R * R) ll.push(a[o], a[o + 1], a[o + 2], a[o + 3]); });
      if (ll.length) lines.push({ id: 'grid-' + k, kv: +k, ll: ll, col: BANDS[k].col });
    });
    var subs = S.halos.subs.filter(function (o) { var m = dxy(o.lat, o.lon); return m[0] * m[0] + m[1] * m[1] <= R * R; })
      .map(function (o, i) { return { id: 'grid-sub-' + i + '-' + o.lat.toFixed(5) + ',' + o.lon.toFixed(5), name: o.name, kv: o.kv, lat: o.lat, lon: o.lon }; });
    return { lat: S.c.lat, lon: S.c.lon, radiusM: Math.round(R), lines: lines, subs: subs };
  }
  var lastFocus = null;
  function stateObject() {
    var b = {}; Object.keys(BANDS).forEach(function (k) { b[k] = { col: BANDS[k].col, w: BANDS[k].w }; });
    return { on: S.on, lat: S.c.lat, lon: S.c.lon, radiusM: Math.round(S.R), baseM: S.km * 1000, ground: S.ground, bands: b, low: LOW_COL, glowByDark: true, reduced: reduced() };
  }
  function emitState(force) {
    var o = stateObject(), L = S.lastState;
    if (!force && L && L.on === o.on && Math.abs(L.radiusM - o.radiusM) < o.radiusM * 0.05 && P.dist(L.lat, L.lon, o.lat, o.lon) < o.radiusM * 0.1) return;
    S.lastState = o; P.emit('dark:state', o);
  }
  P.on('dark:query', function (q) { if (q && typeof q.reply === 'function') q.reply(S.on ? (lastFocus || focusObject()) : null, stateObject()); });
  P.on('darkfx:status', function (s) { var had = S.fx != null; S.fx = s || {}; if (!had) render(); });

  var stateT = 0;
  P.onFrame(function () {
    if (!S.on || !P.camLL) return;
    var c = P.camLL(), R = effR(c), f = focusCentre(c, R);
    S.R = R; S.c = f;
    var now = performance.now();
    if (now - stateT > 250) { stateT = now; emitState(false); }
    if (now - S.haloT > 1000) { S.haloT = now; refreshHalos(); }
    if (now - S.nearT > 500) { S.nearT = now; refreshNear(); }
    if (now - S.focusT > 500) { S.focusT = now; lastFocus = focusObject(); P.emit('dark:focus', lastFocus); }
  });
  P.on('origin', function () { wire.key = ''; });

  // ---- S10 UI: the DARK pill (GridAtlas dock style) + focus radius chips + ground choice (+ Effects if present)
  var esc = P.esc || function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); };
  function render() {
    var h = '<div class="p-dark-row" role="group" aria-label="DARK GRID">' +
      '<button type="button" class="p-dark-btn" data-p-dark="toggle" aria-pressed="' + S.on + '" aria-label="DARK GRID: dark ground, only grid assets glow, focus on the immediate area (K)">' +
      '<span class="p-dark-lab">DARK</span>' + (S.on ? '<span class="p-dark-dot" aria-hidden="true">&nbsp;•</span>' : '') + '</button>';