GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / stars / library

Standalone (part 5)

A JavaScript module in the library folder of Stars that maps Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256, and uses data from the GridAtlas repository.

700 lines of JavaScript from stars, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1567 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. Standalone geodesy · stars / library/standalone.mjs lines 3340–4039

Standalone

A JavaScript module in the library folder of Stars that maps Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256, and uses data from the GridAtlas repository.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 2 comment: // Generated by the modular star 2026-12-05T23:26:43.596Z. Each export is one family's earliest-seen copy, unchanged; the comment links its source.

geodesystars / library/standalone.mjs · lines 3340–4039 of 12585 (continued from section 1562) · Entry point · pattern segmentConductors (shared by 2 files)

What it does
It maps REPD master, heavy emitters UK, notice and substations. Defines 1111 functions or classes, including f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: substations, 750kV, 400kV, 275kV, 132kV, 66kV.
Inputs & outputs
In: data source: gridatlas data; JSON file repd_master.json; JSON file heavy_emitters_uk.json; JSON file notice.json; form fields (user input). Out: canvas drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 1.5kV, 1500V.
Downstream impact
Used directly by 4 files: Code (stars, https://ventusltd.github.io/stars/code.html); Proof (stars); Modular Star Workflow (stars); Testcode — Code Record Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-record/). Reached from 383 other entry points, including Code Generator — Index Page (code-generator, https://ventusltd.github.io/code-generator/); Generate (code-generator, https://ventusltd.github.io/code-generator/); 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html).
What it achieves
It snaps coordinate (`snapCoordinate`), paints cursor (`paintCursor`) and sets plan (`setPlan`). Compiled library of self-contained JavaScript functions that appear in two or more places across Ventusltd code. Its code works with 33 kV, 132 kV and 275 kV. It responds to abort events.
Why it matters
Loaded by the Code page at https://ventusltd.github.io/stars/code.html and 1 other page. Run by Proof and Modular Star Workflow.
Application
stars · library · JavaScript module
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), Declared Connections (estate URL)
Used by
named by URL in Code (estate URL), run by Proof (script call), run by Modular Star Workflow (workflow run), named by URL in Testcode — Code Record Page (estate URL)
Produces
f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf, f8775_parametersOf, f5168_escapeHTML, f8321_suppliedArrivalFields, f8850__anonymous_, f8786_crossing, f8788_legality, f8789_startNodes
Defines here
f147911_twistDeg, f147921_followTopLine, f147943_lsSlope, f147951_pileBoqItems, f148082_stringCounts, f144572_direction, f144573_perspective, f144575_multiply, f144621_guarded, f148201_skinY, f148206_mutualG, f148207_trefoilTouchingG, f148211_lossLoadFactor, f148239_postOf, f148252_summarize, f148462_nuCylinder, f148465_trefoilRow, f148466_row, f148473_voltDrop, f148480_formatNumber, f148673_parseFormat, f148676_pitchStretch, f148723_offsetPath, f148724_turnDeg, f148725_at, f144592_startLayer, off, f144597_sha256Bytes, f144630_blocked, f148932_hvSection
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc library/standalone.mjs:3340-4039 · blob fc3d8c8b93e14d4a56b8a26da47071d60bc5bc4d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
// Family #147911 · element #147911 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/pile-rules.mjs#L119-L122
export const f147911_twistDeg = function twistDeg(bFront, bRear, len, depth, dz = 0) {
  if (!(depth > 0)) return 0;
  return Math.abs(Math.atan((dz + (bRear - bFront) * len) / depth) - Math.atan(dz / depth)) * 180 / Math.PI;
};

// Family #147921 · element #147921 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/piles.mjs#L259-L271
export const f147921_followTopLine = function followTopLine(s, g, nominal, bayMax, passes = 400) {
  const t = g.map(v => v + nominal), n = t.length;
  for (let k = 0; k < passes; k++) {
    let moved = 0;
    for (let i = 1; i < n - 1; i++) {
      const h1 = s[i] - s[i - 1], h2 = s[i + 1] - s[i], mid = (t[i - 1] * h2 + t[i + 1] * h1) / (h1 + h2);
      const e = bayMax / (1 / h1 + 1 / h2), d = t[i] - mid, c = Math.max(-e, Math.min(e, d));
      if (Math.abs(c - d) > 1e-12) { t[i] = mid + c; moved++; }
    }
    if (!moved) break;
  }
  return t;
};

// Family #147943 · element #147943 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-piles.mjs#L28-L33
export const f147943_lsSlope = function lsSlope(s, g) {
  const n = s.length, ms = s.reduce((a, v) => a + v, 0) / n, mg = g.reduce((a, v) => a + v, 0) / n;
  let sxy = 0, sxx = 0;
  for (let i = 0; i < n; i++) { sxy += (s[i] - ms) * (g[i] - mg); sxx += (s[i] - ms) ** 2; }
  return sxx > 0 ? sxy / sxx : 0;
};

// Family #147951 · element #147951 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-piles.mjs#L184-L187
export const f147951_pileBoqItems = function pileBoqItems(id, s, pileType = 'plant') {
  if (!s || !s.piles) return [];
  return [{ id, kind: 'piles', pileType, results: { count: s.piles, totalEmbedmentM: s.embeddedM, totalPileLengthM: s.totalPileLengthM } }];
};

// Family #148082 · element #148082 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/string-design.mjs#L57-L60
export const f148082_stringCounts = function stringCounts({ modules, mps, stringsPerInverter = 24, inverters = null }) {
  const strings = Math.floor(modules / mps), need = Math.ceil(strings / stringsPerInverter);
  return { strings, leftover: modules - strings * mps, invertersNeeded: need, spare: inverters === null ? null : Math.max(0, strings - inverters * stringsPerInverter) };
};

// Family #144572 · element #144572 · 15 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/camera.mjs#L4-L8
export const f144572_direction = function direction(yaw, pitch) {
  // yaw 0 looks north (+y), yaw +π/2 looks east (+x); pitch +π/2 looks straight up
  const c = Math.cos(pitch);
  return [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)];
};

// Family #144573 · element #144573 · 15 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/camera.mjs#L10-L16
export const f144573_perspective = function perspective(fovy, aspect, near, far) {
  const f = 1 / Math.tan(fovy / 2), m = new Float32Array(16);
  m[0] = f / aspect; m[5] = f;
  m[10] = (far + near) / (near - far); m[11] = -1;
  m[14] = (2 * far * near) / (near - far);
  return m;
};

// Family #144575 · element #144575 · 15 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/camera.mjs#L31-L37
export const f144575_multiply = function multiply(a, b) {
  const m = new Float32Array(16);
  for (let c = 0; c < 4; c++)
    for (let r = 0; r < 4; r++)
      m[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
  return m;
};

// Family #144621 · element #144621 · 15 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/substrate.mjs#L45-L47
export const f144621_guarded = (l, fn, fallback) => {
  try { return fn(); } catch (e) { l.layer = null; l.status = 'failed and switched off: ' + e.message; return fallback; }
};

// Family #148201 · element #148201 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cable-iec.mjs#L107-L112
export const f148201_skinY = function skinY(x2) {                    // x2 = xs squared; three ranges of the published skin-effect method
  const x = Math.sqrt(x2);
  if (x <= 2.8) { const x4 = x2 * x2; return x4 / (192 + 0.8 * x4); }
  if (x <= 3.8) return -0.136 - 0.0177 * x + 0.0563 * x2;
  return 0.354 * x - 0.733;
};

// Family #148206 · element #148206 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cable-iec.mjs#L189-L192
export const f148206_mutualG = function mutualG(a, b) {
  const dx = a.x - b.x, d = Math.hypot(dx, a.y - b.y), di = Math.hypot(dx, a.y + b.y);
  return Math.log(di / d);
};

// Family #148207 · element #148207 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cable-iec.mjs#L198-L201
export const f148207_trefoilTouchingG = function trefoilTouchingG(Lm, DeMm) {
  const u = 2 * Lm / (DeMm / 1000);
  return 3 * (Math.log(2 * u) - 0.630);
};

// Family #148211 · element #148211 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cable-iec.mjs#L256-L259
export const f148211_lossLoadFactor = function lossLoadFactor(profile) {
  const m = Math.max(...profile); if (!(m > 0)) return 0;
  return profile.reduce((s, p) => s + (p / m) ** 2, 0) / profile.length;
};

// Family #148239 · element #148239 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cmd-model.mjs#L72-L76
export const f148239_postOf = function postOf(st, T) {
  if (T.tracker) return null;
  const f = st.layout === 'south' ? (st.posts === 1 ? 0.5 : 0.8) : 0.5, reveal = st.edge + T.rise * f - 0.3;
  return { reveal, over: reveal > st.postMax + 1e-9 };
};

// Family #148252 · element #148252 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cmd-model.mjs#L354-L357
export const f148252_summarize = r => (r ? { tables: r.built.tables, mwp: r.built.mwp, mw: r.built.mw, fits: r.fits,
  rowsHa: r.built.tables * r.table.pitch * (r.table.lenU + r.params.tableGapM) / 1e4, trenchM: r.electrical?.trenchM ?? 0,
  trenchByType: { ...(r.electrical?.trenchByType || {}) }, crossReview: r.crossReview || 0, rowGap: r.rowGap ? { ...r.rowGap } : null,
  skipped: { ...r.skipped }, notes: r.notes.slice() } : null);

// Family #148462 · element #148462 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/lv-dc-sizing.mjs#L102-L104
export const f148462_nuCylinder = function nuCylinder(ra, pr = 0.71) {
  return (0.6 + 0.387 * Math.max(ra, 0) ** (1 / 6) / (1 + (0.559 / pr) ** (9 / 16)) ** (8 / 27)) ** 2;
};

// Family #148465 · element #148465 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/lv-dc-sizing.mjs#L142-L150
export const f148465_trefoilRow = function trefoilRow(n, spacingM, depthM, odMm) {
  const D = odMm / 1000, out = [];
  for (let c = 0; c < n; c++) {
    const x = (c - (n - 1) / 2) * spacingM;
    out.push({ x: x - D / 2, y: depthM + D / (2 * Math.sqrt(3)), circuit: c }, { x: x + D / 2, y: depthM + D / (2 * Math.sqrt(3)), circuit: c },
      { x, y: depthM - D / Math.sqrt(3), circuit: c });
  }
  return out;
};

// Family #148466 · element #148466 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/lv-dc-sizing.mjs#L151-L153
export const f148466_row = function row(n, spacingM, depthM) {
  return Array.from({ length: n }, (_, i) => ({ x: (i - (n - 1) / 2) * spacingM, y: depthM, circuit: i }));
};

// Family #148473 · element #148473 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/lv-dc-sizing.mjs#L273-L277
export const f148473_voltDrop = function voltDrop({ dc = false, I, lengthM, r, x = 0, U, pf = 1 }) {
  if (dc) return 2 * I * lengthM * r / U * 100;
  const sin = Math.sqrt(Math.max(0, 1 - pf * pf));
  return Math.sqrt(3) * I * lengthM * (r * pf + x * sin) / U * 100;
};

// Family #148480 · element #148480 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/measure-format.mjs#L12-L19
export const f148480_formatNumber = function formatNumber(x, dp = 1) {
  if (x == null || !Number.isFinite(x)) return 'n/a';
  const v = Math.abs(x) < 0.5 * 10 ** -dp ? 0 : x;   // no "-0.0"
  // Rounded as written in decimal (0.825 -> "0.83"), not as the nearest binary double happens to fall (toFixed gives 0.82).
  const [i, f] = Math.abs(v).toLocaleString('en-GB', { minimumFractionDigits: dp, maximumFractionDigits: dp, useGrouping: false }).split('.');
  const grouped = i.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return (v < 0 ? '-' : '') + grouped + (f ? '.' + f : '');
};

// Family #148673 · element #148673 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/structures.mjs#L28-L31
export const f148673_parseFormat = function parseFormat(w) {
  const m = /^(\d)([pl])(\d*)$/i.exec(String(w || ''));
  return m ? { tiers: Number(m[1]), orient: m[2].toLowerCase() === 'l' ? 'landscape' : 'portrait', cols: m[3] ? Number(m[3]) : null } : null;
};

// Family #148676 · element #148676 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/structures.mjs#L67-L73
export const f148676_pitchStretch = function pitchStretch({ depth, rise, elevDeg, fallN, maxStretch = 2 }) {
  const t = Math.tan(elevDeg * Math.PI / 180);
  if (!(fallN > 0) || !(t > 0)) return 1;
  if (fallN >= t * 0.98) return maxStretch;
  const flat = (depth * t + rise) / t, slopeP = (depth * t + rise) / (t - fallN);
  return Math.min(maxStretch, Math.max(1, slopeP / flat));
};

// Family #148723 · element #148723 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/trench-plan.mjs#L139-L146
export const f148723_offsetPath = function offsetPath(pts, d) {
  if (!d) return pts.map(p => p.slice());
  const n = pts.length, nrm = i => { const a = pts[i], b = pts[i + 1], l = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1; return [-(b[1] - a[1]) / l, (b[0] - a[0]) / l]; };
  return pts.map((p, i) => {
    const a = nrm(Math.max(0, i - 1)), b = nrm(Math.min(n - 2, i)), m = [a[0] + b[0], a[1] + b[1]], k = (m[0] * b[0] + m[1] * b[1]) || 1;
    return [p[0] + m[0] * d / k, p[1] + m[1] * d / k];
  });
};

// Family #148724 · element #148724 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/trench-plan.mjs#L148-L152
export const f148724_turnDeg = (a, b, c) => {
  const u = Math.atan2(b[1] - a[1], b[0] - a[0]), v = Math.atan2(c[1] - b[1], c[0] - b[0]);
  let t = Math.abs(u - v) % (2 * Math.PI); if (t > Math.PI) t = 2 * Math.PI - t;
  return t * 180 / Math.PI;
};

// Family #148725 · element #148725 · 15 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/trench-plan.mjs#L153-L160
export const f148725_at = (pts, s) => {           // the point s metres along a polyline
  for (let i = 1, run = 0; i < pts.length; i++) {
    const L = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    if (run + L >= s - 1e-9) { const k = L ? (s - run) / L : 0; return [pts[i - 1][0] + k * (pts[i][0] - pts[i - 1][0]), pts[i - 1][1] + k * (pts[i][1] - pts[i - 1][1])]; }
    run += L;
  }
  return pts.at(-1).slice();
};

// Family #144592 · element #144592 · 14 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/layers.mjs#L62-L71
export const f144592_startLayer = function startLayer(item, api) {
  const off = e => {
    item.layer = null; item.status = 'failed to start and switched off: ' + (e?.message || e);
    api.invalidate({ ground: false });
  };
  try {
    const r = item.layer?.init?.(api);
    if (r && typeof r.then === 'function') r.then(null, off);
  } catch (e) { off(e); }
};

// Family #144597 · element #144597 · 14 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/layers.mjs#L107-L111
export const f144597_sha256Bytes = async function sha256Bytes(bytes) {
  if (!globalThis.crypto?.subtle) return null;
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
};

// Family #144630 · element #144630 · 14 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/views.mjs#L36-L43
export const f144630_blocked = function blocked([x, y, z], body, solids) {
  for (const b of solids) {
    if (x > b.min[0] - body.radius && x < b.max[0] + body.radius &&
        y > b.min[1] - body.radius && y < b.max[1] + body.radius &&
        z - body.below < b.max[2] && z + body.above > b.min[2]) return true;
  }
  return false;
};

// Family #148932 · element #148932 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/block-trenches.mjs#L54-L62
export const f148932_hvSection = function hvSection(kv) {
  const big = kv > 132, duct = kv > 132 ? 250 : 160, cableOdMm = kv >= 400 ? 145 : kv > 132 ? 125 : 105;
  return { cableOdMm, rated: false, section: {
    id: `hv-connection-${kv}kv`, voltage_class: big ? `${kv} kV connection: to the transmission owner's design` : `${kv} kV connection, fully ducted`,
    formation: big ? 'three ducts flat, spaced' : 'trefoil of three ducts', circuits: 1, cover_to_top_m: big ? 1.0 : 0.91,
    trench_width_m: big ? 1.4 : 0.8, trench_depth_m: big ? 1.6 : 1.4, duct_od_mm: duct, phase_spacing_mm: big ? 450 : duct,
    bedding: { thickness_mm: 100 }, marker: { type: 'protection tile layer', depth_m: big ? 0.85 : 0.8 },
    status: `UNRATED: outline only, duct ${duct} mm OD and cable about ${cableOdMm} mm OD assumed for ${kv} kV; no rating run` } };
};

// Family #148947 · element #148947 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/bs7671-checks.mjs#L24-L28
export const f148947_buriedProtection = function buriedProtection({ armoured = false, ducted = false, kind = 'LV' } = {}) {
  const ok = !!armoured || !!ducted;
  return { name: `${kind} cable in the ground: armoured and earthed, or in a duct (BS 7671 522.8.10)`, ok,
    value: armoured ? 'armoured' : ducted ? 'ducted' : 'unarmoured, laid direct', limit: 'armour or duct' };
};

// Family #149097 · element #149097 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-central.mjs#L21-L39
export const f149097_centralItems = function centralItems(r) {
  const out = [], T = r?.table, t = r?.tables;
  if (!T || !t) return out;
  let q0 = 0;
  for (const st of r.stations || []) {
    const n = st.tables || 0;
    if (st.central) {
      out.push({ kind: 'skid', u: st.u, v: st.v, id: st.id, station: st.id });
      const boxes = Math.max(1, Math.min(st.combiners || 1, n));
      for (let b = 0; b < boxes && n; b++) {
        const a = q0 + Math.floor(b * n / boxes), z = q0 + Math.floor((b + 1) * n / boxes) - 1, m = Math.floor((a + z) / 2);
        const L = r.tableLen?.[m] ?? T.lenU;
        out.push({ kind: 'combiner', u: t[m * 6] + L / 2, v: t[m * 6 + 1] - 0.6, id: `${st.id}-CB${b + 1}`, station: st.id });
      }
    }
    q0 += n;
  }
  return out;
};

// Family #149123 · element #149123 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-packing.mjs#L38-L41
export const f149123_fieldsOf = function fieldsOf(boundary) {
  const b = boundary || [];
  return Array.isArray(b[0]?.[0]) ? b.filter(f => Array.isArray(f) && f.length >= 3) : [b];
};

// Family #149124 · element #149124 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-packing.mjs#L48-L51
export const f149124__anonymous_ = poly => {
    const box = [Math.min(...poly.map(q => q[0])), Math.max(...poly.map(q => q[0])), Math.min(...poly.map(q => q[1])), Math.max(...poly.map(q => q[1]))];
    return { poly, box, sb: null };
  };

// Family #149128 · element #149128 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-packing.mjs#L74-L84
export const f149128_slice = function slice(poly, v) {
  const xs = [];
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > v) !== (yj > v)) xs.push(xi + (v - yi) * (xj - xi) / (yj - yi));
  }
  xs.sort((a, b) => a - b);
  const out = [];
  for (let k = 0; k + 1 < xs.length; k += 2) out.push([xs[k], xs[k + 1]]);
  return out;
};

// Family #149129 · element #149129 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-packing.mjs#L85-L89
export const f149129_intersect = (A, B) => {
  const out = [];
  for (const [a0, a1] of A) for (const [b0, b1] of B) { const lo = Math.max(a0, b0), hi = Math.min(a1, b1); if (hi > lo) out.push([lo, hi]); }
  return out;
};

// Family #149140 · element #149140 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-piles.mjs#L190-L198
export const f149140_layoutTables = function layoutTables(r) {
  const F = r.frame, T = r.table, P = r.params, t = r.tables, out = [];
  for (let q = 0; q < t.length; q += 6) {
    const ua = t[q], va = t[q + 1], L = r.tableLen?.[q / 6] ?? T.lenU;   // a half table closing a row end is shorter
    out.push({ length: L, depth: T.depth, rise: T.rise, lowEdgeM: P.lowEdgeM, eastWest: !T.south && !T.tracker, key: [va, ua, ua + L],
      lineAt: f => [F.en(ua, va + f * T.depth), F.en(ua + L, va + f * T.depth)] });
  }
  return out;
};

// Family #149158 · element #149158 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/site-checks.mjs#L15-L20
export const f149158_dayOf = function dayOf(v) {
  if (v == null || v === '') return null;
  if (v instanceof Date) return Number.isFinite(v.getTime()) ? v.getTime() : null;
  const m = /^(\d{4})(?:-(\d{1,2}))?(?:-(\d{1,2}))?/.exec(String(v).trim());
  return m ? Date.UTC(Number(m[1]), (Number(m[2]) || 1) - 1, Number(m[3]) || 1) : null;
};

// Family #149160 · element #149160 · 14 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/site-checks.mjs#L43-L50
export const f149160_sourceConflict = function sourceConflict(values = [], { tolerance = 0.1, unit = '' } = {}) {
  const v = values.filter(x => Number.isFinite(x?.value) && x.value > 0);
  if (v.length < 2) return null;
  const lo = v.reduce((a, b) => (b.value < a.value ? b : a)), hi = v.reduce((a, b) => (b.value > a.value ? b : a)), spread = (hi.value - lo.value) / lo.value;
  if (spread <= tolerance + 1e-12) return null;
  return { values: v, spread, line: `Sources disagree: ${hi.source} gives ${hi.value}${unit ? ' ' + unit : ''}, ${lo.source} gives ${lo.value}${unit ? ' ' + unit : ''} `
    + `(${Math.round(spread * 100)} % apart). Both are kept; neither is picked.` };
};

// Family #144659 · element #144659 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/arrival.mjs#L11-L14
export const f144659_turn = (from, to) => {
  const d = (to - from) % (2 * Math.PI);
  return d > Math.PI ? d - 2 * Math.PI : d < -Math.PI ? d + 2 * Math.PI : d;
};

// Family #144662 · element #144662 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/attribution.mjs#L7-L13
export const f144662_sourcesFor = function sourcesFor(loadedLayerIds, attribution) {
  const wanted = new Set();
  for (const layerId of loadedLayerIds || []) {
    for (const sid of attribution.layers?.[layerId] || []) wanted.add(sid);
  }
  return Object.keys(attribution.sources || {}).filter((sid) => wanted.has(sid));
};

// Family #144663 · element #144663 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/attribution.mjs#L16-L18
export const f144663_unknownLayers = function unknownLayers(loadedLayerIds, attribution) {
  return (loadedLayerIds || []).filter((id) => !(id in (attribution.layers || {})));
};

// Family #144664 · element #144664 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/attribution.mjs#L20-L23
export const f144664_fillYear = function fillYear(text, src, year) {
  const y = src.year ?? year ?? new Date().getUTCFullYear();
  return text.replaceAll('{year}', String(y));
};

// Family #144665 · element #144665 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/attribution.mjs#L25-L27
export const f144665_licenceOf = function licenceOf(src, attribution) {
  return attribution.licences?.[src.licence] || { short: src.licence, long: src.licence, url: src.licence_url || null };
};

// Family #144784 · element #144784 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/design-ui.mjs#L65-L70
export const f144784_batch = 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 };
  };

// Family #144965 · element #144965 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/layers/grid.mjs#L93-L102
export const f144965_measuredSpans = function measuredSpans(towers, measuredAt) {
  const out = [];
  for (let k = 0; k + 1 < towers.length; k++) {
    const A = towers[k], B = towers[k + 1], n = Math.max(2, Math.ceil(Math.hypot(B.x - A.x, B.y - A.y) / 5));
    let ok = true;
    for (let s = 0; s <= n && ok; s++) ok = Number.isFinite(measuredAt(A.x + (B.x - A.x) * s / n, A.y + (B.y - A.y) * s / n));
    out.push(ok);
  }
  return out;
};

// Family #144967 · element #144967 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/layers/grid.mjs#L123-L133
export const f144967_straightGround = function straightGround(towers, x, y) {
  if (towers.length < 2) return towers[0]?.ground ?? 0;
  let best = Infinity, h = towers[0].ground;
  for (let k = 0; k + 1 < towers.length; k++) {
    const A = towers[k], B = towers[k + 1], dx = B.x - A.x, dy = B.y - A.y, L2 = dx * dx + dy * dy || 1;
    const f = Math.min(1, Math.max(0, ((x - A.x) * dx + (y - A.y) * dy) / L2));
    const d = Math.hypot(A.x + dx * f - x, A.y + dy * f - y);
    if (d < best) { best = d; h = A.ground + (B.ground - A.ground) * f; }
  }
  return h;
};

// Family #145121 · element #145121 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure.mjs#L17-L19
export const f145121_distance2d = function distance2d(a, b) {
  return Math.hypot(b[0] - a[0], b[1] - a[1]);
};

// Family #145122 · element #145122 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure.mjs#L22-L24
export const f145122_distance3d = function distance3d(a, b) {
  return Math.hypot(b[0] - a[0], b[1] - a[1], (b[2] ?? 0) - (a[2] ?? 0));
};

// Family #145124 · element #145124 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure.mjs#L36-L44
export const f145124_signedArea = function signedArea(polygon) {
  let a = 0;
  const n = polygon.length;
  for (let i = 0; i < n; i++) {
    const p = polygon[i], q = polygon[(i + 1) % n];
    a += p[0] * q[1] - q[0] * p[1];
  }
  return a / 2;
};

// Family #145127 · element #145127 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure.mjs#L65-L75
export const f145127_insidePoly = function insidePoly(x, y, vx, vy) {
  let ins = false;
  const n = vx.length;
  for (let i = 0; i < n; i++) {
    const j = (i - 1 + n) % n;
    const x1 = vx[i], y1 = vy[i], x2 = vx[j], y2 = vy[j];
    if (y1 === y2) continue;
    if ((y1 > y) !== (y2 > y) && x < x1 + (y - y1) * (x2 - x1) / (y2 - y1)) ins = !ins;
  }
  return ins;
};

// Family #145129 · element #145129 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure.mjs#L148-L156
export const f145129_slopeAlong = function slopeAlong(groundAt, at, direction, h = 0.5) {
  const l = Math.hypot(direction[0], direction[1]);
  if (!(l > 0)) throw new Error('slopeAlong: direction must be non-zero');
  if (!(h > 0)) throw new Error('slopeAlong: h must be positive');
  const ux = direction[0] / l, uy = direction[1] / l;
  const zf = groundAt(at[0] + ux * h, at[1] + uy * h);
  const zb = groundAt(at[0] - ux * h, at[1] - uy * h);
  return (zf - zb) / (2 * h);
};

// Family #145133 · element #145133 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure.mjs#L264-L284
export const f145133_bendRule = function bendRule(cables, { voltageKv, construction = null, when, odMm }) {
  if (when !== 'final' && when !== 'installation') {
    throw new Error("bendRule: choose when: 'final' or 'installation'");
  }
  if (!(odMm > 0)) throw new Error('bendRule: odMm must be positive');
  const rules = (cables && cables.rules) || [];
  const match = rules.filter((r) => r.voltage_kv === voltageKv && r.when === when
    && (construction == null || r.construction === construction));
  const usable = match.filter((r) => Number.isFinite(r.multiple_of_od));
  const skipped = match.filter((r) => !Number.isFinite(r.multiple_of_od));
  if (!usable.length) return { when, multiple: null, radius: null, rule: null, considered: 0, skipped };
  const rule = usable.reduce((a, b) => (b.multiple_of_od > a.multiple_of_od ? b : a));
  return {
    when,
    multiple: rule.multiple_of_od,
    radius: rule.multiple_of_od * odMm / 1000,
    rule,
    considered: usable.length,
    skipped,
  };
};

// Family #145152 · element #145152 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/origin.mjs#L7-L9
export const f145152_toLocal = function toLocal(origin, e, n) {
  return [e - origin.e, n - origin.n];
};

// Family #145153 · element #145153 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/origin.mjs#L12-L14
export const f145153_toBng = function toBng(origin, x, y) {
  return { e: origin.e + x, n: origin.n + y };
};

// Family #145154 · element #145154 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/origin.mjs#L21-L31
export const f145154_rebaseIfNeeded = function rebaseIfNeeded(origin, pos, { limit = 600, tile = 1000 } = {}) {
  if (!(tile > 0) || !(limit > tile / 2)) throw new Error('rebase needs tile > 0 and limit > tile / 2');
  const [x, y] = pos;
  if (!Number.isFinite(x) || !Number.isFinite(y)) return null; // never rebase onto a broken position
  if (Math.abs(x) <= limit && Math.abs(y) <= limit) return null;
  const e = Math.round((origin.e + x) / tile) * tile;
  const n = Math.round((origin.n + y) / tile) * tile;
  const dx = e - origin.e, dy = n - origin.n;
  if (dx === 0 && dy === 0) return null; // already on the nearest corner; nothing to gain
  return { e, n, shift: [dx, dy] };
};

// Family #145159 · element #145159 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/overhead.mjs#L94-L103
export const f145159_attachments = function attachments(t, spec, d, p) {
  const at = (across, z) => [t.x + p[0] * across, t.y + p[1] * across, t.ground + z];
  if (spec.kind === 'pole') {
    const z = spec.armZ + spec.pin;
    return [at(-spec.armHalf, z), at(0, spec.height), at(spec.armHalf, z)];
  }
  const out = [];
  for (const side of [-1, 1]) for (const arm of spec.arms) out.push(at(side * arm.half, arm.z - spec.insulator));
  return out;
};

// Family #145160 · element #145160 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/overhead.mjs#L106-L146
export const f145160_drawTower = function drawTower(seg, t, spec, d, p) {
  const P = (along, across, z) => [t.x + d[0] * along + p[0] * across, t.y + d[1] * along + p[1] * across, t.ground + z];
  const L = (a, b) => seg.push(a[0], a[1], a[2], b[0], b[1], b[2]);
  if (spec.kind === 'pole') {
    L(P(0, 0, 0), P(0, 0, spec.height));
    L(P(0, -spec.armHalf, spec.armZ), P(0, spec.armHalf, spec.armZ));
    L(P(0, -spec.armHalf * 0.6, spec.armZ), P(0, 0, spec.armZ - 0.8)); // crossarm braces
    L(P(0, spec.armHalf * 0.6, spec.armZ), P(0, 0, spec.armZ - 0.8));
    return;
  }
  // Body: a square tapering from baseHalf at the ground to topHalf at the top arm, then a peak for the earth wire.
  const topZ = spec.arms[0].z, halfAt = (z) => spec.baseHalf + (spec.topHalf - spec.baseHalf) * Math.min(1, z / topZ);
  const levels = [0, ...spec.arms.map((a) => a.z).sort((a, b) => a - b)];
  if (levels[1] > 10) levels.splice(1, 0, levels[1] * 0.45); // a waist panel below the lowest arm
  const corners = [[1, 1], [-1, 1], [-1, -1], [1, -1]];
  const ring = (z) => corners.map(([i, j]) => P(i * halfAt(z), j * halfAt(z), z));
  for (let n = 0; n < levels.length; n++) {
    const r = ring(levels[n]);
    for (let c = 0; c < 4; c++) L(r[c], r[(c + 1) % 4]);              // horizontal ring
    if (n === 0) continue;
    const q = ring(levels[n - 1]);
    for (let c = 0; c < 4; c++) {
      L(q[c], r[c]);                                                   // leg
      L(q[c], r[(c + 1) % 4]); L(q[(c + 1) % 4], r[c]);                // X bracing on each face
    }
  }
  const top = ring(topZ), peak = P(0, 0, spec.height);
  for (let c = 0; c < 4; c++) L(top[c], peak);
  // Cross-arms: a triangle each side, top chord level, bottom chord rising to the tip; a short line for the insulator.
  for (const arm of spec.arms) {
    const h = halfAt(arm.z), depth = Math.min(3, arm.half * 0.35);
    for (const side of [-1, 1]) {
      const tip = P(0, side * arm.half, arm.z);
      for (const along of [-1, 1]) {
        L(P(along * h, side * h, arm.z), tip);
        L(P(along * h, side * h, arm.z - depth), tip);
      }
      L(tip, P(0, side * arm.half, arm.z - spec.insulator));
    }
  }
};

// Family #145161 · element #145161 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/overhead.mjs#L148-L152
export const f145161_solidOf = function solidOf(t, spec) {
  const r = spec.kind === 'pole' ? spec.radius : spec.baseHalf; // an axis-aligned box that covers the base at any heading
  const h = spec.kind === 'pole' ? spec.height : spec.arms[spec.arms.length - 1].z;
  return { min: [t.x - r, t.y - r, t.ground], max: [t.x + r, t.y + r, t.ground + h] };
};

// Family #145214 · element #145214 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/pick.mjs#L9-L20
export const f145214_rayFromScreen = function rayFromScreen(px, py, width, height, eye, yaw, pitch, fovy) {
  const c = Math.cos(pitch);
  const f = [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)];   // camera.mjs direction()
  const r = [Math.cos(yaw), -Math.sin(yaw), 0];                         // camera.mjs view() right
  const u = [r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]]; // r x f
  const t = Math.tan(fovy / 2), aspect = width / height;
  const nx = (2 * px) / width - 1, ny = 1 - (2 * py) / height;          // normalised device coordinates
  const a = nx * t * aspect, b = ny * t;
  const d = [f[0] + r[0] * a + u[0] * b, f[1] + r[1] * a + u[1] * b, f[2] + r[2] * a + u[2] * b];
  const len = Math.hypot(d[0], d[1], d[2]);
  return { origin: [eye[0], eye[1], eye[2]], dir: [d[0] / len, d[1] / len, d[2] / len] };
};

// Family #145216 · element #145216 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/pick.mjs#L48-L52
export const f145216_snapToGrid = function snapToGrid(point, spacing) {
  if (!(spacing > 0)) return [point[0], point[1], point[2]];
  const snap = v => Math.round(v / spacing) * spacing + 0; // + 0 turns -0 into 0
  return [snap(point[0]), snap(point[1]), point[2]];
};

// Family #145342 · element #145342 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/search-ui.mjs#L81-L90
export const f145342_moveSelection = function moveSelection(index, count, key) {
  if (count <= 0) return key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End' ? -1 : null;
  switch (key) {
    case 'ArrowDown': return index < 0 || index >= count - 1 ? 0 : index + 1;
    case 'ArrowUp': return index <= 0 ? count - 1 : index - 1;
    case 'Home': return 0;
    case 'End': return count - 1;
    default: return null;
  }
};

// Family #145343 · element #145343 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/search-ui.mjs#L93-L96
export const f145343_rowForEnter = function rowForEnter(rows, index) {
  if (!rows.length) return null;
  return rows[index >= 0 && index < rows.length ? index : 0];
};

// Family #145345 · element #145345 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/search-ui.mjs#L99-L108
export const f145345_debounce = function debounce(fn, ms, clock = { set: (f, t) => setTimeout(f, t), clear: id => clearTimeout(id) }) { // bound: a bare setTimeout called as clock.set throws 'Illegal invocation' in browsers
  let id = null;
  const d = (...args) => {
    if (id !== null) clock.clear(id);
    id = clock.set(() => { id = null; fn(...args); }, ms);
  };
  d.cancel = () => { if (id !== null) clock.clear(id); id = null; };
  d.flush = (...args) => { d.cancel(); fn(...args); };
  return d;
};

// Family #145363 · element #145363 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/search.mjs#L57-L61
export const f145363_altMatches = function altMatches(row, alt) {
  const c = alt.replace(/ /g, '');
  return row.name.includes(alt) || row.county.includes(alt) || row.ref.includes(alt) ||
    row.postcode.includes(alt) || (c.length > 0 && row.postcodeC.includes(c));
};

// Family #145365 · element #145365 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/search.mjs#L88-L92
export const f145365__anonymous_ = (a, b) =>
    b.score - a.score ||
    (b.capacity_mw ?? -1) - (a.capacity_mw ?? -1) ||
    String(a.name ?? '').localeCompare(String(b.name ?? '')) ||
    String(a.repd_ref ?? '').localeCompare(String(b.repd_ref ?? ''));

// Family #145453 · element #145453 · 13 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/trench.mjs#L290-L293
export const f145453_bisector = function bisector(a, b) {
  const x = a.dx + b.dx, y = a.dy + b.dy, l = Math.hypot(x, y);
  return l < 1e-6 ? [a.dx, a.dy] : [x / l, y / l];
};

// Family #145215 · element #145215 · 12 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/pick.mjs#L26-L44
export const f145215_pickGround = function pickGround(ray, groundAt, { maxDistance = 2000, step = 0.5 } = {}) {
  const { origin: o, dir: d } = ray;
  if (!(step > 0) || !(maxDistance > 0)) return null;
  const below = t => o[2] + d[2] * t <= groundAt(o[0] + d[0] * t, o[1] + d[1] * t);
  if (below(0)) return null;
  let lo = 0, hi = -1;
  for (let t = step; ; t += step) {
    const s = Math.min(t, maxDistance);
    if (below(s)) { hi = s; break; }
    lo = s;
    if (s >= maxDistance) return null;
  }
  while (hi - lo > 0.01) {
    const mid = (lo + hi) / 2;
    if (below(mid)) hi = mid; else lo = mid;
  }
  const t = (lo + hi) / 2, x = o[0] + d[0] * t, y = o[1] + d[1] * t;
  return [x, y, groundAt(x, y)];
};

// Family #145114 · element #145114 · 11 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/measure-format.mjs#L10-L16
export const f145114_formatNumber = function formatNumber(x, dp = 1) {
  if (x == null || !Number.isFinite(x)) return 'n/a';
  const v = Math.abs(x) < 0.5 * 10 ** -dp ? 0 : x;   // no "-0.0"
  const [i, f] = Math.abs(v).toFixed(dp).split('.');
  const grouped = i.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return (v < 0 ? '-' : '') + grouped + (f ? '.' + f : '');
};

// Family #145341 · element #145341 · 11 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/search-ui.mjs#L71-L77
export const f145341_summaryText = function summaryText(result, shown) {
  if (!result) return '';
  if (result.kind === 'coords') return 'Go to this point';
  if (!result.total) return 'No projects match';
  const noun = result.total === 1 ? 'project' : 'projects';
  return shown < result.total ? `${shown} of ${result.total} ${noun}` : `${result.total} ${noun}`;
};

// Family #145958 · element #145958 · 11 places in 2 repositories · https://github.com/Ventusltd/graphics-engines-open-source/blob/79e0bd8ee33844835e553fc84d552b6aa1521152/web/versions/202609262227-site-world/world/labels.mjs#L8-L13
export const f145958_voltage = function voltage(s) {
  const v = String(s.voltage_class || '');
  if (/DC string/i.test(v)) return '1.5 kV DC string';
  if (/^LV/i.test(v)) return 'LV';
  return v.replace(/\s*AC$/i, '').replace(/\s*\(.*\)$/, '').trim() || 'Trench';
};

// Family #30550 · element #30550 · 9 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609060517/atlas/index.html#L46-L56
export const f30550_validateAtlasComposition = function validateAtlasComposition(current) {
  const required=['streaming-parquet-bridge','uk-gazetteer-flyto','substation-intelligence','sld-sandbox'];
  const registry=current?.cartridges,order=current?.cartridge_order;
  if(!Array.isArray(registry)||!Array.isArray(order))throw Error('Cartridge registry and order must be arrays');
  const ids=registry.map(cartridge=>cartridge?.id);
  if(ids.some(id=>typeof id!=='string'||!id.trim())||order.some(id=>typeof id!=='string'||!id.trim()))throw Error('Every cartridge must have a non-empty ID');
  if(new Set(ids).size!==ids.length||new Set(order).size!==order.length)throw Error('Duplicate cartridge IDs are not allowed');
  if(ids.length!==order.length||order.some(id=>!ids.includes(id)))throw Error('Cartridge registry and execution order must contain the same IDs');
  for(const id of required)if(!ids.includes(id))throw Error('Required cartridge missing: '+id);
  return true;
};

// Family #22102 · element #22102 · 8 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609052015/tool-layers/navigation.js#L3-L6
export const f22102_resolveToolDestination = function resolveToolDestination(href, registry, base) {
  const current=new URL(href,base);
  return registry.find(tool=>{const target=new URL(tool.entry,base);return target.origin===current.origin&&target.pathname===current.pathname;}) || null;
};

// Family #5177 · element #5177 · 3 places in 2 repositories · https://github.com/Ventusltd/code-generator/blob/3897d83efcd0259d21dce87704b0c33118fe2c2e/apps/substation-finder/Si/index.html#L364-L367
export const f5177__anonymous_ = c => ({
            type: 'Feature',
            geometry: { type: 'Point', coordinates: c }
        });

// Family #5195 · element #5195 · 3 places in 2 repositories · https://github.com/Ventusltd/code-generator/blob/3897d83efcd0259d21dce87704b0c33118fe2c2e/apps/substation-finder/Si/index.html#L579-L608
export const f5195_snapLines = function snapLines(features, subs) {
    if (!subs || !subs.length) return features;
    const tol = 0.05, rad = Math.PI / 180;
    const snapCoordinate = (coord) => {
        let best = coord, min = Infinity;
        const latCos = Math.cos(coord[1] * rad);
        subs.forEach(s => {
            const sc = s.geometry && s.geometry.coordinates;
            if (!sc) return;
            const dx = (coord[0] - sc[0]) * latCos;
            const dy = (coord[1] - sc[1]);
            const d = (dx * dx) + (dy * dy);
            if (d < min && d < tol * tol) { min = d; best = sc; }
        });
        return best;
    };
    features.forEach(f => {
        const geom = f.geometry;
        if (!geom || !geom.coordinates) return;
        if (geom.type === 'LineString') {