GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / energy-transition-simulator/202609280103/mod

Plan View and 2 more files

A JavaScript file in GlobalGrid2050 that maps plan wire, substations and LiDAR terrain. It applies plan (`applyPlan`) and is built from the wait step (`wait`) and the skip step (`skip`).

674 lines of JavaScript from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 852 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. Scanner Rows render · globalgrid2050 / energy-transition-simulator/202609280103/mod/scanner-rows.js lines 1–155
  2. Plan View render · globalgrid2050 / energy-transition-simulator/202609280202/mod/plan-view.js lines 1–291
  3. Procedural render · globalgrid2050 / energy-transition-simulator/202609280202/mod/procedural.js lines 1–228

Scanner Rows

A JavaScript module in GlobalGrid2050 that fetches LiDAR terrain. It checks farm (`checkFarm`), gets JSON (`getJson`) and loads farms (`loadFarms`).

renderglobalgrid2050 / energy-transition-simulator/202609280103/mod/scanner-rows.js · lines 1–155 of 155 · version 2026-09-28 01:03 · Not reached from any entry point (candidate for review) · pattern distToBboxM (shared by 2 files)

What it does
It fetches LiDAR terrain. Defines 17 functions or classes, including bbox, local, distToBboxM, nearestRowM, checkFarm. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: LiDAR terrain.
Inputs & outputs
In: JSON file scanner-rows.farms.json.
What it achieves
The GPU lab's baked panel rows (lon/lat per public register farm) drawn as tilted tables where they are, labelled "estimated from imagery by the Wire Frame Scanner".
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280103/mod · JavaScript module
Uses
none found
Used by
none found
Produces
bbox, local, distToBboxM, nearestRowM, checkFarm, tableLines, seg, surveyGate, rowSource, rowsAllowed, stripWidthM, getJson
Defines here
bbox, local, distToBboxM, nearestRowM, checkFarm, tableLines, seg, surveyGate, rowSource, rowsAllowed, stripWidthM, getJson, loadFarms, check, drawFarm, run, init
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280103/mod/scanner-rows.js:1-155 · blob 84a2d9f83f932d79a68fd2609374cc146130d8da · 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: duplicate_candidate
// scanner-rows: the GPU lab's baked panel rows (lon/lat per public register farm) drawn as tilted tables where they
// are, labelled "estimated from imagery by the Wire Frame Scanner". Each farm is checked: the rows' bounding box must
// overlap the register point (within PAD_M), else the farm is drawn in no place and the check says FAIL.
//
// Provenance of every value used here:
//   row lon/lat ............ estimated  (GPU lab, from satellite imagery; NumPy witness in the row file)
//   register point ......... derived    (public register coordinates, in scanner-rows.farms.json with its source)
//   strip width in plan .... derived    (sample step px x metres per pixel, both from the row file / farms file)
//   tilt, low edge height .. assumed    (TILT_DEG, LOW_M below; not read from the imagery)
//   build year, survey years, imagery date .. derived (farms file, each with its source; rule R5-9 gate)
//   facing side ............ assumed    (equator side of the row; east when rows run within 30 deg of north-south)
// Plain script: pure helpers export to Node (tests/scanner-rows.test.cjs); in the browser it attaches to window.SIM.
(function () {
  'use strict';
  const LABEL = 'estimated from imagery by the Wire Frame Scanner';
  const TILT_DEG = 25, LOW_M = 0.8, PAD_M = 50, CELL_M = 250, GROUPS_MS = 120;
  const R = 6371008.8, D2R = Math.PI / 180;

  // ---- pure helpers (no DOM, no PF) ----
  function bbox(rows) {
    let w = Infinity, s = Infinity, e = -Infinity, n = -Infinity;
    for (const seg of rows) for (const [lo, la] of seg) { if (lo < w) w = lo; if (lo > e) e = lo; if (la < s) s = la; if (la > n) n = la; }
    return { w, s, e, n };
  }
  // Small-distance local metres around (lat0, lon0): equirectangular, good to well under 0.1 % over a few km.
  const local = (lat0, lon0) => (lat, lon) => [(lon - lon0) * D2R * R * Math.cos(lat0 * D2R), (lat - lat0) * D2R * R];
  function distToBboxM(b, lat, lon) {
    const L = local(lat, lon), cl = [Math.min(Math.max(lon, b.w), b.e), Math.min(Math.max(lat, b.s), b.n)];
    const [x, y] = L(cl[1], cl[0]); return Math.hypot(x, y);
  }
  function nearestRowM(rows, lat, lon) {
    const L = local(lat, lon); let best = Infinity;
    for (const [[lo0, la0], [lo1, la1]] of rows) {
      const [ax, ay] = L(la0, lo0), [bx, by] = L(la1, lo1), dx = bx - ax, dy = by - ay, d2 = dx * dx + dy * dy;
      const t = d2 > 0 ? Math.min(1, Math.max(0, -(ax * dx + ay * dy) / d2)) : 0;
      const d = Math.hypot(ax + t * dx, ay + t * dy); if (d < best) best = d;
    }
    return best;
  }
  // The check: rows' bounding box overlaps the register point (inside, or within padM of its edge).
  function checkFarm(farm, doc, padM = PAD_M) {
    const b = bbox(doc.rows), p = farm.point, d = distToBboxM(b, p.lat, p.lon);
    const L = local(p.lat, p.lon), [x0, y0] = L(b.s, b.w), [x1, y1] = L(b.n, b.e);
    return { register: farm.register, ok: d <= padM, inside: d === 0, distToBboxM: +d.toFixed(2), padM,
      nearestRowM: +nearestRowM(doc.rows, p.lat, p.lon).toFixed(2), runs: doc.rows.length,
      bbox: b, bboxM: [+(x1 - x0).toFixed(1), +(y1 - y0).toFixed(1)] };
  }
  // One run (plan metres a -> b) -> a tilted strip: low edge, high edge, two slanted ends, four legs.
  // widthM is the strip width in plan; facing side as documented above.
  function tableLines(ax, ay, bx, by, widthM, tiltDeg = TILT_DEG, lowM = LOW_M) {
    const dx = bx - ax, dy = by - ay, len = Math.hypot(dx, dy); if (!(len > 0)) return [];
    let nx = dy / len, ny = -dx / len;                          // unit across-row normal
    const ns = Math.abs(dx) / len < 0.5;                        // rows within 30 deg of north-south
    if (ns ? nx < 0 : ny > 0) { nx = -nx; ny = -ny; }           // face east (N-S rows) or south (E-W rows)
    const h = widthM / 2, hi = lowM + widthM * Math.tan(tiltDeg * D2R);
    const lo0 = [ax + nx * h, ay + ny * h, lowM], lo1 = [bx + nx * h, by + ny * h, lowM];
    const hi0 = [ax - nx * h, ay - ny * h, hi], hi1 = [bx - nx * h, by - ny * h, hi];
    const seg = (p, q) => [p[0], p[1], p[2], q[0], q[1], q[2]], gnd = p => [p[0], p[1], 0];
    return [seg(lo0, lo1), seg(hi0, hi1), seg(lo0, hi0), seg(lo1, hi1), seg(gnd(lo0), lo0), seg(gnd(lo1), lo1), seg(gnd(hi0), hi0), seg(gnd(hi1), hi1)];
  }
  // Rule R5-9 (survey year before scanning). The LiDAR under a farm is "pre-construction ground" when the build year
  // is the same as or later than ANY DSM or DTM survey year under it, or when any of those years is unknown. Rows are
  // scanned from LiDAR only when every DSM and DTM survey year is later than the build year. Otherwise rows may come
  // only from imagery, labelled estimated. Returns { lidarRows, ground, reason }.
  function surveyGate(buildYear, dsmYears, dtmYears) {
    const yrs = [...(dsmYears || []), ...(dtmYears || [])], ok = y => Number.isInteger(y) && y > 1900;
    if (!ok(buildYear)) return { lidarRows: false, ground: 'pre-construction', reason: 'build year unknown' };
    if (!(dsmYears || []).length || !(dtmYears || []).length || !yrs.every(ok))
      return { lidarRows: false, ground: 'pre-construction', reason: 'a DSM or DTM survey year is unknown' };
    const early = yrs.filter(y => y <= buildYear);
    if (early.length) return { lidarRows: false, ground: 'pre-construction',
      reason: `LiDAR survey ${Math.min(...early)} is not later than the build year ${buildYear}` };
    return { lidarRows: true, ground: 'post-construction', reason: `every LiDAR survey (${yrs.join(', ')}) is later than the build year ${buildYear}` };
  }
  // Where the row file came from: 'lidar' if its source or method names LiDAR/DSM, else 'imagery'.
  const rowSource = doc => /lidar|dsm|dtm/i.test(`${doc.source || ''} ${doc.method || ''}`) ? 'lidar' : 'imagery';
  // Decide whether a farm's row file may be drawn: imagery rows always (labelled estimated); LiDAR rows only past the gate.
  function rowsAllowed(farm, doc) {
    const ly = farm.lidar_survey_years || {}, g = surveyGate(farm.build_year && farm.build_year.value, ly.dsm, ly.dtm);
    const src = rowSource(doc);
    return Object.assign({ source: src, allowed: src === 'imagery' || g.lidarRows }, g);
  }
  const stripWidthM = (farm, doc) => (farm.sample_step_px ? farm.sample_step_px.value : 3) * doc.metres_per_pixel;
  const api = { LABEL, TILT_DEG, LOW_M, PAD_M, surveyGate, rowSource, rowsAllowed, bbox, distToBboxM, nearestRowM, checkFarm, tableLines, stripWidthM };
  if (typeof module !== 'undefined' && module.exports) { module.exports = api; return; }

  // ---- browser ----
  const BASE = (document.currentScript && document.currentScript.src.replace(/[^/]*$/, '')) || 'mod/';
  const state = { farms: null, docs: {}, checks: [], busy: false };
  const getJson = async u => { const r = await fetch(BASE + u); if (!r.ok) throw new Error(u + ' ' + r.status); return r.json(); };
  async function loadFarms() { if (!state.farms) state.farms = (await getJson('scanner-rows.farms.json')).farms; return state.farms; }
  async function check() {
    const farms = await loadFarms(); state.checks = [];
    for (const f of farms) { const doc = state.docs[f.rows] || (state.docs[f.rows] = await getJson(f.rows)); state.checks.push(checkFarm(f, doc)); }
    return state.checks;
  }
  // Draw one farm: rows binned into CELL_M cells, each cell a block anchored at its own place key (so the terrain
  // under each block is read near its own rows), plus a 30 m mast and a PAD_M ring at the register point.
  async function drawFarm(S, PF, farm, fly) {
    const doc = state.docs[farm.rows] || (state.docs[farm.rows] = await getJson(farm.rows));
    const res = checkFarm(farm, doc); res.gate = rowsAllowed(farm, doc); res.imagery = farm.imagery || null;
    if (!res.gate.allowed) { res.ok = false; return res; }
    if (!res.ok) return res;
    const p = farm.point, a0 = PF.placeKey(p.lat, p.lon), W = stripWidthM(farm, doc), cells = new Map();
    for (const seg of doc.rows) {
      const [[lo0, la0], [lo1, la1]] = seg, q = PF.toLocal(a0, (la0 + la1) / 2, (lo0 + lo1) / 2, 0);
      const k = Math.floor(q.x / CELL_M) + ',' + Math.floor(q.y / CELL_M);
      (cells.get(k) || cells.set(k, []).get(k)).push(seg);
    }
    if (fly) S.map.easeTo({ center: [p.lon, p.lat], zoom: 15.4, pitch: 55, bearing: -20, duration: 1200 });
    let n = 0;
    for (const segs of cells.values()) {
      let sl = 0, so = 0; for (const [[lo0, la0], [lo1, la1]] of segs) { sl += la0 + la1; so += lo0 + lo1; }
      const an = PF.placeKey(sl / (2 * segs.length), so / (2 * segs.length)), L = [];
      for (const [[lo0, la0], [lo1, la1]] of segs) {
        const A = PF.toLocal(an, la0, lo0, 0), B = PF.toLocal(an, la1, lo1, 0);
        for (const l of tableLines(A.x, A.y, B.x, B.y, W)) L.push(l);
      }
      S.addBlock({ lon: an.lon, lat: an.lat, anchor: an, lines: L, buf: PF.wireBuffer(an, L), scannerRows: farm.register, sat: true });
      n += segs.length; await new Promise(r => setTimeout(r, GROUPS_MS));
    }
    const M = [[0, 0, 0, 0, 0, 30]];
    for (let i = 0; i < 48; i++) { const t0 = i / 48 * 2 * Math.PI, t1 = (i + 1) / 48 * 2 * Math.PI; M.push([PAD_M * Math.cos(t0), PAD_M * Math.sin(t0), 0.5, PAD_M * Math.cos(t1), PAD_M * Math.sin(t1), 0.5]); }
    const ap = PF.placeKey(p.lat, p.lon), o = PF.toLocal(ap, p.lat, p.lon, 0);
    const Mo = M.map(l => [l[0] + o.x, l[1] + o.y, l[2], l[3] + o.x, l[4] + o.y, l[5]]);
    S.addBlock({ lon: ap.lon, lat: ap.lat, anchor: ap, lines: Mo, buf: PF.wireBuffer(ap, Mo), scannerRows: farm.register, registerPoint: true });
    return Object.assign(res, { drawnRuns: n, cells: cells.size, stripWidthM: +W.toFixed(3) });
  }
  async function run(btn) {
    const S = window.SIM, PF = window.__pf && window.__pf.PF; if (!S || !PF || state.busy) return state.checks; state.busy = true;
    try {
      btn.textContent = 'Scanner rows: loading...'; S.removeWhere(b => b.scannerRows);
      const farms = await loadFarms(), out = [];
      for (let i = 0; i < farms.length; i++) out.push(await drawFarm(S, PF, farms[i], i === 0));
      state.checks = out;
      const good = out.filter(r => r.ok), f0 = good[0];
      S.info(`Panel rows ${LABEL} (not measured, not a survey). ${good.length}/${out.length} farms pass the on-farm check ` +
        `(rows' box overlaps the register point within ${PAD_M} m). ` + (f0 ? `${f0.register}: ${f0.drawnRuns} runs, box ${f0.bboxM[0]} x ${f0.bboxM[1]} m, ` +
        `nearest row ${f0.nearestRowM} m from the register point. Strip width ${f0.stripWidthM} m (derived); tilt ${TILT_DEG} deg and low edge ${LOW_M} m assumed. ` : '') +
        (f0 && f0.imagery ? `Imagery captured ${f0.imagery.capture_date}, provider accuracy ${f0.imagery.stated_accuracy_m} m. ` : '') +
        (f0 ? `Rule R5-9: ${f0.gate.reason}, so the LiDAR here is ${f0.gate.ground} ground` +
          (f0.gate.lidarRows ? '. ' : ' (for piles and earthworks, never scanned for rows). ') : '') +
        out.filter(r => r.gate && !r.gate.allowed).map(r => `${r.register}: LiDAR rows refused (${r.gate.reason}). `).join('') +
        'Mast and ring mark the register point.');
      btn.textContent = `Scanner rows (${good.length}/${out.length})`;
    } catch (e) { btn.textContent = 'Scanner rows: failed'; console.error(e); }
    state.busy = false; return state.checks;
  }
  function init() {
    if (!window.SIM) return setTimeout(init, 200);
    const b = window.SIM.addButton('Scanner rows', () => run(b));
    window.SIM.scannerRows = Object.assign({ run: () => run(b), check, state }, api);
  }
  init();
})();

Plan View

A JavaScript file in GlobalGrid2050 that maps plan wire, substations and LiDAR terrain. It applies plan (`applyPlan`) and is built from the wait step (`wait`) and the skip step (`skip`).

renderglobalgrid2050 / energy-transition-simulator/202609280202/mod/plan-view.js · lines 1–291 of 291 · version 2026-09-28 02:02 · Not reached from any entry point (candidate for review) · pattern applyPlan (shared by 2 files)

What it does
It maps plan wire, substations and LiDAR terrain. Defines 29 functions or classes, including wait, skip, isRow, kindOf, provOf. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: substations, LiDAR terrain.
Inputs & outputs
Out: SVG drawing.
What it achieves
Plan: the massive plan in 2D, the close-up in 3D. It responds to keydown and click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280202/mod · script
Uses
none found
Used by
none found
Produces
wait, skip, isRow, kindOf, provOf, labelOf, drawing, hull, sigOf, keep, applyPlan, add
Defines here
wait, skip, isRow, kindOf, provOf, labelOf, drawing, hull, sigOf, keep, applyPlan, add, clearPlan, kvText, relabel, take, place, scale, ease, after, on, off, to3d, toPlan, leave, toggle, mark, init, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280202/mod/plan-view.js:1-291 · blob 9c2de1c393cc399e711dd6262f360b4c2c41456d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// mod/plan-view.js - Plan: the massive plan in 2D, the close-up in 3D.
// View > Plan, the key P, or type "plan" (Enter) in any box. Plan puts the camera north-up and flat (pitch 0,
// bearing 0), dims the imagery to 35 % brightness, and redraws what is already on the map as a thin 2D line drawing: every
// wire block projected from its own buffer (the exact vertices the 3D wire draws, heights dropped), the mapped
// grid lines by voltage, substations as rings, and any AC trench and bund layers left exactly as their module drew
// them. Labels come only from objects already on the map, in their provenance style: solid = measured,
// dashed = documented, ghost = estimated (designs are ghost and say "imagined"). A scale bar and a north arrow sit
// top left; the grid-reference line (#where) is untouched.
// Zoom into the wireframe: in plan, zooming in past z17.5 eases the pitch to 60 over 0.6 s and the real 3D wire
// comes back (movement keeps the current mode's speed); zooming back out past z16.5 eases back to plan.
// Walk, Drone or Map (or keys 1 2 3) leave plan: plan off, then the mode's own pitch, zoom and speed; plan adds no ease.
// The 3D wire itself is never restyled: in plan it is hidden, in 3D it is shown as it was.
// Look carried over from the Kuiper drawing look (its published stage tokens: background #090c13, ink #d5dcea,
// dim #7d8799, cyan #2ee6e6, warm #e8b36a, row strokes #8ba6bb at 0.55 to 1.5 px). Values only; no code copied.
// Plain script; attaches to window.SIM. Test hook: SIM.plan = { on(), off(), toggle(), state() }.
(function () {
  'use strict';
  const K = { bg: 'rgba(9,12,19,.78)', ink: '#d5dcea', dim: '#7d8799', row: '#8ba6bb', obj: '#d5dcea', hot: '#e8b36a',
    kv: { '400': '#2ee6e6', '275': '#e8b36a', '132': '#9fd8a8' } };
  const IN = 17.5, OUT = 16.5, EASE = 600, DIM = 0.35, PITCH3D = 60;
  const PROV = ['measured', 'documented', 'estimated'];
  const st = { left: [], kinds: {}, on: false, in3d: false, easing: false, saved: {}, prev: null, eases: [], labels: 0, lines: 0, sig: '' };
  let SIM, map, hud, labelsEl, btn, labelList = [];

  function wait(n) { const S = window.SIM; if (S && S.map && (S.PF || window.__pf)) init(S); else if (n < 400) setTimeout(() => wait(n + 1), 50); }
  // ---- which blocks are what: read from the tags the other mods already set ----
  const skip = b => b.substationLabel !== undefined || b.pulse || b.ground || !b.buf || !b.anchor;
  const isRow = b => !b.registerPoint && !!(b.sat || b.rowsGeometry || b.scannerRows || b.gpuRows || b.registerPoint === undefined && b.plant === false);
  // What each projected block is, from its own module's tag (counted in state().kinds, so a check can say what plan drew).
  const kindOf = b => b.scannerRows ? (b.registerPoint ? 'register-point' : 'scanner-rows') : b.gpuRows ? 'gpu-rows' : b.rowsGeometry ? 'rows-geometry'
    : b.procedural ? 'procedural' : b.pylonsReal ? 'pylons' : b.substation !== undefined ? 'substation' : b.lidarStream ? 'lidar-stream'
    : b.trench || b.kind === 'trench' ? 'trench' : b.plant ? 'plant' : 'other';
  // Only the overlay's 3D wire and its look are hidden in plan. Other modules' own layers (procedural ghost, lidar-stream
  // tiles over imagery, trench-measure) stay exactly as their module draws them: at pitch 0 they are seen from above.
  const HIDE = new Set(['wire', 'wire-look-grid', 'lidar-stream-sat']);   // the streamed ground mesh would cover the 2D drawing (W-ui-plan, 01:55)
  function provOf(b) {
    const p = typeof b.prov === 'string' ? b.prov : '';
    if (b.registerPoint) return 'documented';
    if (/measur/i.test(p) || b.lidar || b.lidarStream) return 'measured';
    if (b.est || b.procedural || b.sat || b.gpuRows || b.scannerRows || b.designPlant || b.built || /estimat|assum|derived/i.test(p)) return 'estimated';
    return 'documented';
  }
  function labelOf(b) {
    if (b.designPlant) return 'design ' + b.designPlant + ' (imagined)';
    if (b.built) return 'block (imagined)';
    if (b.scannerRows && b.registerPoint) return b.scannerRows + ' register point';
    if (b.scannerRows) return 'rows, scanner (estimated)';
    if (b.procedural) return 'procedural ' + b.procedural + ' (estimated)';
    if (b.gpuRows) return 'rows, GPU (estimated)';
    if (b.rowsGeometry) return 'rows (estimated)';
    if (b.substation !== undefined) return '';            // substations are labelled from their mapped points
    if (b.bund) return 'bund ' + b.bund;
    if (b.trench || b.kind === 'trench') return 'trench';
    if (b.plant) return 'solar plant outline (mapped)';
    return '';
  }

  // ---- the 2D drawing: each block's own buffer, anchor-relative Mercator, heights dropped ----
  function drawing() {
    const PF = SIM.PF || window.__pf.PF, feats = [], marks = [], kinds = {};
    let n = 0;
    for (const b of SIM.blocks) {
      if (skip(b)) continue;
      const kd = kindOf(b); kinds[kd] = (kinds[kd] || 0) + 1;
      const o = PF.toMercator(b.anchor.lat, b.anchor.lon, 0), v = b.buf, segs = [];
      let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
      for (let k = 0; k + 5 < v.length; k += 6) {
        const ax = v[k], ay = v[k + 1], bx = v[k + 3], by = v[k + 4];
        if (Math.abs(ax - bx) < 1e-10 && Math.abs(ay - by) < 1e-10) continue;     // a vertical: a point in plan
        const A = [PF.lngFromMercatorX(o.x + ax), PF.latFromMercatorY(o.y + ay)], B = [PF.lngFromMercatorX(o.x + bx), PF.latFromMercatorY(o.y + by)];
        segs.push([A, B]); x0 = Math.min(x0, A[0], B[0]); x1 = Math.max(x1, A[0], B[0]); y0 = Math.min(y0, A[1], B[1]); y1 = Math.max(y1, A[1], B[1]);
      }
      if (!segs.length) continue;
      n += segs.length;
      const prov = provOf(b);
      if (isRow(b)) {
        // Rows as block outlines: the convex hull of the row ends (derived from the rows, nothing added) at plan scale;
        // the row lines themselves (pieces of 5 m or more; shorter ones are table ends and legs seen from above) from z15.5.
        const pts = []; for (const [A, B] of segs) pts.push(A, B);
        feats.push({ type: 'Feature', properties: { cls: 'row', prov, hull: 1 }, geometry: { type: 'LineString', coordinates: hull(pts) } });
        const k = Math.cos(b.anchor.lat * Math.PI / 180), long = segs.filter(([A, B]) => Math.hypot((B[0] - A[0]) * k, B[1] - A[1]) * 111320 >= 5);
        if (long.length) feats.push({ type: 'Feature', properties: { cls: 'row', prov, hull: 0 }, geometry: { type: 'MultiLineString', coordinates: long } });
      } else feats.push({ type: 'Feature', properties: { cls: 'obj', prov, hull: 0 }, geometry: { type: 'MultiLineString', coordinates: segs } });
      const t = labelOf(b); if (t) marks.push({ t, prov, at: [(x0 + x1) / 2, (y0 + y1) / 2] });
    }
    st.lines = n; st.kinds = kinds;
    return { fc: { type: 'FeatureCollection', features: feats }, marks };
  }
  function hull(P) {                                    // monotone chain, closed ring
    const p = P.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]), cr = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
    const lo = [], up = [];
    for (const q of p) { while (lo.length > 1 && cr(lo[lo.length - 2], lo[lo.length - 1], q) <= 0) lo.pop(); lo.push(q); }
    for (let i = p.length - 1; i >= 0; i--) { const q = p[i]; while (up.length > 1 && cr(up[up.length - 2], up[up.length - 1], q) <= 0) up.pop(); up.push(q); }
    const r = lo.slice(0, -1).concat(up.slice(0, -1)); r.push(r[0]); return r;
  }
  const sigOf = () => SIM.blocks.length + ':' + SIM.blocks.reduce((s, b) => s + (b.buf ? b.buf.length : 0), 0);

  // ---- plan look on / off (layers only; the 3D wire is hidden, never changed) ----
  function keep(id, what, val) { const k = id + '|' + what; if (!(k in st.saved)) st.saved[k] = val; }
  function applyPlan() {
    if (!map.getStyle()) return;
    // Custom layers (the 3D wire) are left out of getStyle().layers, so walk the live layer order instead.
    const ids = map.getLayersOrder ? map.getLayersOrder() : (map.style && map.style._order) || [];
    for (const L of ids.map(id => map.getLayer(id)).filter(Boolean)) {
      if (L.id.startsWith('plan-')) continue;
      // Dim by brightness, not opacity: a parent and child tile drawn together at 35 % alpha would add up to a light patch.
      if (L.type === 'raster') { keep(L.id, 'o', map.getPaintProperty(L.id, 'raster-brightness-max') ?? 1); map.setPaintProperty(L.id, 'raster-brightness-max', DIM); }
      else if (L.type === 'custom' && HIDE.has(L.id) || /^g(400|275|132)$/.test(L.id) || L.id === 'subs') {
        keep(L.id, 'v', map.getLayoutProperty(L.id, 'visibility') || 'visible'); map.setLayoutProperty(L.id, 'visibility', 'none');
      }
    }
    const d = drawing(); st.sig = sigOf(); st.marks = d.marks;
    if (map.getSource('plan-wire')) map.getSource('plan-wire').setData(d.fc); else map.addSource('plan-wire', { type: 'geojson', data: d.fc });
    const col = ['match', ['get', 'cls'], 'row', K.row, K.obj];
    const add = (id, spec) => { if (!map.getLayer(id)) map.addLayer(Object.assign({ id }, spec)); };
    add('plan-estimated', { type: 'line', source: 'plan-wire', filter: ['all', ['==', ['get', 'prov'], 'estimated'], ['any', ['==', ['get', 'cls'], 'obj'], ['==', ['get', 'hull'], 1], ['>=', ['zoom'], 15.5]]], paint: { 'line-color': col, 'line-width': 0.7, 'line-opacity': 0.5 } });
    add('plan-documented', { type: 'line', source: 'plan-wire', filter: ['all', ['==', ['get', 'prov'], 'documented'], ['any', ['==', ['get', 'cls'], 'obj'], ['==', ['get', 'hull'], 1], ['>=', ['zoom'], 15.5]]], paint: { 'line-color': col, 'line-width': 0.9, 'line-opacity': 0.9, 'line-dasharray': [4, 2] } });
    add('plan-measured', { type: 'line', source: 'plan-wire', filter: ['all', ['==', ['get', 'prov'], 'measured'], ['any', ['==', ['get', 'cls'], 'obj'], ['==', ['get', 'hull'], 1], ['>=', ['zoom'], 15.5]]], paint: { 'line-color': col, 'line-width': 1, 'line-opacity': 1 } });
    for (const kv of ['132', '275', '400']) {           // the mapped lines, thin, dashed = documented (GridAtlas)
      if (!map.getSource('g' + kv)) continue;
      const on = st.saved['g' + kv + '|v'] !== 'none';
      add('plan-g' + kv, { type: 'line', source: 'g' + kv, layout: { visibility: on ? 'visible' : 'none' }, paint: { 'line-color': K.kv[kv], 'line-width': kv === '400' ? 1.3 : 1, 'line-opacity': 0.9, 'line-dasharray': [6, 2] } });
    }
    if (map.getSource('subs')) add('plan-subs', { type: 'circle', source: 'subs', paint: { 'circle-radius': 3.5, 'circle-color': 'rgba(0,0,0,0)', 'circle-stroke-color': K.hot, 'circle-stroke-width': 1 } });
    hud.hidden = false; labelsEl.hidden = false; relabel(); scale();
  }
  function clearPlan() {
    for (const id of ['plan-measured', 'plan-documented', 'plan-estimated', 'plan-g400', 'plan-g275', 'plan-g132', 'plan-subs']) if (map.getLayer(id)) map.removeLayer(id);
    if (map.getSource('plan-wire')) map.removeSource('plan-wire');
    for (const k of Object.keys(st.saved)) {
      const [id, what] = k.split('|'); if (!map.getLayer(id)) continue;
      if (what === 'o') map.setPaintProperty(id, 'raster-brightness-max', st.saved[k]); else map.setLayoutProperty(id, 'visibility', st.saved[k]);
    }
    st.saved = {}; hud.hidden = true; labelsEl.hidden = true; labelsEl.textContent = ''; labelList = [];
    map.triggerRepaint();
  }

  // ---- labels: only from objects on the map; border = provenance ----
  const BORDER = { measured: '1px solid', documented: '1px dashed', estimated: '1px dotted' };
  function kvText(v) {
    const l = String(v || '').split(/[;,]/).map(s => Math.round(+s / 1000)).filter(x => x > 0).sort((a, b) => b - a);
    return l.length ? Array.from(new Set(l)).join('/') + ' kV' : '';
  }
  function relabel() {
    if (!st.on || st.in3d) return;
    const b = map.getBounds(), z = map.getZoom(), W = map.getCanvas().clientWidth, cell = 150, used = new Set(), out = [];
    const take = (t, at, prov, color) => {
      if (!b.contains(at)) return; const p = map.project(at), key = Math.floor(p.x / cell) + ',' + Math.floor(p.y / cell);
      if (used.has(key) || out.length >= 60) return; used.add(key); out.push({ t, at, prov, color });
    };
    for (const m of st.marks || []) take(m.t, m.at, m.prov, m.t.startsWith('rows') ? K.row : K.ink);
    if (map.getSource('act-bunds')) for (const f of map.querySourceFeatures('act-bunds')) {   // AC trench module, if present
      const r = f.geometry.coordinates[0]; if (!r) continue; let x = 0, y = 0; for (const c of r) { x += c[0]; y += c[1]; }
      take('bund ' + (f.properties.id || ''), [x / r.length, y / r.length], 'estimated', K.ink);
    }
    if (map.getSource('act-trench')) { const f = map.querySourceFeatures('act-trench')[0]; if (f) { const c = f.geometry.type === 'LineString' ? f.geometry.coordinates : (f.geometry.coordinates[0] || []); if (c.length) take('AC trench (model)', c[Math.floor(c.length / 2)], 'estimated', K.hot); } }
    if (z >= 11 && map.getSource('subs')) for (const f of map.querySourceFeatures('subs')) {
      if (f.geometry.type !== 'Point') continue; const t = kvText(f.properties.voltage);
      take('substation' + (t ? ' ' + t : ''), f.geometry.coordinates, 'documented', K.hot);
    }
    for (const kv of ['400', '275', '132']) {
      if (!map.getLayer('plan-g' + kv) || map.getLayoutProperty('plan-g' + kv, 'visibility') === 'none') continue;
      for (const f of map.querySourceFeatures('g' + kv)) {
        const lines = f.geometry.type === 'LineString' ? [f.geometry.coordinates] : f.geometry.coordinates;
        for (const l of lines) { const inV = l.filter(c => b.contains(c)); if (inV.length) take(kv + ' kV line', inV[Math.floor(inV.length / 2)], 'documented', K.kv[kv]); }
      }
    }
    labelsEl.textContent = ''; labelList = out;
    for (const L of out) {
      const d = document.createElement('div'); d.className = 'plan-label'; d.textContent = L.t;
      d.style.cssText = `position:absolute;left:0;top:0;white-space:nowrap;font:10px/1.3 ui-monospace,Consolas,monospace;color:${L.color};` +
        `background:${K.bg};border:${BORDER[L.prov]} ${L.color};opacity:${L.prov === 'estimated' ? 0.7 : 1};padding:0 4px;border-radius:2px;`;
      d.dataset.prov = L.prov; labelsEl.appendChild(d); L.el = d;
    }
    st.labels = out.length; place(); void W;
  }
  function place() { for (const L of labelList) { const p = map.project(L.at); L.el.style.transform = `translate(${Math.round(p.x + 6)}px,${Math.round(p.y - 16)}px)`; } }

  // ---- scale bar and north arrow ----
  function scale() {
    if (hud.hidden) return;
    const c = map.getCenter(), mpp = 40075016.686 * Math.cos(c.lat * Math.PI / 180) / (512 * 2 ** map.getZoom());
    const max = 120 * mpp, e = 10 ** Math.floor(Math.log10(max)), m = [5, 2, 1].map(k => k * e).find(v => v <= max) || e, px = m / mpp;
    const txt = m >= 1000 ? (m / 1000) + ' km' : m + ' m';
    hud.querySelector('.plan-bar').setAttribute('width', px.toFixed(1));
    hud.querySelector('.plan-bar-mid').setAttribute('x1', (px / 2).toFixed(1)); hud.querySelector('.plan-bar-mid').setAttribute('x2', (px / 2).toFixed(1));
    hud.querySelector('.plan-bar-end').setAttribute('x1', px.toFixed(1)); hud.querySelector('.plan-bar-end').setAttribute('x2', px.toFixed(1));
    hud.querySelector('.plan-scale-t').textContent = txt;
    hud.querySelector('.plan-north').style.transform = `rotate(${-map.getBearing()}deg)`;
    hud.dataset.metres = m; hud.dataset.px = px.toFixed(1);
  }

  // ---- modes ----
  function ease(pitch, why) {
    st.easing = true; const t0 = performance.now(); st.eases.push({ why, pitch, from: map.getPitch(), t: Math.round(t0) });
    map.easeTo({ pitch, bearing: 0, duration: EASE });
    map.once('moveend', () => { st.easing = false; st.eases[st.eases.length - 1].ms = Math.round(performance.now() - t0); after(); });
  }
  // After the ease, touch the dim once more: with terrain on, a tile rendered to texture mid-ease can keep its
  // earlier look (seen as one lighter square); a fresh paint value makes every tile redraw.
  function after() {
    if (!st.on || st.in3d) return;
    for (const k of Object.keys(st.saved)) { const [id, what] = k.split('|'); if (what === 'o' && map.getLayer(id)) map.setPaintProperty(id, 'raster-brightness-max', map.getPaintProperty(id, 'raster-brightness-max') === DIM ? DIM + 0.001 : DIM); }
    relabel(); scale();
  }
  function on() {
    if (st.on) return; st.on = true; st.in3d = false; st.prev = { pitch: map.getPitch(), bearing: map.getBearing() };
    mark(true); applyPlan();
    ease(0, 'plan');
    SIM.info && SIM.info('Plan: north-up 2D drawing of what is on the map. Solid = measured, dashed = documented, dotted/ghost = estimated. Zoom in past z17.5 for the 3D wire; P or View > Plan to leave.');
  }
  function off() {
    if (!st.on) return; st.on = false; mark(false); clearPlan();
    if (!st.in3d) map.easeTo({ pitch: st.prev ? Math.max(st.prev.pitch, 0) : 0, duration: EASE }); st.in3d = false;
  }
  // One frame later, so the zoom's own moveend has passed before the ease listens for its end.
  // (If plan was left in that frame, e.g. by Walk, the ease is dropped: the mode's own camera wins.)
  function to3d() { st.in3d = true; clearPlan(); st.easing = true; requestAnimationFrame(() => st.on ? ease(PITCH3D, 'zoom-in') : (st.easing = false)); }
  function toPlan() { st.in3d = false; applyPlan(); st.easing = true; requestAnimationFrame(() => st.on ? ease(0, 'zoom-out') : (st.easing = false)); }
  // Walk, Drone or Map (buttons, View menu, keys 1 2 3) leave plan cleanly: plan off, its look cleared, and NO camera
  // move of plan's own, so the mode's pitch, zoom, speed and the current bearing are exactly what the mode sets.
  function leave(why) {
    if (!st.on) return; st.on = false; st.in3d = false; st.easing = false; mark(false); clearPlan();
    st.left.push({ why, t: Math.round(performance.now()) });
  }
  const toggle = () => (st.on ? off() : on());
  function mark(v) { if (btn) { btn.classList.toggle('on', v); btn.setAttribute('aria-pressed', String(v)); } }

  function init(S) {
    if (SIM) return; SIM = S; map = S.map;
    hud = document.createElement('div'); hud.id = 'plan-hud'; hud.hidden = true;
    hud.style.cssText = `position:fixed;left:10px;top:calc(var(--btn, 30px) + 10px);z-index:6;pointer-events:none;color:${K.ink};` +
      `font:10px/1.3 ui-monospace,Consolas,monospace;background:${K.bg};border:1px solid #1a2030;border-radius:4px;padding:6px 8px;`;
    hud.innerHTML = '<div style="display:flex;align-items:center;gap:10px">'
      + '<svg class="plan-north" width="18" height="26" viewBox="0 0 18 26" aria-label="North"><path d="M9 2 L15 20 L9 16 L3 20 Z" fill="none" stroke="' + K.ink + '" stroke-width="1"/><path d="M9 2 L9 16 L3 20 Z" fill="' + K.ink + '"/><text x="9" y="26" fill="' + K.ink + '" font-size="7" text-anchor="middle">N</text></svg>'
      + '<svg width="130" height="22" aria-label="Scale bar"><g transform="translate(2,4)"><rect class="plan-bar" x="0" y="6" width="100" height="3" fill="none" stroke="' + K.ink + '" stroke-width="1"/>'
      + '<line x1="0" x2="0" y1="3" y2="12" stroke="' + K.ink + '"/><line class="plan-bar-mid" x1="50" x2="50" y1="6" y2="12" stroke="' + K.ink + '"/><line class="plan-bar-end" x1="100" x2="100" y1="3" y2="12" stroke="' + K.ink + '"/></g></svg>'
      + '<span class="plan-scale-t"></span></div>'
      + '<div style="color:' + K.dim + ';margin-top:3px">PLAN · north up · <span style="border-bottom:1px solid">measured</span> <span style="border-bottom:1px dashed">documented</span> <span style="border-bottom:1px dotted;opacity:.7">estimated</span></div>';
    document.body.appendChild(hud);
    labelsEl = document.createElement('div'); labelsEl.id = 'plan-labels'; labelsEl.hidden = true;
    labelsEl.style.cssText = 'position:fixed;inset:0;z-index:4;pointer-events:none;overflow:hidden';
    document.body.appendChild(labelsEl);

    map.on('move', () => { if (st.on && !st.in3d) { place(); scale(); } });
    // Blocks other mods add after a move (substation fences, towers) join the drawing at the next moveend or idle.
    const refresh = force => { if (!st.on || st.in3d || st.easing) return; const changed = sigOf() !== st.sig; if (changed) { const d = drawing(); st.sig = sigOf(); st.marks = d.marks; const s = map.getSource('plan-wire'); if (s) s.setData(d.fc); } if (changed || force) relabel(); };
    map.on('moveend', () => refresh(true)); map.on('idle', () => refresh(false));
    // Crossings only: in plan, a zoom that ENDS deeper than z17.5 after starting shallower eases into 3D, and back.
    map.on('zoomstart', () => { if (!st.easing) st.z0 = map.getZoom(); });
    map.on('zoomend', () => {
      if (!st.on || st.easing) return; const z = map.getZoom(), z0 = st.z0 ?? z;
      if (!st.in3d && z > IN && z0 <= IN) to3d(); else if (st.in3d && z < OUT && z0 >= OUT) toPlan();
    });
    map.on('style.load', () => setTimeout(() => { if (st.on && !st.in3d) { st.saved = {}; applyPlan(); } }, 150));
    addEventListener('keydown', e => {
      if (e.ctrlKey || e.metaKey || e.altKey) return;
      const t = e.target, typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
      if (typing) {
        if (e.key !== 'Enter') return; const v = String(t.value || '').trim().toLowerCase();
        if (!/^plan( on| off)?$/.test(v)) return;
        e.preventDefault(); e.stopImmediatePropagation(); t.value = '';
        if (v === 'plan on') on(); else if (v === 'plan off') off(); else toggle(); return;
      }
      if (e.key === 'p' || e.key === 'P') toggle();
      else if ((e.key === '1' || e.key === '2' || e.key === '3') && !(window.walkFps && window.walkFps.state().on)) leave('key ' + e.key);
    }, true);
    // Clicks reach #walk / #drone / #map2d from the bar and from the View menu (its items click them); capture phase,
    // so plan is off before the page's setMode starts its ease.
    document.addEventListener('click', e => { const t = e.target && e.target.closest && e.target.closest('#walk,#drone,#map2d'); if (t) leave(t.id); }, true);

    // View > Plan: once the menu bar is up, the item sits after Map (3); without a menu bar it is a plain button.
    (function menu(n) {
      const slot = document.querySelector('.gm-panel[data-menu="View"] .gm-slot[data-key="map-item"]');
      if (!slot && n < 200) return setTimeout(() => menu(n + 1), 100);
      btn = document.createElement('button'); btn.id = 'plan-view'; btn.textContent = 'Plan (P)'; btn.setAttribute('aria-pressed', 'false');
      btn.addEventListener('click', () => { toggle(); if (SIM.menu) SIM.menu.close(); });
      if (slot) { const s = document.createElement('div'); s.className = 'gm-slot'; s.dataset.key = 'plan'; s.appendChild(btn); slot.after(s); }
      else if (S.addButton) { const b = S.addButton('Plan (P)', toggle); btn = b; b.id = 'plan-view'; }
      mark(st.on);
    })(0);

    SIM.plan = { on, off, toggle,
      state: () => ({ on: st.on, in3d: st.in3d, easing: st.easing, pitch: +map.getPitch().toFixed(2), bearing: +map.getBearing().toFixed(2), zoom: +map.getZoom().toFixed(2),
        scaleBar: !!(hud && !hud.hidden && hud.querySelector('.plan-bar')), scaleM: hud ? +hud.dataset.metres || 0 : 0, scalePx: hud ? +hud.dataset.px || 0 : 0,
        labels: st.labels, kinds: Object.assign({}, st.kinds), left: st.left.slice(), labelProv: labelList.map(l => l.prov), lines: st.lines, eases: st.eases.slice(),
        dimmed: Object.keys(st.saved).filter(k => k.endsWith('|o')).length, hidden: Object.keys(st.saved).filter(k => k.endsWith('|v')).map(k => k.split('|')[0]) }),
      thresholds: { in: IN, out: OUT, easeMs: EASE, pitch3d: PITCH3D, dim: DIM }, provenance: PROV };
  }
  wait(0);                                              // last, so every const above exists
})();

Procedural

A JavaScript file in GlobalGrid2050 that maps cables, find go, battery storage (BESS) and overhead lines (OHL). It adds layer (`addLayer`) and fits rows (`fitRows`).

renderglobalgrid2050 / energy-transition-simulator/202609280202/mod/procedural.js · lines 1–228 of 228 · version 2026-09-28 02:02 · Not reached from any entry point (candidate for review) · pattern halfSide (shared by 2 files)

What it does
It maps cables, find go, battery storage (BESS) and overhead lines (OHL). Defines 23 functions or classes, including E, start, mount, addLayer, drop. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: cables, battery storage (BESS), overhead lines (OHL).
Inputs & outputs
In: JSON file cables.json; JSON file find-go.data.json.
What it achieves
Procedural fill ANYWHERE. Each public register asset (Renewable Energy Planning Database (REPD): ground solar and battery storage) in view gets a wireframe anchored at its published register point and sized from its published capacity. Its code works with 3.7 MWh.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280202/mod · script
Uses
none found
Used by
none found
Produces
E, start, mount, addLayer, drop, say, place, box, segD, ohlNear, ohlSay, crosses
Defines here
E, start, mount, addLayer, drop, say, place, box, segD, ohlNear, ohlSay, crosses, rowDocs, sig, wrap90, halfSide, fitRows, solar, turn, bess, near, refresh, inView
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280202/mod/procedural.js:1-228 · blob 88a0f234551c26554726e003e714f66c45025413 · 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: unreached_review
// procedural.js: procedural fill ANYWHERE. Each public register asset (REPD: ground solar and battery storage) in view
// gets a wireframe anchored at its published register point and sized from its published capacity.
// Solar: the morning engine's own generator, the same one plant.js runs (engine/cmd-model.mjs derive + layoutInput,
// engine/plant-layout.mjs layoutPlantAsync), on a square of open land sized by plant.js's open-land rule. No new generator.
// Battery storage: a container yard sized by a stated, ASSUMED rule (below), since the engine has no battery generator.
// EV forecourts: not drawn, because no public register of forecourts with capacity is loaded here (said on screen).
// Calibration, said as it is: see CALIB below. No layout dimension is calibrated on a measured sample yet (N = 0).
// Every dimension is an engine default or an assumption, and says so.
// Arrival and view only: the register index is the overlay's own local file; nothing is fetched on movement.
(function () {
  'use strict';
  const here = document.currentScript && document.currentScript.src ? document.currentScript.src : location.href;
  const E = n => new URL('engine/' + n, here).href;
  // Calibration state, said as it is: the six measured samples hold ground heights only (no row pitch, no fenced area), so
  // N = 0 measured samples calibrate the south formula. Where the page has loaded imagery row runs (Scanner rows, derived
  // from imagery, estimated) INSIDE a site's own box, the rows are fitted to them (azimuth, and pitch when the engine rule
  // accepts it); a site with none inside its box keeps the south formula, tagged not calibrated. MW per hectare stays engine-derived.
  const CALIB = { N: 0, pitchTag: 'engine default (gcr formula), not calibrated', mwPerHaTag: 'derived from the engine site box, not calibrated' };
  const LABEL = `procedural estimate (formula calibrated on ${CALIB.N} measured samples: the 6 samples hold ground only; imagery row runs, estimated, set row azimuth and pitch only for a site with runs inside its own box)`;
  const MAX_ASSETS = 4, MIN_ZOOM = 12, REACH_DEG = 0.015;   // a site whose register point is within ~1.5 km of the view counts
  // GHOST style (the night's line-style rule: solid = measured, dashed = documented, ghost = estimated). Procedural wire is
  // estimated, so it is drawn by this module's OWN layer, faint and see-through, never in the solid cyan of measured wire,
  // and the satellite stays visible under it.
  const GHOST_RGBA = [0.82, 0.95, 1.0, 0.32];
  // Battery yard, ASSUMED (not measured, not cited): 2 h duration, 3.7 MWh per 20 ft container (6.06 x 2.44 x 2.9 m),
  // containers in rows of 10 at 3 m gaps, rows 6 m apart, fence 10 m outside.
  const BESS = { hours: 2, mwhPerUnit: 3.7, w: 6.06, d: 2.44, h: 2.9, perRow: 10, gap: 3, aisle: 6, fence: 10 };
  // Overhead line zones. Line geometry: READ from what pylons-real already loaded (its towersOf runs along the GridAtlas
  // lines), never copied or fetched here. reachM, ASSUMED: the conductor outreach pylons-real estimates for the voltage
  // (its largest arm half-length) plus 6 m horizontal, the barrier distance of HSE GS6, which the engine's plant-layout
  // cites for its overhead line zone ("GS6 planning zone, illustrative"). The engine adds its own ohlMarginM on top.
  const GS6_M = 6, SQUARE = 'square site box at register point, not the real field';

  function start(SIM, PF) {
    Promise.all([import(E('cmd-model.mjs')), import(E('plant-layout.mjs')), fetch(E('data/cables.json')).then(r => r.json()),
      fetch(new URL('find-go.data.json', here).href).then(r => r.json())])
      .then(([CM, PL, catalogue, reg]) => mount(SIM, PF, CM, PL, catalogue, reg))
      .catch(e => SIM.info('Procedural: did not load (' + e.message + ')'));
  }

  function mount(SIM, PF, CM, PL, catalogue, reg) {
    const f = reg.fields, ix = k => f.indexOf(k);
    const rows = reg.records.map(x => ({ ref: x[ix('ref')], tech: reg.tech[x[ix('tech')]], mw: x[ix('mw10')] / 10,
      lat: x[ix('lat5')] / 1e5, lon: x[ix('lon5')] / 1e5 })).filter(r => (r.tech === 'solar' || r.tech === 'bess') && r.mw > 0);
    const map = SIM.map, cache = new Map(), ghost = [];
    let on = false, busy = false, pending = false, shown = [];
    const layer = { id: 'procedural-ghost', type: 'custom', renderingMode: '3d',
      onAdd(m, gl) { const sh = (t, s) => { const o = gl.createShader(t); gl.shaderSource(o, s); gl.compileShader(o); return o; };
        this.pr = gl.createProgram();
        gl.attachShader(this.pr, sh(gl.VERTEX_SHADER, 'uniform mat4 u; attribute vec3 p; void main(){ gl_Position = u * vec4(p, 1.0); }'));
        gl.attachShader(this.pr, sh(gl.FRAGMENT_SHADER, 'precision mediump float; uniform vec4 c; void main(){ gl_FragColor = c; }'));
        gl.linkProgram(this.pr); this.gl = gl; },
      render(gl, args) {
        if (!ghost.length) return;
        const m = args.defaultProjectionData?.mainMatrix || args, loc = gl.getAttribLocation(this.pr, 'p');
        gl.useProgram(this.pr); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
        gl.uniform4fv(gl.getUniformLocation(this.pr, 'c'), GHOST_RGBA);
        for (const b of ghost) {
          if (!b.vbo) { b.vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b.vbo); gl.bufferData(gl.ARRAY_BUFFER, b.buf, gl.STATIC_DRAW); }
          const a = b.anchor, gz = (map.queryTerrainElevation && map.queryTerrainElevation([a.lon, a.lat])) || 0, o = PF.toMercator(a.lat, a.lon, gz), r = Array.from(m);
          for (let k = 0; k < 4; k++) r[12 + k] = m[k] * o.x + m[4 + k] * o.y + m[8 + k] * o.z + m[12 + k];
          gl.bindBuffer(gl.ARRAY_BUFFER, b.vbo); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
          gl.uniformMatrix4fv(gl.getUniformLocation(this.pr, 'u'), false, new Float32Array(r)); gl.drawArrays(gl.LINES, 0, b.buf.length / 3);
        }
        gl.depthMask(true);
      } };
    const addLayer = () => { try { if (!map.getLayer(layer.id)) map.addLayer(layer); } catch (e) { map.once('idle', addLayer); } };
    addLayer(); map.on('style.load', addLayer);                 // the Satellite / Dark / Wire buttons replace the style
    const drop = fn => { for (let i = ghost.length - 1; i >= 0; i--) if (fn(ghost[i])) { const b = ghost.splice(i, 1)[0];
      if (b.vbo && layer.gl) layer.gl.deleteBuffer(b.vbo); } map.triggerRepaint(); };
    const cap = document.createElement('div'); cap.id = 'procedural-caption';   // its own caption, never #info
    cap.style.cssText = 'position:absolute;right:8px;top:150px;z-index:2;max-width:440px;font:12px sans-serif;color:rgba(225,245,255,.9);'
      + 'background:rgba(0,0,0,.55);padding:6px 8px;border-radius:6px;border:1px dashed rgba(210,242,255,.45);display:none';
    document.body.appendChild(cap);
    const say = t => { cap.textContent = t; cap.style.display = t ? 'block' : 'none'; };

    function place(r, lines) {                                  // local metres at the register point -> anchored block
      const a = PF.placeKey(r.lat, r.lon), off = PF.toLocal(a, r.lat, r.lon, 0), out = [];
      for (let i = 0; i < lines.length; i += 20000) {
        const L = lines.slice(i, i + 20000).map(([x0, y0, z0, x1, y1, z1]) => [x0 + off.x, y0 + off.y, z0, x1 + off.x, y1 + off.y, z1]);
        out.push({ lon: r.lon, lat: r.lat, anchor: a, lines: L, buf: PF.wireBuffer(a, L), procedural: r.ref });
      }
      return out;
    }
    const box = (out, x, y, w, d, z0, h) => { const c = [[x, y], [x + w, y], [x + w, y + d], [x, y + d]];
      for (let i = 0; i < 4; i++) { const p = c[i], q = c[(i + 1) % 4]; out.push([p[0], p[1], z0, q[0], q[1], z0], [p[0], p[1], z0 + h, q[0], q[1], z0 + h], [p[0], p[1], z0, p[0], p[1], z0 + h]); } };

    const segD = (px, py, ax, ay, bx, by) => { const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy,
      t = L ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / L)) : 0; return Math.hypot(px - ax - t * dx, py - ay - t * dy); };
    // Overhead lines (round r4): every GridAtlas line the page has ALREADY loaded (pylons-real holds the whole national files),
    // never only the tiles in view, so a site's clearance does not change with pan or zoom. Only spans within the site's own
    // reach (sqrt2*h + reachM + 50 m of the register point) count. Nothing fetched here. null = no line data loaded yet.
    function ohlNear(r, R) {                                    // real line spans within reach of the site box, in its local metres
      const P = window.__pylonsReal; if (!P || !P.lines || !P.towersOf || !P.KV) return null;
      const kvs = Object.keys(P.KV); if (!kvs.every(kv => Array.isArray(P.lines[kv]))) return null;
      const a = PF.placeKey(r.lat, r.lon), off = PF.toLocal(a, r.lat, r.lon, 0), out = [], k = Math.cos(r.lat * Math.PI / 180);
      for (const kv of kvs) { const reachM = Math.max(...P.KV[kv].arm) + GS6_M, lim = Math.SQRT2 * R + reachM + 50, dLa = (lim + 200) / 111320, dLo = dLa / k;
        P.lines[kv].forEach((ln, li) => { const [w, s, e, n] = ln.bbox;
          if (e < r.lon - dLo || w > r.lon + dLo || n < r.lat - dLa || s > r.lat + dLa) return;   // bbox far from the site: skip
          const pts = P.towersOf(kv, li).map(t => { const q = PF.toLocal(a, t.lat, t.lon, 0); return [q.x - off.x, q.y - off.y]; });
          for (let i = 1; i < pts.length; i++) if (segD(0, 0, ...pts[i - 1], ...pts[i]) < lim) out.push({ pts: [pts[i - 1], pts[i]], closed: false, reachM, kv }); }); }
      return out;                                               // one zone per span near the site, so far-away spans cost nothing
    }
    const ohlSay = (ohl, what) => ohl === null ? 'no overhead line data loaded for this site box: clearance not applied'
      : ohl.length ? what : 'no mapped overhead line within reach of this site box: nothing kept out';
    const crosses = (c, a, b) => { const ccw = (p, q, r) => (r[1] - p[1]) * (q[0] - p[0]) > (q[1] - p[1]) * (r[0] - p[0]);
      return c.some((p, i) => { const q = c[(i + 1) % 4]; return ccw(p, a, b) !== ccw(q, a, b) && ccw(p, q, a) !== ccw(p, q, b); }); };
    const rowDocs = () => { const R = window.SIM && window.SIM.scannerRows; return R && R.state && R.state.docs ? Object.values(R.state.docs) : []; };
    const sig = () => { const P = window.__pylonsReal;          // redo when the national line files or row files arrive, never on camera moves
      return 'lines' + (P && P.lines ? Object.keys(P.lines).filter(kv => Array.isArray(P.lines[kv])).sort().join(',') : '') + '|rows' + rowDocs().length; };
    // Row fit (round r3): the measured rows the page has ALREADY loaded (Scanner rows: the lab's row files, lon/lat runs from
    // imagery), never fetched here. Only runs whose midpoint lies inside THIS site's own square box (within h of the register
    // point, in PF.toLocal metres) count, so a site is never credited with a neighbour's rows and the fit does not depend on
    // the camera. The box used for the test is the south default box (the engine's layout before any fit), so it does not
    // depend on the fit it feeds. Azimuth: axial median, compass degrees 0-180; pitch: the row file's own reading.
    // No runs inside the box: null, and the south formula stays, tagged not calibrated.
    const wrap90 = d => ((d % 180) + 270) % 180 - 90;           // to (-90, 90]
    function halfSide(st, latDeg) {                                     // plant.js's open-land rule: half the square site box side, metres
      const tpl = CM.derive(st, { catalogue }).tpl, ld = { ...PL.LAYOUT_DEFAULTS, ...(CM.layoutInput(st, { latDeg, catalogue }).options || {}) }, T0 = PL.tableGeometry(st.layout, ld, tpl);
      return (Math.sqrt(Math.ceil(tpl.counts.strings / 2) * T0.pitch * (T0.lenU + PL.LAYOUT_DEFAULTS.tableGapM) * 1.5) + 2 * st.fence) / 2;
    }
    function fitRows(r) {
      const a = PF.placeKey(r.lat, r.lon), off = PF.toLocal(a, r.lat, r.lon, 0), hBox = halfSide({ ...CM.DEFAULTS, mw: r.mw }, r.lat), az = [], pitches = [];
      for (const doc of rowDocs()) { let n0 = 0;
        for (const [[lo0, la0], [lo1, la1]] of doc.rows || []) {
          const M = PF.toLocal(a, (la0 + la1) / 2, (lo0 + lo1) / 2, 0);
          if (Math.abs(M.x - off.x) > hBox || Math.abs(M.y - off.y) > hBox) continue;
          const A = PF.toLocal(a, la0, lo0, 0), B = PF.toLocal(a, la1, lo1, 0); az.push(Math.atan2(B.x - A.x, B.y - A.y) * 180 / Math.PI); n0++; }
        if (n0 && doc.row_pitch_m > 0) pitches.push(doc.row_pitch_m); }
      if (!az.length) return { n: 0, boxHalfM: hBox };
      let sx = 0, sy = 0; for (const d of az) { sx += Math.cos(d * Math.PI / 90); sy += Math.sin(d * Math.PI / 90); }
      const c = Math.atan2(sy, sx) * 90 / Math.PI, dev = az.map(d => wrap90(d - c)).sort((p, q) => p - q);
      pitches.sort((p, q) => p - q);
      return { azDeg: ((c + dev[dev.length >> 1]) % 180 + 180) % 180, pitchM: pitches.length ? pitches[pitches.length >> 1] : null, n: az.length, boxHalfM: hBox };
    }

    async function solar(r) {                                   // the engine's generator, as plant.js runs it
      // Rows fitted to the measured rows inside the site's own box when there are any: rows within 45 deg of north-south use the engine's
      // east-west (tent) layout, others its south layout; the residual angle turns the whole layout about the register point.
      const fr = fitRows(r), fit = fr.n ? fr : null, st = { ...CM.DEFAULTS, mw: r.mw };
      let rot = 0, pitchUsed = false;
      if (fit) { st.layout = Math.abs(wrap90(fit.azDeg)) <= 45 ? 'east-west' : 'south'; rot = wrap90(fit.azDeg - (st.layout === 'south' ? 90 : 0));
        if (fit.pitchM) { const d = CM.derive({ ...st, pitch: fit.pitchM }, { catalogue });   // the engine's own pitch rule, kept only if it fits
          pitchUsed = st.layout === 'south' ? d.gcr > 0 && d.gcr <= 0.9 : d.ewGapM >= 0.5; if (pitchUsed) st.pitch = fit.pitchM; } }
      const env = { latDeg: r.lat, catalogue }, inp = CM.layoutInput(st, env);
      const h = halfSide(st, r.lat), side = 2 * h;
      const ohlR = ohlNear(r, h), ohl = ohlR || [], th = rot * Math.PI / 180, cs = Math.cos(th), sn = Math.sin(th);
      const turn = ([e, n], s = 1) => [e * cs + s * n * sn, -s * e * sn + n * cs];     // clockwise by rot (s = -1: back)
      const ohlL = ohl.map(z => ({ ...z, pts: z.pts.map(q => turn(q, -1)) }));        // the real spans, in the layout's own frame
      const res = await PL.layoutPlantAsync({ boundary: [[-h, -h], [h, -h], [h, h], [-h, h]], targetMW: r.mw, layout: st.layout, template: inp.template,
        piles: false, groundAt: () => 0, grid: null, water: [], ohl: ohlL.length ? ohlL : null, options: { ...inp.options, slopeLimitPct: st.slope, fenceSetbackM: st.fence } });
      const Fr0 = res.frame, Fr = { en: (u, v) => turn(Fr0.en(u, v)) }, T = res.table, P = res.params, out = [], at = (u, v, z) => [...Fr.en(u, v), z], seg = (a, b) => out.push([...a, ...b]);
      const rowAz = ((st.layout === 'south' ? 90 : 0) + rot + 180) % 180;
      const rowTag = fit ? `row azimuth ${rowAz.toFixed(1)} deg, pitch ${T.pitch.toFixed(2)} m, fitted to ${fit.n.toLocaleString('en-GB')} measured rows inside a ${Math.round(2 * fit.boxHalfM).toLocaleString('en-GB')} m square around the register point`
        + (pitchUsed ? ' (pitch: the row file reading, estimated from imagery)' : ` (pitch: engine default, the row file's ${fit.pitchM ? fit.pitchM + ' m' : 'none'} did not fit the engine rule)`)
        : `south formula, not calibrated: row azimuth 90 deg, pitch ${T.pitch.toFixed(2)} m`;
      for (const fl of res.fields || [res.boundary]) for (let i = 0; i < fl.length; i++) seg(at(...fl[i], 1.5), at(...fl[(i + 1) % fl.length], 1.5));
      const lo = P.lowEdgeM, hi = lo + T.rise, t = res.tables;
      for (let q = 0; q < t.length; q += 6) { const ua = t[q], va = t[q + 1], ub = ua + (res.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth;
        const A = at(ua, va, lo), B = at(ub, va, lo), C = at(ub, vb, hi), D = at(ua, vb, hi); seg(A, B); seg(B, C); seg(C, D); seg(D, A); }
      const tb = [];
      for (let q = 0; q < t.length; q += 6) { const ua = t[q], va = t[q + 1], ub = ua + (res.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth;
        tb.push([Fr.en(ua, va), Fr.en(ub, va), Fr.en(ub, vb), Fr.en(ua, vb)]); }
      for (const s of res.stations) { const [e, n] = Fr.en(s.u, s.v); box(out, e - 6, n - 1.5, 12, 3, 0, 3); }
      const kept = (res.skipped && res.skipped.ohl) || 0, areaHa = side * side / 1e4, mwPerHa = r.mw / areaHa;
      const rowsV = [...new Set(Array.from({ length: t.length / 6 }, (_, i) => Math.round(t[6 * i + 1] * 1000) / 1000))].sort((a, b) => a - b);
      return { lines: out, geom: { ohl, ohlLoaded: ohlR !== null, ohlRadiusM: h, marginM: P.ohlMarginM, tables: tb, containers: [], skipped: kept,
          formula: { pitchM: T.pitch, pitchTag: fit && pitchUsed ? 'row file reading, estimated from imagery' : CALIB.pitchTag, rowAzDeg: rowAz, layout: st.layout, fitN: fit ? fit.n : 0, fitBoxHalfM: fr.boxHalfM, fitAzDeg: fit ? fit.azDeg : null, rowTag, areaHa, mwPerHa, mwPerHaTag: CALIB.mwPerHaTag, N: CALIB.N,
            boundary: [[-h, -h], [h, -h], [h, h], [-h, h]], rowsV } },
        text: `${r.mw} MW solar: ${res.built.tables.toLocaleString('en-GB')} tables, ${rowTag}, `
          + `site box ${areaHa.toFixed(1)} ha = ${mwPerHa.toFixed(2)} MW/ha (${CALIB.mwPerHaTag}), ${res.built.stations} stations; `
          + ohlSay(ohlR, `${kept.toLocaleString('en-GB')} table positions kept out of overhead line zones (illustrative)`)
          + `; ${SQUARE}` };
    }
    function bess(r) {                                          // ASSUMED yard rule (see BESS above)
      const n = Math.max(1, Math.ceil(r.mw * BESS.hours / BESS.mwhPerUnit)), cols = Math.min(n, BESS.perRow), nr = Math.ceil(n / BESS.perRow);
      const W = cols * BESS.w + (cols - 1) * BESS.gap, D = nr * BESS.d + (nr - 1) * BESS.aisle, out = [], ohlR = ohlNear(r, Math.max(W, D) / 2 + BESS.fence), ohl = ohlR || [];
      const margin = PL.LAYOUT_DEFAULTS.ohlMarginM, cont = [];  // the engine's own margin, so tables and containers keep the same clearance
      const near = c => ohl.some(z => { const [a, b] = z.pts, lim = z.reachM + margin;   // box within reach + margin of the span
        return c.some(p => segD(...p, ...a, ...b) < lim) || [a, b].some(p => Math.hypot(Math.max(c[0][0] - p[0], 0, p[0] - c[2][0]),
          Math.max(c[0][1] - p[1], 0, p[1] - c[2][1])) < lim) || crosses(c, a, b); });
      let dropped = 0;
      for (let k = 0; k < n; k++) { const x = -W / 2 + (k % BESS.perRow) * (BESS.w + BESS.gap), y = -D / 2 + Math.floor(k / BESS.perRow) * (BESS.d + BESS.aisle);
        const c = [[x, y], [x + BESS.w, y], [x + BESS.w, y + BESS.d], [x, y + BESS.d]];
        if (near(c)) { dropped++; continue; } cont.push(c); box(out, x, y, BESS.w, BESS.d, 0, BESS.h); }
      box(out, -W / 2 - BESS.fence, -D / 2 - BESS.fence, W + 2 * BESS.fence, D + 2 * BESS.fence, 0, 2.4);
      return { lines: out, geom: { ohl, ohlLoaded: ohlR !== null, ohlRadiusM: Math.max(W, D) / 2 + BESS.fence, marginM: margin, tables: [], containers: cont, skipped: dropped },
        text: `${r.mw} MW storage: ${n - dropped} of ${n} containers (assumed 2 h, 3.7 MWh each); `
          + ohlSay(ohlR, `${dropped} container positions kept out of overhead line zones (illustrative)`) + `; ${SQUARE}` };
    }

    async function refresh() {
      if (!on) return; if (busy) { pending = true; return; } busy = true;
      try {
        const c = map.getCenter(), b = map.getBounds(), k = Math.cos(c.lat * Math.PI / 180);
        const inView = r => r.lat > b.getSouth() - REACH_DEG && r.lat < b.getNorth() + REACH_DEG && r.lon > b.getWest() - REACH_DEG / k && r.lon < b.getEast() + REACH_DEG / k;
        const near = map.getZoom() < MIN_ZOOM ? [] : rows.filter(inView)
          .map(r => ({ r, d: Math.hypot(r.lat - c.lat, (r.lon - c.lng) * k) })).sort((a, z) => a.d - z.d).slice(0, MAX_ASSETS).map(x => x.r);
        const texts = [];
        for (const r of near) {
          const sg = sig(), old = cache.get(r.ref);            // redo once the real lines arrive (pylons-real loads them async)
          if (!old || old.sig !== sg) { const g = r.tech === 'bess' ? bess(r) : await solar(r);
            if (old) { drop(x => x.procedural === r.ref); shown = shown.filter(z => z !== r.ref); }
            cache.set(r.ref, { blocks: place(r, g.lines), text: g.text, n: g.lines.length, geom: g.geom, sig: sg }); }
          texts.push(cache.get(r.ref).text);
        }
        const keep = new Set(near.map(r => r.ref));
        drop(x => !keep.has(x.procedural));
        for (const r of near) if (!shown.includes(r.ref)) for (const bl of cache.get(r.ref).blocks) { delete bl.vbo; ghost.push(bl); }
        map.triggerRepaint();
        shown = near.map(r => r.ref);
        btn.textContent = `Procedural (${shown.length})`;
        say(shown.length ? `${LABEL}. Ghost lines = estimated (solid = measured, dashed = documented). At register points, sized from register capacity: ${texts.join('; ')}. EV forecourts: no register loaded, not drawn.`
          : `Procedural: no register solar or storage in view${map.getZoom() < MIN_ZOOM ? ' (zoom in to ' + MIN_ZOOM + ')' : ''}. ${LABEL}.`);
        window.__procedural = { label: LABEL, style: 'ghost', ghostBlocks: ghost.length, layer: !!map.getLayer(layer.id), calibN: CALIB.N, shown: near.map(r => ({ ref: r.ref, tech: r.tech, mw: r.mw, lat: r.lat, lon: r.lon, segments: cache.get(r.ref).n, text: cache.get(r.ref).text, geom: cache.get(r.ref).geom })) };
      } catch (e) { say('Procedural: ' + e.message); }
      busy = false; if (pending) { pending = false; refresh(); }
    }
    const btn = SIM.addButton('Procedural', () => { on = !on; btn.classList.toggle('on', on); if (on) refresh(); else { drop(() => true); shown = []; say(''); btn.textContent = 'Procedural'; } });
    btn.id = 'procedural';
    map.on('moveend', refresh);
    window.__proceduralRefresh = refresh; window.__proceduralFit = ref => { const r = rows.find(x => x.ref === ref); return r ? fitRows(r) : null; }; window.__proceduralGhost = () => ghost.length;
    window.__proceduralOhl = ref => { const r = rows.find(x => x.ref === ref), c = cache.get(ref); if (!r || !c) return null;   // fresh, not the cache
      const o = ohlNear(r, c.geom.ohlRadiusM); return { loaded: o !== null, spans: o ? o.length : 0, key: o ? o.map(z => z.kv + ':' + z.pts.flat().map(v => v.toFixed(2)).join(',')).join('|') : '' }; };
  }

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