GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/layers

National and 3 more files

A JavaScript module in the layers folder of GlobalGrid2050 that works with 33kV, substations, 400kV and 275kV, using SHA-256. It rebuilds step (`rebuildStep`), starts near (`startNear`) and loads index (`loadIndex`).

610 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 135 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. National electrical · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/layers/national.mjs lines 1–390
  2. Lift transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/lift.mjs lines 1–22
  3. Overhead Line (OHL) Gs6 transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/ohl-gs6.mjs lines 1–59
  4. Overhead Line (OHL) UI render · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/ohl-ui.mjs lines 1–139

National

A JavaScript module in the layers folder of GlobalGrid2050 that works with 33kV, substations, 400kV and 275kV, using SHA-256. It rebuilds step (`rebuildStep`), starts near (`startNear`) and loads index (`loadIndex`).

Set aside from the main view: 92% of its lines are the same as solar-design-studio/202609271853-site-world/world/layers/national.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with National; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9222 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/layers/national.mjs:1-396 2e325fd7a569debc22b40faee4077ff33009ed9e
  • sha256 9d039371650d1e90efd459d4caed3b283176bcf9d9e511ad9043713b24f7976c
  • target sha256 16876c2c7ea717fa8a0d0229d3f4e72acb450718eb18292791f016a5cd515c6c
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/layers/national.mjs · lines 1–390 of 390 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern createNational (shared by 2 files)

What it does
It calculates 33kV, substations, 400kV and 275kV. Defines 33 functions or classes, including rebuildStep, voltageClass, clipToCircle, boxDist, wantedFiles.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV, substations, 400kV, 275kV, 132kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 33kV.
What it achieves
Roads, mainline railways, overhead lines with their towers, and every substation in Great Britain, from GridAtlas's national files (OpenStreetMap, ODbL), cut into 10 km tiles by `tools/features/cut_national.py`. Its code works with 33 kV, 132 kV and 275 kV.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world/layers · JavaScript module
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
MILE_M, RANGES_MI, NEAR_LINE_M, BAND_M, MAX_IN_FLIGHT, rebuildStep, GAUGE_M, KINDS, COLORS, COMPOUND, voltageClass, clipToCircle
Defines here
rebuildStep, voltageClass, clipToCircle, boxDist, wantedFiles, boxOf, buildNational, zAt, out, seg, r2, skip, run, pieces, polyline, plainLift, power, isNear, flush, substation, createNational, zero, startNear, now, clockMs, loadIndex, wanted, request, pump, evict
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270145-site-world-v3/world/layers/national.mjs:1-390 · blob 1c6d98d7e3be608bd37c4cc6ff4f6dee489d6d31 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Layer: national. Roads, mainline railways, overhead lines with their towers, and every substation in Great Britain,
// from GridAtlas's national files (OpenStreetMap, ODbL), cut into 10 km tiles by tools/features/cut_national.py;
// B and minor roads (kind osroads) from OS Open Roads (OGL), in their own files, as GridAtlas has none.
// Self-contained: no imports (it runs from a blob URL). Towers and conductors come from api.lib.overhead.
//
// Only what lies inside a circle of the chosen range around the viewer is loaded and drawn: 2, 5 or 10 miles
// (config.range_miles, then layer.setRange(miles)). Files are fetched through the substrate's hash check:
//   index.json (config.index + config.sha256) -> squares/*.json (one per 100 km) -> tiles/<kind>/*.odbl.json
// nearest first, at most MAX_IN_FLIGHT at a time, least recently used forgotten past the cache size.
//
// Drawing, by distance from the viewer:
//   roads      one centreline per carriageway, by class (motorway, trunk, primary; B and minor from osroads)
//   rail       two rails at standard gauge within TWIN_RAIL_M, one line beyond (the pair is under a pixel there)
//   power      within NEAR_LINE_M: towers, insulators and sagging conductors (api.lib.overhead.buildOverhead);
//              beyond: a plain line at the lowest typical attachment height
//   substation within NEAR_SUB_M: a fenced compound (a solid); beyond: a mast marker
// Heights: measured ground (ctx.measuredAt) where terrain tiles are loaded within MEASURE_M of the viewer, draped every
// DRAPE_STEP m within DRAPE_M; elsewhere the height of the ground under the viewer, NOT measured there (the status says
// how many points). Terrain tiles only stream in near the viewer, so asking further out would cost time for nothing.
// Batches are placed relative to an origin at the viewer (local metres), so positions stay small on the GPU.
// ASSUMED: tower positions (inferred from OpenStreetMap vertices), tower shapes, sag, compound and marker sizes.

export const MILE_M = 1609.344;
export const RANGES_MI = [2, 5, 10];
export const NEAR_LINE_M = 2000, NEAR_SUB_M = 1000, TWIN_RAIL_M = 1000, DRAPE_M = 400, DRAPE_STEP = 10, MEASURE_M = 1000;
export const BAND_M = NEAR_LINE_M; // the near band: everything whose look depends on the ground or on being close
export const MAX_IN_FLIGHT = 2, MIN_CACHE = 48, GROUND_REBUILD_MS = 3000, GROUND_SETTLE_FRAMES = 2;
// The drawing is rebuilt after the viewer moves this far: a twentieth of the range, 160-400 m.
export const rebuildStep = rangeM => Math.min(400, Math.max(160, rangeM / 20));
export const GAUGE_M = 1.435, FENCE_H = 2.4;
export const KINDS = ['roads', 'osroads', 'rail', 'power', 'substations'];

export const COLORS = {
  motorway: [0.80, 0.80, 0.80, 0.60], trunk: [0.72, 0.72, 0.72, 0.50], primary: [0.64, 0.64, 0.64, 0.42],
  B: [0.58, 0.58, 0.58, 0.36], minor: [0.50, 0.50, 0.50, 0.30],
  rail: [0.66, 0.64, 0.61, 0.50],
  '400kV': [0.55, 0.66, 1.00, 0.62], '275kV': [1.00, 0.56, 0.56, 0.55], '132kV': [1.00, 0.80, 0.48, 0.50],
  '33kV': [0.56, 0.86, 0.62, 0.45]
};
// Compound footprint east-west by north-south (m) and far marker height (m) by class. ASSUMED, not surveyed.
export const COMPOUND = { '400kV': [300, 200, 60], '275kV': [220, 150, 50], '132kV': [90, 60, 35], '33kV': [30, 20, 20] };
const PLAIN_LIFT = { '400kV': 22, '275kV': 18.5, '132kV': 14, '33kV': 8.9 }; // used when the library has no tower table

export function voltageClass(kv) {
  const v = Number(kv);
  if (!(v > 0)) return '33kV';
  return v >= 345 ? '400kV' : v >= 220 ? '275kV' : v >= 66 ? '132kV' : '33kV';
}

// Pure: the part [t0, t1] of segment a->b inside the circle (c, r), or null.
export function clipToCircle(ax, ay, bx, by, cx, cy, r) {
  const dx = bx - ax, dy = by - ay, fx = ax - cx, fy = ay - cy;
  const A = dx * dx + dy * dy, B = 2 * (fx * dx + fy * dy), C = fx * fx + fy * fy - r * r;
  if (A === 0) return C <= 0 ? [0, 1] : null;
  const disc = B * B - 4 * A * C;
  if (disc < 0) return null;
  const s = Math.sqrt(disc), lo = Math.max(0, (-B - s) / (2 * A)), hi = Math.min(1, (-B + s) / (2 * A));
  return lo < hi ? [lo, hi] : null;
}

// Distance from (x, y) to the box [e0, n0, e1, n1] (0 inside).
export const boxDist = (x, y, b) => Math.hypot(Math.max(b[0] - x, 0, x - b[2]), Math.max(b[1] - y, 0, y - b[3]));

// Pure: the files needed for a circle at national-grid (e, n), nearest first.
// squares: the top index's list. tiles: entries from loaded square files. kinds: the kinds switched on.
export function wantedFiles(squares, tiles, kinds, e, n, r) {
  const out = [];
  for (const s of squares) {
    const d = boxDist(e, n, [s.e0, s.n0, s.e0 + 100000, s.n0 + 100000]);
    if (d <= r) out.push({ id: 'sq/' + s.key, type: 'square', path: s.file, sha256: s.sha256, d, bytes: s.bytes });
  }
  for (const t of tiles) for (const k of kinds) {
    const f = t.files?.[k];
    if (!f) continue;
    const d = boxDist(e, n, f.bbox);
    if (d <= r) out.push({ id: `${k}/${t.key}`, type: 'tile', kind: k, e0: t.e0, n0: t.n0, path: f.file, sha256: f.sha256, d, bytes: f.bytes });
  }
  return out.sort((a, b) => (a.type === b.type ? a.d - b.d : a.type === 'square' ? -1 : 1));
}

// The box [x0, y0, x1, y1] of a flat point list in tile metres, worked out once per list (tiles are immutable).
const BOXES = new WeakMap();
export function boxOf(p) {
  let b = BOXES.get(p);
  if (!b) {
    b = [Infinity, Infinity, -Infinity, -Infinity];
    for (let i = 0; i < p.length; i += 2) { b[0] = Math.min(b[0], p[i]); b[1] = Math.min(b[1], p[i + 1]); b[2] = Math.max(b[2], p[i]); b[3] = Math.max(b[3], p[i + 1]); }
    BOXES.set(p, b);
  }
  return b;
}

// Pure: every batch and solid for the loaded tiles. v: { x, y, r, kinds: Set, o: { e, n }, band? } in local metres.
// band 'near' draws only inside BAND_M of (x, y) (towers, compounds, measured ground), 'far' only outside it,
// 'all' (default) both: the two bands meet exactly, so the near one can be rebuilt alone when new ground arrives.
// ground: { at(x, y) -> measured height or NaN, fallback: metres }. lib: api.lib.overhead (may be null).
// memo: a Map the caller keeps while the origin stays the same; towers and wires on unchanged ground are reused.
export function buildNational(tiles, v, ground, lib, memo = new Map()) {
  const bo = [Math.round(v.x / 100) * 100, Math.round(v.y / 100) * 100, ground.fallback], band = v.band || 'all';
  const groups = {}, solids = [], count = { measured: 0, fallback: 0, features: 0 }, used = new Set();
  const zAt = (x, y) => {
    const h = (x - v.x) ** 2 + (y - v.y) ** 2 <= MEASURE_M * MEASURE_M ? ground.at(x, y) : NaN; // terrain streams near the viewer
    if (Number.isFinite(h)) { count.measured++; return h; }
    count.fallback++; return ground.fallback;
  };
  const out = g => (groups[g] ||= []);
  const seg = (a, ax, ay, az, bx, by, bz) => a.push(ax - bo[0], ay - bo[1], az - bo[2], bx - bo[0], by - bo[1], bz - bo[2]);
  const r2 = (x, y) => Math.hypot(x - v.x, y - v.y);
  // A line whose box lies wholly outside this band is skipped without looking at its segments.
  const reach = band === 'near' ? Math.min(BAND_M, v.r) : v.r;
  const skip = (p, tx, ty) => {
    const b = boxOf(p), cx = v.x - tx, cy = v.y - ty;
    if (boxDist(cx, cy, b) > reach) return true;
    if (band !== 'far') return false;
    const fx = Math.max(Math.abs(cx - b[0]), Math.abs(cx - b[2])), fy = Math.max(Math.abs(cy - b[1]), Math.abs(cy - b[3]));
    return Math.hypot(fx, fy) < BAND_M; // wholly inside the near band
  };

  // A straight run, clipped to the circle, shifted sideways by `side` m, draped near the viewer.
  function run(a, ax, ay, bx, by, lift, side = 0) {
    const dx = bx - ax, dy = by - ay, L = Math.hypot(dx, dy) || 1, nx = -dy / L * side, ny = dx / L * side;
    for (const c of pieces(ax, ay, bx, by)) {
      const x0 = ax + dx * c[0] + nx, y0 = ay + dy * c[0] + ny, x1 = ax + dx * c[1] + nx, y1 = ay + dy * c[1] + ny;
      const near = Math.min(r2(x0, y0), r2(x1, y1)) < DRAPE_M;
      const k = near ? Math.max(1, Math.ceil(L * (c[1] - c[0]) / DRAPE_STEP)) : 1;
      let px = x0, py = y0, pz = zAt(x0, y0) + lift;
      for (let j = 1; j <= k; j++) {
        const x = x0 + (x1 - x0) * j / k, y = y0 + (y1 - y0) * j / k, z = zAt(x, y) + lift;
        seg(a, px, py, pz, x, y, z); px = x; py = y; pz = z;
      }
    }
  }
  // The parts [t0, t1] of a->b in this band: inside the range, and inside or outside the near circle.
  function pieces(ax, ay, bx, by) {
    const c = clipToCircle(ax, ay, bx, by, v.x, v.y, v.r);
    if (!c || band === 'all') return c ? [c] : [];
    const h = clipToCircle(ax, ay, bx, by, v.x, v.y, BAND_M);
    if (band === 'near') return h && Math.min(c[1], h[1]) > Math.max(c[0], h[0]) ? [[Math.max(c[0], h[0]), Math.min(c[1], h[1])]] : [];
    if (!h) return [c];
    return [[c[0], Math.min(c[1], Math.max(c[0], h[0]))], [Math.max(c[0], Math.min(c[1], h[1])), c[1]]].filter(q => q[1] - q[0] > 1e-9);
  }
  function polyline(a, p, tx, ty, lift, from = 0, to = p.length / 2 - 1, twin = false) {
    for (let i = from; i < to; i++) {
      const ax = tx + p[2 * i], ay = ty + p[2 * i + 1], bx = tx + p[2 * i + 2], by = ty + p[2 * i + 3];
      if (twin && r2((ax + bx) / 2, (ay + by) / 2) < TWIN_RAIL_M) { run(a, ax, ay, bx, by, lift, GAUGE_M / 2); run(a, ax, ay, bx, by, lift, -GAUGE_M / 2); }
      else run(a, ax, ay, bx, by, lift);
    }
  }
  const types = lib?.TOWER_TYPES;
  const plainLift = cls => {
    const s = types?.[cls];
    if (!s) return PLAIN_LIFT[cls];
    return s.kind === 'pole' ? s.armZ : Math.min(...s.arms.map(a => a.z)) - s.insulator;
  };

  function power(f, tx, ty, id) {
    const cls = voltageClass(f.kv), a = out('power/' + cls), p = f.p, n = p.length / 2;
    const idx = Array.isArray(f.t) && f.t.length ? f.t : [...Array(n).keys()];
    const T = idx.map(i => ({ i, x: tx + p[2 * i], y: ty + p[2 * i + 1] }));
    const lift = plainLift(cls), canSag = band !== 'far' && typeof lib?.buildOverhead === 'function';
    const isNear = t => canSag && r2(t.x, t.y) <= NEAR_LINE_M;
    polyline(a, p, tx, ty, lift, 0, idx[0]);             // before the first tower and after the last: plain
    polyline(a, p, tx, ty, lift, idx[idx.length - 1]);
    let group = [];
    const flush = () => {
      if (!group.length) return;
      const towers = group.map((t, k) => ({ id: `T${k}`, x: t.x, y: t.y, ground: zAt(t.x, t.y), type: cls }));
      const mk = `${id}|${group[0].i}|${towers.map(t => t.ground.toFixed(2)).join(',')}`; // same towers on the same ground
      const o = memo.get(mk) || lib.buildOverhead(towers, { step: 10 });
      memo.set(mk, o); used.add(mk);
      for (let k = 0; k < o.lines.length; k += 3) a.push(o.lines[k] - bo[0], o.lines[k + 1] - bo[1], o.lines[k + 2] - bo[2]);
      solids.push(...o.solids);
      group = [];
    };
    for (let k = 0; k < T.length; k++) {
      if (isNear(T[k])) { group.push(T[k]); }
      else flush();
      if (k + 1 < T.length && !(isNear(T[k]) && isNear(T[k + 1]))) { flush(); polyline(a, p, tx, ty, lift, T[k].i, T[k + 1].i); }
    }
    flush();
  }

  function substation(f, tx, ty) {
    const x = tx + f.x, y = ty + f.y, d = r2(x, y), cls = voltageClass(f.kv);
    if (d > v.r || (band === 'near' && d > BAND_M) || (band === 'far' && d <= BAND_M)) return;
    const [w, dd, mast] = COMPOUND[cls], a = out('sub/' + cls), g = zAt(x, y);
    if (d > NEAR_SUB_M) { // a mast with a diamond on top, seen from far off
      const s = mast / 6;
      seg(a, x, y, g, x, y, g + mast);
      const P = [[x + s, y, g + mast], [x, y + s, g + mast + s], [x - s, y, g + mast], [x, y - s, g + mast - s]];
      for (let k = 0; k < 4; k++) seg(a, ...P[k], ...P[(k + 1) % 4]);
      return;
    }
    const c = [[x - w / 2, y - dd / 2], [x + w / 2, y - dd / 2], [x + w / 2, y + dd / 2], [x - w / 2, y + dd / 2]];
    let lo = Infinity, hi = -Infinity;
    for (let k = 0; k < 4; k++) {
      const [ax, ay] = c[k], [bx, by] = c[(k + 1) % 4], m = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / 10));
      for (let i = 0; i < m; i++) {
        const x0 = ax + (bx - ax) * i / m, y0 = ay + (by - ay) * i / m, x1 = ax + (bx - ax) * (i + 1) / m, y1 = ay + (by - ay) * (i + 1) / m;
        const z0 = zAt(x0, y0), z1 = zAt(x1, y1);
        lo = Math.min(lo, z0, z1); hi = Math.max(hi, z0, z1);
        seg(a, x0, y0, z0, x1, y1, z1); seg(a, x0, y0, z0 + FENCE_H, x1, y1, z1 + FENCE_H);
      }
      const z = zAt(ax, ay);
      seg(a, ax, ay, z, ax, ay, z + FENCE_H);
    }
    solids.push({ min: [x - w / 2, y - dd / 2, lo], max: [x + w / 2, y + dd / 2, hi + FENCE_H] });
  }

  for (const t of tiles) {
    if (!v.kinds.has(t.kind)) continue;
    const doc = t.doc, tx = doc.e0 - v.o.e, ty = doc.n0 - v.o.n;
    if (boxDist(v.x, v.y, [tx, ty, tx + (doc.size || 10000), ty + (doc.size || 10000)]) > reach) continue; // tile outside this band
    if (t.kind === 'roads' || t.kind === 'osroads' || t.kind === 'rail') {
      for (const [cls, list] of Object.entries(doc.lines || {})) {
        const a = out(t.kind === 'rail' ? 'rail' : 'roads/' + cls);
        for (const p of list) { if (skip(p, tx, ty)) continue; polyline(a, p, tx, ty, 0.1, 0, p.length / 2 - 1, t.kind === 'rail'); count.features++; }
      }
    } else if (t.kind === 'power') (doc.features || []).forEach((f, i) => { if (skip(f.p, tx, ty)) return; power(f, tx, ty, `${t.id}#${i}`); count.features++; });
    else for (const f of doc.features || []) { substation(f, tx, ty); count.features++; }
  }
  if (band !== 'far' && v.kinds.has('power')) for (const k of memo.keys()) if (!used.has(k)) memo.delete(k); // forget lines no longer near
  const batches = Object.entries(groups).filter(([, a]) => a.length).map(([g, a]) => ({
    key: `national/${band}/${g}`, origin: bo, color: COLORS[g.split('/').pop()] || COLORS.primary, positions: new Float32Array(a) }));
  return { batches, solids, count };
}

export function createNational() {
  let api = null, rangeM = 5 * MILE_M, kinds = new Set(KINDS);
  let index = null, indexState = 'idle', dataVersion = 0, clock = 0, lastPos = null;
  const squares = new Map(), files = new Map(), inFlight = new Set(), failed = new Set();
  const stats = { requested: [], evicted: [], bytes: 0, buildMs: 0, builds: [] }; // builds: the last 20 [when, ms, why]
  // The far band is built one kind per frame into `next` and swapped in whole; the near band (towers, compounds,
  // measured ground) is rebuilt alone when new ground arrives. Both share one centre, so they meet exactly.
  const zero = () => ({ measured: 0, fallback: 0, features: 0 });
  let centre = { key: null, at: null, fallback: 0 }, next = null, memo = { key: null, map: new Map() };
  let nextNear = null; // { far?, todo, batches, solids, count, gv, t, why, ms }: the near band being built
  const startNear = (farNext, gv, t, why) => ({ far: farNext, todo: [...kinds], batches: [], solids: [], count: zero(), gv, t, why, ms: 0 });
  let gvSeen = { gv: null, frames: 0 }; // new ground is drawn under the lines a couple of frames after it arrives, not in its frame
  let far = { batches: [], count: zero() }, near = { batches: [], solids: [], count: zero(), gv: -1, t: -Infinity }, all = [];
  const now = () => (api && typeof api.origin === 'function' ? api.origin() : { e: 0, n: 0, id: 0 });
  const clockMs = () => (globalThis.performance ? performance.now() : Date.now());

  function loadIndex() {
    if (indexState !== 'idle' || !api) return;
    const path = api.config?.index, sha = api.config?.sha256;
    if (!path || !sha) { indexState = 'failed'; layer.status = 'no national index configured (config.index and config.sha256)'; return; }
    indexState = 'loading';
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      if (!j || !Array.isArray(j.squares)) throw Error('index.json has no squares list');
      const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '';
      index = { ...j, dir };
      indexState = 'ready'; dataVersion++;
      api.invalidate({ ground: false });
    }).catch(e => { indexState = 'failed'; layer.status = 'national index failed: ' + e.message; });
  }

  let want = { key: null, list: [] }; // worked out again only after a 50 m move or new data
  function wanted() {
    if (!index || !lastPos) return [];
    const o = now(), e = o.e + lastPos[0], n = o.n + lastPos[1];
    const key = `${Math.round(e / 50)},${Math.round(n / 50)}|${dataVersion}|${squares.size}`;
    if (want.key === key) return want.list;
    const tiles = [...squares.values()].flatMap(s => s.doc.tiles || []);
    want = { key, list: wantedFiles(index.squares, tiles, [...kinds], e, n, rangeM) };
    return want.list;
  }

  function request(w) {
    inFlight.add(w.id); stats.requested.push(w.id);
    Promise.resolve().then(() => api.fetchJSON(index.dir + w.path, w.sha256)).then(doc => {
      stats.bytes += w.bytes || 0;
      (w.type === 'square' ? squares : files).set(w.id, { doc, kind: w.kind, used: ++clock });
      dataVersion++; evict();
      api.invalidate({ ground: false });
    }).catch(e => { failed.add(w.id); layer.status = `national ${w.id} failed: ${e.message}`; })
      .finally(() => { inFlight.delete(w.id); pump(); });
  }

  function pump() {
    if (indexState !== 'ready') return;
    for (const w of wanted()) {
      const have = (w.type === 'square' ? squares : files).get(w.id);
      if (have) { have.used = ++clock; continue; }
      if (inFlight.size >= MAX_IN_FLIGHT) break;
      if (!inFlight.has(w.id) && !failed.has(w.id)) request(w);
    }
  }

  function evict() {
    const need = new Set(wanted().map(w => w.id));
    for (const [map, cap] of [[files, Math.max(MIN_CACHE, need.size + 16)], [squares, 8]]) {
      while (map.size > cap) {
        let oldest = null;
        for (const [k, v] of map) if (!need.has(k) && (!oldest || v.used < map.get(oldest).used)) oldest = k;
        if (!oldest) break;
        map.delete(oldest); stats.evicted.push(oldest);
      }
    }
  }

  function writeStatus(count) {
    const want = wanted().filter(w => w.type === 'tile'), have = want.filter(w => files.has(w.id)).length;
    const all = count.measured + count.fallback, pct = all ? Math.round(100 * count.measured / all) : 0;
    layer.status = `range ${(rangeM / MILE_M).toFixed(0)} miles; ${have}/${want.length} tiles loaded` +
      `${inFlight.size ? ` (${inFlight.size} loading)` : ''}; ${count.features} features; ${pct}% of points on measured ground,` +
      ` the rest at ${Number(centre.fallback).toFixed(1)} m, the ground under the viewer (not measured there);` +
      ' assumed: towers inferred from OpenStreetMap, tower shapes, sag, compound and marker sizes';
  }

  const layer = {
    id: 'national',
    status: 'waiting for init',
    init(a) {
      api = a;
      const mi = Number(a.config?.range_miles);
      if (RANGES_MI.includes(mi)) rangeM = mi * MILE_M;
      if (Array.isArray(a.config?.kinds)) kinds = new Set(a.config.kinds.filter(k => KINDS.includes(k))); // e.g. roads and rail only
      layer.status = 'ready to load'; loadIndex();
    },
    setRange(miles) {
      if (!RANGES_MI.includes(Number(miles))) throw Error(`range must be one of ${RANGES_MI.join(', ')} miles`);
      if (rangeM === Number(miles) * MILE_M) return rangeM;
      rangeM = Number(miles) * MILE_M; dataVersion++; pump(); api?.invalidate({ ground: false });
      return rangeM;
    },
    range: () => rangeM,
    setKinds(list) { kinds = new Set([...list].filter(k => KINDS.includes(k))); dataVersion++; pump(); api?.invalidate({ ground: false }); },
    lines(ctx) {
      if (!api) return [];
      if (indexState === 'idle') loadIndex();
      lastPos = ctx.pos;
      pump();
      const o = now(), t = clockMs(), gv = ctx.groundVersion ?? 0, key = `${o.id}|${dataVersion}|${rangeM}`;
      gvSeen = gvSeen.gv === gv ? { gv, frames: gvSeen.frames + 1 } : { gv, frames: 0 };
      const lib = api.lib?.overhead || null, at = [ctx.pos[0], ctx.pos[1]];
      const tiles = k => [...files.entries()].filter(([, f]) => k.includes(f.kind)).map(([id, f]) => ({ id, kind: f.kind, doc: f.doc }));
      const view = (k, band, c) => ({ x: c[0], y: c[1], r: rangeM, kinds: new Set(k), o, band });
      if (!next && !nextNear?.far && (centre.key !== key || !centre.at || Math.hypot(at[0] - centre.at[0], at[1] - centre.at[1]) > rebuildStep(rangeM))) {
        const fb = typeof ctx.heightAt === 'function' ? ctx.heightAt(at[0], at[1]) : 0;
        next = { key, at, fallback: Number.isFinite(fb) ? fb : 0, todo: [...kinds], batches: [], count: zero(), ms: 0 };
      }
      // One kind per frame, far band first, then the near band; both are swapped in together, so they always meet.
      let worked = false;
      if (next) {
        const k = next.todo.shift();
        if (k) {
          const g = buildNational(tiles([k]), view([k], 'far', next.at), { at: () => NaN, fallback: next.fallback }, lib);
          next.batches.push(...g.batches.map(b => ({ ...b, version: `${key}@f${t.toFixed(0)}` })));
          for (const c in g.count) next.count[c] += g.count[c];
          next.ms += clockMs() - t; worked = true;
        }
        if (!next.todo.length) { nextNear = startNear(next, gv, t, 'moved or data'); next = null; }
      } else if (!nextNear && centre.at && gv !== near.gv && gvSeen.frames >= GROUND_SETTLE_FRAMES && t - near.t > GROUND_REBUILD_MS) {
        nextNear = startNear(null, gv, t, 'ground');
      }
      if (nextNear && !worked) {
        const t0 = clockMs(), c = nextNear.far || { ...far, ...centre }, k = nextNear.todo.shift();
        if (memo.key !== o.id) memo = { key: o.id, map: new Map() }; // local positions change with the origin
        if (k) {
          const measured = typeof ctx.measuredAt === 'function' ? ctx.measuredAt : () => NaN;
          const g = buildNational(tiles([k]), view([k], 'near', c.at), { at: measured, fallback: c.fallback }, lib, memo.map);
          nextNear.batches.push(...g.batches.map(b => ({ ...b, version: `${key}@n${t.toFixed(0)}` })));
          nextNear.solids.push(...g.solids);
          for (const q in g.count) nextNear.count[q] += g.count[q];
          nextNear.ms += clockMs() - t0;
        }
        if (!nextNear.todo.length) {
          const n = nextNear;
          if (n.far) { centre = { key: n.far.key, at: n.far.at, fallback: n.far.fallback }; far = n.far; }
          near = { batches: n.batches, solids: n.solids, count: n.count, gv: n.gv, t: n.t };
          nextNear = null;
          stats.buildMs = n.ms + (n.far ? n.far.ms : 0);
          stats.builds = [...stats.builds.slice(-19), [Math.round(t), +stats.buildMs.toFixed(1), n.why]];
          all = near.batches.concat(far.batches);
          const count = zero();
          for (const q in count) count[q] = near.count[q] + far.count[q];
          writeStatus(count);
        }
      }
      return all;
    },
    solids() { return near.solids; },
    debug: () => ({ indexState, rangeM, kinds: [...kinds], files: [...files.keys()], squares: [...squares.keys()],
      inFlight: [...inFlight], failed: [...failed], ...stats, count: { near: near.count, far: far.count } })
  };
  return layer;
}

export default createNational();

Lift

A JavaScript module in the world folder of GlobalGrid2050. It is built from the hold step (`hold`) and the release step (`release`).

transformglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/lift.mjs · lines 1–22 of 22 · version 2026-09-27 01:45 · Entry point · pattern release (shared by 21 files)

What it does
It calculates its inputs. Defines attachLift, hold, release.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 4 files: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
Up and Down (drone): hold to climb or sink; a quick tap moves `TAP_M`, so a tap is never lost. It responds to pointerdown events.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by Substrate.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
none found
Used by
preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import)
Produces
TAP_MS, attachLift
Defines here
attachLift, hold, release
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270145-site-world-v3/world/lift.mjs:1-22 · blob d39afce89790a9f2e73a2a3e77b318fa2c341d2f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Up and Down (drone): hold to climb or sink; a quick tap moves TAP_M, so a tap is never lost.
export const TAP_MS = 250, TAP_M = 10;

// buttons: elements with data-lift="1" or "-1". setLift(dir): held climb rate (0 stops). tap(dir): one quick step.
export function attachLift(buttons, { setLift, tap, now = () => performance.now() }) {
  for (const b of buttons) {
    let down = 0;
    const hold = e => {
      e.preventDefault(); down = now();
      try { b.setPointerCapture(e.pointerId); } catch { /* synthetic or finished pointer */ }
      setLift(Number(b.dataset.lift));
    };
    const release = e => {
      if (!down) return;
      const quick = e.type === 'pointerup' && now() - down < TAP_MS;
      down = 0; setLift(0);
      if (quick) tap(Number(b.dataset.lift));
    };
    b.addEventListener('pointerdown', hold);
    for (const t of ['pointerup', 'pointercancel', 'pointerleave']) b.addEventListener(t, release);
  }
}

Overhead Line (OHL) Gs6

A JavaScript module in the world folder of GlobalGrid2050 that works with 132kV and overhead lines (OHL).

transformglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/ohl-gs6.mjs · lines 1–59 of 59 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review)

What it does
It calculates 132kV and overhead lines (OHL). Defines zoneDistance, exclusionFor.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 132kV, overhead lines (OHL), 400kV, 275kV, 66kV, 33kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV.
Downstream impact
Used directly by 3 files: Overhead Line (OHL) UI (globalgrid2050); Overhead Line (OHL) Zones (globalgrid2050); Overhead Line (OHL) UI (globalgrid2050).
What it achieves
It is built from the zone distance helper (`zoneDistance`) and the exclusion for helper (`exclusionFor`). Overhead line zones: the distances, each with where it comes from. Its code works with 132 kV, 275 kV and 33 kV.
Why it matters
Imported by Overhead Line (OHL) UI and Overhead Line (OHL) Zones.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Overhead Line (OHL) UI (import), imported by Overhead Line (OHL) Zones (import), imported by Overhead Line (OHL) UI (import)
Produces
GS6, GS6_4, GS6_3, DISCLAIMER, ACTION, ZONES, EXCLUSION, SWAY, POSITION_ALLOWANCE, GOALPOSTS, WORKING_HEIGHT, ITEM_HALF
Defines here
zoneDistance, exclusionFor
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270145-site-world-v3/world/ohl-gs6.mjs:1-59 · blob fe8341fd4fda1351903258d5e9868f8c1499a054 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Overhead line zones: the distances, each with where it comes from. Pure data, no DOM.
// Figures read from the public HSE documents on 27 September 2026 and cited by title, edition and paragraph only;
// no text is copied. Where a figure is this tool's own, it says so (kind 'assumed' or 'user').
//
// What the world draws from these (ohl-zones.mjs): measured on the ground, horizontally, from below the nearest
// conductor as drawn by the grid layer. Tower heights and sag are ASSUMED there, so every zone is illustrative.
// The zones are generous on purpose. They never show that a place is free of danger: only that it needs checking.

export const GS6 = 'HSE Guidance Note GS6, Avoiding danger from overhead power lines';
export const GS6_4 = `${GS6} (fourth edition, 2013)`;
export const GS6_3 = `${GS6.replace('Avoiding danger from', 'Avoidance of danger from')} electric power lines (third edition, 1997, withdrawn)`;

// The fixed on-screen line (owner's wording rule). The only sentence in the feature that may use the word it uses.
export const DISCLAIMER = 'Illustrative only. Not a safe system of work. Follow HSE GS6 and the network operator\'s instructions.';
// What every flag tells the reader to do.
export const ACTION = 'plan the work under GS6 with the network operator';

export const ZONES = Object.freeze({
  // Ground-level barriers: the safety zone on either side of the line, from the nearest wire. Same for poles and towers.
  barrier: { m: 6, kind: 'guidance', source: `${GS6_4}, paragraph 19` },
  // Work planned within this of the nearest wire (at ground level, horizontally) has risks to manage.
  planning: { m: 10, kind: 'guidance', source: `${GS6_4}, paragraph 11` },
  // The earlier edition's distances for high machinery, by support: kept as a generous floor for the zone, since the
  // current edition gives one planning distance for both. Wood poles 9 m; metal towers and structures 15 m.
  support: { pole: 9, tower: 15, kind: 'guidance', source: `${GS6_3}, paragraph 38` }
});

// Exclusion zones round the conductors for plant, by line voltage (the current edition quotes the ENA figures).
// 66 kV and 132 kV share the 132 kV figure here (the grid layer's classes), which is the larger of the two.
export const EXCLUSION = Object.freeze({
  byClass: { '33kV': 3, '132kV': 6, '275kV': 7, '400kV': 7 },
  kind: 'guidance', source: `${GS6_4}, paragraph 25 (the Energy Networks Association figures it quotes)`
});

// Conductor swing in wind: the current edition asks for the zone to allow for it (paragraph 19) and the earlier
// one names lateral swing on long spans (paragraph 15, note). No figure is given, so this tool supplies one:
// the conductor may swing out through SWING_DEG, so it moves sideways by sag x sin(SWING_DEG). ASSUMED.
export const SWAY = Object.freeze({ swingDeg: 45, minM: 1, kind: 'assumed',
  source: `${GS6_4}, paragraph 19; ${GS6_3}, paragraph 15: allowance asked for, figure assumed by this tool` });
// Uncertainty in where the conductors are: tower positions are inferred from open map data. ASSUMED.
export const POSITION_ALLOWANCE = Object.freeze({ m: 2, kind: 'assumed',
  source: `${GS6_4}, paragraph 25 (allow for uncertainty in measuring); figure assumed by this tool` });

// Goalpost crossing points where plant must pass under the line: through the barriers, one at each end.
export const GOALPOSTS = Object.freeze({ kind: 'guidance', source: `${GS6_4}, paragraphs 21 and 22` });

// The height of plant working on the design (piling rig mast, crane jib, tipper body). USER-SET: the default is a
// typical piling rig mast, not a figure from any source; the reader should enter the tallest plant on the job.
export const WORKING_HEIGHT = Object.freeze({ defaultM: 12, minM: 0, maxM: 80, kind: 'user',
  source: 'Set by the user: the tallest plant or load on the work (default a typical piling rig mast, assumed)' });

// Half-widths of design items (centreline to edge), metres, where the design does not give one. ASSUMED.
export const ITEM_HALF = Object.freeze({ trench: 0.5, cable: 0.5, road: 3, fence: 0.5, piles: 2.5, hdd: 1, pad: 0 });
// A pad drawn by its centre only: its footprint is taken as a disc of this radius. ASSUMED (a large skid pad).
export const PAD_RADIUS_M = 8;

// The zone distance (plan metres from the nearest conductor) for a line on a given support.
export const zoneDistance = support => Math.max(ZONES.planning.m, ZONES.support[support === 'pole' ? 'pole' : 'tower']);
export const exclusionFor = cls => EXCLUSION.byClass[cls] ?? Math.max(...Object.values(EXCLUSION.byClass));

Overhead Line (OHL) UI

A JavaScript module in the world folder of GlobalGrid2050 that creates OHL layer (`createOhlLayer`), mounts OHL control (`mountOhlControl`) and calculates planar distances, covering overhead lines (OHL).

Set aside from the main view: 90% of its lines are the same as solar-design-studio/202609271740-site-world/world/ohl-ui.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with Overhead Line (OHL) UI; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.904 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/ohl-ui.mjs:1-145 7559761c3b19e0f97a3a695141dc781a1b63277d
  • sha256 a7718312a66c847c556c3bd5c182fc7de3c2a07ac6f96c956aa361d2261d43ac
  • target sha256 9403571769c99bdf3b0ae396d921367812e86d65bbfeebb3b59be170d0aa42af
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/ohl-ui.mjs · lines 1–139 of 139 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern mountOhlControl (shared by 2 files)

What it does
It draws overhead lines (OHL). Defines 14 functions or classes, including readout, n, boqItems, get, goalpostLines. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: overhead lines (OHL).
Inputs & outputs
In: form fields (user input).
What it achieves
It creates OHL layer (`createOhlLayer`) and attaches OHL (`attachOhl`). Overhead line safety zones on the page: a layer that draws the zones on the ground from the grid layer's conductors, the design checks (`ohl-zones.mjs`), a short readout with the working height input, and the bill rows. It responds to change events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
Overhead Line (OHL) Zones (import), Overhead Line (OHL) Gs6 (import), Buffers (import)
Used by
mentioned in Standalone (comment link)
Produces
ID, COLORS, readout, boqItems, goalpostLines, createOhlLayer, mountOhlControl, attachOhl
Defines here
readout, n, boqItems, get, goalpostLines, g, P, createOhlLayer, refresh, lines, mountOhlControl, update, attachOhl, gridItem
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270145-site-world-v3/world/ohl-ui.mjs:1-139 · blob ebd09c6e561fafc5680731ebb61e1c1a69ac18c4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// Overhead line safety zones on the page: a layer that draws the zones on the ground from the grid layer's conductors,
// the design checks (ohl-zones.mjs), a short readout with the working height input, and the bill rows.
// Nothing is fetched: the conductors are the grid layer's own (layer.wires()), the design is the one in memory.
// A frame is drawn only when something changes (the substrate's frame gate): 0 fps when still.
import { buildSpans, zoneRings, checkDesign, designItems } from './ohl-zones.mjs';
import { DISCLAIMER, WORKING_HEIGHT, ZONES } from './ohl-gs6.mjs';
import { dashRing, drapePieces } from './layers/buffers.mjs';

export const ID = 'ohl-safety';
export const COLORS = { zone: [1.0, 0.62, 0.25, 0.85], barrier: [1.0, 0.38, 0.30, 0.9], flag: [1.0, 0.30, 0.30, 1], goalpost: [1.0, 1.0, 1.0, 0.95] };
const LIFT_M = 0.12, CROSS_M = 2, POST_M = 5, POST_HALF_M = 3; // marker sizes, metres (symbols, not designs)

// Pure: the readout line. No flag is never shown as a good sign: places without a flag are not assessed.
export function readout(spans, result, height) {
  if (!spans.length) return 'Overhead line zones: no overhead line conductors drawn near here yet.';
  const n = f => result.flags.filter(x => x.flag === f).length;
  const items = new Set(result.flags.filter(f => f.flag !== 'height').map(f => f.item)).size;
  const parts = [`Overhead line zones round ${spans.length} span${spans.length === 1 ? '' : 's'}`,
    items ? `${items} design item${items === 1 ? '' : 's'} inside a zone (${n('crosses')} crossing under)` : 'no design item flagged (not assessed beyond the zones)',
    result.goalposts.length ? `${result.goalposts.length / 2} goalpost crossing${result.goalposts.length === 2 ? '' : 's'} suggested` : '',
    height > 0 ? `plant ${height} m tall (user-set) reaches an exclusion distance at ${n('height')} item${n('height') === 1 ? '' : 's'}` : '',
    result.unmeasured ? `${result.unmeasured} points not assessed: no measured ground` : ''];
  return parts.filter(Boolean).join(' · ') + '.';
}

// Pure: the bill items: one per design item with any flag, counting its zone flags, height flags and goalposts.
export function boqItems(result) {
  const by = new Map();
  const get = id => { if (!by.has(id)) by.set(id, { id: `ohl-${id}`, kind: 'ohlZone', zone: 0, height: 0, goalposts: 0 }); return by.get(id); };
  for (const f of result.flags) get(f.item)[f.flag === 'height' ? 'height' : 'zone']++;
  for (const g of result.goalposts) get(g.item).goalposts++;
  return [...by.values()];
}

// Pure: goalpost marker at (x, y) across a road heading (dx, dy): two posts and a crossbar, xyz pairs relative to o.
export function goalpostLines(x, y, dx, dy, heightAt, o) {
  const L = Math.hypot(dx, dy) || 1, px = -dy / L * POST_HALF_M, py = dx / L * POST_HALF_M, out = [];
  const g = (a, b) => (Number.isFinite(heightAt(a, b)) ? heightAt(a, b) : o[2]);
  const P = (a, b, up) => [a - o[0], b - o[1], g(a, b) + up - o[2]];
  const A = [x + px, y + py], B = [x - px, y - py];
  out.push(...P(...A, 0), ...P(...A, POST_M), ...P(...B, 0), ...P(...B, POST_M), ...P(...A, POST_M), ...P(...B, POST_M));
  return out;
}

// deps: { grid() -> grid layer or null, gridShown() -> bool, design() snapshot, origin(), measuredAt, invalidate() }
export function createOhlLayer({ grid, gridShown = () => true, design, origin, measuredAt, invalidate = () => {} }) {
  let enabled = true, height = WORKING_HEIGHT.defaultM, spans = [], rings = [], result = { flags: [], goalposts: [], unmeasured: 0 };
  let wiresKey = '', checkKey = '', cache = { key: null, batches: [] }, version = 0;
  const layer = {
    id: ID, status: 'waiting for the grid layer', summary: DISCLAIMER,
    get enabled() { return enabled; },
    setEnabled(on) { enabled = !!on; invalidate(); return enabled; },
    setHeight(h) { const v = Number(h); if (Number.isFinite(v)) { height = Math.min(WORKING_HEIGHT.maxM, Math.max(WORKING_HEIGHT.minM, v)); refresh(); invalidate(); } return height; },
    height: () => height, result: () => result, spans: () => spans, boqItems: () => boqItems(result),
    refresh, lines, debug: () => ({ enabled, spans: spans.length, flags: result.flags.length, goalposts: result.goalposts.length, height })
  };
  // Rebuilds the zones when the grid's conductors change, and the checks when the design, ground or height changes.
  function refresh(groundVersion = 0) {
    const w = grid()?.wires?.(), o = origin();
    if (!w || !w.origin || w.origin.e !== o.e || w.origin.n !== o.n) { layer.status = 'waiting for the grid layer to draw'; return false; }
    if (w.version !== wiresKey) { spans = buildSpans(w.wires); rings = zoneRings(spans); wiresKey = w.version; checkKey = ''; version++; }
    const d = design(), key = `${wiresKey}|${height}|${groundVersion}|${JSON.stringify([d.trenches, d.cables, d.works])}`;
    if (key !== checkKey) {
      result = checkDesign(designItems(d, o), spans, measuredAt, { height });
      checkKey = key; version++;
    }
    layer.status = `${readout(spans, result, height)} Zone ${ZONES.planning.m} m or more from the nearest `
      + `conductor plus sway, barrier line ${ZONES.barrier.m} m plus sway (HSE GS6 paragraphs 11 and 19); tower heights and sag assumed`;
    return true;
  }
  function lines(ctx) {
    if (!enabled || !gridShown()) return [];
    refresh(ctx.groundVersion || 0);
    const key = `${version}@${ctx.groundVersion || 0}`;
    if (cache.key === key && cache.heightAt === ctx.heightAt) return cache.batches;
    const batches = [], h = ctx.heightAt, fin = (x, y) => (Number.isFinite(h(x, y)) ? h(x, y) : 0);
    for (const r of rings) for (const kind of ['zone', 'barrier']) {
      const pieces = r[kind].flatMap(ring => dashRing(ring, kind === 'zone' ? { dash: 4, gap: 2 } : { dash: 1.5, gap: 1.5 }));
      if (!pieces.length) continue;
      const [x, y] = r[kind][0][0], o = [x, y, fin(x, y)];
      batches.push({ key: `${ID}/${kind}/${r.line}`, version: key, origin: o, color: COLORS[kind], positions: drapePieces(pieces, h, LIFT_M, o) });
    }
    if (result.flags.length) {
      const c = CROSS_M / 2, pieces = result.flags.flatMap(({ at: [px, py] }) => [[px - c, py - c, px + c, py + c], [px - c, py + c, px + c, py - c]]);
      const [x, y] = result.flags[0].at, o = [x, y, fin(x, y)];
      batches.push({ key: `${ID}/flags`, version: key, origin: o, color: COLORS.flag, positions: drapePieces(pieces, h, LIFT_M * 2, o) });
    }
    if (result.goalposts.length) {
      const [x, y] = result.goalposts[0].at, o = [x, y, fin(x, y)], out = [];
      for (let i = 0; i + 1 < result.goalposts.length; i += 2) {
        const a = result.goalposts[i].at, b = result.goalposts[i + 1].at;
        out.push(...goalpostLines(a[0], a[1], b[0] - a[0], b[1] - a[1], h, o), ...goalpostLines(b[0], b[1], b[0] - a[0], b[1] - a[1], h, o));
      }
      batches.push({ key: `${ID}/goalposts`, version: key, origin: o, color: COLORS.goalpost, positions: new Float32Array(out) });
    }
    cache = { key, heightAt: h, batches };
    return batches;
  }
  return layer;
}

// The readout under the Layers panel: one line, the working height input and the fixed disclaimer.
export function mountOhlControl(host, layer) {
  if (!host || !layer) return null;
  const doc = host.ownerDocument || document, box = doc.createElement('fieldset');
  box.className = 'sun-time ohl-box';
  box.hidden = true;
  box.innerHTML = '<legend>Overhead line safety zones</legend>'
    + `<label>Working height, m (user-set: tallest plant or load) <input type="number" inputmode="decimal" min="${WORKING_HEIGHT.minM}" `
    + `max="${WORKING_HEIGHT.maxM}" step="0.5" data-ohl="height"></label>`
    + '<p class="note" aria-live="polite" data-ohl="readout"></p><p class="note" data-ohl="disclaimer"></p>';
  const input = box.querySelector('[data-ohl="height"]'), line = box.querySelector('[data-ohl="readout"]');
  box.querySelector('[data-ohl="disclaimer"]').textContent = DISCLAIMER;
  input.value = String(layer.height());
  input.addEventListener('change', () => { input.value = String(layer.setHeight(input.value)); update(); });
  const update = () => { line.textContent = readout(layer.spans(), layer.result(), layer.height()); };
  host.appendChild(box);
  update();
  return { element: box, show(v) { box.hidden = !v; if (v) update(); }, update };
}

// Page wiring, kept here so the substrate stays small. items: loadLayers(...).layers; the zones layer joins them before
// the Layers panel is drawn. Switching the grid on switches its zones on with it (they are on whenever the grid is).
// Returns { layer, onChange(ids, panel), mount(host, panel), update() }.
export function attachOhl(items, deps) {
  const gridItem = () => items.find(l => l.id === 'grid');
  const layer = createOhlLayer({ ...deps, grid: () => gridItem()?.layer || null, gridShown: () => !!gridItem()?.layer && !gridItem().hidden });
  items.push({ id: ID, layer, status: 'loaded, worked out on the page from the grid layer' });
  let gridWasOn = false, ui = null;
  return {
    layer,
    onChange(ids, panel) {
      if (ids.includes('grid') && !gridWasOn && !ids.includes(ID)) setTimeout(() => panel()?.set(ID, true));
      gridWasOn = ids.includes('grid'); ui?.show(ids.includes(ID));
    },
    mount(host, panel) { ui = mountOhlControl(host, layer); ui?.show(!!panel()?.isOn(ID)); },
    update: () => ui?.update()
  };
}