GLOBALGRID2050 / EXPLORE CODE

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

Drums and 2 more files (part 2)

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, 33kV and 66kV.

556 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 153 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. Drums transform · globalgrid2050 / solar-design-studio/202609270439-site-world/world/drums.mjs lines 1–288
  2. Find Mount render · globalgrid2050 / solar-design-studio/202609270439-site-world/world/find-mount.mjs lines 1–42
  3. Layers render · globalgrid2050 / solar-design-studio/202609270439-site-world/world/layers.mjs lines 1–226

Drums

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, 33kV and 66kV.

transformglobalgrid2050 / solar-design-studio/202609270439-site-world/world/drums.mjs · lines 1–288 of 288 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern drawJointBays (shared by 2 files)

What it does
It calculates cables, 33kV and 66kV. Defines 16 functions or classes, including val, massPerMetre, barrelRule, drumCapacity, chooseDrum.
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, 33kV, 66kV, 2kV.
Inputs & outputs
Voltage levels named: 66kV, 33kV, 2kV.
Downstream impact
Used directly by 1 file: Design Earthworks (globalgrid2050).
What it achieves
It draws joint bays (`drawJointBays`) and is built from the val step (`val`) and the mass per metre helper (`massPerMetre`). Split a cable route into drum lengths, place joint bays, and produce a drum schedule. Its code works with 33 kV, 66 kV and 2 kV.
Why it matters
Imported by Design Earthworks.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
Uses
Boq Assumptions (import)
Used by
imported by Design Earthworks (import)
Produces
ASSUMED, DRUMS, massPerMetre, barrelRule, drumCapacity, chooseDrum, planDrums, drawJointBays
Defines here
val, massPerMetre, barrelRule, drumCapacity, chooseDrum, profile, interp, pointAt, bayProblems, planDrums, coreLen, need, fits, reach, drawJointBays, seg
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/202609270439-site-world/world/drums.mjs:1-288 · blob ea23d78617345e6023f03522a17f9392cddcd5a0 · 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
// Drums: split a cable route into drum lengths, place joint bays, and produce a drum schedule.
// Pure: no DOM, no WebGL; imports only the shared cable allowances from boq-assumptions.mjs. Local east (x), north (y), up (z), metres, as cable-route.mjs.
//
// planDrums({ route, cable, rules, crossings, groundAt, options })
//   route      the object returned by routeCable() in cable-route.mjs
//   cable      one entry of web/world/data/cables.json "cables"
//   rules      the "rules" array of the same file (used for the drum barrel bend check); optional
//   crossings  [{ at }] or [{ from, to }] plan chainages (metres) of roads, pipes, ditches; optional
//   groundAt   (x, y) -> ground height, for the top of the drawn joint bays; optional
//   options    overrides for any value in ASSUMED below, plus drums (a drum table) and maxDrumLength
//
// Lengths are true 3D lengths along each core (the three cores differ slightly in bends), plus allowances.
// Every figure not taken from cables.json is an assumption, listed in ASSUMED with its basis, and
// returned in the schedule so nobody mistakes it for a measured value.

import { CABLE_ALLOWANCES } from './boq-assumptions.mjs';

// Termination tail and snaking come from CABLE_ALLOWANCES, the one set the bill of quantities uses too.
export const ASSUMED = {
  terminationAllowance: { value: CABLE_ALLOWANCES.terminationM.value, unit: CABLE_ALLOWANCES.terminationM.unit, basis: CABLE_ALLOWANCES.terminationM.basis },
  jointAllowance: { value: 1.5, unit: 'm per core per cable end at a joint', basis: 'Assumed: overlap and cut-back needed in the bay to make the joint.' },
  snaking: { value: CABLE_ALLOWANCES.snakingPct.value / 100, unit: 'fraction of 3D route length', basis: CABLE_ALLOWANCES.snakingPct.basis },
  drumEndWaste: { value: 2, unit: 'm per drum', basis: 'Assumed: inner end left on the drum for sealing and testing, and the damaged pulling end.' },
  orderIncrement: { value: 10, unit: 'm', basis: 'Assumed: each drum length is ordered rounded up to this step.' },
  freeboard: { value: 0.075, unit: 'm', basis: 'Assumed: clearance between the outer layer and the flange rim, at least one cable diameter.' },
  maxFlange: { value: 4.3, unit: 'm', basis: 'Assumed: on a low-loader deck of about 0.5 m the loaded height stays below 5.03 m '
    + '(16 ft 6 in), the GB bridge height below which bridges carry height signs; there is no general legal height limit.' },
  maxPullLength: { value: 1000, unit: 'm per section', basis: 'Assumed cap on one pull, no source: stands in for a pulling-tension '
    + 'and sidewall-pressure check, which this module does not yet make. Drum capacity alone would allow pulls of 2 km or more.' },
  maxPayload: { value: 25, unit: 't cable per drum', basis: 'Assumed: a 44 t six-axle articulated vehicle (GB authorised weight) less tractor, trailer and drum.' },
  bayLength: { value: 8, unit: 'm (33 kV); 10 m above 66 kV', basis: 'Assumed typical joint bay length for three single-core joints side by side.' },
  bayWidth: { value: 1.8, unit: 'm (33 kV); 2.5 m above 66 kV', basis: 'Assumed typical joint bay width.' },
  bayFloorBelowCable: { value: 0.3, unit: 'm', basis: 'Assumed: working space below the cable in the bay.' },
  bayMargin: { value: 3, unit: 'm', basis: 'Assumed: straight run needed beyond each end of the bay before a bend starts.' },
  maxBaySlope: { value: 0.05, unit: 'rise over run', basis: 'Assumed 1 in 20: bays are kept near level so the joint sits flat and water drains away.' },
  crossingClearance: { value: 10, unit: 'm', basis: 'Assumed: keep a bay this far from any crossing so the crossing is not re-excavated.' },
  coverIfNoGround: { value: 1.0, unit: 'm', basis: 'Assumed: drawn bay rim height above the cable when no ground function is given.' },
  endClearance: { value: 20, unit: 'm', basis: 'Assumed: keep a bay this far from either end of the route.' },
  densityAl: { value: 1.6, unit: 't/m3 over the outer diameter', basis: 'Assumed equivalent density to estimate mass per metre of an aluminium cable when none is given.' },
  densityCu: { value: 2.5, unit: 't/m3 over the outer diameter', basis: 'Assumed; close to the 2.5-2.7 implied by the purchaser figures (S7) in cables.json.' },
  densityOther: { value: 2.2, unit: 't/m3 over the outer diameter', basis: 'Assumed for a conductor metal not stated.' },
};

// Typical drum sizes, rounded; assumed, not copied from any maker's table. Check against the supplier's drum schedule.
export const DRUMS = [
  { id: 'D18', flange: 1.8, barrel: 1.0, width: 1.1, tare: 0.35 },
  { id: 'D22', flange: 2.2, barrel: 1.3, width: 1.3, tare: 0.6 },
  { id: 'D26', flange: 2.6, barrel: 1.6, width: 1.5, tare: 0.9 },
  { id: 'D30', flange: 3.0, barrel: 1.8, width: 1.8, tare: 1.4 },
  { id: 'D36', flange: 3.6, barrel: 2.2, width: 2.2, tare: 2.2 },
  { id: 'D40', flange: 4.0, barrel: 2.4, width: 2.4, tare: 3.0 },
  { id: 'D43', flange: 4.3, barrel: 2.8, width: 2.4, tare: 3.6 },
];

const val = (opts, k) => (opts[k] !== undefined ? opts[k] : ASSUMED[k].value);

// Mass per metre: the catalogue figure if cables.json gives one, else estimated from the outer diameter.
export function massPerMetre(cable, opts = {}) {
  if (cable.mass_kg_m > 0) return { kgPerM: cable.mass_kg_m, basis: 'cables.json mass_kg_m' };
  const k = cable.conductor === 'Al' ? 'densityAl' : cable.conductor === 'Cu' ? 'densityCu' : 'densityOther';
  const d = cable.od_mm / 1000;
  return { kgPerM: val(opts, k) * 1000 * Math.PI * d * d / 4, basis: `estimated from OD with ${k} (assumed)` };
}

// The static (final position) bend multiple from cables.json that sets the drum barrel: barrel >= 2 x multiple x OD,
// i.e. 30 x OD for a 33 kV single core. ASSUMED AND CONSERVATIVE: drum packaging rules allow tighter barrels (NEMA WC 26
// Table 3-1 (not checked against the standard here): 12 x OD for extruded wire-shielded cable over 2 kV, 14 x OD tape-shielded; more
// for metallic sheaths), because a cable wound slowly on a supported drum may bend tighter than when installed.
// The maker's drum schedule governs.
export function barrelRule(cable, rules = []) {
  const armoured = /armoured/.test(cable.id);
  const want = cable.voltage_kv > 66 ? 'single_core_metallic_sheath' : armoured ? 'single_core_armoured' : 'single_core_unarmoured';
  const fits = rules.filter((r) => r.voltage_kv === cable.voltage_kv && r.when === 'final' && r.status === 'verified' && r.multiple_of_od > 0);
  const pool = fits.filter((r) => r.construction === want).length ? fits.filter((r) => r.construction === want) : fits;
  if (!pool.length) return { multiple: 15, source: 'No verified static rule in cables.json for this cable; 15 x OD assumed.' };
  const r = pool.reduce((a, b) => (b.multiple_of_od < a.multiple_of_od ? b : a));
  return { multiple: r.multiple_of_od, source: r.source };
}

// Length a drum can hold, square-wound layers: each layer i holds floor(width / OD) turns at diameter barrel + (2i - 1) OD.
export function drumCapacity(drum, odM, freeboard) {
  const layers = Math.floor((drum.flange - drum.barrel - 2 * Math.max(freeboard, odM)) / (2 * odM));
  const turns = Math.floor(drum.width / odM);
  let len = 0;
  for (let i = 1; i <= layers; i++) len += Math.PI * (drum.barrel + (2 * i - 1) * odM) * turns;
  return Math.max(0, len);
}

// Choose the drum that carries the longest length within the flange, payload and barrel limits.
export function chooseDrum(cable, rules, opts = {}) {
  const od = cable.od_mm / 1000;
  const mass = massPerMetre(cable, opts);
  const bend = barrelRule(cable, rules);
  const minBarrel = 2 * bend.multiple * od;
  const table = opts.drums || DRUMS;
  let best = null;
  const rejected = [];
  for (const d of table) {
    if (d.flange > val(opts, 'maxFlange') + 1e-9) { rejected.push({ id: d.id, reason: 'flange above the transport limit' }); continue; }
    if (d.barrel < minBarrel - 1e-9) { rejected.push({ id: d.id, reason: `barrel below ${minBarrel.toFixed(2)} m (2 x ${bend.multiple} x OD, assumed conservative)` }); continue; }
    const capacity = drumCapacity(d, od, val(opts, 'freeboard'));
    const byWeight = Math.max(0, (val(opts, 'maxPayload') - (d.tare || 0)) * 1000 / mass.kgPerM);
    let maxLength = Math.min(capacity, byWeight);
    let governs = capacity <= byWeight ? 'drum capacity' : 'payload weight';
    const cap = val(opts, 'maxPullLength');
    if (cap > 0 && cap < maxLength) { maxLength = cap; governs = 'pulling length cap (assumed)'; }
    if (opts.maxDrumLength > 0 && opts.maxDrumLength < maxLength) { maxLength = opts.maxDrumLength; governs = 'maxDrumLength option'; }
    const c = { ...d, capacity, byWeight, maxLength, governs };
    if (!best || c.maxLength > best.maxLength) best = c;
  }
  return { drum: best, rejected, mass, bend, minBarrel };
}

// Per-sample arrays along the route: plan chainage, 3D distance, and 3D length of each core.
function profile(route) {
  const cl = route.centreline;
  const n = cl.length;
  const plan = [0], d3 = [0];
  for (let k = 1; k < n; k++) {
    const dx = cl[k][0] - cl[k - 1][0], dy = cl[k][1] - cl[k - 1][1], dz = cl[k][2] - cl[k - 1][2];
    plan.push(plan[k - 1] + Math.hypot(dx, dy));
    d3.push(d3[k - 1] + Math.hypot(dx, dy, dz));
  }
  // Chords are a hair shorter than arcs; scale so the plan chainage matches the route's exact length2d.
  const f = plan[n - 1] > 0 ? route.length2d / plan[n - 1] : 1;
  for (let k = 0; k < n; k++) plan[k] *= f;
  const cores = (route.cores && route.cores.length ? route.cores : [{ polyline: cl }]).map((c) => {
    const acc = [0];
    for (let k = 1; k < n; k++) {
      const p = c.polyline[k], q = c.polyline[k - 1];
      acc.push(acc[k - 1] + Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]));
    }
    return acc;
  });
  return { cl, plan, d3, cores, n, xs: cl.map((p) => p[0]), ys: cl.map((p) => p[1]), zs: cl.map((p) => p[2]) };
}

// Linear interpolation of any per-sample array at 3D distance t.
function interp(pr, arr, t) {
  const { d3, n } = pr;
  if (t <= 0) return arr[0];
  if (t >= d3[n - 1]) return arr[n - 1];
  let lo = 0, hi = n - 1;
  while (hi - lo > 1) { const m = (lo + hi) >> 1; if (d3[m] <= t) lo = m; else hi = m; }
  const u = (t - d3[lo]) / (d3[hi] - d3[lo] || 1);
  return arr[lo] + (arr[hi] - arr[lo]) * u;
}

function pointAt(pr, t) {
  return [interp(pr, pr.xs, t), interp(pr, pr.ys, t), interp(pr, pr.zs, t)];
}

// Why a bay centred at 3D distance t is not acceptable; empty when it is.
function bayProblems(pr, route, t, cfg, crossings) {
  const out = [];
  const total = pr.d3[pr.n - 1];
  const half = cfg.bayLength / 2;
  if (t - half < cfg.endClearance || t + half > total - cfg.endClearance) out.push('too near a route end');
  const s = interp(pr, pr.plan, t);
  const a = interp(pr, pr.plan, t - half) - cfg.bayMargin, b = interp(pr, pr.plan, t + half) + cfg.bayMargin;
  for (const g of route.segments) if (g.type === 'arc' && g.s1 > a && g.s0 < b) { out.push('on or near a bend'); break; }
  const za = interp(pr, pr.zs, t - half), zb = interp(pr, pr.zs, t + half);
  const run = interp(pr, pr.plan, t + half) - interp(pr, pr.plan, t - half);
  if (run > 0 && Math.abs(zb - za) / run > cfg.maxBaySlope) out.push('slope above the limit');
  for (const c of crossings) {
    const lo = (c.from !== undefined ? c.from : c.at) - cfg.crossingClearance - half;
    const hi = (c.to !== undefined ? c.to : c.at) + cfg.crossingClearance + half;
    if (s > lo && s < hi) { out.push('near a crossing'); break; }
  }
  return out;
}

export function planDrums({ route, cable, rules = [], crossings = [], groundAt = null, options = {} } = {}) {
  if (!route || !Array.isArray(route.centreline) || route.centreline.length < 2) throw Error('planDrums needs a route from routeCable');
  if (!cable || !(cable.od_mm > 0)) throw Error('planDrums needs a cable with od_mm');
  const opts = options;
  const hv = cable.voltage_kv > 66;
  const cfg = {};
  for (const k of Object.keys(ASSUMED)) cfg[k] = val(opts, k);
  if (opts.bayLength === undefined && hv) cfg.bayLength = 10;
  if (opts.bayWidth === undefined && hv) cfg.bayWidth = 2.5;
  const pick = chooseDrum(cable, rules, opts);
  if (!pick.drum) throw Error('no drum in the table meets the flange, barrel and payload limits');
  const maxL = pick.drum.maxLength;
  const pr = profile(route);
  const total = pr.d3[pr.n - 1];
  const step = opts.searchStep || 1;
  const coreLen = (t0, t1) => Math.max(...pr.cores.map((c) => interp(pr, c, t1) - interp(pr, c, t0)));
  // Ordered length of one core for the section between 3D distances t0 and t1 (before rounding).
  const need = (t0, t1) => {
    const ends = (t0 <= 0 ? cfg.terminationAllowance : cfg.jointAllowance) + (t1 >= total ? cfg.terminationAllowance : cfg.jointAllowance);
    return coreLen(t0, t1) * (1 + cfg.snaking) + ends + cfg.drumEndWaste;
  };
  const fits = (t0, t1) => Math.ceil(need(t0, t1) / cfg.orderIncrement - 1e-9) * cfg.orderIncrement <= maxL + 1e-9;
  // Farthest end t1 reachable from t0 on one drum (bisection on the monotone need()).
  const reach = (t0) => {
    if (fits(t0, total)) return total;
    let lo = t0, hi = total;
    for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (fits(t0, m)) lo = m; else hi = m; }
    return lo;
  };
  const issues = [];
  let joints = [];
  // Fewest drums first, then balance: aim each joint at an equal share of what is left, move it to the nearest
  // acceptable spot that the drum can still reach. Add a drum and retry when the balanced plan does not close.
  const n0 = Math.max(1, Math.ceil(total * (1 + cfg.snaking) / maxL));
  for (let n = n0; ; n++) {
    if (n > n0 + 200) { issues.push('no balanced plan found within 200 extra drums per core'); break; }
    const placed = [];
    let prev = 0;
    for (let k = 1; k < n; k++) {
      const far = reach(prev);
      const target = prev + (total - prev) / (n - k + 1);
      let best = null;
      for (let d = 0; d <= far - prev; d += step) {
        for (const t of d === 0 ? [target] : [target - d, target + d]) {
          if (t <= prev + cfg.bayLength || t > far) continue;
          if (!bayProblems(pr, route, t, cfg, crossings).length) { best = t; break; }
        }
        if (best !== null) break;
      }
      if (best === null) { best = Math.min(target, far); placed.push({ t: best, forced: true }); } else placed.push({ t: best, forced: false });
      prev = best;
    }
    joints = placed;
    if (fits(prev, total)) break; // the last section ends at the termination: test it with that allowance
  }
  const cuts = [0, ...joints.map((j) => j.t), total];
  const cores = pr.cores.length;
  const sections = [];
  for (let i = 0; i < cuts.length - 1; i++) {
    const t0 = cuts[i], t1 = cuts[i + 1];
    const len = coreLen(t0, t1);
    const ordered = Math.ceil(need(t0, t1) / cfg.orderIncrement - 1e-9) * cfg.orderIncrement;
    sections.push({
      index: i + 1, from: t0, to: t1, fromChainage: interp(pr, pr.plan, t0), toChainage: interp(pr, pr.plan, t1),
      routeLength3d: t1 - t0, coreLength3d: len, snaking: len * cfg.snaking,
      endAllowances: need(t0, t1) - len * (1 + cfg.snaking) - cfg.drumEndWaste, drumEndWaste: cfg.drumEndWaste,
      orderedPerCore: ordered, drums: cores, withinDrum: ordered <= maxL + 1e-9,
    });
  }
  const bays = joints.map((j, i) => {
    const [x, y, z] = pointAt(pr, j.t);
    const q = pointAt(pr, Math.min(total, j.t + 0.5)), p = pointAt(pr, Math.max(0, j.t - 0.5));
    const problems = bayProblems(pr, route, j.t, cfg, crossings);
    if (problems.length) issues.push(`joint bay ${i + 1} at ${interp(pr, pr.plan, j.t).toFixed(1)} m: ${problems.join(', ')}`);
    return { index: i + 1, distance3d: j.t, chainage: interp(pr, pr.plan, j.t), x, y, z, heading: Math.atan2(q[1] - p[1], q[0] - p[0]), problems };
  });
  for (const s of sections) if (!s.withinDrum) issues.push(`section ${s.index} needs ${s.orderedPerCore} m per core, over the ${maxL.toFixed(0)} m drum limit`);
  const installed = sections.reduce((a, s) => a + s.coreLength3d * (1 + cfg.snaking), 0) * cores;
  const ordered = sections.reduce((a, s) => a + s.orderedPerCore, 0) * cores;
  const schedule = {
    cable: { id: cable.id, od_mm: cable.od_mm, massKgPerM: pick.mass.kgPerM, massBasis: pick.mass.basis },
    drum: { id: pick.drum.id, flange: pick.drum.flange, barrel: pick.drum.barrel, width: pick.drum.width, capacity: pick.drum.capacity,
      byWeight: pick.drum.byWeight, maxLength: maxL, governs: pick.drum.governs, minBarrel: pick.minBarrel, barrelRule: pick.bend, rejected: pick.rejected,
      basis: opts.drums ? 'drum table passed in' : "assumed typical drum sizes, not a maker's table" },
    sections,
    joints: bays,
    totals: {
      routeLength3d: total, cores, drums: sections.length * cores, jointBays: bays.length, joints: bays.length * cores,
      orderedPerCore: ordered / cores, orderedTotal: ordered, installedTotal: installed, waste: ordered - installed,
      wasteFraction: ordered > 0 ? (ordered - installed) / ordered : 0,
    },
    assumptions: Object.keys(ASSUMED).map((k) => ({ name: k, value: cfg[k], unit: ASSUMED[k].unit, basis: ASSUMED[k].basis, overridden: opts[k] !== undefined })),
    issues,
  };
  schedule.drawLines = () => drawJointBays(bays, cfg, groundAt);
  return schedule;
}

// Joint bays as small outlined pits: rim rectangle at ground, floor rectangle, four corner edges. Float32Array of x,y,z pairs.
export function drawJointBays(bays, cfg = {}, groundAt = null) {
  const L = cfg.bayLength || ASSUMED.bayLength.value, W = cfg.bayWidth || ASSUMED.bayWidth.value;
  const below = cfg.bayFloorBelowCable !== undefined ? cfg.bayFloorBelowCable : ASSUMED.bayFloorBelowCable.value;
  const cover = cfg.coverIfNoGround !== undefined ? cfg.coverIfNoGround : ASSUMED.coverIfNoGround.value;
  const out = new Float32Array(bays.length * 12 * 6);
  let o = 0;
  const seg = (a, b) => { out[o++] = a[0]; out[o++] = a[1]; out[o++] = a[2]; out[o++] = b[0]; out[o++] = b[1]; out[o++] = b[2]; };
  for (const b of bays) {
    const c = Math.cos(b.heading), s = Math.sin(b.heading);
    const corners = [[-L / 2, -W / 2], [L / 2, -W / 2], [L / 2, W / 2], [-L / 2, W / 2]].map(([u, v]) => [b.x + u * c - v * s, b.y + u * s + v * c]);
    const floor = b.z - below;
    const top = corners.map(([x, y]) => [x, y, groundAt ? groundAt(x, y) : b.z + cover]);
    const bot = corners.map(([x, y]) => [x, y, floor]);
    for (let i = 0; i < 4; i++) { seg(top[i], top[(i + 1) % 4]); seg(bot[i], bot[(i + 1) % 4]); seg(top[i], bot[i]); }
  }
  return out;
}

Find Mount

A JavaScript module in the world folder of GlobalGrid2050 that draws projects and postcodes, using OSTN15.

renderglobalgrid2050 / solar-design-studio/202609270439-site-world/world/find-mount.mjs · lines 1–42 of 42 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern mountFind (shared by 3 files)

What it does
It draws projects and postcodes. Defines mountFind, siteNear, loadIndex. 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: postcodes.
Inputs & outputs
In: JSON file projects.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It loads index (`loadIndex`) and is built from the mount find helper (`mountFind`) and the site near helper (`siteNear`). Find in the dash: a Renewable Energy Planning Database (REPD) project, postcode or "lat, lon"; the drone flies there. It reads `./world/data/projects.json`. It responds to keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
Uses
Search UI (import), Bng (import), OSTN15 (import), Origin (import)
Used by
none found
Produces
mountFind
Defines here
mountFind, siteNear, loadIndex
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/202609270439-site-world/world/find-mount.mjs:1-42 · blob 22aa6e882c768145dd0ff99a7173ace6c1732503 · 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: unreached_review
// Find in the dash: a REPD project, postcode or "lat, lon"; the drone flies there. Near the staged site there is terrain.
// Loaded just after the first frame with the other tools (review E). ctx: { site(), attribution, origin(), SITE_HALF_M,
// first(), canvas, close(), flyTo(x, y) }. Returns the search panel ({ element, open, close }).
import { createSearchPanel, arrivalNote } from './search-ui.mjs';
import { wgs84ToBng } from './bng.mjs';
import { createOstn15 } from './ostn15.mjs';
import { toLocal } from './origin.mjs';

export function mountFind({ site, attribution, origin, SITE_HALF_M, first, canvas, close, flyTo, doc = document, ostn = createOstn15() }) {
  const siteNear = (lat, lon) => {
    const s = site();
    if (!s) return false;
    const p = wgs84ToBng(lat, lon);
    return Math.abs(p.e - s.centre_e) <= SITE_HALF_M && Math.abs(p.n - s.centre_n) <= SITE_HALF_M;
  };
  const loadIndex = () => fetch('./world/data/projects.json', { cache: 'no-cache' })
    .then(r => { if (!r.ok) throw Error(`HTTP ${r.status}`); return r.json(); });
  const search = createSearchPanel(doc.body, {
    loadIndex, attribution, hasTerrain: siteNear, liveTerrain: true,
    onChoose: async choice => { // a postcode brings its own national-grid figures; a lat, lon goes through OSTN15
      const { lat, lon, e, n } = choice, given = Number.isFinite(e) && Number.isFinite(n);
      if (!given) await ostn.need(lat, lon);
      const p = given ? { e, n, ostn15: true } : ostn.toBng(lat, lon), [x, y] = toLocal(origin(), p.e, p.n);
      close();
      flyTo(x, y);
      const note = arrivalNote(choice, siteNear, true);
      first()?.showPlace(choice, p.e, p.n, p.ostn15 ? note : `${note ? note + ' ' : ''}Position approximate (±5 m): outside the OSTN15 blocks held here.`);
      canvas.focus();
    }
  });
  search.element.id = 'find';
  // Test sites (staged locally) sit under the search; project-ui.mjs fills the list and shows it.
  const sites = doc.createElement('section'), h = doc.createElement('h3'), box = doc.createElement('div');
  Object.assign(sites, { id: 'site-section', className: 'site-section', hidden: true });
  h.textContent = 'Test sites'; box.id = 'site-box';
  sites.append(h, box); search.element.append(sites);
  // Escape inside the box closes it; keep the Find button in step.
  search.element.addEventListener('keydown', e => {
    if (e.key === 'Escape') { doc.getElementById('find-toggle').setAttribute('aria-expanded', 'false'); delete doc.body.dataset.panel; }
  });
  return search;
}

Layers

A JavaScript module in the world folder of GlobalGrid2050 that loads base (`loadBase`) and lib (`loadLib`) and fetches checked (`fetchChecked`), using SHA-256.

renderglobalgrid2050 / solar-design-studio/202609270439-site-world/world/layers.mjs · lines 1–226 of 226 · version 2026-09-27 04:39 · Entry point · pattern fetchChecked (shared by 2 files)

What it does
It fetches data. Defines 20 functions or classes, including loadBase, withBase, loadLib, no, libRefusal. 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.
Downstream impact
Used directly by 7 files: Layers UI (globalgrid2050); Buffers UI (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Cmd Run (globalgrid2050); and 3 more.
What it achieves
It loads base (`loadBase`), loads lib (`loadLib`) and imports text (`importText`). The manifest lists layers in order; each layer file is fetched, its SHA-256 compared with the manifest, and only then imported.
Why it matters
Loaded by the Site World page at https://globalgrid2050.com/solar-design-studio/202609271853-site-world/. Also imported by 6 files, including Layers UI, Buffers UI and Cmd Run.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
Uses
Site World V3 — World (import), Overhead (dynamic import), Trench (dynamic import), Cable Route (dynamic import)
Used by
imported by Layers UI (import), imported by Buffers UI (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Cmd Run (import), imported by Packs Mount (import), imported by Plant Ground (import), imported by Substrate (import)
Produces
loadBase, loadLib, libRefusal, loadLayers, REFUSED, statusLine, startLayer, makeApi, normalise, sha256, sha256Bytes
Defines here
loadBase, withBase, loadLib, no, libRefusal, earlyFetch, importText, loadLayers, fetchChecked, start, fetchOne, statusLine, startLayer, off, makeApi, fetchVerified, fetchJSON, normalise, sha256, sha256Bytes
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/202609270439-site-world/world/layers.mjs:1-226 · blob c5cee451f0c37eabf7fc8d7fd1240de196f66ef6 · 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: production_core
// Layer loader. The manifest lists layers in order; each layer file is fetched, its SHA-256 compared
// with the manifest, and only then imported. A layer whose hash differs is refused and named, never run.
// A layer is a module whose default export may offer:
//   init(api)        -> called once after the layer is verified and imported (may return a promise)
//   lines(ctx)       -> [{ key, version, positions: Float32Array, color: [r,g,b,a], origin?: [x,y,z] }]
//   heightAt(x, y)   -> ground height in metres (the first layer offering a finite height is the ground)
//   solids(ctx)      -> [{ min: [x,y,z], max: [x,y,z] }] boxes nobody can walk or fly through
// Layers are self-contained: no imports (they run from a blob URL). Positions are in local metres
// from the site origin, never national-grid coordinates: the GPU pair (tools/gpu/world_pair.py) measured
// 32-bit drawing error passing 0.1 px about 200 m from the origin and 0.5 px about 1 km out.
// A batch may carry an origin (local metres) with its positions relative to it, so it stays sharp far out.
//
// The api handed to init(api):
//   base                         absolute URL of the manifest's folder
//   fetchVerified(path, sha256)  -> Promise<ArrayBuffer>; the raw bytes are hashed as sent, nothing normalised
//   fetchJSON(path, sha256)      -> Promise<any>; the same check, then the text is decoded and parsed
//   invalidate({ ground })       asks for a redraw; ground (default true) says new ground has arrived
//   origin()                     -> { e, n, id }: the site origin in national-grid metres and its change count
//   lib                          pure helpers a self-contained layer may call: lib.overhead (buildOverhead, catenarySpan...),
//                                lib.trench (createTrench, composeGround), lib.cableRoute (routeCable), and the shared
//                                world library (web/world/lib): lib.version, lib.tiles, lib.drape, lib.earthworks
// The shared library's files are in the manifest (manifest.lib: { version, files: [{ id, path, sha256 }] }) and are
// hash-checked and imported like layers before any layer starts. A layer written for it declares the version
// (export const LIB_VERSION; the manifest repeats it as the entry's lib) and is refused unless it is the one served.

import SHARED, { LIB_VERSION, LIB_FILES } from './lib/index.mjs';

// lib.overhead, lib.trench and lib.cableRoute are not needed to draw the ground, so they load after it (loadBase,
// review E): until then those three read undefined. The layers that use them start after loadBase has finished.
let BASE = null, baseP = null;
export const loadBase = () => (baseP ||= Promise.all([import('./overhead.mjs'), import('./trench.mjs'), import('./cable-route.mjs')])
  .then(([overhead, t, c]) => (BASE = Object.freeze({ overhead, trench: Object.freeze({ createTrench: t.createTrench, composeGround: t.composeGround }),
    cableRoute: Object.freeze({ routeCable: c.routeCable }) }))));
const withBase = o => Object.freeze(Object.defineProperties(o, Object.fromEntries(['overhead', 'trench', 'cableRoute']
  .map(k => [k, { get: () => BASE?.[k], enumerable: true }]))));
const LIB = withBase({ ...SHARED });

// The shared library as the manifest lists it: every file fetched, hash-checked and imported, or { lib: null, why }.
// get and load are for tests (load(text) imports checked module text).
export async function loadLib(entry, base, { get = (u, o) => fetch(u, o), load = importText } = {}) {
  const no = why => ({ lib: null, why });
  if (!entry) return no('the manifest lists no lib');
  if (entry.version !== LIB_VERSION) return no(`the manifest's lib is version ${entry.version}, this page serves ${LIB_VERSION}`);
  const mods = {};
  // All files fetched at once (one round trip on a slow phone link, review E), then checked and imported in order.
  const got = await Promise.all((entry.files || []).map(async f => {
    const res = await get(new URL(f.path, base).href, { cache: 'no-cache' });
    return { f, res, text: res.ok ? normalise(await res.text()) : null };
  }));
  for (const { f, res, text } of got) {
    if (!res.ok) return no(`lib ${f.id}: HTTP ${res.status}`);
    const hash = await sha256(text);
    if (!hash) return no('this browser cannot check hashes here (needs https)');
    if (hash !== f.sha256) return no(`lib ${f.id} hash ${hash.slice(0, 12)} is not the manifest's ${String(f.sha256).slice(0, 12)}`);
    mods[f.id] = Object.freeze({ ...await load(text) });
  }
  const missing = LIB_FILES.filter(id => !mods[id]);
  if (missing.length) return no(`the manifest's lib has no ${missing.join(', ')}`);
  return { lib: withBase({ version: LIB_VERSION, ...mods }), why: null };
}

// Why a layer that declares lib version `want` cannot run on `lib` (null when it can, or declares none).
export function libRefusal(want, lib, why) {
  if (want === undefined || want === null) return null;
  if (!lib) return `refused: it needs lib version ${want} and the lib was refused (${why})`;
  return want === lib.version ? null : `refused: it declares lib version ${want}, the substrate serves ${lib.version}`;
}

// A fetch world.html started with the page (window.__early, keyed by absolute URL) is used once; otherwise a new one.
function earlyFetch(url) {
  const m = globalThis.__early, p = m?.get?.(url);
  if (p) { m.delete(url); return p; }
  return fetch(url, { cache: 'no-cache' });
}

async function importText(text) {
  const blob = URL.createObjectURL(new Blob([text], { type: 'text/javascript' }));
  try { return await import(blob); } finally { URL.revokeObjectURL(blob); }
}

// hooks.started(item): called as each layer starts (the substrate mounts a layer's own controls, imagery's date slider).
// hooks.site: a staged site chosen on the page ({ name, centre_e, centre_n, tiles, sha256 } from data/sites.json);
// its tile index replaces the manifest's for the terrain layer, and it becomes the site the world centres on.
export async function loadLayers(manifestUrl, hooks = {}) {
  const base = new URL(manifestUrl, location.href);
  // The lib's files are asked for alongside the manifest (their hashes are checked once it arrives): one round trip less.
  // world.html starts the manifest, the lib's texts and the first layers with the page (earlyFetch): each is taken once.
  const early = new Map(LIB_FILES.map(id => { const u = new URL(`./lib/${id}.mjs`, base).href; return [u, earlyFetch(u)]; }));
  const res = await earlyFetch(base.href);
  if (!res.ok) throw Error(`manifest HTTP ${res.status}`);
  const manifest = await res.json();
  // The shared library is fetched and checked alongside the first layers (not before them: the first frame waits
  // for neither more than it must); a layer starts only once the lib is known.
  const libP = loadLib(manifest.lib, base, { get: (u, o) => early.get(u) || fetch(u, o) }).catch(e => ({ lib: null, why: 'lib: ' + e.message }));
  let lib = null, why = null, api = null;
  const ready = libP.then(r => { ({ lib, why } = r); api = makeApi(new URL('./', base).href, { ...hooks, lib: lib || withBase({}) }); });
  // Fetch and hash: the layers that start on all at once, in parallel; import and start them in manifest order.
  // hooks.deferred: ids of layers that start switched off; they are fetched, checked and started only when first
  // switched on (item.load()), so the first frame does not wait for them (review E, win 1).
  const fetchChecked = async entry => {
    if (!entry.sha256) return { status: 'refused: the manifest gives no hash' };
    const res = await earlyFetch(new URL(entry.path, base).href);
    if (!res.ok) throw Error(`HTTP ${res.status}`);
    const text = normalise(await res.text());
    const hash = await sha256(text);
    if (!hash) return { status: 'refused: this browser cannot check hashes here (needs https)' };
    if (hash !== entry.sha256) return { status: `refused: file hash ${hash.slice(0, 12)} is not the manifest's ${entry.sha256.slice(0, 12)}` };
    return { text };
  };
  const start = async (item, entry, got) => {
    if (!got.text) { item.status = got.status; return; }
    await ready;
    const refused = libRefusal(entry.lib, lib, why);
    if (refused) { item.status = refused; return; }
    const mod = await importText(got.text);
    const late = libRefusal(mod.LIB_VERSION, lib, why);
    if (late) { item.status = late; return; }
    item.layer = mod.default; item.status = 'loaded, hash matches';
    const pick = entry.id === 'terrain' && hooks.site ? { index: hooks.site.tiles, sha256: hooks.site.sha256 } : null;
    startLayer(item, Object.freeze({ ...api, config: pick ? { ...entry.config, ...pick } : entry.config || null })); // per-layer settings
    try { hooks.started?.(item); } catch (e) { item.status += ' (its controls failed: ' + e.message + ')'; }
  };
  // hooks.first: ids the first frame needs (the ground); the other layers that start on are fetched once those have
  // arrived and started just after, and loadLayers returns without waiting for them (its rest promise says when).
  const deferred = new Set(hooks.deferred || []), entries = manifest.layers || [];
  const first = hooks.first ? new Set(hooks.first) : null, isFirst = e => !first || first.has(e.id);
  const fetchOne = e => fetchChecked(e).then(got => got, err => ({ status: 'failed: ' + err.message }));
  const pending = entries.map(e => (deferred.has(e.id) || !isFirst(e) ? null : fetchOne(e)));
  const later = Promise.all(pending).then(() => {
    const base = loadBase().catch(() => null), got = entries.map((e, i) => pending[i] || (deferred.has(e.id) ? null : fetchOne(e)));
    return base.then(() => got);
  });
  const out = [], rest = [];
  for (const [i, entry] of entries.entries()) {
    const item = { id: entry.id, status: 'loading' };
    out.push(item);
    if (deferred.has(entry.id)) {
      item.status = 'ready: loads when switched on';
      let once = null;
      item.load = () => (once ||= (async () => {
        item.status = 'ready: loading now'; // stays available in the panel while it loads
        await loadBase().catch(() => {});
        try { await start(item, entry, await fetchChecked(entry)); } catch (e) { item.status = 'failed: ' + e.message; }
        if (item.layer && !item.hidden && typeof item.layer.setEnabled === 'function' && !item.layer.enabled) item.layer.setEnabled(true);
        hooks.invalidate?.({ ground: false });
      })());
      continue;
    }
    if (!isFirst(entry)) { rest.push([item, entry, i]); continue; }
    try { await start(item, entry, await pending[i]); } catch (e) { item.status = 'failed: ' + e.message; }
  }
  await ready;
  const restP = rest.length ? (async () => {
    const got = await later;
    for (const [item, entry, i] of rest) {
      try { await start(item, entry, await got[i]); } catch (e) { item.status = 'failed: ' + e.message; }
      hooks.invalidate?.({ ground: false });
    }
  })().catch(() => {}) : loadBase().catch(() => {});
  const s = hooks.site, site = s ? { ...manifest.site, name: s.name, centre_e: s.centre_e, centre_n: s.centre_n } : manifest.site || null;
  return { generation: manifest.generation, site, layers: out, rest: restP, lib: lib ? `version ${lib.version}, hashes match` : `refused: ${why}` };
}

// A layer's loader status with its own words. "hash matches" is about the layer's code; when the layer's own data
// (a tile index, a data file) was refused or failed, the words say that and never "hash matches".
export const REFUSED = /refused|failed|no .*hash|not hash-checked|mismatch/i;
export function statusLine(item) {
  const own = typeof item?.layer?.status === 'string' ? item.layer.status : '';
  const base = String(item?.status ?? '');
  if (own && REFUSED.test(own)) return `${base.replace(/,? hash matches/, '')} (${own})`;
  return own ? `${base} (${own})` : base;
}

// Runs a layer's init. A layer whose init throws, or whose promise rejects, is switched off and named.
export 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); }
}

// base: absolute URL of a folder. hooks: { invalidate(opts), origin(), lib }; fetchImpl is for tests; lib defaults to the static copy.
// hooks.towers(): known tower positions [{ e, n }] from the grid and national layers (the canopy masks them).
export function makeApi(base, { invalidate = () => {}, origin = () => ({ e: 0, n: 0, id: 0 }), fetchImpl, lib = LIB, towers = () => [] } = {}) {
  const get = fetchImpl || ((u, o) => fetch(u, o));
  async function fetchVerified(path, sha) {
    if (typeof sha !== 'string' || !/^[0-9a-f]{64}$/i.test(sha)) throw Error(`${path}: no valid SHA-256 given`);
    const res = await get(new URL(path, base).href, { cache: 'no-cache' });
    if (!res.ok) throw Error(`${path}: HTTP ${res.status}`);
    const bytes = await res.arrayBuffer();
    const hash = await sha256Bytes(bytes);
    if (!hash) throw Error(`${path}: this browser cannot check hashes here (needs https)`);
    if (hash !== sha.toLowerCase()) throw Error(`${path}: hash ${hash.slice(0, 12)} is not the expected ${sha.slice(0, 12)}`);
    return bytes;
  }
  async function fetchJSON(path, sha) {
    return JSON.parse(new TextDecoder().decode(await fetchVerified(path, sha)));
  }
  return Object.freeze({
    base,
    fetchVerified,
    fetchJSON,
    invalidate: (opts = {}) => invalidate({ ground: opts.ground !== false }),
    origin: () => { const o = origin(); return { e: o.e, n: o.n, id: o.id }; },
    towers: () => { try { const t = towers(); return Array.isArray(t) ? t : []; } catch { return []; } },
    lib
  });
}

// Line endings and a byte-order mark are normalised so a Windows checkout and the published file hash the same.
// This applies to layer code only; data files are hashed exactly as sent (see fetchVerified).
export const normalise = text => text.replace(/^/, '').replace(/\r\n/g, '\n');

export async function sha256(text) {
  return sha256Bytes(new TextEncoder().encode(text));
}

export 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('');
}