GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / energy-transition-simulator / prototype/mod

LiDAR Stream and 2 more files (part 2)

A JavaScript module in the tests folder of Energy Transition Simulator that tests LiDAR terrain, using SHA-256.

648 lines of JavaScript and HTML from energy-transition-simulator, galaxies-wafers, in 3 files. Topic: Maps, GIS and field navigation. Section 486 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. Walk Fps interaction · energy-transition-simulator / prototype/mod/walk-fps.js lines 1–165
  2. LiDAR Stream test · energy-transition-simulator / tests/lidar-stream.cjs lines 1–314
  3. Galaxies Wafers — Atlas Page render · galaxies-wafers / atlas/index.html lines 1–169

Walk Fps

A JavaScript file in the prototype folder of Energy Transition Simulator that works with seg dist (`segDist`) and look up (`lookUp`) and calculates planar distances.

interactionenergy-transition-simulator / prototype/mod/walk-fps.js · lines 1–165 of 165 · Not reached from any entry point (candidate for review) · pattern solidOf (shared by 3 files)

What it does
It draws its content. Defines 14 functions or classes, including mPerDeg, start, solidOf, segDist, blocked. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
It is built from the m per deg helper (`mPerDeg`), the start step (`start`) and the solid of helper (`solidOf`). First-person walk on the real terrain, inside the map's own camera. It responds to keydown, keyup and blur events.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/mod · script
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
mPerDeg, start, solidOf, segDist, blocked, ground, place, tick, hud, enter, leave, joyAt
Defines here
mPerDeg, start, solidOf, segDist, blocked, ground, place, tick, hud, enter, leave, joyAt, up, lookUp
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/walk-fps.js:1-165 · blob d473400f838c7db6dd54924278ab18b9ebb96248 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// walk-fps: first-person walk on the real terrain, inside the map's own camera.
// Eye 1.7 m above the terrain (map.queryTerrainElevation) at the walker's real lon/lat; mouse look with pointer
// lock; WASD (Shift to run) or the on-screen joystick on phones, drag to look on touch; smooth acceleration;
// the wireframe tables (satellite rows, mapped rows, built blocks) are solid: you stop at a table.
// Plain script: attaches to window.SIM { map, blocks, addBlock, removeWhere, repaint, info }. Toggle: "FPS" button or V.
// Limits (MapLibre 4): pitch tops out at 85 degrees, so the view can look to 5 degrees below the horizon, not above it.
(function () {
  'use strict';
  const EYE = 1.7, WALK = 1.4, RUN = 6, R = 0.35;           // m, m/s (1.4 m/s: a preferred adult walking pace), m body radius
  const PMIN = 55, PMAX = 85;                                // camera pitch range, degrees from straight down
  const A = 6378137, E2 = 0.00669437999014;                  // WGS84
  const mPerDeg = lat => { const s = Math.sin(lat * Math.PI / 180), w = 1 - E2 * s * s;
    return { y: A * (1 - E2) / Math.pow(w, 1.5) * Math.PI / 180, x: A / Math.sqrt(w) * Math.cos(lat * Math.PI / 180) * Math.PI / 180 }; };

  function start(SIM) {
    const map = SIM.map, canvas = map.getCanvas();
    let on = false, lon = 0, lat = 0, yaw = 0, pitch = 82, eyeZ = null, vx = 0, vy = 0, locked = false, saved = null;
    const keys = new Set(), joy = { x: 0, y: 0, id: null }, look = { id: null, x: 0, y: 0 };

    // ---- Solid tables: per block, horizontal wire segments above 0.5 m (table tops) in a 4 m spatial hash, built once.
    const solids = new WeakMap(), CELL = 4;
    function solidOf(b) {
      let s = solids.get(b); if (s && s.n === b.lines.length) return s;
      const h = new Map(), segs = [];
      if (b.sat || b.plant || b.built) for (const l of b.lines) {
        if (Math.abs(l[2] - l[5]) > 0.3 || l[2] < 0.5 || l[2] > 6) continue;      // only the table tops
        const k = segs.length; segs.push(l);
        const x0 = Math.floor((Math.min(l[0], l[3]) - R) / CELL), x1 = Math.floor((Math.max(l[0], l[3]) + R) / CELL);
        const y0 = Math.floor((Math.min(l[1], l[4]) - R) / CELL), y1 = Math.floor((Math.max(l[1], l[4]) + R) / CELL);
        if ((x1 - x0 + 1) * (y1 - y0 + 1) > 400) continue;
        for (let i = x0; i <= x1; i++) for (let j = y0; j <= y1; j++) { const key = i + ',' + j; (h.get(key) || h.set(key, []).get(key)).push(k); }
      }
      s = { h, segs, n: b.lines.length }; solids.set(b, s); return s;
    }
    const segDist = (px, py, l) => { const dx = l[3] - l[0], dy = l[4] - l[1], q = dx * dx + dy * dy;
      const t = q ? Math.max(0, Math.min(1, ((px - l[0]) * dx + (py - l[1]) * dy) / q)) : 0;
      return Math.hypot(px - l[0] - t * dx, py - l[1] - t * dy); };
    function blocked(la, lo) {
      for (const b of SIM.blocks) {
        if (!(b.sat || b.plant || b.built)) continue;
        const an = b.anchor || b, m = mPerDeg(an.lat), x = (lo - an.lon) * m.x, y = (la - an.lat) * m.y;
        if (Math.abs(x) > 5000 || Math.abs(y) > 5000) continue;
        const s = solidOf(b), c = s.h.get(Math.floor(x / CELL) + ',' + Math.floor(y / CELL)); if (!c) continue;
        for (const k of c) if (segDist(x, y, s.segs[k]) < R) return true;
      }
      return false;
    }

    // ---- Camera: MapLibre orbits a centre on the ground; put the centre ahead of the eye so the camera sits on it.
    // Absolute metres. MapLibre 4 returns queryTerrainElevation relative to the centre's elevation (transform.elevation),
    // so add that back; measured 27 Sept at the farm: camera altitude minus this ground = 1.70 m.
    const ground = (lo, la) => { const g = map.queryTerrainElevation ? map.queryTerrainElevation([lo, la]) : 0; return (g == null ? 0 : g) + (map.transform.elevation || 0); };
    function place() {
      const g = ground(lon, lat), want = g + EYE;
      eyeZ = eyeZ == null ? want : eyeZ + (want - eyeZ) * 0.25;                  // smooth the step over rough terrain
      const p = pitch * Math.PI / 180, b = yaw * Math.PI / 180, m = mPerDeg(lat);
      let d = EYE / Math.cos(p), cLo = lon, cLa = lat;
      for (let i = 0; i < 2; i++) {                                               // centre ground height differs from the eye's
        const ahead = d * Math.sin(p);
        cLa = lat + Math.cos(b) * ahead / m.y; cLo = lon + Math.sin(b) * ahead / m.x;
        d = Math.max(0.3, (eyeZ - ground(cLo, cLa)) / Math.cos(p));
      }
      const tr = map.transform, H = canvas.clientHeight || 600, c2c = tr.cameraToCenterDistance || 1.5 * H;
      const mpp = d / c2c, zoom = Math.log2(40075016.686 * Math.cos(cLa * Math.PI / 180) / (512 * mpp));
      map.jumpTo({ center: [cLo, cLa], zoom: Math.min(24, zoom), bearing: yaw, pitch });
    }

    let last = performance.now();
    function tick(t) {
      const dt = Math.min(0.1, (t - last) / 1000); last = t;
      if (!on) return;
      const f = (keys.has('w') || keys.has('arrowup') ? 1 : 0) - (keys.has('s') || keys.has('arrowdown') ? 1 : 0) - joy.y;
      const r = (keys.has('d') || keys.has('arrowright') ? 1 : 0) - (keys.has('a') || keys.has('arrowleft') ? 1 : 0) + joy.x;
      yaw += ((keys.has('e') ? 1 : 0) - (keys.has('q') ? 1 : 0)) * 90 * dt;
      const run = keys.has('shift') || Math.hypot(joy.x, joy.y) > 0.95, sp = run ? RUN : WALK, b = yaw * Math.PI / 180;
      const n = Math.hypot(f, r) > 1 ? Math.hypot(f, r) : 1;
      const tx = (f * Math.sin(b) + r * Math.cos(b)) / n * sp, ty = (f * Math.cos(b) - r * Math.sin(b)) / n * sp;
      const k = 1 - Math.exp(-dt * 8); vx += (tx - vx) * k; vy += (ty - vy) * k;  // east, north m/s, eased
      if (Math.abs(vx) + Math.abs(vy) > 0.01) {
        const m = mPerDeg(lat), dLo = vx * dt / m.x, dLa = vy * dt / m.y;
        if (!blocked(lat + dLa, lon + dLo)) { lat += dLa; lon += dLo; }
        else if (!blocked(lat, lon + dLo)) { lon += dLo; vy = 0; }                // slide along the table
        else if (!blocked(lat + dLa, lon)) { lat += dLa; vx = 0; }
        else { vx = vy = 0; stopped = t; }
      }
      place(); hud(t);
      requestAnimationFrame(tick);
    }
    let stopped = -1e9;
    const hudEl = document.createElement('div');
    hudEl.style.cssText = 'position:absolute;left:50%;top:50%;z-index:4;transform:translate(-50%,-50%);pointer-events:none;font:12px monospace;color:#dfe;text-align:center;display:none;text-shadow:0 0 3px #000';
    document.body.appendChild(hudEl);
    function hud(t) {
      const g = ground(lon, lat), sp = Math.hypot(vx, vy);
      hudEl.innerHTML = '<div style="font-size:18px;line-height:18px">+</div>' + (t - stopped < 800 ? '<div>table</div>' : '');
      SIM.info && SIM.info(`First-person walk. Eye ${EYE} m above terrain; ground ${g.toFixed(1)} m (open terrain tiles, an estimate). ` +
        `${lat.toFixed(6)}, ${lon.toFixed(6)} heading ${Math.round((yaw % 360 + 360) % 360)}°, ${sp.toFixed(1)} m/s. ` +
        `Click to look with the mouse (Esc frees it), W A S D to walk, Shift to run, V to leave. Tables are solid.`);
    }

    function enter() {
      if (on) return; on = true;
      const c = map.getCenter(); lon = c.lng; lat = c.lat; yaw = map.getBearing(); pitch = 82; eyeZ = null; vx = vy = 0;
      saved = { maxZoom: map.getMaxZoom(), dragPan: map.dragPan.isEnabled(), dragRotate: map.dragRotate.isEnabled(), scroll: map.scrollZoom.isEnabled(), kb: map.keyboard.isEnabled() };
      map.setMaxZoom(24); map.dragPan.disable(); map.dragRotate.disable(); map.scrollZoom.disable(); map.keyboard.disable(); map.touchZoomRotate.disable();
      hudEl.style.display = 'block'; btn.classList.add('on'); keys.clear();
      last = performance.now(); requestAnimationFrame(tick);
    }
    function leave() {
      if (!on) return; on = false; if (document.pointerLockElement) document.exitPointerLock();
      hudEl.style.display = 'none'; btn.classList.remove('on');
      if (saved) { if (saved.dragPan) map.dragPan.enable(); if (saved.dragRotate) map.dragRotate.enable(); if (saved.scroll) map.scrollZoom.enable(); if (saved.kb) map.keyboard.enable(); map.touchZoomRotate.enable(); }
      map.easeTo({ center: [lon, lat], zoom: 18.5, pitch: 70, duration: 700 });
      setTimeout(() => saved && map.setMaxZoom(saved.maxZoom), 750);
    }

    // Keys: while walking, take them before the page's own movement sees them (document, capture phase).
    const own = new Set(['w', 'a', 's', 'd', 'q', 'e', 'r', 'f', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', 'shift', '1', '2', '3']);
    document.addEventListener('keydown', e => {
      if (e.target && e.target.tagName === 'INPUT') return;
      const k = e.key.toLowerCase();
      if (k === 'v') { on ? leave() : enter(); e.stopPropagation(); return; }
      if (!on) return;
      if (k === 'escape') return;
      if (own.has(k)) { keys.add(k); e.stopPropagation(); e.preventDefault(); }
    }, true);
    document.addEventListener('keyup', e => { const k = e.key.toLowerCase(); keys.delete(k); if (on && own.has(k)) e.stopPropagation(); }, true);
    addEventListener('blur', () => keys.clear());

    // Mouse look (pointer lock) on desktop.
    canvas.addEventListener('click', () => { if (on && !document.pointerLockElement && canvas.requestPointerLock) canvas.requestPointerLock(); });
    document.addEventListener('pointerlockchange', () => { locked = document.pointerLockElement === canvas; });
    document.addEventListener('mousemove', e => { if (!on || !locked) return;
      yaw += e.movementX * 0.15; pitch = Math.max(PMIN, Math.min(PMAX, pitch - e.movementY * 0.12)); });

    // Phones: the page's joystick drives the walk; a drag anywhere else on the map looks around.
    const joyEl = document.getElementById('joy'), knob = document.getElementById('knob');
    const joyAt = e => { const r = joyEl.getBoundingClientRect(), h = r.width / 2; let x = (e.clientX - r.left - h) / (h - 10), y = (e.clientY - r.top - h) / (h - 10);
      const d = Math.hypot(x, y); if (d > 1) { x /= d; y /= d; } joy.x = x; joy.y = y;
      if (knob) { knob.style.left = (40 + x * 40) + 'px'; knob.style.top = (40 + y * 40) + 'px'; } };
    if (joyEl) {
      joyEl.addEventListener('pointerdown', e => { if (!on) return; e.stopImmediatePropagation(); joy.id = e.pointerId; joyEl.setPointerCapture(e.pointerId); joyAt(e); }, true);
      joyEl.addEventListener('pointermove', e => { if (!on) return; e.stopImmediatePropagation(); if (e.pointerId === joy.id) joyAt(e); }, true);
      const up = e => { if (!on) return; e.stopImmediatePropagation(); if (e.pointerId !== joy.id) return; joy.id = null; joy.x = joy.y = 0; if (knob) knob.style.left = knob.style.top = '40px'; };
      joyEl.addEventListener('pointerup', up, true); joyEl.addEventListener('pointercancel', up, true);
    }
    canvas.addEventListener('pointerdown', e => { if (!on || e.pointerType === 'mouse') return; look.id = e.pointerId; look.x = e.clientX; look.y = e.clientY; });
    canvas.addEventListener('pointermove', e => { if (!on || e.pointerId !== look.id) return;
      yaw -= (e.clientX - look.x) * 0.25; pitch = Math.max(PMIN, Math.min(PMAX, pitch + (e.clientY - look.y) * 0.2)); look.x = e.clientX; look.y = e.clientY; });
    const lookUp = e => { if (e.pointerId === look.id) look.id = null; };
    canvas.addEventListener('pointerup', lookUp); canvas.addEventListener('pointercancel', lookUp);

    // The button, beside the page's own Walk / Drone / Map.
    const btn = document.createElement('button'); btn.id = 'walk-fps'; btn.textContent = 'FPS';
    btn.title = 'First-person walk, eye at 1.7 m (V)'; btn.onclick = () => (on ? leave() : enter());
    const bar = document.getElementById('bar'), ref = document.getElementById('map2d');
    if (bar) bar.insertBefore(btn, ref ? ref.nextSibling : null); else { btn.style.cssText = 'position:absolute;left:8px;top:8px;z-index:5'; document.body.appendChild(btn); }

    window.walkFps = { enter, leave, state: () => ({ on, lon, lat, yaw, pitch, eyeZ, ground: ground(lon, lat) }),
      set: o => { if (o.lon != null) lon = o.lon; if (o.lat != null) lat = o.lat; if (o.yaw != null) yaw = o.yaw; if (o.pitch != null) pitch = o.pitch; },
      press: k => keys.add(k), release: k => keys.delete(k), blocked: (la, lo) => blocked(la, lo) };
  }

  (function wait() { if (window.SIM && window.SIM.map) start(window.SIM); else setTimeout(wait, 100); })();
})();

LiDAR Stream

A JavaScript module in the tests folder of Energy Transition Simulator that tests LiDAR terrain, using SHA-256.

testenergy-transition-simulator / tests/lidar-stream.cjs · lines 1–314 of 314 · Not reached from any entry point (candidate for review) · pattern chunk (shared by 3 files)

What it does
It tests LiDAR terrain. Defines 11 functions or classes, including DTM, BUILDING, crc, chunk, png. Uses libraries http, fs, path, url, crypto. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: JSON file index.json. Out: interactive map; WebGL/WebGPU drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It is built from the crc step (`crc`), the chunk step (`chunk`) and the png step (`png`). Check for `mod/lidar-stream.js` (rule R5 in the browser).
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · tests · JavaScript module
Uses
http, fs, path, url, crypto, playwright, zlib
Used by
none found
Produces
DTM, BUILDING, crc, chunk, png, ll, demTile, proj, litRate, ld, lit
Defines here
DTM, BUILDING, crc, chunk, png, ll, demTile, proj, litRate, ld, lit
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/lidar-stream.cjs:1-314 · blob cdd628c7b2f92911b0d757440ee972cd30ab6e73 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
// Check for mod/lidar-stream.js (rule R5 in the browser). It NEVER calls the EA: every request to the EA WCS is
// answered by a SYNTHETIC GeoTIFF made here, in the service's own form, and any request that escapes is a FAIL.
// Part 1 (node): lattice, clipping, decoder round trip, zero-run rule, receipt hash, pacer.
// Part 2 (Chrome): arrive, stream DTM then DSM, draw ground + above-ground wire, receipt + licence on screen,
// no fetch on movement, and "no measured ground here" outside the envelope. Screenshots to test-output/ or $SHOTS.
const http = require('http'), fs = require('fs'), path = require('path'), { pathToFileURL } = require('url');
const { webcrypto } = require('crypto');
const ROOT = path.join(__dirname, '..', 'prototype'), OUT = process.env.SHOTS || path.join(__dirname, '..', 'test-output');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
fs.mkdirSync(OUT, { recursive: true });
const results = []; const check = (name, ok, evidence) => results.push({ name, ok: !!ok, evidence: String(evidence).slice(0, 240) });
const DTM = (e, n) => 100 + 0.01 * (e % 2048) + 5 * Math.sin((n % 2048) / 150);
const BUILDING = (e, n) => { const u = e % 2048, v = n % 2048; return u >= 1004 && u < 1044 && v >= 1004 && v < 1044 ? 10 : 0; };

(async () => {
  const R5 = await import(pathToFileURL(path.join(ROOT, 'mod', 'lidar-stream', 'r5.mjs')).href);
  // ---- Part 1: pure maths ----
  const t = R5.tileOf(463500.4, 262100.9);
  check('lattice tile corner on 2,048 m', t.e0 === 462848 && t.n0 === 260096 && t.e1 - t.e0 === 2048, JSON.stringify(t));
  check('negative-side cell stays in its tile', R5.tileOf(462848, 260096).key === '462848_260096' && R5.tileOf(462847.99, 260096).e0 === 460800, 'edges');
  check('clip to envelope', JSON.stringify(R5.clip(R5.tileOf(655900, 300000), R5.SOURCES.dtm.env)) === JSON.stringify({ e0: 655360, n0: 299008, e1: 656000, n1: 301056 }), 'east edge');
  check('outside envelope is null', R5.clip(R5.tileOf(330000, 700000), R5.SOURCES.dtm.env) === null, 'Scotland');
  check('DSM card is the catalogue URL (not the 404 guess)', /digital-surface-model-first-return-dsm-1m\/wcs$/.test(R5.SOURCES.dsm.url) && /FZ_DSM_1m$/.test(R5.SOURCES.dsm.coverage), R5.SOURCES.dsm.url);
  const tif = R5.synthTiff(1000, 2064, 64, 64, (i, j) => (i === 3 && j === 5 ? -3.4028234663852886e38 : 50 + i + 100 * j));
  const g = await R5.decodeGeoTiff(tif);
  check('decoder round trip', g.width === 64 && g.west === 1000 && g.north === 2064 && g.res === 1 && g.data[2 * 64 + 7] === 257 && g.hasNodata, `${g.width} ${g.west} ${g.north} ${g.data[2 * 64 + 7]}`);
  const m = R5.measuredMask(g);
  check('nodata cell is unmeasured', m.mask[5 * 64 + 3] === 0 && m.valid === 64 * 64 - 1, `valid ${m.valid}`);
  const z = await R5.decodeGeoTiff(R5.synthTiff(0, 64, 64, 64, () => 0, null));
  check('all-zero box without nodata tag = no measured ground', R5.measuredMask(z).valid === 0, 'valid 0');
  const zr = await R5.decodeGeoTiff(R5.synthTiff(0, 64, 64, 64, i => (i < 20 ? 0 : i === 30 ? 0 : 7), null));
  const zm = R5.measuredMask(zr);
  check('zero run >= 16 dropped, lone zero kept', zm.mask[0] === 0 && zm.mask[30] === 1 && zm.mask[25] === 1, `row0 ${zm.mask.slice(0, 32).join('')}`);
  const s1 = await R5.cellSha256(g.data, webcrypto.subtle), s2 = await R5.cellSha256(new Float32Array(g.data), webcrypto.subtle);
  check('receipt hash is over cells (stable, 64 hex)', s1 === s2 && /^[0-9a-f]{64}$/.test(s1), s1);
  let now = 0; const pc = R5.createPacer({ clock: () => now });
  const a1 = pc.take(); const a2 = pc.take(); pc.done(200); now += 39999; const a3 = pc.take(); now += 1; const a4 = pc.take();
  check('pacer: one at a time, 40 s gap', a1 && !a2 && !a3 && a4, `${a1} ${a2} ${a3} ${a4}`);
  pc.done(429); now += R5.GAP_MS; const b1 = pc.take(); now += R5.PAUSE_MS; const b2 = pc.take();
  check('pacer: refusal pauses 5 min', !b1 && b2, `${b1} ${b2}`);
  const cap = R5.createPacer({ clock: () => now, used: 16 });
  check('pacer: 16 a day', !cap.take() && /daily cap/.test(cap.why()), cap.why());

  // ---- Part 2: the browser, with the fixture ----
  const { chromium } = require('playwright');
  const server = http.createServer((q, s) => {
    const f = path.join(ROOT, decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html');
    if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
    let body = fs.readFileSync(f);
    if (f.endsWith(path.join('mod', 'index.json'))) { const l = JSON.parse(body); if (!l.includes('lidar-stream')) l.push('lidar-stream'); body = JSON.stringify(l); } // scratch switch-on
    s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); s.end(body);
  });
  await new Promise(r => server.listen(0, '127.0.0.1', r));
  const base = `http://127.0.0.1:${server.address().port}/overlay.html`;
  const b = await chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
  const p = await b.newPage({ viewport: { width: 1280, height: 800 } });
  const errs = [], ea = [];
  p.on('pageerror', e => errs.push(e.message));
  await p.route(/environment\.data\.gov\.uk/, async route => {
    const u = decodeURIComponent(route.request().url()); ea.push({ u, at: Date.now() });
    const E = u.match(/subset=E\((\d+),(\d+)\)/), N = u.match(/subset=N\((\d+),(\d+)\)/);
    if (!E || !N) return route.fulfill({ status: 400, body: 'fixture: bad request' });
    const e0 = +E[1], e1 = +E[2], n0 = +N[1], n1 = +N[2], dsm = /DSM/.test(u);
    const body = R5.synthTiff(e0, n1, e1 - e0, n1 - n0, (i, j) => { const e = e0 + i + 0.5, n = n1 - j - 0.5; return DTM(e, n) + (dsm ? BUILDING(e, n) : 0); });
    route.fulfill({ status: 200, headers: { 'content-type': 'image/tiff', 'access-control-allow-origin': '*' }, body: Buffer.from(body) });
  });
  await p.goto(`${base}?lat=52.2441634&lon=-1.0453368`, { waitUntil: 'load' });
  await p.waitForFunction(() => window.__lidarStream, null, { timeout: 30000 });
  check('module loads, adds its button', (await p.$$eval('button', bs => bs.map(x => x.textContent))).includes('Stream ground'), 'button');
  check('no EA request before arrival', ea.length === 0, `${ea.length}`);
  await p.evaluate(() => window.__lidarStream.useFixture(null, 3000)); // fixture served by route; gap shortened for the test only
  await p.evaluate(() => document.getElementById('wire').click()); await p.waitForTimeout(1500);
  await p.evaluate(() => window.SIM.map.jumpTo({ pitch: 60, zoom: 15.2, bearing: 30 }));
  await p.evaluate(() => document.getElementById('drone').click()); // arrival
  await p.waitForFunction(() => window.__lidarStream.blocks().some(b => b.kind === 'above-ground'), null, { timeout: 30000 });
  await p.waitForTimeout(1500);
  const bl = await p.evaluate(() => window.__lidarStream.blocks()), rc = await p.evaluate(() => window.__lidarStream.receipt());
  check('two requests: DTM then DSM', ea.length === 2 && /DTM/.test(ea[0].u) && /DSM/.test(ea[1].u), ea.map(x => x.u.slice(0, 120)).join(' | '));
  check('DSM waited the gap after the DTM', ea.length === 2 && ea[1].at - ea[0].at >= 2900, ea.length === 2 ? `${ea[1].at - ea[0].at} ms` : '-');
  check('one 2,048 m box per product', ea.every(x => { const E = x.u.match(/E\((\d+),(\d+)\)/); return E && +E[2] - +E[1] === 2048 && +E[1] % 2048 === 0; }), ea.map(x => (x.u.match(/E\([^)]*\)/) || [''])[0]).join(' '));
  const gr = bl.find(x => x.kind === 'ground'), ab = bl.find(x => x.kind === 'above-ground');
  const gh = bl.find(x => x.kind === 'ground' && x.style === 'ghost'), gAll = bl.filter(x => x.kind === 'ground').reduce((s, x) => s + x.segs, 0);
  check('ground wire: 8 m grid over the tile, measured solid (+ any near-lifted ghost)', gr && gAll === 2 * 256 * 255 && gr.prov === 'measured' && gr.style === 'solid' && (!gh || (gh.prov === 'estimated' && gh.n === 4 * gh.segs)), JSON.stringify(gr) + ' ghost ' + (gh ? `${gh.segs} segs, ${gh.lifted} nodes` : 'none'));
  check('above-ground posts: the 40 m block (derived)', ab && ab.prov === 'derived' && ab.n / 5 >= 25 && ab.n / 5 <= 36, JSON.stringify(ab));
  check('anchored near the tile centre (real lat/lon)', gr && Math.abs(gr.lat - 52.25) < 0.03 && Math.abs(gr.lon + 1.05) < 0.03, gr ? `${gr.lat} ${gr.lon}` : '-');
  check('receipt on screen with sha256 and licence', /sha256\(cells\) [0-9a-f]{64}/.test(rc) && /Open Government Licence v3\.0/.test(rc) && /Environment Agency/.test(rc), rc.slice(0, 200));
  check('survey year stated as not read (rule 9)', /pre-construction ground/.test(rc), 'rule 9 words');
  // HEIGHT DATUM: heightAt against the fixture's own formula (independent truth), then the drawn height at 200 nodes.
  const hq = await p.evaluate(() => { const g = window.__lidarStream.tiles.values().next().value.tile; return { g, r: window.__lidarStream.heightAt(g.e0 + 700.3, g.n0 + 900.8) }; });
  const hTrue = DTM(hq.g.e0 + 700.5, hq.g.n0 + 900.5);
  check('heightAt = the measured cell, with its receipt', hq.r.h != null && Math.abs(hq.r.h - hTrue) < 1e-3 && /^[0-9a-f]{12}$/.test(hq.r.receipt) && hq.r.prov === 'measured', `${hq.r.h} vs ${hTrue.toFixed(4)} receipt ${hq.r.receipt}`);
  const pr = await p.evaluate(() => window.__lidarStream.probe(200));
  check('datum probe: 200 nodes drawn at their own DTM height, |D| < 0.5 m', pr.nodes === 200 && pr.maxAbsD < 0.5, `max|D| ${pr.maxAbsD.toFixed(4)} m, mean ${pr.meanD.toFixed(4)} m; map DEM vs DTM max ${pr.maxAbsDemD} m over ${pr.demNodes} loaded nodes (item 3; fixture DTM is synthetic)`);
  await p.screenshot({ path: path.join(OUT, 'stream-1-drone.png') });
  // LAYER ORDER: Satellite moves the measured wire to its own see-through layer (imagery stays visible); Wire takes it back.
  await p.evaluate(() => document.getElementById('sat').click()); await p.waitForTimeout(2500);
  const ls = await p.evaluate(() => window.__lidarStream.layer());
  check('Satellite: measured wire on its own see-through layer above the imagery, not in the solid wire', ls.satellite && ls.onMap && ls.own >= 1 && ls.inWire === 0 && ls.alpha < 0.5, JSON.stringify(ls));
  await p.screenshot({ path: path.join(OUT, 'stream-2-satellite.png') });
  await p.evaluate(() => document.getElementById('wire').click()); await p.waitForTimeout(1500);
  const lw = await p.evaluate(() => window.__lidarStream.layer());
  check('Wire: blocks back in the solid wire layer, own layer empty', !lw.satellite && lw.own === 0 && lw.inWire === bl.length, JSON.stringify(lw));
  // The receipt panel never covers the landing caption (#info, with the pylons line): bounding rects must not intersect.
  await p.evaluate(() => { const i = document.getElementById('info'); i.style.display = ''; i.textContent = 'Pylons: caption overlap check, a long line that runs across the bottom of the screen like the mapped pylons caption does'; });
  await p.waitForTimeout(200);
  await p.waitForTimeout(1200);
  // STRICT (r4): the receipt's visible box against EVERY visible caption element on the page: any element that holds its
  // own text, is rendered (checkVisibility, so position:fixed captions count too; offsetParent is null for those) and has
  // a non-empty rect. Fails on 7cc775a, where the box sat over #where, the note and the attribution strip.
  const ov = await p.evaluate(() => { const R = document.getElementById('lidar-stream-receipt'), vis = e => e.getClientRects().length > 0 && (!e.checkVisibility || e.checkVisibility({ checkOpacityProperty: true, checkVisibilityCSS: true }));
    const shown = [...R.querySelectorAll('*'), R].filter(e => vis(e) && [...e.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())).map(e => e.getBoundingClientRect()).filter(r => r.width > 0 && r.height > 0);
    const hits = [], caps = [];
    for (const el of document.body.querySelectorAll('*')) {
      if (R.contains(el) || !vis(el) || ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) continue;
      const c = el.getBoundingClientRect(); if (!(c.width > 0 && c.height > 0)) continue; caps.push(el.id || el.className || el.tagName);
      for (const a of shown) if (a.left < c.right && c.left < a.right && a.top < c.bottom && c.top < a.bottom) hits.push(`${el.id || el.tagName}:${el.textContent.trim().slice(0, 30)}`);
    }
    return { receiptRects: shown.length, lines: shown.map(r => Math.round(r.height)), caps: caps.length, hits, visibleIds: caps.filter(x => typeof x === 'string' && /^(where|attribution|sim-note|procedural-caption|info)$/.test(x)) }; });
  check('receipt is ONE line and overlaps NO visible caption (#where, note, pylon/placement caption, attribution)', ov.receiptRects === 1 && ov.lines[0] <= 16 && ov.hits.length === 0 && ov.visibleIds.includes('where') && ov.visibleIds.includes('attribution') && ov.visibleIds.includes('sim-note'), `receipt text boxes ${ov.receiptRects} (h ${ov.lines.join(',')}); ${ov.caps} visible captions incl ${o  … [line shortened here: 466 characters; full line on GitHub]
  const ln = await p.evaluate(() => window.__lidarStream.line());
  check('one dim line reads "measured ground: EA LiDAR 1 m, tile E/N, receipt sha8"', /^measured ground: EA LiDAR 1 m, tile \d+\/\d+, receipt [0-9a-f]{8}$/.test(ln.text) && !ln.open, ln.text);
  await p.click('#lidar-stream-line'); await p.waitForTimeout(300);
  const op = await p.evaluate(() => { const f = document.getElementById('lidar-stream-full'); return { vis: !f.hidden && f.getClientRects().length > 0, t: f.textContent }; });
  await p.screenshot({ path: path.join(OUT, 'stream-6-receipt-open.png') });
  await p.click('#lidar-stream-line'); await p.waitForTimeout(300);
  const cl = await p.evaluate(() => document.getElementById('lidar-stream-full').hidden);
  check('click opens the full receipt (sha256, licence), click again closes it', op.vis && /sha256\(cells\) [0-9a-f]{64}/.test(op.t) && /Open Government Licence/.test(op.t) && cl, `open ${op.vis}, closed after ${cl}`);
  // WALK (r3): the measured wire is visible near the walker (Satellite, Walk pose). The frame must be healthy
  // (transform.elevation = the ground at the centre); the overlay's stuck MapLibre _elevationFreeze is cleared here and
  // reported to the lead as a separate camera fault. Checks: node count within 100 m on screen, some in the lower third,
  // and pixels the layer adds in the lower third (shown vs hidden).
  await p.evaluate(() => document.getElementById('sat').click()); await p.waitForTimeout(2500);
  await p.evaluate(() => { const m = window.SIM.map; m.jumpTo({ center: [-1.0453368, 52.2441634], zoom: 16.5, pitch: 60, bearing: 30 }); m._elevationFreeze = false; m.triggerRepaint(); });
  await p.waitForTimeout(1500);
  await p.evaluate(() => window.SIM.map.easeTo({ zoom: 18.5, pitch: 80, duration: 900 }));
  await p.evaluate(() => new Promise(r => { const m = window.SIM.map; setTimeout(() => { m.once('idle', r); m.triggerRepaint(); setTimeout(r, 6000); }, 1500); }));
  const near = await p.evaluate(() => { const m = window.SIM.map, T = m.transform, M = T.customLayerMatrix(), c = m.getCenter(), E = T.elevation || 0;
    const mc = maplibregl.MercatorCoordinate.fromLngLat(c, 0), mpm = maplibregl.MercatorCoordinate.fromLngLat(c, 1).z, o2 = { E, nodes: 0, onScreen: 0, low: 0 };
    for (const t of window.__lidarStream.tiles.values()) for (const b of t.blks || []) { if (b.kind !== 'ground') continue;
      const o = maplibregl.MercatorCoordinate.fromLngLat([b.anchor.lon, b.anchor.lat], b.gz + (b.E || 0) - E);
      for (let i = 0; i < b.buf.length; i += 3) { const x = b.buf[i] + o.x, y = b.buf[i + 1] + o.y, z = b.buf[i + 2] + o.z; if (Math.hypot(x - mc.x, y - mc.y) / mpm > 100) continue; o2.nodes++;
        const w = M[3] * x + M[7] * y + M[11] * z + M[15], X = (M[0] * x + M[4] * y + M[8] * z + M[12]) / w, Y = (M[1] * x + M[5] * y + M[9] * z + M[13]) / w;
        if (w > 0 && Math.abs(X) <= 1 && Math.abs(Y) <= 1) { o2.onScreen++; if (Y < -1 / 3) o2.low++; } } }
    return o2; });
  const shotA = await p.screenshot({ path: path.join(OUT, 'stream-5-walk-near.png') });
  await p.evaluate(() => { const m = window.SIM.map; m.setLayoutProperty('lidar-stream-sat', 'visibility', 'none'); m.triggerRepaint(); }); await p.waitForTimeout(700);
  const shotB = await p.screenshot();
  await p.evaluate(() => { const m = window.SIM.map; m.setLayoutProperty('lidar-stream-sat', 'visibility', 'visible'); m.triggerRepaint(); });
  const lowPx = await p.evaluate(async ([A, B]) => { const ld = s => new Promise(r => { const i = new Image(); i.onload = () => r(i); i.src = 'data:image/png;base64,' + s; });
    const [ia, ib] = await Promise.all([ld(A), ld(B)]), W = ia.width, H = ia.height, cv = document.createElement('canvas'); cv.width = W; cv.height = H; const g = cv.getContext('2d');
    g.drawImage(ia, 0, 0); const da = g.getImageData(0, 0, W, H).data; g.drawImage(ib, 0, 0); const db = g.getImageData(0, 0, W, H).data; let n = 0;
    for (let y = Math.floor(2 * H / 3); y < H; y++) for (let x = 0; x < W; x++) { const k = 4 * (y * W + x); if (Math.abs(da[k] - db[k]) + Math.abs(da[k + 1] - db[k + 1]) + Math.abs(da[k + 2] - db[k + 2]) > 24) n++; }
    return n; }, [shotA.toString('base64'), shotB.toString('base64')]);
  check('Walk: measured wire visible near the walker (nodes on screen, lower third lit)', near.E > 50 && near.onScreen > 100 && near.low > 0 && lowPx > 500, `E ${near.E.toFixed(2)} m; ${near.onScreen}/${near.nodes} nodes within 100 m on screen, ${near.low} in the lower third; ${lowPx} px drawn in the lower third`);
  const pw = await p.evaluate(() => window.__lidarStream.probe(200));
  check('Walk frame: nodes still at their own DTM height with E set, |D| < 0.05 m', pw.maxAbsD < 0.05, `max|D| ${pw.maxAbsD.toFixed(4)} m at E ${near.E.toFixed(2)} m`);
  await p.evaluate(() => document.getElementById('wire').click()); await p.waitForTimeout(1500);
  // Movement never fetches: walk and pan.
  const n0 = ea.length;
  await p.evaluate(() => window.SIM.map.jumpTo({ center: [-1.046, 52.2436], zoom: 17.5, pitch: 72 }));
  await p.keyboard.down('w'); await p.waitForTimeout(1500); await p.keyboard.up('w');
  await p.evaluate(() => window.SIM.map.panBy([300, 0], { duration: 0 })); await p.waitForTimeout(1500);
  check('walking and panning never fetch', ea.length === n0, `${ea.length - n0} new`);
  await p.screenshot({ path: path.join(OUT, 'stream-2-walk.png') });
  // Outside coverage: Scotland (outside the envelope), by the Stream ground button (an arrival).
  await p.evaluate(() => window.SIM.map.jumpTo({ center: [-3.19, 55.95], zoom: 14 })); await p.waitForTimeout(800);
  await p.$$eval('button', bs => bs.find(x => x.textContent === 'Stream ground').click()); await p.waitForTimeout(1500);
  const rc2 = await p.evaluate(() => window.__lidarStream.receipt());
  check('outside coverage says "no measured ground here", no request', /no measured ground here/.test(rc2) && ea.length === n0, rc2.slice(0, 160));
  await p.screenshot({ path: path.join(OUT, 'stream-3-outside.png') });
  // The landing caption (#info) belongs to the overlay; arrival text goes only to this module's receipt panel.
  const inf0 = await p.evaluate(() => (document.getElementById('info') || {}).textContent);
  await p.evaluate(() => window.__lidarStream.arrive('check')); await p.waitForTimeout(300);
  const inf1 = await p.evaluate(() => (document.getElementById('info') || {}).textContent), rc3 = await p.evaluate(() => window.__lidarStream.receipt());
  check('#info unchanged by arrive(); arrival line is the receipt panel first line', inf0 != null && inf1 === inf0 && /^Arrived \(check\): measured ground for tile \d+ E \d+ N streams here; moving never fetches\./.test(rc3) && ea.length === n0, `info "${String(inf1).slice(0, 60)}" | receipt "${rc3.split('\n')[0].slice(0, 90)}"`);
  // Network error (status 0): exactly one retry in the same arrival, never on movement; then the honest label.
  await p.evaluate(() => { window.__calls = 0; window.__lidarStream.useFixture((u, o) => { window.__calls++; if (window.__calls === 1) throw new TypeError('Failed to fetch'); return fetch(u, o); }, 1500); });
  await p.evaluate(() => window.SIM.map.jumpTo({ center: [-1.30, 51.75], zoom: 15, pitch: 50 })); await p.waitForTimeout(600);
  await p.$$eval('button', bs => bs.find(x => x.textContent === 'Stream ground').click());
  await p.waitForFunction(() => /complete/.test(window.__lidarStream.receipt()), null, { timeout: 30000 });
  const c1 = await p.evaluate(() => window.__calls), rc4 = await p.evaluate(() => window.__lidarStream.receipt());
  check('network error: DTM retried once, then DTM and DSM (fetchImpl 3 calls: fail, DTM, DSM)', c1 === 3 && /DTM receipt [0-9a-f]{12}/.test(rc4), `calls ${c1}`);
  await p.evaluate(() => { window.__calls = 0; window.__lidarStream.useFixture((u, o) => { window.__calls++; if (window.__calls === 1) throw new TypeError('Failed to fetch'); return fetch(u, o); }, 1500); });
  await p.evaluate(() => window.SIM.map.jumpTo({ center: [-1.60, 51.75], zoom: 15, pitch: 50 })); await p.waitForTimeout(600);
  await p.evaluate(() => window.__lidarStream.arrive('check'));
  await p.waitForFunction(() => /DTM receipt/.test(window.__lidarStream.receipt()), null, { timeout: 30000 });
  const c2 = await p.evaluate(() => window.__calls);
  check('throws once then succeeds: exactly 2 DTM calls', c2 === 2, `calls ${c2}`);
  await p.waitForFunction(() => /complete/.test(window.__lidarStream.receipt()), null, { timeout: 30000 });
  await p.evaluate(() => { window.__calls = 0; window.__lidarStream.useFixture(() => { window.__calls++; throw new TypeError('Failed to fetch'); }, 1500); });
  await p.evaluate(() => window.SIM.map.panBy([400, 200], { duration: 0 })); await p.keyboard.down('w'); await p.waitForTimeout(1500); await p.keyboard.up('w');
  await p.evaluate(() => window.SIM.map.jumpTo({ center: [-1.90, 51.75], zoom: 15 })); await p.waitForTimeout(2500);
  check('0 fetch calls on move, pan or walk', (await p.evaluate(() => window.__calls)) === 0, `calls ${await p.evaluate(() => window.__calls)}`);
  await p.evaluate(() => window.__lidarStream.arrive('check'));
  await p.waitForFunction(() => /no measured ground shown/.test(window.__lidarStream.receipt()), null, { timeout: 30000 });
  await p.waitForTimeout(3000);
  const c3 = await p.evaluate(() => window.__calls), rc5 = await p.evaluate(() => window.__lidarStream.receipt());
  check('two network errors: 2 calls, labelled "DTM fetch failed (<reason>); no measured ground shown"', c3 === 2 && /DTM fetch failed \(Failed to fetch\); no measured ground shown/.test(rc5) && !/DTM: no measured ground here/.test(rc5), `calls ${c3} | ${rc5.split('\n')[1]}`);
  await p.screenshot({ path: path.join(OUT, 'stream-4-fetch-failed.png') });
  await p.evaluate(() => window.__lidarStream.useFixture(null, 3000));
  // RIDGE (r5): does the Satellite layer's depth bias let a hill hide the far wire, and still draw the far wire the
  // camera can see? A fully SYNTHETIC world on its own page: the EA WCS fixture AND the map's DEM tiles (terrarium) both
  // come from one steep N-S ridge made here; no live heights. The imagery is a flat grey tile made here, unless
  // RIDGE_REAL_SAT=1 (then the live satellite is drawn, for the look). Each node >= 1 km away (every 13th vertex, on
  // screen, its projected 8 m segment >= 1 px; sub-pixel ones are skipped, not failed) is classed by line of sight over
  // the synthetic ground: HIDDEN if the ground rises > 3 m above the sight line; VISIBLE if the sight line clears the
  // ground by >= 3 m everywhere except the last 50 m before the node; otherwise ambiguous (counted, not asserted).
  // Drawn = the 3x3 pixels round the node differ from the same view with the layer off. RIDGE_BIAS overrides the
  // module's DEPTH_BIAS in the served copy only (for the bias search).
  // NEAR (r6), on a second page: guards the reason DEPTH_BIAS exists (r3). The map DEM is set 2 m ABOVE the DTM
  // fixture (the r3 case: coarse DEM over 1 m DTM). The camera stands in the Walk pose on the front (east) slope,
  // about 2 m above measured ground, at grazing pitch, looking up at the crest. Nodes 20-300 m away are classed
  // VISIBLE when the sight line clears the DTM by >= 3 m over its middle 80 % (the camera end is at eye height and
  // the node end is on the ground, so both ends are left out); >= 95 % of them must be drawn, each class alone
  // against a layer-off shot as above. The rest (the foreground, which cannot clear 3 m from eye height) is drawn
  // alone too and REPORTED, not asserted. RIDGE_DEM_OFF overrides the 2 m (e.g. 0.001 for the DEM = DTM control).
  for (const NEAR of [false, true]) {
    const BNG = await import(pathToFileURL(path.join(ROOT, 'world', 'bng.mjs')).href);
    const RT = { e0: 374784, n0: 243712 }, RE = RT.e0 + 500, DEM_OFF = NEAR ? +(process.env.RIDGE_DEM_OFF || 2) : 0, RIDGE = (e) => 50 + 180 * Math.exp(-((e - RE) ** 2) / (2 * 250 * 250));
    const realSat = process.env.RIDGE_REAL_SAT === '1', bias = process.env.RIDGE_BIAS;
    const zlib = require('zlib'), crcT = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
    const crc = b => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
    const chunk = (ty, d) => { const L = Buffer.alloc(4), T = Buffer.from(ty), C = Buffer.alloc(4); L.writeUInt32BE(d.length); C.writeUInt32BE(crc(Buffer.concat([T, d]))); return Buffer.concat([L, T, d, C]); };
    const png = (px) => { const raw = Buffer.alloc(256 * 769); for (let y = 0; y < 256; y++) { raw[y * 769] = 0; for (let x = 0; x < 256; x++) { const [r, g, bb] = px(x, y); raw[y * 769 + 1 + 3 * x] = r; raw[y * 769 + 2 + 3 * x] = g; raw[y * 769 + 3 + 3 * x] = bb; } }
      const h = Buffer.alloc(13); h.writeUInt32BE(256, 0); h.writeUInt32BE(256, 4); h[8] = 8; h[9] = 2;
      return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', h), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); };
    const ll = (z, x, y) => ({ lon: x / 2 ** z * 360 - 180, lat: Math.atan(Math.sinh(Math.PI * (1 - 2 * y / 2 ** z))) * 180 / Math.PI });
    const demTile = (z, x, y) => { const c = [[0, 0], [1, 0], [0, 1], [1, 1]].map(([i, j]) => { const g = ll(z, x + i, y + j); return BNG.wgs84ToBng(g.lat, g.lon); });
      return png((px, py) => { const u = (px + 0.5) / 256, v = (py + 0.5) / 256, e = (1 - v) * ((1 - u) * c[0].e + u * c[1].e) + v * ((1 - u) * c[2].e + u * c[3].e);
        const h = Math.round((z < 9 ? 50 : RIDGE(e) + DEM_OFF) * 256) + 32768 * 256; return [(h >> 16) & 255, (h >> 8) & 255, h & 255]; }); };
    const grey = png(() => [128, 128, 128]);
    const q = await b.newPage({ viewport: { width: 1280, height: 800 } }), rErr = [];
    q.on('pageerror', e => rErr.push(e.message));
    if (bias) await q.route(/mod\/lidar-stream\.js/, async r => { const f = await r.fetch(); r.fulfill({ response: f, body: (await f.text()).replace(/DEPTH_BIAS = [0-9.]+/,`DEPTH_BIAS = ${bias}`) }); });
    await q.route(/elevation-tiles-prod\/terrarium\/\d+\/\d+\/\d+\.png/, r => { const [z, x, y] = r.request().url().match(/terrarium\/(\d+)\/(\d+)\/(\d+)\.png/).slice(1).map(Number);
      r.fulfill({ status: 200, headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' }, body: demTile(z, x, y) }); });
    if (!realSat) await q.route(/World_Imagery/, r => r.fulfill({ status: 200, headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' }, body: grey }));
    await q.route(/environment\.data\.gov\.uk/, r => { const u = decodeURIComponent(r.request().url()), E = u.match(/subset=E\((\d+),(\d+)\)/), N = u.match(/subset=N\((\d+),(\d+)\)/);
      if (!E || !N) return r.fulfill({ status: 400, body: 'fixture: bad request' });
      const e0 = +E[1], e1 = +E[2], n0 = +N[1], n1 = +N[2];
      r.fulfill({ status: 200, headers: { 'content-type': 'image/tiff', 'access-control-allow-origin': '*' }, body: Buffer.from(R5.synthTiff(e0, n1, e1 - e0, n1 - n0, i => RIDGE(e0 + i + 0.5))) }); });
    const c0 = BNG.bngToWgs84(RT.e0 + 1024, RT.n0 + 1024);
    await q.goto(`${base}?lat=${c0.lat}&lon=${c0.lon}`, { waitUntil: 'load' });
    await q.waitForFunction(() => window.__lidarStream && window.SIM && window.SIM.map && document.querySelector('canvas.maplibregl-canvas'), null, { timeout: 60000 });
    const gpu = await q.evaluate(() => { const g = document.createElement('canvas').getContext('webgl'), d = g && g.getExtension('WEBGL_debug_renderer_info'); return d ? g.getParameter(d.UNMASKED_RENDERER_WEBGL) : '?'; });
    await q.evaluate(() => window.__lidarStream.useFixture(null, 3000));
    await q.evaluate(() => document.getElementById('sat').click()); await q.waitForTimeout(2000);
    await q.evaluate(() => window.__lidarStream.arrive('ridge check'));
    await q.waitForFunction(() => /DTM receipt/.test(window.__lidarStream.receipt()) && window.__lidarStream.blocks().some(b => b.kind === 'ground'), null, { timeout: 60000 });
    // Walker 1.4 km east of the crest, looking west across it: move the centre until the CAMERA stands there.
    // NEAR: the walker stands 800 m east of the crest, at the foot of the front slope, looking up it. Zoom is solved for
    // 2 m over the DTM, with the page's maxZoom raised 20 -> 22 on this test page only (at z20 the camera cannot get below ~10 m).
    const camE = NEAR ? RE + 800 : RT.e0 + 1900, cam = BNG.bngToWgs84(camE, RT.n0 + 1024), camTarget = NEAR ? RIDGE(camE) + 2 : null;
    await q.evaluate(async ([la, lo, tH]) => { const m = window.SIM.map; if (tH) m.setMaxZoom(22); let c = [lo - (tH ? 0.0003 : 0.004), la], z = tH ? 20 : 17.2, pt = tH ? Math.min(85, m.getMaxPitch()) : 84;
      for (let k = 0; k < (tH ? 7 : 4); k++) { m.jumpTo({ center: c, zoom: z, pitch: pt, bearing: 270 }); m._elevationFreeze = false; m.triggerRepaint();
        await new Promise(r => setTimeout(r, 1500)); const cp = m.transform.getCameraPosition(), p = cp.lngLat, E = m.transform.elevation || 0;
        c = [c[0] + lo - p.lng, c[1] + la - p.lat]; if (tH) z = Math.min(m.getMaxZoom(), tH - E > 0.05 && cp.altitude - E > 0.05 ? z + Math.log2((cp.altitude - E) / (tH - E)) : m.getMaxZoom()); } }, [cam.lat, cam.lon, camTarget]);
    await q.evaluate(() => new Promise(r => { const m = window.SIM.map; setTimeout(() => { m.once('idle', r); m.triggerRepaint(); setTimeout(r, 12000); }, 1500); }));
    await q.waitForTimeout(2000);
    const tag = `${NEAR ? `near-dem+${DEM_OFF}-` : ''}${realSat ? 'sat-live' : 'grey'}-bias${bias || 'module'}`;
    await q.screenshot({ path: path.join(OUT, `stream-7-ridge-${tag}.png`) });
    // Classify (full wire on the map), then draw ONE class at a time: with the whole mesh drawn, a node behind the crest
    // projects onto pixels the front slope's own wire already lights, so a per-pixel check cannot tell them apart.
    const rs = await q.evaluate((NEAR) => {
      const m = window.SIM.map, T = m.transform, M = T.customLayerMatrix(), E = T.elevation || 0, cp = T.getCameraPosition(), PF = window.SIM.PF || window.__pf.PF, LS = window.__lidarStream;
      const W = m.getCanvas().clientWidth, H = m.getCanvas().clientHeight, cb = PF.toBng(cp.lngLat.lat, cp.lngLat.lng), camH = cp.altitude;
      const proj = (x, y, z) => { const w = M[3] * x + M[7] * y + M[11] * z + M[15]; return w <= 0 ? null : [(M[0] * x + M[4] * y + M[8] * z + M[12]) / w, (M[1] * x + M[5] * y + M[9] * z + M[13]) / w]; };
      const st = { E: +E.toFixed(1), camAlt: +camH.toFixed(1), camOverDtm: +(camH - LS.heightAt(cb.e, cb.n).h).toFixed(2), hidden: 0, visible: 0, ambiguous: 0, subPixel: 0, minHidden: 1e9 }, cls = { hidden: [], visible: [], ambiguous: [] }, segs = { hidden: [], visible: [], ambiguous: [] };
      const ground = [...LS.tiles.values()].flatMap(t => t.blks || []).filter(b => b.kind === 'ground');
      ground.forEach((bk, bi) => { const o = maplibregl.MercatorCoordinate.fromLngLat([bk.anchor.lon, bk.anchor.lat], bk.gz + (bk.E || 0) - E);
        for (let v = 0; v < bk.buf.length / 3; v += NEAR ? 2 : 13) { const i = 3 * v, j = 3 * (v ^ 1), x = bk.buf[i] + o.x, y = bk.buf[i + 1] + o.y, z = bk.buf[i + 2] + o.z;
          const P = proj(x, y, z); if (!P || Math.abs(P[0]) > 0.98 || Math.abs(P[1]) > 0.98) continue;
          const ll = new maplibregl.MercatorCoordinate(x, y, 0).toLngLat(), nb = PF.toBng(ll.lat, ll.lng), nh = LS.heightAt(nb.e, nb.n).h; if (nh == null) continue;
          const d = Math.hypot(nb.e - cb.e, nb.n - cb.n); if (NEAR ? d < 20 || d > 300 : d < 1000) continue;
          const Q = proj(bk.buf[j] + o.x, bk.buf[j + 1] + o.y, bk.buf[j + 2] + o.z); if (!Q || Math.hypot((P[0] - Q[0]) * W / 2, (P[1] - Q[1]) * H / 2) < 1) { st.subPixel++; continue; }
          let up = -1e9, upFar = -1e9; for (let s = 1; s < 200; s++) { const f = s / 200, h = LS.heightAt(cb.e + (nb.e - cb.e) * f, cb.n + (nb.n - cb.n) * f).h; if (h == null) continue; const x2 = h - (camH + (nh - camH) * f); up = Math.max(up, x2); if (NEAR ? f >= 0.1 && f <= 0.9 : (1 - f) * d > 50) upFar = Math.max(upFar, x2); }
          const k = up > 3 ? 'hidden' : upFar <= -3 ? 'visible' : null; if (!k) { st.ambiguous++; cls.ambiguous.push([(P[0] + 1) / 2, (1 - P[1]) / 2]); segs.ambiguous.push([bi, Math.min(v, v ^ 1)]); continue; }
          st[k]++; if (k === 'hidden') st.minHidden = Math.min(st.minHidden, Math.round(d));
          cls[k].push([(P[0] + 1) / 2, (1 - P[1]) / 2]); segs[k].push([bi, Math.min(v, v ^ 1)]); } });
      const keep = ground.map(b => b.buf);
      window.__ridgeShow = k => { const impl = m.style._layers['lidar-stream-sat'].implementation; impl.vbo = new WeakMap();
        ground.forEach((b, bi) => { if (!k) { b.buf = keep[bi]; return; } const s = segs[k].filter(x => x[0] === bi), f = new Float32Array(s.length * 6);
          s.forEach(([, v], n) => f.set(keep[bi].subarray(3 * v, 3 * v + 6), 6 * n)); b.buf = f; }); m.triggerRepaint(); };
      window.__ridgeCls = cls; return st; }, NEAR);
    const litRate = async (k) => {
      await q.evaluate(k => window.__ridgeShow(k), k); await q.waitForTimeout(1200);
      const A = await q.screenshot({ path: path.join(OUT, `stream-7-ridge-${tag}-only-${k}.png`) });
      await q.evaluate(() => { const m = window.SIM.map; m.setLayoutProperty('lidar-stream-sat', 'visibility', 'none'); m.triggerRepaint(); }); await q.waitForTimeout(900);
      const B = await q.screenshot();
      await q.evaluate(() => { const m = window.SIM.map; m.setLayoutProperty('lidar-stream-sat', 'visibility', 'visible'); m.triggerRepaint(); });
      return q.evaluate(async ([a, bb, k]) => {
        const ld = s => new Promise(r => { const i = new Image(); i.onload = () => r(i); i.src = 'data:image/png;base64,' + s; });
        const [ia, ib] = await Promise.all([ld(a), ld(bb)]), W = ia.width, H = ia.height, cv = document.createElement('canvas'); cv.width = W; cv.height = H; const g = cv.getContext('2d');
        g.drawImage(ia, 0, 0); const da = g.getImageData(0, 0, W, H).data; g.drawImage(ib, 0, 0); const db = g.getImageData(0, 0, W, H).data;
        const lit = (px, py) => { for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { const x = px + dx, y = py + dy; if (x < 0 || y < 0 || x >= W || y >= H) continue; const i = 4 * (y * W + x); if (Math.abs(da[i] - db[i]) + Math.abs(da[i + 1] - db[i + 1]) + Math.abs(da[i + 2] - db[i + 2]) > 24) return true; } return false; };
        return window.__ridgeCls[k].filter(([u, v]) => lit(Math.round(u * W), Math.round(v * H))).length; }, [A.toString('base64'), B.toString('base64'), k]);
    };
    rs.hiddenDrawn = await litRate('hidden'); rs.visibleDrawn = await litRate('visible'); if (NEAR) rs.ambiguousDrawn = await litRate('ambiguous');
    await q.evaluate(() => window.__ridgeShow(null));
    const hr = rs.hidden ? rs.hiddenDrawn / rs.hidden : 1, vr = rs.visible ? rs.visibleDrawn / rs.visible : 0;
    console.log('RIDGE', tag, gpu.slice(0, 70), JSON.stringify(rs));
    if (NEAR) { check(`near wire, DEM ${DEM_OFF} m over DTM: visible nodes 20-300 m drawn >= 95 % (bias ${bias || 'module'})`, rs.visible >= 50 && vr >= 0.95, `${rs.visibleDrawn}/${rs.visible} = ${(100 * vr).toFixed(1)} %; hidden drawn ${rs.hiddenDrawn}/${rs.hidden}; REPORTED, not asserted: nodes that do not clear 3 m (the foreground) drawn ${rs.ambiguousDrawn}/${rs.ambiguous}; camera ${rs.camOver  … [line shortened here: 431 characters; full line on GitHub]
      check('near page: no page errors', rErr.length === 0, rErr.join(' | ') || 'none'); await q.close(); continue; }
    check(`ridge: hidden nodes >= 1 km drawn <= 1 % (${realSat ? 'live satellite' : 'grey fixture imagery'})`, rs.hidden >= 200 && hr <= 0.01, `${rs.hiddenDrawn}/${rs.hidden} = ${(100 * hr).toFixed(2)} %; nearest hidden ${rs.minHidden} m`);
    check(`ridge: visible nodes >= 1 km (>= 1 px) drawn >= 80 % (${realSat ? 'live satellite' : 'grey fixture imagery'})`, rs.visible >= 50 && vr >= 0.8, `${rs.visibleDrawn}/${rs.visible} = ${(100 * vr).toFixed(1)} %; sub-pixel skipped ${rs.subPixel}, ambiguous ${rs.ambiguous}; camera ${rs.camAlt} m, E ${rs.E} m`);
    check('ridge page: no page errors', rErr.length === 0, rErr.join(' | ') || 'none');
    await q.close();
  }
  check('no page errors', errs.length === 0, errs.join(' | ') || 'none');
  await b.close(); server.close();
  for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'}  ${r.name}  -- ${r.evidence}`);
  const failed = results.filter(r => !r.ok).length; console.log(`\n${results.length - failed} passed, ${failed} failed`);
  process.exit(failed ? 1 : 0);
})().catch(e => { console.error(e); process.exit(2); });

Galaxies Wafers — Atlas Page

A map page that maps grid 400kV, grid 275kV, grid 220kV and grid 132kV, and uses data from the GridAtlas repository. Published at https://ventusltd.github.io/galaxies-wafers/atlas/.

rendergalaxies-wafers / atlas/index.html · lines 1–169 of 169 · Entry point · pattern setState (shared by 3 files)

What it does
It maps grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 9 functions or classes, including url, $, esc, setState, hydrate. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV, 275kV, 220kV, 132kV, 66kV. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: data source: gridatlas data; GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_substations.geojson; GeoJSON file power_plants.geojson. Out: web page; interactive map. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 66kV.
Downstream impact
Used directly by 1 file: Galaxies Wafers — Iterations Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/). Reached from 18 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Iterations — 24 Electrification Model Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/24-electrification-model/); Iterations — 25 One Feeder Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/25-one-feeder/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/atlas/.
What it achieves
It sets state (`setState`), renders panel (`renderPanel`) and writes URL (`writeURL`). The Ground — Grid Atlas's own layers, lifted whole. Its code works with 100 kW, 400 kV and 132 kV. It responds to change and click events.
Why it matters
Loaded by the Iterations page at https://ventusltd.github.io/galaxies-wafers/iterations/.
Application
galaxies-wafers · atlas · page
Uses
https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js
Used by
linked from Galaxies Wafers — Iterations Page (link)
Produces
url, $, esc, setState, hydrate, toggle, renderPanel, writeURL, readURL
Defines here
url, $, esc, setState, hydrate, toggle, renderPanel, writeURL, readURL
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 atlas/index.html:1-169 · blob 620e573c1e5d4db3c4a5e3dfa4aa0277d81b7b72 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>The Ground — Grid Atlas's own layers, lifted whole</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='6.5' fill='none' stroke='%230054ff' stroke-width='2'/%3E%3Ccircle cx='8' cy='8' r='2' fill='%23fff'/%3E%3C/svg%3E">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css">
<style>
  :root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--beam:#5ec8f2;
        --top:env(safe-area-inset-top,0px);--bot:env(safe-area-inset-bottom,0px)}
  *{box-sizing:border-box} html,body{height:100%}
  body{margin:0;background:var(--ground);color:var(--ink);font:12px/1.4 ui-monospace,Menlo,Consolas,monospace;overflow:hidden}
  #map{position:fixed;inset:0}
  #bar{position:fixed;left:0;right:0;top:0;z-index:3;display:flex;gap:.7rem;align-items:baseline;flex-wrap:wrap;
       padding:calc(var(--top) + .5rem) .75rem .5rem;background:linear-gradient(#0b0d12ee,#0b0d1200);pointer-events:none}
  #wordmark{letter-spacing:.14em;font-size:11px} .dim{color:var(--dim)}
  #layers{position:fixed;z-index:5;right:.5rem;top:calc(var(--top) + 2.4rem);max-width:min(22rem,calc(100% - 1rem))}
  #layersToggle{float:right;background:#11151f;color:var(--beam);border:1px solid var(--beam);border-radius:6px;
       padding:.35rem .7rem;font:inherit;letter-spacing:.1em;cursor:pointer}
  #layersBody{clear:both;margin-top:.4rem;max-height:62vh;overflow:auto;background:#0e121bf4;border:1px solid var(--edge);
       border-radius:8px;padding:.5rem .6rem}
  #layersBody[hidden]{display:none!important}
  .lgroup{color:var(--dim);font-size:10.5px;letter-spacing:.08em;margin:.55rem 0 .15rem;text-transform:uppercase}
  .lrow{display:flex;gap:.45rem;align-items:center;margin:.15rem 0}
  .ltag{font-size:10.5px}.ltag.WAIT{color:var(--dim)}.ltag.LOAD{color:#ffd54a}.ltag.OK{color:#7fd6a2}.ltag.EMPTY{color:#b39ddb}.ltag.FAIL{color:#ff8a80}
  #foot{position:fixed;z-index:2;left:0;right:0;bottom:0;padding:.3rem .75rem calc(var(--bot) + .3rem);font-size:10px;
        background:linear-gradient(#0b0d1200,#0b0d12ee);pointer-events:none;display:flex;flex-direction:column;gap:.1rem}
  .maplibregl-ctrl-attrib{font:10px ui-monospace,monospace;background:#0b0d12cc!important;color:var(--dim)}
  .maplibregl-ctrl-attrib a{color:var(--beam)}
</style>
</head>
<body>
<div id="map"></div>
<header id="bar"><span id="wordmark">THE GROUND</span><span id="count" class="dim">Grid Atlas's own layer engine, lifted whole; nothing redrawn by hand</span></header>
<section id="layers"><button id="layersToggle" type="button">LAYERS</button><div id="layersBody" hidden></div></section>
<footer id="foot">
  <span class="dim">engine and layers: Ventus Core, the Grid Atlas engine (globalgrid2050/repd_grid_atlasv8/ventus-corev8engine.js and the v9 release 202608300453), lifted as it stands: colours, widths, filters, one empty source per layer, hydrate on tick, one writer of state · data fetched from that release · basemap CARTO dark matter · © OpenStreetMap contributors where the data is theirs</span>
  <span class="dim">physics drawing via computers, not engineering: anything above 100 kW needs a chartered electrical engineer, manufacturer supervision, the applicable standards and finite element analysis where required; this is the substrate, not that study</span>
</footer>
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
<script>
/* THE GROUND. Grid Atlas draws the UK's published network with one engine: a
   MapLibre map over CARTO dark matter, and an array of layer configurations,
   each a colour, a width or a radius expression, a data URL and a preload flag.
   This page lifts that array as it stands in the v9 release and drives the
   same engine with it. Nothing is redrawn by hand: the 400 kV line is #0054ff
   at 2.5 px because that is what the Atlas says it is. Layers hydrate on tick,
   in the Atlas's own state vocabulary. */
const RELEASE = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/';
const ORIGIN  = 'https://globalgrid2050.com/';   /* the v8 origin: root-relative layer files live beside repd_grid_atlasv8 */
const url = u => u.startsWith('/') ? ORIGIN + u.slice(1) : RELEASE + u;

/* Lifted from gridatlas/atlas/releases/202608300453-atlas-v9/index.html, the
   `ukConfig` groups, values verbatim. Groups whose data the Atlas serves from
   the release or its origin are included; groups that need the Atlas's own
   DuckDB/Parquet plane (REPD, heavy industry) are not, because that plane is a
   different engine and lifting the config without it would draw nothing. */
const GROUPS = [
 { group: "Topology (GeoJSON)", layers: [
  { id: "400",  label: "400kV", color: "#0054ff", type: "line", width: 2.5, url: "data/grid_400kv.geojson" },
  { id: "275",  label: "275kV", color: "#ff0000", type: "line", width: 2.0, url: "data/grid_275kv.geojson" },
  { id: "220",  label: "220kV", color: "#ff9900", type: "line", width: 1.8, url: "data/grid_220kv.geojson" },
  { id: "132",  label: "132kV", color: "#00cc00", type: "line", width: 1.5, url: "data/grid_132kv.geojson" },
  { id: "66",   label: "66kV",  color: "#b200ff", type: "line", width: 1.2, url: "data/grid_66kv.geojson" },
  { id: "subs", label: "Subs",  color: "#ffffff", type: "point", radius: ['interpolate', ['linear'], ['zoom'], 5, 3, 10, 5, 14, 10, 18, 22], url: "data/grid_substations.geojson" } ] },
 { group: "Assets (GeoJSON)", layers: [
  { id: "nuc",  label: "Nuclear",   color: "#39ff14", type: "point", radius: 4.5, url: "data/power_plants.geojson", filter: ['==', ['get', 'source'], 'nuclear'] },
  { id: "gas",  label: "Gas",       color: "#ff4500", type: "point", radius: 4.5, url: "data/power_plants.geojson", filter: ['!=', ['get', 'source'], 'nuclear'] },
  { id: "ind",  label: "Industry",  color: "#ff6600", type: "point", radius: 4.5, url: "data/industrial_offtakers.geojson" },
  { id: "dc",   label: "Data Ctrs", color: "#00ffff", type: "point", radius: 4.5, url: "data/datacentres.geojson" },
  { id: "air",  label: "Airports",  color: "#ff00ff", type: "point", radius: 4.5, url: "data/airports.geojson" },
  { id: "rail", label: "Railways",  color: "#ffd700", type: "point", radius: 4.5, url: "data/railways.geojson" } ] },
 { group: "Transit (GeoJSON)", layers: [
  { id: "elizabeth", label: "Elizabeth Line", color: "#60399E", type: "point", radius: 5, url: "data/elizabeth_line.geojson" },
  { id: "lu",    label: "London Underground", color: "#e32017", type: "point", radius: 5, url: "data/london_underground.geojson" },
  { id: "mainline_rail", label: "UK Mainline Railways", color: "#ff8800", type: "line", width: 1.5, url: "/uk_mainline_railways.geojson" },
  { id: "hs2",   label: "HS2", color: "#2c6fad", type: "point", radius: 4, url: "data/hs2.geojson" },
  { id: "eurostar_route", label: "Eurostar (HS1) UK & Europe", color: "#001489", type: "line", width: 2.5, url: "data/eurostar.geojson", filter: ['==', ['get', 'type'], 'route'] },
  { id: "eurostar_station", label: "Eurostar Stations UK & Europe", color: "#ffd700", type: "point", radius: 5.5, url: "data/eurostar.geojson", filter: ['==', ['get', 'type'], 'eurostar_station'] } ] },
 { group: "Highway Infrastructure", layers: [
  { id: "motorways", label: "Motorways", color: "#0054ff", type: "line", width: 2.5, url: "/uk_motorways.geojson" },
  { id: "trunk_roads", label: "Major A-Roads (Trunk)", color: "#00cc00", type: "line", width: 1.8, url: "/uk_trunk_roads.geojson" },
  { id: "primary_roads", label: "A-Roads (Primary)", color: "#ff4400", type: "line", width: 1.2, url: "/uk_primary_roads.geojson" },
  { id: "motorway_services", label: "Motorway Services", color: "#ff00ff", type: "point", radius: 5.5, url: "data/motorway_services.geojson" } ] },
 { group: "Global Data Backbone", layers: [
  { id: "subsea_data_cables", label: "Subsea Data Cables (Fibre)", color: "#00e5ff", type: "line", width: 1.5, url: "data/subsea_data_cables.geojson" } ] },
 { group: "EV (GeoJSON)", layers: [
  { id: "ev", label: "EV Rapid (100kW+)", color: "#00ff88", type: "point", radius: 5, url: "data/ev_chargers.geojson" } ] }
];

const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const state = new Map();
for (const g of GROUPS) for (const l of g.layers) state.set(l.id, { status: 'WAIT', on: false, n: 0 });

const map = new maplibregl.Map({
  container: 'map',
  style: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
  center: [-2.5, 54.3], zoom: 5.2, attributionControl: true
});
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), 'bottom-right');

/* The Atlas's own hydration: an empty source per layer, created at load with
   visibility none; a fetch on tick; setData; the state written by one function. */
map.on('load', () => {
  for (const g of GROUPS) for (const l of g.layers) {
    map.addSource('src-' + l.id, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
    const base = { id: 'l-' + l.id, source: 'src-' + l.id, layout: { visibility: 'none' } };
    if (l.filter) base.filter = l.filter;
    if (l.type === 'line') map.addLayer({ ...base, type: 'line', paint: { 'line-color': l.color, 'line-width': l.width, 'line-opacity': 0.9 } });
    else map.addLayer({ ...base, type: 'circle', paint: { 'circle-color': l.color, 'circle-radius': l.radius, 'circle-opacity': 0.85, 'circle-stroke-color': '#0b0d12', 'circle-stroke-width': 0.6 } });
  }
  renderPanel();
  readURL();
});

function setState(id, status, extra) { Object.assign(state.get(id), { status }, extra || {}); renderPanel(); }

async function hydrate(l) {
  const s = state.get(l.id);
  if (s.status === 'OK' || s.status === 'LOAD') return;
  setState(l.id, 'LOAD');
  try {
    const r = await fetch(url(l.url), { cache: 'default' });
    if (!r.ok) throw new Error('HTTP ' + r.status);
    const doc = await r.json();
    const feats = doc.features || [];
    map.getSource('src-' + l.id).setData({ type: 'FeatureCollection', features: feats });
    setState(l.id, feats.length ? 'OK' : 'EMPTY', { n: feats.length, why: feats.length ? '' : 'the file holds no features' });
  } catch (e) { setState(l.id, 'FAIL', { why: e.message }); }
}

function toggle(l, on) {
  state.get(l.id).on = on;
  map.setLayoutProperty('l-' + l.id, 'visibility', on ? 'visible' : 'none');
  if (on) hydrate(l);
  writeURL(); renderPanel();
}

function renderPanel() {
  $('layersBody').innerHTML = GROUPS.map(g => `<div class="lgroup">${esc(g.group)}</div>` + g.layers.map(l => {
    const s = state.get(l.id);
    const tag = s.status === 'OK' ? `OK · ${s.n.toLocaleString('en-GB')}` : s.status + (s.why ? ' · ' + esc(s.why) : '');
    return `<div class="lrow"><input type="checkbox" id="L-${esc(l.id)}" ${s.on ? 'checked' : ''}>
      <label for="L-${esc(l.id)}" style="color:${esc(l.color)}">${esc(l.label)} <span class="ltag ${s.status}">[${tag}]</span></label></div>`;
  }).join('')).join('');
  for (const g of GROUPS) for (const l of g.layers) $('L-' + l.id).addEventListener('change', e => toggle(l, e.target.checked));
  const on = [...state.values()].filter(s => s.on).length, ok = [...state.values()].filter(s => s.status === 'OK').length;
  $('count').textContent = `${GROUPS.reduce((a, g) => a + g.layers.length, 0)} layers lifted from Grid Atlas v9 · ${on} on · ${ok} drawn`;
}
$('layersToggle').addEventListener('click', () => { $('layersBody').hidden = !$('layersBody').hidden; });

/* URL: only layer ids the config names travel; unknown ids are dropped. */
function writeURL() {
  const on = []; for (const g of GROUPS) for (const l of g.layers) if (state.get(l.id).on) on.push(l.id);
  const u = new URL(location.href);
  on.length ? u.searchParams.set('layers', on.join(',')) : u.searchParams.delete('layers');
  history.replaceState(null, '', u.pathname + u.search.replace(/%2C/gi, ',') + u.hash);
}
function readURL() {
  const raw = new URL(location.href).searchParams.get('layers') || '';
  const ids = new Set(raw.split(',').map(s => s.trim()).filter(Boolean));
  for (const g of GROUPS) for (const l of g.layers) if (ids.has(l.id)) { $('L-' + l.id).checked = true; toggle(l, true); }
}
</script>
</body>
</html>