GLOBALGRID2050 / EXPLORE CODE

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

Design UI and 2 more files

A JavaScript module in the world folder of GlobalGrid2050 that converts to local pts (`toLocalPts`), shows readout (`showReadout`), converts to nearest substation (`toNearestSubstation`) and calculates planar distances (units: kV).

614 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 139 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. Design UI geodesy · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/design-ui.mjs lines 1–385
  2. Layers UI interaction · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/layers-ui.mjs lines 1–104
  3. MV Network ingest · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/mv-network.mjs lines 1–125

Design UI

A JavaScript module in the world folder of GlobalGrid2050 that converts to local pts (`toLocalPts`), shows readout (`showReadout`), converts to nearest substation (`toNearestSubstation`) and calculates planar distances (units: kV).

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

Evidence
  • line-jaccard 0.9388 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/design-ui.mjs:1-388 fc9622bb3d0234793332873b7975a0b836578f4a
  • sha256 aab1599f1055cd05b0a1b373e63aba48281896240f722c07d4b72be8d8a03e22
  • target sha256 2cd22eabd33e6c02eb28faa533e0b214377ccf1f6be6123418f426c3b5966319
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesyglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/design-ui.mjs · lines 1–385 of 385 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern toNearestSubstation (shared by 2 files)

What it does
It draws cables, trench sections, substations and solar. Defines 35 functions or classes, including createDesign, $, groundVersion, groundShare, section. Side effects: changes the web page (DOM); makes network requests.
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: cables, substations, solar.
Inputs & outputs
In: JSON file cables.json; JSON file trench-sections.json.
What it achieves
It creates design (`createDesign`), shows readout (`showReadout`) and shows results (`showResults`). Design tools in the world: Trench and Cable, drawn by clicking the ground. It responds to click, change and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
Origin (import), Pick (import), Route Tool (import), Trench (import), Cable Route (import), Measure (import), Measure Format (import), Design Earthworks (import), and 5 more
Used by
none found
Produces
createDesign
Defines here
createDesign, $, groundVersion, groundShare, section, cableSpec, toLocalPts, effOf, cableOf, build, heightAt, designItems, batch, marker, tightIndices, batches, nearFrom, gridRow, levelsAlong, measure, showReadout, showResults, finish, finishNow, choose, pickAt, add, toNearestSubstation, shift, schedule
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/202609270220-site-world-v3/world/design-ui.mjs:1-385 · blob 1c518ef6b0abe802fb7fdeb68247a450b2bf6316 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// Design tools in the world: Trench and Cable, drawn by clicking the ground. The substrate hands in the ground,
// the origin and the viewer; this module owns the design panel (world.html #design), the design held in memory
// and the lines it draws. Routes are kept in national-grid metres, so they survive every move of the origin.
// A trench cuts the ground (composeGround): walkers and the drone follow its floor. A cable is laid in trefoil
// on the floor of its own trench, with the governing installation bend radius for its size; bends tighter than
// that are flagged. Numbers come from measure.mjs, so the readout says what the panels and exports will say.

import { toBng, toLocal } from './origin.mjs';
import { rayFromScreen, pickGround } from './pick.mjs';
import { createRouteTool, describeControls } from './route-tool.mjs';
import { createTrench, composeGround, floorGround } from './trench.mjs';
import { routeCable } from './cable-route.mjs';
import { profile, cableSummary, bendRule, coverAchieved, DESIGN_DEFAULTS } from './measure.mjs';
import { formatNumber, formatLength, formatVolume, formatGradient } from './measure-format.mjs';
import { createEarthworks } from './design-earthworks.mjs';
import { BASIS } from './boq-assumptions.mjs';
import { sectionLabel, cableLabel, pressWord, designHint } from './labels.mjs';
import { groundShareOf, groundRowOf, drawProfile } from './design-ground.mjs';
import { snapPoint, connectionText, draftToNearest, measuredShare, snapRing, nearestSubstation, bearingDeg } from './snap.mjs';
import { createSections } from './design-sections.mjs';

const COLOUR = { draft: [1, 1, 1, 0.95], trench: [1, 0.78, 0.45, 1], cable: [0.55, 1, 0.62, 1], tight: [1, 0.36, 0.3, 1],
  snap: [0.45, 0.92, 1, 1] };
const WHEN = 'installation'; // the cable is being pulled in: the larger of the two radii governs the route

// deps: { doc, canvas, fov, baseHeight(x, y), origin(), viewer() -> state, invalidate({ ground }), redraw(), assets() }
// assets() -> [{ kind, e, n, kv }] grid equipment (snap.mjs) the cable snaps to and ends at (may be empty).
// measuredAt(x, y) -> measured ground or NaN: the readout says how much of a route stands on measured LiDAR.
// nearest(e, n) -> Promise<substation asset | null>: the nearest substation anywhere (the national index, read tile by
// tile). Without it the nearest of assets() is used. animate(): the solar block's build sequence started or stopped.
export function createDesign({ doc, canvas, fov, baseHeight, origin, viewer, invalidate, redraw, assets = () => [],
  measuredAt = null, onChange = () => {}, nearest = null, extraItems = () => [], animate = () => {} }) {
  const $ = id => doc.getElementById(id);
  const catalogue = { sections: [], cables: [], rules: [], json: null };
  // view: what the panel is showing. 'choose' a tool, 'draw' a route, or the 'result' of the one just finished.
  const design = { tool: null, trenches: [], cables: [], finished: 0, drafts: 0, last: null, view: 'choose' };
  const coarse = matchMedia('(pointer: coarse)').matches, press = pressWord(coarse);
  let built = { o: -1, g: -1, f: -1, key: '', ground: baseHeight, trenches: [], cables: [] };
  let groundVersion = () => 0;
  let snaps = []; // snaps[i]: the asset route point i sits on, if it snapped (kept in step with the route's points)
  const route = createRouteTool({ onChange: st => {
    snaps.length = Math.min(snaps.length, st.points.length); design.drafts++; if (st.points.length) design.view = 'draw';
    showReadout(); redraw();
  } });
  // Road, pad, fence, piles and drilled crossing; drum schedule and bill of quantities (design-earthworks.mjs).
  const works = createEarthworks({ doc, origin, baseHeight, groundVersion: () => groundVersion(), heightAt: (x, y) => heightAt(x, y),
    catalogue: () => catalogue, cables: () => build().cables.map(c => ({ route: c, spec: c.spec })), designItems, extraItems,
    groundRow: pts => groundRow(pts) });
  const groundShare = pts => groundShareOf(pts, measuredAt), groundRow = pts => groundRowOf(pts, measuredAt); // design-ground.mjs

  const section = id => catalogue.sections.find(s => s.id === id) || catalogue.sections[0];
  const cableSpec = id => catalogue.cables.find(c => c.id === id) || catalogue.cables[0];
  const toLocalPts = path => path.map(p => toLocal(origin(), p.e, p.n));
  // Specification, ground condition, plant layout and solar block (design-sections.mjs, each loaded when first opened).
  const extras = createSections({ doc, origin, viewer, measuredAt, heightAt: (x, y) => heightAt(x, y), baseHeight, assets, nearest,
    redraw, animate, onChange: () => showReadout() });
  const effOf = sectionId => extras.effOf(section(sectionId)); // the trench as it will be dug, in the chosen ground
  const trenchOf = (sectionId, pts, eff = effOf(sectionId)) => createTrench({ path: pts, width: eff.width, depth: eff.depth, benchSlope: eff.benchSlope });
  // Trefoil on the floor: the centreline is lifted so the lower two cores rest on it (on the bed, above any over-dig).
  const cableOf = (cableId, ground, pts, sectionId, overdig = 0) => {
    const spec = cableSpec(cableId), od = spec.od_mm / 1000;
    const bed = (Number(section(sectionId)?.bedding?.thickness_mm) || 0) / 1000 + overdig;
    const bend = bendRule(catalogue.json, { voltageKv: spec.voltage_kv, when: WHEN, odMm: spec.od_mm });
    // The bend rule applies at the cable's inner edge, so the centreline bends at rule + OD/2.
    const r = routeCable({ points: pts, minBendRadius: (bend.radius || 0) + od / 2,
      depthBelowGround: -(bed + od / 2 + od / (2 * Math.sqrt(3))), groundAt: ground, formation: 'trefoil', spacing: od, step: 0.5 });
    return Object.assign(r, { spec, bend, summary: cableSummary(r, { cables: catalogue.json, cableId: spec.id, when: WHEN }) });
  };

  // Local geometry, rebuilt only when the origin, the ground or the finished design changes (plain number checks:
  // heightAt runs this for every height anyone asks for).
  function build() {
    const o = origin(), g = groundVersion(), w = works.version(), bk = extras.key();
    if (built.o === o.id && built.g === g && built.f === design.finished && built.w === w && built.bk === bk) return built;
    const all = [...design.trenches, ...design.cables], under = works.ground(baseHeight); // roads and pads first
    const extra = extras.extra(toLocalPts); // the solar block's open trenches, after the drawn ones
    const trenches = [...all.map(t => trenchOf(t.section, toLocalPts(t.path), t.eff)), ...extra.trenches];
    const ground = trenches.length ? composeGround(under, trenches) : under;
    const sections = [...all.map(t => extras.cross(section(t.section), t.eff || effOf(t.section), t.cable ? cableSpec(t.cable).od_mm : null)),
      ...extra.sections];
    built = { o: o.id, g, w, f: design.finished, bk, key: `${o.id}:${g}:${w}:${design.finished}:${bk}`, ground, trenches, sections, cables: [],
      near: {}, walls: [] };
    // Each cable lies on its own trench's floor (the trench it was drawn with), not on the composed ground.
    const n = design.trenches.length;
    built.cables = design.cables.map((c, i) => cableOf(c.cable, floorGround(trenches[n + i], under), toLocalPts(c.path), c.section, c.eff?.overdig));
    return built;
  }
  const heightAt = (x, y) => build().ground(x, y);
  // Trenches and cables as the bill of quantities reads them (boq.mjs); every cable lies in its own trench.
  function designItems() {
    const b = build(), n = design.trenches.length;
    return [...design.trenches, ...design.cables].flatMap((t, i) => {
      const id = i < n ? `trench-${i + 1}` : `cable-${i - n + 1}`;
      // Spoil from the trench as rebuilt on the ground of now (cached per build), not the figure kept at Finish.
      const spoil = (b.spoil ||= [])[i] ??= b.trenches[i].spoilVolumeOn(baseHeight);
      const trench = { id, kind: 'trench', sectionId: t.section, results: { length3d: b.trenches[i].length3dOn(baseHeight), spoil } };
      // The trench cut for a cable is billed with it (spoil, bedding, tile), never left out.
      // A two-circuit section carries two trefoils: the bill counts both (code review 3); the drawing shows one route.
      return i < n ? [trench] : [{ id: `${id}-cable`, kind: 'cable', cableId: t.cable, circuits: section(t.section).circuits || 1, results: b.cables[i - n],
        trench: { sectionId: trench.sectionId, results: trench.results } }];
    });
  }

  // Positions relative to their first point, worked out in doubles, so far-out lines stay sharp on the GPU.
  function batch(key, version, pos, color) {
    if (!pos || pos.length < 6) return null;
    const o = [pos[0], pos[1], pos[2]], out = new Float32Array(pos.length);
    for (let i = 0; i < pos.length; i++) out[i] = pos[i] - o[i % 3];
    return { key, version, positions: out, color, origin: o };
  }
  const marker = (v, [x, y, z], h, arm) => v.push(x, y, z, x, y, z + h, x - arm, y, z + h, x + arm, y, z + h, x, y - arm, z + h, x, y + arm, z + h);
  const tightIndices = c => [...new Set([...c.violations.map(v => v.index), ...c.summary.below.map(b => b.index)])].sort((a, b) => a - b);

  function batches() {
    const b = build(), out = [];
    b.trenches.forEach((t, i) => out.push(batch('design-trench-' + i, b.key, b.walls[i] ||= t.wallLines(baseHeight), COLOUR.trench)));
    out.push(...extras.detail(b, batch)); // cross-sections near the viewer; cables drawn at their outside diameter
    b.cables.forEach((c, i) => {
      const tight = [], pts = toLocalPts(design.cables[i].path);
      for (const k of tightIndices(c)) { const [x, y] = pts[k]; marker(tight, [x, y, heightAt(x, y)], 3, 1.2); }
      out.push(batch('design-tight-' + i, b.key, tight, COLOUR.tight));
    });
    const d = route.state.points, v = [];
    for (let i = 0; i < d.length; i++) {
      const [x, y] = d[i], z = heightAt(x, y) + 0.05;
      if (i) { const [px, py] = d[i - 1]; v.push(px, py, heightAt(px, py) + 0.05, x, y, z); }
      marker(v, [x, y, z], 1.5, 0.4);
    }
    out.push(batch('design-draft', `${b.key}:${design.drafts}`, v, COLOUR.draft), ...works.batches());
    const rings = [];
    d.forEach(([x, y], i) => { if (snaps[i]) rings.push(...snapRing([x, y, heightAt(x, y)])); });
    out.push(batch('design-snap', `${b.key}:${design.drafts}`, rings, COLOUR.snap), ...extras.batches());
    return out.filter(Boolean);
  }

  // ---- readout ----------------------------------------------------------------------------------------
  // Where the route meets the grid: the substation it ends at, else the nearest substation's distance and bearing.
  // The nearest substation is looked up once per end point; while it is being read the row says so, and the row is
  // filled in (live or finished readout alike) when the answer lands.
  const nearCache = new Map(), waiting = [];
  function nearFrom(end) {
    if (!nearest) return nearestSubstation(end, assets());
    const k = `${Math.round(end.e)},${Math.round(end.n)}`;
    if (nearCache.has(k)) return nearCache.get(k);
    if (nearCache.size > 500) nearCache.clear();
    nearCache.set(k, 'pending');
    Promise.resolve().then(() => nearest(end.e, end.n)).catch(() => null).then(a => {
      nearCache.set(k, a ? { asset: a, d: Math.hypot(a.e - end.e, a.n - end.n), bearing: bearingDeg(end, a) } : null);
      for (const w of waiting.splice(0).filter(w => { if (w.k !== k) waiting.push(w); return w.k === k; })) {
        w.row[1] = connectionText(nearCache.get(k), w.endAsset);
      }
      showReadout();
    });
    return 'pending';
  }
  function gridRow(pts, endAsset) {
    const [x, y] = pts[pts.length - 1], end = toBng(origin(), x, y);
    const row = ['Grid connection', ''];
    const near = endAsset?.kind === 'substation' ? null : nearFrom(end);
    row[1] = connectionText(near, endAsset);
    if (near === 'pending') waiting.push({ k: `${Math.round(end.e)},${Math.round(end.n)}`, row, endAsset });
    return row;
  }
  // Ground for the profile, walked in route order: measured LiDAR where there is some; past its edge the last
  // measured level is held, so the edge of the data never shows up as a cliff in the gradient.
  function levelsAlong() {
    if (!measuredAt) return baseHeight;
    let last = NaN;
    return (x, y) => { const h = measuredAt(x, y); if (Number.isFinite(h)) last = h; return Number.isFinite(last) ? last : baseHeight(x, y); };
  }
  // Rows for the readout and the level profile. spoil: undefined = not yet worked out.
  function measure(kind, sectionId, cableId, pts, spoil, endAsset = null, eff = effOf(sectionId)) {
    const s = section(sectionId), t = trenchOf(s.id, pts, eff);
    const rows = [['Trench', `${sectionLabel(s)} · ${formatNumber(eff.width, 2)} m floor × ${formatNumber(eff.depth, 2)} m deep`]];
    let plan = pts, odMm = null;
    if (kind === 'cable') {
      const c = cableOf(cableId, heightAt, pts, sectionId, eff.overdig), cs = c.summary, tight = tightIndices(c);
      odMm = c.spec.od_mm;
      plan = c.centreline.map(p => [p[0], p[1]]);
      rows.unshift(['Cable', cableLabel(c.spec)]);
      rows.push(['Minimum bend radius', cs.required.radius == null ? `no ${WHEN} rule for this cable`
        : `${formatNumber(cs.required.radius, 2)} m (${formatNumber(cs.required.multiple, 0)} × OD, ${WHEN})`],
      ['Cable length (plan)', formatLength(cs.length2d)], ['Cable length (3D)', formatLength(cs.length3d)],
      ['Tight bends', tight.length ? `${tight.length} (at point${tight.length > 1 ? 's' : ''} ${tight.map(k => k + 1).join(', ')})` : 'none']);
    }
    const cv = coverAchieved(s, odMm);
    rows.splice(kind === 'cable' ? 2 : 1, 0,
      ['Cover', `${formatNumber(cv.cover, 2)} m to the top of the ${s.duct_od_mm ? 'duct' : 'cable'} · section minimum ${formatNumber(cv.required, 2)} m`
        + (cv.ok ? '' : ' · too shallow: choose a deeper section'), !cv.ok],
      ['Section basis', `${s.status}: ${s.source}`, s.status !== 'verified'], ...extras.rows(eff));
    const p = profile(levelsAlong(), plan, 1);
    rows.push(['Trench length (plan)', formatLength(t.length2d)], ['Trench length (3D)', formatLength(t.length3dOn(baseHeight))],
      ['Spoil volume', spoil === undefined ? 'on finish' : spoil === null ? 'working out…' : `${formatVolume(spoil, 2)} (${BASIS.spoil})`], ...extras.spoilRows(spoil, eff),
      ['Ground level', groundShare(pts).none ? 'not measured (no LiDAR here)' : `${formatNumber(p.min, 2)} to ${formatNumber(p.max, 2)} ${BASIS.datum}`],
      groundRow(pts), ['Steepest gradient', groundShare(pts).none ? 'not measured' : formatGradient(p.gradient.max)],
      gridRow(pts, endAsset));
    if (measuredAt) {
      const m = measuredShare(pts, measuredAt);
      if (m.known < m.total - 0.5) rows.push(['Measured ground', `${formatLength(m.known)} of ${formatLength(m.total)}`
        + ' on measured LiDAR; beyond it levels are held flat, not measured']);
    }
    if (design.drafted) rows.push(['Route', 'straight-line first draft to the substation; edit it (Undo removes the last leg)']);
    return { rows, profile: p, depth: eff.depth };
  }
  function showReadout() {
    const pts = route.state.points.map(p => [p[0], p[1]]);
    if (!design.tool && design.view === 'draw') design.view = 'choose';
    // One line that says what to do next, and which parts of the panel show (world.html styles #design[data-state]).
    $('design').dataset.state = design.view;
    $('design-hint').textContent = designHint(design.tool, design.view, pts.length, press);
    let m = design.last || { rows: [['Status', design.tool ? `${press.toLowerCase()} the ground to start a ${design.tool}` : 'choose a design tool']] };
    if (works.handles(design.tool) && (pts.length || ![design.tool, 'schedule'].includes(design.last?.kind))) m = works.measure(design.tool, pts);
    else if (works.handles(design.tool)) m = design.last;
    else if (design.tool === 'boundary') m = { rows: [['Status', `${pts.length} corner${pts.length === 1 ? '' : 's'} · Done closes the boundary`]] };
    else if (design.tool && pts.length >= 2) {
      try { m = measure(design.tool, $('trench-section').value, $('cable-type').value, pts, undefined, snaps[pts.length - 1]); }
      catch (e) { m = { rows: [['Status', e.message]] }; }
    } else if (design.tool && pts.length === 1) m = { rows: [['Status', '1 point · add another']] };
    $('design-readout').replaceChildren(...m.rows.flatMap(([k, v, warn]) => {
      const dt = doc.createElement('dt'), dd = doc.createElement('dd');
      dt.textContent = k; dd.textContent = v;
      if ((k === 'Tight bends' && v !== 'none') || warn) dd.className = 'warn';
      return [dt, dd];
    }));
    drawProfile(doc, m.profile ? m : null);
    const toSub = $('design-to-substation');
    if (toSub) toSub.disabled = design.tool !== 'cable' || !pts.length || snaps[pts.length - 1]?.kind === 'substation';
  }

  // ---- actions ----------------------------------------------------------------------------------------
  // The results of a Finish are brought into view in the Design sheet (on a phone they sat below its fold).
  const showResults = () => $('design-readout')?.scrollIntoView?.({ block: 'start', behavior: 'smooth' });
  function finish() {
    const done = finishNow();
    if (done) showResults();
    return done;
  }
  function finishNow() {
    const pts = route.state.points, kind = design.tool;
    if (works.handles(kind)) {
      const r = works.finish(kind, pts.map(p => [p[0], p[1]]));
      if (!r) return false;
      design.last = r;
      if (r.done) { design.view = 'result'; route.clear(); invalidate({ ground: true }); onChange(); } // roads and pads are new ground
      showReadout();
      return true;
    }
    if (!kind || !route.finish()) return false;
    if (kind === 'boundary') { // the plant boundary (Plant layout), not a trench
      extras.setBoundary(pts.map(([x, y]) => toBng(origin(), x, y))).then(ok => { if (ok) choose('boundary'); redraw(); });
      route.clear(); return true;
    }
    const o = origin(), path = pts.map(([x, y]) => toBng(o, x, y)), plan = pts.map(p => [p[0], p[1]]);
    const endAsset = snaps[pts.length - 1] || null;
    const item = { path, section: $('trench-section').value, ...(kind === 'cable' ? { cable: $('cable-type').value } : {}),
      ...(endAsset ? { ends_at: { kind: endAsset.kind, e: endAsset.e, n: endAsset.n, kv: endAsset.kv ?? null } } : {}) };
    item.eff = effOf(item.section); item.ground = extras.snapshot().options.ground; item.spec = item.eff.specLabel;
    (kind === 'trench' ? design.trenches : design.cables).push(item);
    design.finished++;
    design.lastItem = { key: design.finished, kind, path: path.map(p => [p.e, p.n]) };
    const last = measure(kind, item.section, item.cable, plan, null, endAsset, item.eff); // measured on the ground it has just cut
    design.last = last; design.drafted = false; design.view = 'result';
    route.clear();
    invalidate({ ground: true }); // new ground: walkers and the drone follow the trench floor
    onChange();
    // Spoil is a fine grid over the whole trench; work it out after the frame, then say it.
    setTimeout(() => {
      const spoil = trenchOf(item.section, plan, item.eff).spoilVolumeOn(baseHeight);
      item.spoil_m3 = spoil;
      if (design.last === last) { design.last = measure(kind, item.section, item.cable, plan, spoil, endAsset, item.eff); showReadout(); }
    }, 0);
    return true;
  }
  function choose(tool) {
    design.tool = design.tool === tool ? null : tool;
    works.choose(design.tool);
    design.drafted = false; design.view = design.tool ? 'draw' : 'choose';
    route.clear();
    for (const b of doc.querySelectorAll('[data-tool]')) b.setAttribute('aria-pressed', String(b.dataset.tool === design.tool));
    showReadout();
  }
  function pickAt(x, y) {
    if (!design.tool) return false;
    const s = viewer();
    const ray = rayFromScreen(x, y, canvas.clientWidth, canvas.clientHeight, s.pos, s.yaw, s.pitch, fov);
    const p = pickGround(ray, heightAt, { maxDistance: 3000 });
    if (!p) return false;
    const snap = design.tool === 'cable' ? snapPoint(p, assets(), origin()) : null;
    return add(snap ? [snap.x, snap.y, heightAt(snap.x, snap.y)] : p, snap?.asset);
  }
  function add(p, asset = null) {
    const n = route.state.points.length;
    snaps[n] = asset; // set first: addPoint redraws the readout
    if (route.addPoint(p)) return true;
    snaps.length = n;
    return false;
  }
  // 'Route to nearest substation': a straight first draft from the last point, ending on the substation.
  // Async: the national index may need a tile read first. Resolves true when the draft point was added.
  async function toNearestSubstation() {
    const pts = route.state.points;
    if (design.tool !== 'cable' || !pts.length) return false;
    const last = pts[pts.length - 1], end = toBng(origin(), last[0], last[1]), n = pts.length;
    const asset = nearest ? await nearest(end.e, end.n).catch(() => null) : nearestSubstation(end, assets())?.asset;
    if (route.state.points.length !== n || route.state.finished) return false; // the route changed meanwhile
    const t = draftToNearest(route.state.points[n - 1], asset, origin());
    if (!t) return false;
    design.drafted = true;
    return add([t.x, t.y, heightAt(t.x, t.y)], t.asset);
  }
  // The origin moved by (dx, dy): the route being drawn moves the other way, so it stays put in the world.
  const shift = (dx, dy) => route.state.points.forEach((p, i) => route.movePoint(i, [p[0] - dx, p[1] - dy, p[2]]));

  // ---- page wiring ------------------------------------------------------------------------------------
  for (const b of doc.querySelectorAll('[data-tool]')) b.addEventListener('click', () => { choose(b.dataset.tool); canvas.focus(); });
  $('design-undo').addEventListener('click', () => { design.drafted = false; route.removeLast(); });
  $('design-finish').addEventListener('click', () => finish());
  $('design-clear').addEventListener('click', () => { design.drafted = false; route.clear(); });
  $('design-to-substation')?.addEventListener('click', () => { toNearestSubstation(); canvas.focus(); });
  const schedule = fn => { design.last = { ...fn(), kind: 'schedule' }; if (!design.tool) design.view = 'result'; showReadout(); redraw(); };
  $('design-drums')?.addEventListener('click', () => schedule(works.drumSchedule));
  $('design-boq')?.addEventListener('click', () => schedule(works.billOfQuantities));
  $('works-option')?.addEventListener('change', () => { showReadout(); canvas.focus(); });
  // Section and cable choices sit behind Options; on a phone, choosing one folds them away again so the ground stays clear.
  const options = open => { $('design-options').hidden = !open; $('design-options-toggle').setAttribute('aria-expanded', String(open)); };
  $('design-options-toggle').addEventListener('click', () => options($('design-options').hidden));
  for (const id of ['trench-section', 'cable-type']) $(id).addEventListener('change', () => { if (coarse) options(false); showReadout(); canvas.focus(); });
  addEventListener('keydown', e => {
    if (!design.tool || e.ctrlKey || e.metaKey || e.altKey) return;
    if (['SELECT', 'INPUT', 'TEXTAREA', 'BUTTON'].includes(e.target?.tagName)) return;
    if (e.code === 'Backspace') { design.drafted = false; route.removeLast(); e.preventDefault(); }
    else if (e.code === 'Enter' || e.code === 'NumpadEnter') { finish(); e.preventDefault(); }
    else if (e.code === 'Escape') { design.drafted = false; route.clear(); }
  });
  $('design-keys').className = coarse ? 'touch' : 'keys';
  $('design-keys').replaceChildren(...describeControls({ touch: coarse }).flatMap(([k, v]) => {
    const dt = doc.createElement('dt'), dd = doc.createElement('dd');
    dt.textContent = k; dd.textContent = v; return [dt, dd];
  }));

  async function loadCatalogue() {
    try {
      const get = async p => { const r = await fetch(p, { cache: 'no-cache' }); if (!r.ok) throw Error(`${p}: HTTP ${r.status}`); return r.json(); };
      const [cables, trenches] = await Promise.all([get('./world/data/cables.json'), get('./world/data/trench-sections.json')]);
      Object.assign(catalogue, { sections: trenches.sections || [], cables: cables.cables || [], rules: cables.rules || [], json: cables });
      const fill = (id, items, label, chosen) => $(id).replaceChildren(...items.map(it => {
        const o = new Option(label(it), it.id); o.selected = it.id === chosen; return o;
      }));
      fill('trench-section', catalogue.sections, s => `${sectionLabel(s)} · ${s.trench_width_m} × ${s.trench_depth_m} m`, DESIGN_DEFAULTS.section);
      fill('cable-type', catalogue.cables, cableLabel, DESIGN_DEFAULTS.cable);
    } catch (e) {
      for (const b of doc.querySelectorAll('[data-tool]')) b.disabled = true;
      design.last = { rows: [['Status', 'design data could not be loaded: ' + e.message]] };
    }
    showReadout();
  }

  return {
    heightAt, batches, pickAt, shift, finish, loadCatalogue, toNearestSubstation,
    animating: extras.animating, plantApi: extras.plantApi, blockApi: extras.blockApi, // Plant layout and Solar block
    setGroundVersion: fn => { groundVersion = fn; },
    // The last finished trench or cable: { key, kind, path: [[e, n], ...] } in national-grid metres, or null.
    lastFinished: () => design.lastItem || null,
    putDown: () => { if (design.tool) choose(design.tool); },
    drawing: () => !!design.tool,
    // Replaces the whole design (open a file or a link, undo, redo). Paths are national-grid metres.
    // Items that cannot be built (under two points, unknown section or cable) are left out, so one bad file or
    // link never stops the world drawing (review, code finding 1).
    replace({ trenches = [], cables = [], works: earthworks = [] } = {}) {
      route.clear();
      works.replace(earthworks);
      const ok = t => { try { trenchOf(t.section, toLocalPts(t.path)); if (t.cable !== undefined) cableSpec(t.cable); return true; } catch { return false; } };
      Object.assign(design, { trenches: trenches.filter(ok).map(t => ({ ...t })), cables: cables.filter(ok).map(c => ({ ...c })),
        last: null, lastItem: null });
      design.finished++;
      showReadout();
      invalidate({ ground: true });
    },
    // The design in memory, in national-grid metres (export and import come later).
    snapshot: () => JSON.parse(JSON.stringify({ tool: design.tool, trenches: design.trenches, cables: design.cables, works: works.snapshot(),
      draft: route.state.points.map(([x, y]) => toBng(origin(), x, y)),
      snaps: route.state.points.map((_, i) => (snaps[i] ? { kind: snaps[i].kind, e: snaps[i].e, n: snaps[i].n } : null)),
      readout: design.last?.rows || null, ...extras.snapshot() }))
  };
}

Layers UI

A JavaScript module in the world folder of GlobalGrid2050 that reads overhead lines (OHL). It writes footer (`writeFooter`), fits footer (`fitFooter`) and shows range (`showRange`).

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

Evidence
  • line-jaccard 0.9659 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/layers-ui.mjs:1-105 35bda640fd88d5820b00a1eb7525c440b929c5a0
  • sha256 ee7a1fdbaaa4097b07814e1278950d0a5065222a3a8853c23e1dd851fdb0785f
  • target sha256 d8db273314e43f03c27b749df3baf944e67f0f74907a9fe112cd9f441e43a749
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/layers-ui.mjs · lines 1–104 of 104 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern mountLayersUi (shared by 2 files)

What it does
It loads overhead lines (OHL). Defines 8 functions or classes, including panelLayers, footerFor, applyOn, mountLayersUi, writeFooter. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
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).
What it achieves
Page wiring for the Layers panel. It responds to resize and close events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Layers Panel (import), Layers (import), Attribution (import), Range UI (import), Fade (import)
Used by
none found
Produces
DEFAULT_ON, panelLayers, footerFor, applyOn, mountLayersUi
Defines here
panelLayers, footerFor, applyOn, mountLayersUi, writeFooter, fitFooter, showRange, 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 solar-design-studio/202609270220-site-world-v3/world/layers-ui.mjs:1-104 · blob e1f02a8eb87b7edba04795ece707605b30da2601 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// Page wiring for the Layers panel. The panel sits inside the Controls panel (no dash button of its own).
// Switching a layer on calls its setEnabled(true) when it has one and lets the substrate draw it; switching it off
// hides it (item.hidden, which the substrate skips). The footer credits exactly the data on screen: every loaded
// base layer plus the optional layers switched on (layers-panel.mjs sourceKeysFor, attribution.mjs footerText).
import { OPTIONAL_LAYERS, START_OFF, createLayersPanel, shownIds, sourceKeysFor } from './layers-panel.mjs';
import { REFUSED } from './layers.mjs';
import { footerText, aboutList } from './attribution.mjs';
import { mountRange } from './range-ui.mjs';
import { MILE_M } from './fade.mjs';

const OPTIONAL = new Set(OPTIONAL_LAYERS.map(l => l.id));
export const DEFAULT_ON = Object.freeze(['grid', 'ohl-safety']); // the grid network and its overhead line zones show from the start

// The loader's items as the panel reads them: a loaded layer's own status line follows the hash check.
export function panelLayers(items) {
  return (items || []).map(it => {
    const own = it.layer && typeof it.layer.status === 'string' && it.layer.status ? it.layer.status : '';
    const loaded = !!it.layer && String(it.status).startsWith('loaded');
    const status = loaded && own ? (REFUSED.test(own) ? `${String(it.status).replace(/,? hash matches/, '')}; ${own}` : `${it.status}; ${own}`) : String(it.status);
    // The public words: the layer's own short summary if it gives one, else a plain word (the details stay in status).
    const short = /^ready/.test(String(it.status)) ? 'Off: loads when switched on.' : !loaded ? 'Not available here.' : own && REFUSED.test(own) ? 'Not available here: its data was refused.'
      : typeof it.layer?.summary === 'string' && it.layer.summary ? it.layer.summary : 'On.';
    return { id: it.id, status, short };
  });
}

// { full, short } footer text for the ids on screen.
export function footerFor(items, on, attribution, year) {
  const keys = sourceKeysFor(shownIds(panelLayers(items), on));
  const byLine = new Map(); // sources that share one required line (OS Open Rivers and Roads) are credited once
  for (const a of aboutList(keys, attribution, { year })) {
    const k = `${a.line} · ${a.licence_name}`;
    byLine.set(k, [...(byLine.get(k) || []), a.name]);
  }
  const full = [...byLine].map(([k, names]) => `${names.join(', ')}: ${k}`).join(' · ');
  return { full, short: footerText(keys, attribution, { year }) };
}

// Marks each optional item hidden unless it is on, and tells layers that load on demand.
export function applyOn(items, on) {
  const set = new Set(on);
  for (const it of items || []) {
    if (!OPTIONAL.has(it.id)) continue;
    const want = set.has(it.id);
    it.hidden = !want;
    if (want && !it.layer && typeof it.load === 'function') { it.load(); continue; } // first switch-on: fetch, check, start
    if (it.layer && typeof it.layer.setEnabled === 'function' && !!it.layer.enabled !== want) {
      try { it.layer.setEnabled(want); } catch (e) { it.layer = null; it.status = 'failed to switch and switched off: ' + e.message; }
    }
  }
}

// items: loadLayers(...).layers (live objects). host: element the panel goes in. footer: the #attribution element.
// Returns { panel, refresh() } or null when there is nothing to host it.
// onChange(ids) is called with the ids switched on, at start and after every change (e.g. to show the sun control).
export function mountLayersUi({ items, host, footer, attribution, invalidate = () => {}, on = DEFAULT_ON, year, onChange = () => {} } = {}) {
  if (!host) return null;
  const start = on.filter(id => !START_OFF.includes(id)).filter(id => panelLayers(items).some(l => l.id === id && l.status.startsWith('loaded')));
  applyOn(items, start);
  const writeFooter = ids => {
    if (!footer || !attribution) return;
    const f = footerFor(items, ids, attribution, year), full = footer.querySelector('.full'), short = footer.querySelector('.short');
    if (full) full.textContent = f.full; if (short) short.textContent = f.short;
    footer.title = f.full;
    fitFooter();
  };
  // On a phone the footer wraps to as many lines as the credit needs (world.html, max-width 600px); --foot-fit tells
  // everything placed above the footer how tall it came out, so no credit line is cut off.
  const fitFooter = () => {
    const h = footer?.scrollHeight, root = footer?.ownerDocument?.documentElement;
    if (Number.isFinite(h) && h > 0 && root?.style?.setProperty) root.style.setProperty('--foot-fit', `${h}px`);
  };
  if (footer && typeof globalThis.addEventListener === 'function') globalThis.addEventListener('resize', fitFooter);
  const panel = createLayersPanel(host, {
    layers: panelLayers(items), attribution, on: start, year,
    onToggle: (_id, _on, ids) => { applyOn(items, ids); writeFooter(ids); showRange(ids); onChange(ids); invalidate(); }
  });
  panel.element.classList.add('in-help');
  // Range (2, 5 or 10 miles) for the wider-area roads and rail, shown under the panel while that layer is on.
  let store = null;
  try { store = globalThis.localStorage || null; } catch { /* no storage */ }
  let range = null;
  try {
    range = mountRange(host, { store, coarse: !!globalThis.matchMedia?.('(pointer: coarse)').matches,
      layer: () => (items || []).find(it => it.id === 'national')?.layer || null, onChange: () => invalidate() });
  } catch { /* no document to draw it in (tests) */ }
  const showRange = ids => range?.show(ids.includes('national'));
  panel.element.addEventListener('close', () => { panel.element.hidden = false; }); // Escape closes Controls, not this part of it
  writeFooter(panel.onIds());
  showRange(panel.onIds());
  onChange(panel.onIds());
  let last = '';
  const refresh = () => { // statuses change as data streams in; redraw the panel only when they do
    if (panel.isOn('national')) range?.apply(); // the layer loads after its first switch-on, at its own start range
    const now = panelLayers(items), key = JSON.stringify(now);
    if (key === last) return;
    last = key;
    panel.update(now);
    applyOn(items, panel.onIds());
    writeFooter(panel.onIds());
  };
  // The wider-area range in metres while that layer is on (the drone's fade reaches it), else 0.
  return { panel, refresh, range, rangeM: () => (range && panel.isOn('national') ? range.miles() * MILE_M : 0) };
}

MV Network

A JavaScript module in the world folder of GlobalGrid2050 that reads routes (`readRoutes`) (units: kV, MVA), covering cables and transformers. It reads routes (`readRoutes`) and places network (`placeNetwork`).

Set aside from the main view: 98% of its lines are the same as energy-transition-simulator/202609280014/mod/engine/mv-network.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with MV Network; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9789 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/mv-network.mjs:1-127 e9f525f9bb51d517a255234dec1d9233f900b117
  • sha256 085d3631940cb73819659f7665d3b3a29cc1400ac953bc4fd2146ba777bcafff
  • target sha256 498ed85b4f48de07de1a77aaf147082813f17aa4a6a6c35874c59c47228fec4a
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/mv-network.mjs · lines 1–125 of 125 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern drawingToGround (shared by 3 files)

What it does
Defines 9 functions or classes, including equipmentSolids, box, solidLines, readRoutes, pt.
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: cables, transformers.
Downstream impact
Used directly by 5 files: Block Build (globalgrid2050); Design Options (globalgrid2050); Plant UI (globalgrid2050); Block Build (globalgrid2050); and 1 more.
What it achieves
The medium-voltage network from the stations to the grid, as equipment outlines with solids and cable routes, placed on the ground by the user.
Why it matters
Imported by 5 files, including Block Build, Design Options and Plant UI.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Station (import), Plant Template (import)
Used by
imported by Block Build (import), imported by Design Options (import), imported by Plant UI (import), imported by Block Build (import), imported by Plant UI (import)
Produces
ROUTES_SCHEMA, EQUIPMENT, equipmentSolids, solidLines, readRoutes, drawingToGround, placeNetwork, cableLines
Defines here
equipmentSolids, box, solidLines, readRoutes, pt, drawingToGround, placeNetwork, kindOf, cableLines
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/202609270220-site-world-v3/world/mv-network.mjs:1-125 · blob 56b77a7818e69173818e9c50410223de7bef615c · 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
// mv-network.mjs: the medium-voltage network from the stations to the grid, as equipment outlines with solids
// and cable routes, placed on the ground by the user.
//
// Input is a block diagram (plant-template.mjs: nodes and links) and, optionally, a route file in DRAWING
// coordinates (schema mv-routes.v1: node positions and cable polylines in the units of some drawing). This module
// never knows where a real site is: the user places the drawing with a transform (a point on the ground, metres
// per drawing unit, a rotation). Without a route file the diagram is laid out on a plain grid instead.
//
// Equipment sizes are generic and rounded (ring main unit, station skid, switchroom, grid transformer in its bund,
// cable sealing-end structure at the connection); they are outlines for scale, not any maker's product.
// Pure: no DOM. Imports only the placement helper.

import { placer } from './station.mjs';
import { layoutDiagram } from './plant-template.mjs';

export const ROUTES_SCHEMA = 'mv-routes.v1';

// Footprint w (across) x d (along) and height h, metres.
export const EQUIPMENT = Object.freeze({
  rmu: { w: 1.6, d: 0.9, h: 1.8, label: 'ring main unit' },
  station: { w: 6.1, d: 2.5, h: 2.9, label: 'station skid: transformer, LV and MV switchgear' },
  switchboard: { w: 20, d: 8, h: 4.5, label: 'MV switchroom' },
  'grid-transformer': { w: 10, d: 6, h: 7, label: 'grid transformer', bund: { w: 16, d: 12, h: 0.6 } },
  poc: { w: 4, d: 4, h: 9, label: 'connection structure (cable sealing ends)' }
});

/** Solids for one item: the body, plus a bund wall ring where the kind has one. */
export function equipmentSolids(kind, at = [0, 0, 0], heading = 0, id = kind) {
  const e = EQUIPMENT[kind];
  if (!e) throw new Error(`mv-network: unknown equipment kind ${kind}`);
  const P = placer(at, heading), out = [];
  const box = (part, min, max) => out.push(P.box({ kind, part, id, min, max }));
  box('body', [-e.w / 2, -e.d / 2, 0], [e.w / 2, e.d / 2, e.h]);
  if (e.bund) {                                        // four low walls round the transformer, 0.25 m thick
    const { w, d, h } = e.bund, t = 0.25, x = w / 2, y = d / 2;
    box('bund', [-x, -y, 0], [x, -y + t, h]); box('bund', [-x, y - t, 0], [x, y, h]);
    box('bund', [-x, -y, 0], [-x + t, y, h]); box('bund', [x - t, -y, 0], [x, y, h]);
  }
  return out;
}

/** Edge lines (x, y, z pairs) of placed solids: the rotated footprint at the base and the top, and the uprights. */
export function solidLines(solids) {
  const v = [];
  for (const s of solids) {
    const q = s.quad, z0 = s.min[2], z1 = s.max[2];
    for (let i = 0; i < 4; i++) {
      const a = q[i], b = q[(i + 1) % 4];
      v.push(a[0], a[1], z0, b[0], b[1], z0, a[0], a[1], z1, b[0], b[1], z1, a[0], a[1], z0, a[0], a[1], z1);
    }
  }
  return new Float32Array(v);
}

/** Validate a route file. Returns { units, nodes: Map(id -> [x, y]), links: [{ from, to, points }] } or throws. */
export function readRoutes(json) {
  if (!json || json.schema !== ROUTES_SCHEMA) throw new Error(`mv-network: route file schema must be "${ROUTES_SCHEMA}"`);
  const pt = p => Array.isArray(p) && p.length >= 2 && p.every(Number.isFinite);
  const nodes = new Map();
  for (const [id, p] of Object.entries(json.nodes || {})) { if (!pt(p)) throw new Error(`mv-network: node ${id} needs [x, y]`); nodes.set(id, [p[0], p[1]]); }
  const links = (json.links || []).map((l, i) => {
    if (!l || typeof l.from !== 'string' || typeof l.to !== 'string') throw new Error(`mv-network: link ${i + 1} needs from and to`);
    const points = l.points || [];
    if (!points.every(pt)) throw new Error(`mv-network: link ${i + 1} has a bad point`);
    return { from: l.from, to: l.to, points: points.map(p => [p[0], p[1]]) };
  });
  return { units: String(json.units || 'drawing'), yDown: json.y_down === true, nodes, links };
}

/**
 * drawingToGround({ at, metresPerUnit, heading, yDown }) -> (x, y) -> [east, north] local metres.
 * The drawing's first axis runs along the heading's right-hand side; y down (as in PDF sheets) is flipped.
 */
export function drawingToGround({ at = [0, 0], metresPerUnit = 1, heading = 0, yDown = false } = {}) {
  const c = Math.cos(heading), s = Math.sin(heading);
  return (x, y) => {
    const u = x * metresPerUnit, v = (yDown ? -y : y) * metresPerUnit;
    return [at[0] + u * c + v * s, at[1] - u * s + v * c];
  };
}

/**
 * placeNetwork(diagram, { routes, at, heading, metresPerUnit, spacing, groundAt })
 * -> { equipment: [{ id, kind, label, solids }], cables: [{ from, to, kv, mva, normallyOpen, points: [[x, y, z]] }], missing }
 * With routes: node positions and polylines from the file. Without: layoutDiagram on a `spacing` metre grid.
 */
export function placeNetwork(diagram, { routes = null, at = [0, 0], heading = 0, metresPerUnit = 1, spacing = 40, groundAt = () => 0 } = {}) {
  const map = routes
    ? drawingToGround({ at, metresPerUnit, heading, yDown: routes.yDown })
    : drawingToGround({ at, metresPerUnit: spacing, heading, yDown: true });
  const where = new Map(), missing = [];
  if (routes) for (const [id, p] of routes.nodes) where.set(id, map(p[0], p[1]));
  else for (const n of layoutDiagram(diagram)) where.set(n.id, map(n.x, n.y));
  const kindOf = n => (n.kind in EQUIPMENT ? n.kind : null);
  const equipment = [];
  for (const n of diagram.nodes) {
    const k = kindOf(n), p = where.get(n.id);
    if (!k) continue;
    if (!p) { missing.push(n.id); continue; }
    equipment.push({ id: n.id, kind: k, label: n.label, solids: equipmentSolids(k, [p[0], p[1], groundAt(p[0], p[1])], heading, n.id) });
  }
  const drawn = new Map();
  if (routes) for (const l of routes.links) drawn.set(`${l.from}>${l.to}`, l.points);
  const cables = [];
  for (const l of diagram.links) {
    const a = where.get(l.from), b = where.get(l.to);
    if (!a || !b) continue;
    const path = drawn.get(`${l.from}>${l.to}`) || [...(drawn.get(`${l.to}>${l.from}`) || [])].reverse();
    const plan = path.length ? path.map(p => map(p[0], p[1])) : [a, b];
    const depth = l.kv >= 100 ? 1.2 : 0.9;
    cables.push({ from: l.from, to: l.to, kind: l.kind, kv: l.kv, mva: l.mva, normallyOpen: !!l.normallyOpen,
      points: plan.map(([x, y]) => [x, y, groundAt(x, y) - (l.kind === 'mv-bus' || l.kind === 'station-tee' ? 0 : depth)]) });
  }
  return { equipment, cables, missing };
}

/** Line pairs for the cables of a placed network (optionally only one kind). */
export function cableLines(cables, kind = null) {
  const v = [];
  for (const c of cables) {
    if (kind && c.kind !== kind) continue;
    for (let i = 1; i < c.points.length; i++) v.push(...c.points[i - 1], ...c.points[i]);
  }
  return new Float32Array(v);
}