GLOBALGRID2050 / EXPLORE CODE

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

Substrate and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that sets origin (`setOrigin`), writes readout (`writeReadout`), opens panel (`openPanel`) and calculates planar distances (units: kV).

697 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 194 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. Single-Line Diagram (SLD) Rules electrical · globalgrid2050 / solar-design-studio/202609271853-site-world/world/sld-rules.mjs lines 1–93
  2. Structure Presets transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/structure-presets.mjs lines 1–72
  3. Structures ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/structures.mjs lines 1–134
  4. Substrate geodesy · globalgrid2050 / solar-design-studio/202609271853-site-world/world/substrate.mjs lines 1–398

Single-Line Diagram (SLD) Rules

A JavaScript module in the world folder of GlobalGrid2050 that works with cables, transformers, battery storage (BESS) and solar, using IEC 60502-2 and BS 7671.

electricalglobalgrid2050 / solar-design-studio/202609271853-site-world/world/sld-rules.mjs · lines 1–93 of 93 · version 2026-09-27 18:53 · pattern isolationChecks (shared by 3 files)

What it does
It calculates cables, transformers, battery storage (BESS) and solar. Defines groupFactor, economicSize, cost, isolationChecks, zOf.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, transformers, battery storage (BESS), solar, 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 12 files: Block MV (globalgrid2050); Single-Line Diagram (SLD) Calc (globalgrid2050); Single-Line Diagram (SLD) Graph (globalgrid2050); Single-Line Diagram (SLD) Plant (globalgrid2050); and 8 more. Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It groups factor (`groupFactor`) and is built from the economic size helper (`economicSize`) and the cost step (`cost`). The generic electrical rules the single-line diagram generator shares (`sld-plant.mjs`, `block-mv.mjs`, `sld-graph.mjs`): group factors for circuits sharing a trench, an economic step on top of the technical cable size, the switching and protection devices of each functional way. Its code works with 33 kV.
Why it matters
Imported by 12 files, including Block MV, Single-Line Diagram (SLD) Calc and Single-Line Diagram (SLD) Graph.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Cable Rating (import), Elec Style (import), Measure Format (import)
Used by
imported by Block MV (import), imported by Single-Line Diagram (SLD) Calc (import), imported by Single-Line Diagram (SLD) Graph (import), imported by Single-Line Diagram (SLD) Plant (import), imported by Single-Line Diagram (SLD) Source (import), imported by Earth Mount (import), imported by Hud Drops (import), imported by Single-Line Diagram (SLD) Follow (import), and 4 more
Produces
SLD_LABEL, groupFactor, ECONOMIC, PALETTE, economicSize, DEVICES, INVERTER_ISOLATION, isolationChecks, SLD_DEFAULTS, C, zOf
Defines here
groupFactor, economicSize, cost, isolationChecks, zOf
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/202609271853-site-world/world/sld-rules.mjs:1-93 · blob b27d1862239e37c3517715c170d703a643f6ca81 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// sld-rules.mjs: the generic electrical rules the single-line diagram generator shares (sld-plant.mjs, block-mv.mjs,
// sld-graph.mjs): group factors for circuits sharing a trench, an economic step on top of the technical cable size,
// the switching and protection devices of each functional way, and the assumed impedances and source.
// Every value here is generic practice or a public standard, or is marked assumed. Illustrative, not a design for any
// site. Pure: imports only the cable rating.

import { rating, SIZES } from './cable-rating.mjs';

export const SLD_LABEL = 'Illustrative, not a design for any site.';

// Group factors for 33 kV trefoil circuits laid direct side by side, about 0.4-0.45 m apart: approximate values in the
// style of the IEC 60502-2 annex tables (a rating study replaces them). Index = circuits in the trench.
const GROUP = [1, 1, 0.87, 0.78, 0.73, 0.69, 0.66, 0.64, 0.62];
export const groupFactor = n => GROUP[Math.max(1, Math.min(GROUP.length - 1, Math.round(n) || 1))];

// Economic step (assumed unit costs, not any supplier's): capitalised I2R loss against a cable cost that grows with the
// conductor area. Loss hours and the present-worth factor are generic solar figures; money is in plain cost units.
export const ECONOMIC = Object.freeze({ lossHours: 1100, pricePerMWh: 60, years: 25, rate: 0.06, costPerM: 30, costPerMm2M: 0.09 });
export const PALETTE = Object.freeze([120, 185, 300, 500, 630, 800, 1000]); // a small stock of sizes, not the full series

/**
 * economicSize(technicalArea, mva, lengthM, opts) -> the palette size, at or above the technical size, whose cable cost
 * plus capitalised losses is least. opts: cable-rating options plus { economic }.
 */
export function economicSize(area, mva, lengthM, opts = {}) {
  const e = { ...ECONOMIC, ...(opts.economic || {}) }, kv = opts.kv || 33, I = mva * 1e6 / (Math.sqrt(3) * kv * 1000);
  const pw = (1 - (1 + e.rate) ** -e.years) / e.rate;
  const cost = a => {
    const R = rating(a, opts).R;                               // ohm per metre at the rated temperature (conservative)
    return lengthM * (e.costPerM + e.costPerMm2M * a * 3) + 3 * I * I * R * lengthM * e.lossHours / 1e6 * e.pricePerMWh * pw;
  };
  const list = PALETTE.filter(a => a >= area && SIZES.includes(a));
  if (!list.length) return area;
  return list.reduce((best, a) => (cost(a) < cost(best) - 1e-9 ? a : best), list[0]);
}

// Devices of each functional way, as the diagram draws them (state: closed unless marked open).
export const DEVICES = Object.freeze({
  'rmu-in': ['switch-disconnector', 'earth-switch'],
  'rmu-out': ['switch-disconnector', 'earth-switch'],
  'rmu-tx': ['circuit-breaker', 'protection 50/51 50N/51N', 'earth-switch'],
  'lv-main': ['main breaker', 'insulation monitor', 'surge protection', 'meter'],
  'lv-way': ['breaker'],                                       // one per inverter; no local isolator at the inverter end
  'mv-way': ['vacuum circuit breaker', 'protection 50/51 50N/51N', 'earth-switch'],
  'mv-incomer': ['vacuum circuit breaker', 'protection 51 87T'],
  'bus-tie': ['vacuum circuit breaker (normally open)'],
  'hv-bay': ['disconnector', 'earth switch', 'surge arresters', 'current and voltage transformers'],
  'gis-bay': ['gas-insulated circuit breaker', 'disconnector', 'earth switch'],
  'earthing': ['earthing transformer (zigzag)', 'neutral earthing resistor']
});

// Isolation at the inverter from every source that feeds it (BS 7671 537 and 712.537; IEC 62548-1 isolation clauses):
// each source present needs a named means of isolation at the inverter. Defaults as the diagram draws them: the PV side's
// DC switch-disconnector is taken from the inverter's datasheet (assumed); the AC side has only the board breaker, no
// local isolator at the inverter end; no BESS. A plain check with editable inputs, not a design.
export const INVERTER_ISOLATION = Object.freeze({ pv: 'DC switch-disconnector in the inverter (datasheet, assumed)', grid: null, bess: undefined });
export function isolationChecks(at = INVERTER_ISOLATION) {
  const WORDS = { pv: 'PV (DC)', grid: 'grid (AC)', bess: 'battery (BESS)' };
  return Object.entries(WORDS).filter(([k]) => at[k] !== undefined).map(([k, w]) => ({ source: w, ok: !!at[k], device: at[k] || 'none at the inverter' }));
}

// Assumed impedances and the grid source. Transformer impedances sit inside the usual ranges (station 6-10 %).
export const SLD_DEFAULTS = Object.freeze({
  sBaseMVA: 100, c: 1.1,                       // IEC 60909 voltage factor for maximum fault current
  sourceKA: null, sourceXR: 14,                // grid fault level at the landing: set, or by voltage below (assumed)
  sourceKAByKv: { 400: 40, 275: 40, 132: 25, 33: 12.5 },
  stZPct: 7, stXR: 10, stVector: 'Dy11y11',    // station transformer, one unit with a list of LV windings
  gtZPct: 14, gtXR: 40, gtVector: 'YNd11', gtHvNeutral: 'solid', gtTwoLvFromMVA: 120,
  tapRange: 0.10, tapStep: 0.0125, tapTarget: 1.0,  // grid transformer on-load tap changer (illustrative, editable)
  hvCableOhmKm: [0.012, 0.19],                 // single-core HV cable, large copper (assumed)
  ohlOhmKm: [0.03, 0.3],                       // overhead line option (assumed)
  lvXOhmKm: 0.08,                              // single-core LV cable reactance (assumed)
  busPu: [1e-6, 1e-5],                         // busbars and closed switching devices
  nerA: 1000, powerFactor: 0.95,               // NER limit (assumed); export at 0.95 for the drop (reactive duty)
  module: { w: 660, vmp: 38.6, imp: 17.1, voc: 45.9 }, dcAreaMm2: 6, dcOhmKm20: 3.08, dcTempC: 70
});

/** Complex numbers as [re, im]: the few operations the solvers need. */
export const C = Object.freeze({
  add: (a, b) => [a[0] + b[0], a[1] + b[1]], sub: (a, b) => [a[0] - b[0], a[1] - b[1]],
  mul: (a, b) => [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]],
  div: (a, b) => { const d = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / d, (a[1] * b[0] - a[0] * b[1]) / d]; },
  conj: a => [a[0], -a[1]], abs: a => Math.hypot(a[0], a[1])
});

/** An impedance of |z| per unit at ratio X/R, as [r, x]. */
export const zOf = (mag, xr) => { const r = mag / Math.sqrt(1 + xr * xr); return [r, r * xr]; };

// Every electrical readout ends with this line (earthing, the single-line diagram, Follow, the check HUD's working).
export { ELEC_FOOTER } from './elec-style.mjs';   // one source for the words

// Quantities by the one number rule (measure-format.mjs): significant figures, one dash for none.
export { fmtQ } from './measure-format.mjs';

Structure Presets

A JavaScript module in the world folder of GlobalGrid2050 that works with solar and transformers.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/structure-presets.mjs · lines 1–72 of 72 · version 2026-09-27 18:53 · pattern presetById (shared by 3 files)

What it does
It calculates solar and transformers. Defines presetById, presetText.
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: solar, transformers.
Downstream impact
Used directly by 3 files: Cmd Grammar Plant (globalgrid2050); Cmd Grammar (globalgrid2050); Cmd Model (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It is built from the preset by id helper (`presetById`) and the preset text helper (`presetText`). Generic plant presets from an open-data study of large operational UK solar farms, typed as "preset " (or "structure "). Its code works with 3 MVA, 3 MW and 300 kVA.
Why it matters
Imported by Cmd Grammar Plant, Cmd Grammar and Cmd Model.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Cmd Grammar Plant (import), imported by Cmd Grammar (import), imported by Cmd Model (import)
Produces
PRESET_NOTE, PRESETS, PRESET_IDS, presetById, presetText
Defines here
presetById, presetText
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/202609271853-site-world/world/structure-presets.mjs:1-72 · blob a95aa3b87591ba199e38b3379e91c1ec324126f2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// structure-presets.mjs: generic plant presets from an open-data study of large operational UK solar farms, typed as
// "preset <id>" (or "structure <id>"). Each sets typed values the owner can change afterwards; none sets the Solar
// block (its defaults are the owner's and stay as they are).
//
// The study measured rows as built from open 1 m LiDAR (a GPU pair with a CPU witness) at a few older plants, and read
// public planning and trade records at the others. Every preset says its evidence tier: measured (as built), public
// design (planning or public counts), or hypothesis (consistent but not resolved). Sites are not named, and no preset
// reproduces any one plant: module classes are generic and the values sit inside the ranges found.
// Measured distribution behind the defaults: row pitch 8.0-9.3 m as built at four plants (the v09 default was 11.97 m);
// plan cover (GCR) 0.41-0.52 at 2 portrait plants and 0.63-0.70 at 6-high landscape plants; tilt 15-25°.
// Pure: no DOM, no imports.

export const PRESET_NOTE = 'Generic preset from open-data studies of operational UK plants; illustrative class values, not a design for any site.';

// set: typed values (cmd-grammar KEYS). moduleLong/moduleShort are generic module classes (60-cell about 1.65 x 0.99 m).
export const PRESETS = Object.freeze([
  { id: 'central-6l-20', label: 'Central inverters, landscape 6-high tables, about 20°, dense',
    set: { layout: 'south', tiers: 6, orient: 'landscape', tableCols: null, tilt: 20, gcr: 0.65, edge: 0.7, moduleLong: 1.65, moduleShort: 0.99,
      wp: 260, voc: 38, inverterClass: 'central', inverterKVA: 2000, invertersPerStation: 1, packing: 'fields' },
    ranges: 'tilt 18-20°; lowest edge 0.65-0.8 m; top 2.35-3.0 m; slant 6.0-6.5 m; pitch 9.1-9.2 m; GCR 0.63-0.66; row runs 140-150 m',
    evidence: 'measured as built at two plants (6-high landscape chosen over 3P, 4L and 2P by slant length and by row length x public module count)' },
  { id: 'central-deep-15', label: 'Central inverter skids of about 3 MVA, deep 6-7 m tables, 15°, flat drained levels',
    set: { layout: 'south', tiers: 6, orient: 'landscape', tableCols: null, tilt: 15, gcr: 0.66, edge: 0.6, moduleLong: 2.0, moduleShort: 1.0,
      wp: 380, voc: 48, inverterClass: 'central', inverterKVA: 3000, invertersPerStation: 1, packing: 'fields' },
    ranges: 'pitch 9.3 m; plan GCR about 0.7; high edge about 2.1 m; tilt at least 14°',
    evidence: 'rows measured as built (pitch, depth), skid class public; the table form (3P, 4P or 6L) is a hypothesis' },
  { id: 'central-2p-22', label: 'Central inverters with string combiners, 2 portrait, 22°, one spine with pad pairs',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, tilt: 22, gcr: 0.41, edge: 0.96, moduleLong: 1.65, moduleShort: 0.99,
      wp: 255, voc: 38, inverterClass: 'central', inverterKVA: 1500, invertersPerStation: 2, packing: 'fields', bandM: 2000, runM: 280 },
    ranges: 'tilt 21-24°; plan depth 3.2-3.35 m; pitch 8.0 m; GCR 0.41; rows unbroken up to about 280 m; one spine, no east-west tracks',
    evidence: 'measured as built at one plant (rows, pitch, spine, pad pairs); inverter class public' },
  { id: 'central-4l-25', label: 'Container central stations, landscape 4-high (full and half tables), 25°, pitch follows the slope',
    set: { layout: 'south', tiers: 4, orient: 'landscape', tableCols: 26, tilt: 25, gcr: 0.53, edge: 0.8, moduleLong: 2.28, moduleShort: 1.13,
      wp: 550, voc: 50, inverterClass: 'central', inverterKVA: 2250, invertersPerStation: 2, packing: 'fields', rowGap: 'slope' },
    ranges: 'full 4 x 26 and half 4 x 13 tables; top about 2.9 m; pitch 8.66-12.69 m stretched on north-falling ground',
    evidence: 'public design at one plant (planning drawings); a slope-following fill matched its planning module count within 1 %' },
  { id: 'central-3l-25', label: 'Central inverters in pairs at switchgear stations, landscape 3-high, 25°, 3 m height cap',
    set: { layout: 'south', tiers: 3, orient: 'landscape', tableCols: null, tilt: 25, gcr: 0.4, edge: 1.0, postMax: 3,
      inverterClass: 'central', inverterKVA: 1700, invertersPerStation: 2, packing: 'fields' },
    ranges: 'clear gap between rows about 5.4 m; highest point 3 m',
    evidence: 'hypothesis (a planning drawing reference, not seen); the built capacity may need 4L or 2P' },
  { id: 'container-2p', label: 'Container inverter and transformer stations of about 3 MW at zone centres, 2 portrait, 20°',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, tilt: 20, gcr: 0.5, edge: 0.85,
      inverterClass: 'string', inverterKVA: 300, invertersPerStation: 10, packing: 'fields' },
    ranges: 'tilt 10-30°; lowest edge 0.8-0.9 m; top at most 3 m; row gap 2-6 m; 20 ft or 40 ft containers',
    evidence: 'public design at three plants; the inverter class is not stated publicly (string inverters assumed here)' },
  { id: 'string-ew-bifacial', label: 'String inverters, east-west bifacial, tight gap, large field transformers',
    set: { layout: 'east-west', tiers: 1, orient: 'portrait', tableCols: null, tiltEw: 10, pitch: 6, moduleLong: 2.38, moduleShort: 1.3,
      wp: 660, voc: 46, inverterClass: 'string', inverterKVA: 300, invertersPerStation: 30, packing: 'fields' },
    ranges: 'gap between tables about 1 m; pitch about 6 m; two-sided cover about 0.79',
    evidence: 'public design at one plant; the 1 m gap was fitted, not measured' },
  { id: 'string-2p-modern', label: 'String inverters, 2 portrait bifacial, 690 W class, GCR about 0.5',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, tilt: 22, gcr: 0.52, moduleLong: 2.38, moduleShort: 1.3,
      wp: 690, voc: 48, inverterClass: 'string', inverterKVA: 300, invertersPerStation: 20, packing: 'fields' },
    ranges: 'tilt 20-25°; GCR about 0.52; about 170 string inverters of 300 kVA for 50 MW',
    evidence: 'public counts at one plant; the table geometry is assumed' },
  { id: 'early-2p', label: 'Early small plant, 2 portrait, shallow pitch',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, tilt: 20, gcr: 0.45, moduleLong: 1.65, moduleShort: 0.99, wp: 250, voc: 38 },
    ranges: 'tilt 16-22°; plan depth 2.0-4.1 m; pitch 4.9-6.3 m',
    evidence: 'measured as built at two small arrays' },
  { id: 'uk-dense', label: 'UK practice default: south, GCR 0.5-0.55, 15-20°, 5 m setback',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, tilt: 18, gcr: 0.52, fence: 5, packing: 'fields' },
    ranges: 'GCR 0.5-0.55; tilt 15-20°; fence setback 5 m',
    evidence: 'fitted: brings capacity within about 3-11 % of public DC figures at four plants (capacity match only, not geometry)' }
]);
export const PRESET_IDS = PRESETS.map(s => s.id);
export const presetById = id => PRESETS.find(s => s.id === id) || null;

/** The presets in words (typed "preset" alone). */
export function presetText() {
  return ['Presets (type preset <name>):', ...PRESETS.map(s => `${s.id}: ${s.label}. ${s.ranges}. Evidence: ${s.evidence}.`), PRESET_NOTE].join('\n');
}

Structures

A JavaScript module in the world folder of GlobalGrid2050 that parses format (`parseFormat`) and formats name (`formatName`) and refusal (`formatRefusal`) (units: kVA), using IEC 62548-1.

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/structures.mjs · lines 1–134 of 134 · version 2026-09-27 18:53 · pattern structureChecks (shared by 3 files)

What it does
It lists and searches its content. Defines 11 functions or classes, including parseFormat, formatName, formatRefusal, tableShape, halfCols.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 4 files: Cmd Grammar (globalgrid2050); Cmd Model (globalgrid2050); Hud Checks (globalgrid2050); Plant Layout (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It parses format (`parseFormat`), formats name (`formatName`) and formats refusal (`formatRefusal`). The mounting structures the typed bar can build, and the structure checks they raise.
Why it matters
Imported by 4 files, including Cmd Grammar, Cmd Model and Hud Checks.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Cmd Grammar (import), imported by Cmd Model (import), imported by Hud Checks (import), imported by Plant Layout (import)
Produces
STRUCTURE_NOTE, parseFormat, formatName, FORMATS, DEFAULT_COLS, formatRefusal, tableShape, halfCols, pitchStretch, winterNoonDeg, STRUCTURES, structureById
Defines here
parseFormat, formatName, formatRefusal, tableShape, halfCols, pitchStretch, winterNoonDeg, structureById, catalogueText, mpptCap, structureChecks
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/202609271853-site-world/world/structures.mjs:1-134 · blob 0e94499cf3f8a12465ef87a0cd2163fc888b37db · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// structures.mjs: the mounting structures the typed bar can build, and the structure checks they raise. Pure: no DOM, no imports.
//
// TABLE FORMATS  "kPn" or "kLn": k modules high up the slope (tiers), portrait (P) or landscape (L), n modules along
//   each tier. South-facing fixed tilt takes 2P, 3P, 4P and landscape 3L, 4L, 5L, 6L (the landscape tables of UK
//   central-inverter plants, measured as built 4 and 6 high); east-west takes 1P (one portrait module each side of
//   the ridge); trackers take 1P or 2P across the torque tube, with 1 to 4 strings along a row. Half tables (half the
//   modules along each tier) fill the ends of rows where a full table does not fit (plant-packing.mjs).
// CATALOGUE  five generic structure classes from the structure study (27 Sept): class ranges only, generic labels; no
//   product, maker, site or person is named, no datasheet text or table copied. Each preset sets typed values the
//   owner can change afterwards; every figure is illustrative and to be replaced by the chosen product's datasheet,
//   the project spec and the geotechnical report.
// CHECKS
//   slope-aware row gap  on ground falling to the north at s (m/m), the winter-noon shadow reaches further: the
//     no-shade pitch is (depth tan(el) + rise) / (tan(el) - s). The typed pitch is stretched by the ratio of that pitch
//     to its flat-ground value, so a north-facing row is shaded no more than the typed pitch shades on the flat.
//     Never shrunk on south-facing ground. Where tan(el) <= s no pitch clears the shadow: the stretch is capped.
//   tracker cross slope  slope across a tracker row (east-west): over the review line the row is kept and flagged for
//     the maker's review; over the exclusion line the row is left out.
//   post height          the post reveal against a hard maximum (a tall rear post at a steep tilt), flagged on the HUD.
//   MPPT cap             strings per inverter at most MPPT inputs x strings per input; with short strings the cap
//     can hold DC/AC under the target, which is said.

export const STRUCTURE_NOTE = 'Illustrative class ranges, generic; replace with the chosen product\'s datasheet, the project spec and the geotechnical report.';

/** "3P12" -> { tiers: 3, orient: 'portrait', cols: 12 }; "4L" -> { tiers: 4, orient: 'landscape', cols: null }; else null. */
export 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;
}
export const formatName = (tiers, orient, cols) => `${tiers}${orient === 'landscape' ? 'L' : 'P'}${cols || ''}`;

// Formats each layout builds; anything else is refused in words.
export const FORMATS = Object.freeze({ south: ['2P', '3P', '4P', '3L', '4L', '5L', '6L'], 'east-west': ['1P'], tracker: ['1P', '2P'] });
export const DEFAULT_COLS = 12; // 3P, 4P and landscape tables when no count is typed (the study's example tables)

/** Refusal in words when a format does not suit a layout, else null. */
export function formatRefusal(layout, tiers, orient) {
  const f = formatName(tiers, orient), ok = FORMATS[layout] || [];
  if (ok.includes(f)) return null;
  const where = Object.entries(FORMATS).filter(([, v]) => v.includes(f)).map(([k]) => k);
  return `${f} tables are ${where.length ? `built for ${where.join(' and ')} layouts` : 'not built here'}; ${layout} takes ${ok.join(', ')}`;
}

/**
 * The table's shape from its format: { tiers, orient, along, up, cols, slope } with along = module side along the row,
 * up = side up the slope, slope = the slant (tiers x up + gaps). p: { moduleLongM, moduleShortM, moduleGapM, tiers, orient, tableCols }.
 */
export function tableShape(p, mps, layout) {
  const tracker = layout === 'tracker', ew = layout === 'east-west';
  const tiers = ew ? 1 : Math.max(1, Math.round(p.tiers || (tracker ? 1 : 2)));
  const orient = !tracker && !ew && p.orient === 'landscape' ? 'landscape' : 'portrait';
  const along = orient === 'landscape' ? p.moduleLongM : p.moduleShortM, up = orient === 'landscape' ? p.moduleShortM : p.moduleLongM;
  const slope = tiers * up + (tiers - 1) * p.moduleGapM;
  let cols;
  if (tracker) cols = Math.ceil((p.trackerStrings || 2) * mps / tiers);
  else if (ew) cols = mps;
  else cols = p.tableCols || (tiers === 2 && orient === 'portrait' ? mps : DEFAULT_COLS);
  return { tiers, orient, along, up, slope, cols, modules: tiers * cols * (ew ? 2 : 1) };
}
/** Columns of a half table: half the modules along each tier (rounded up), at least one. */
export const halfCols = cols => Math.max(1, Math.ceil(cols / 2));

// ---- slope-aware row gap ----
/** Pitch stretch for ground falling to the north at s (m/m; negative = rising): >= 1, capped at maxStretch. */
export 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));
}
export const winterNoonDeg = latDeg => 90 - latDeg - 23.44;

// ---- the catalogue ----
// set: typed values (cmd-grammar KEYS) the preset puts in; ranges: the class's range figures in words.
export const STRUCTURES = Object.freeze([
  { id: 'fixed-2p', study: 's1', label: 'Fixed tilt, south facing, 2P portrait (3P and 3L/4L variants; one or two post lines)',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, posts: 2, tilt: 25, gcr: 0.4, edge: 0.8, postMax: 3.0 },
    ranges: 'tilt 15-35° (2P), 5-20° (3P); GCR 0.3-0.5; lowest edge 0.5-1.2 m; post spacing 3-7.5 m; slope 15 % along, 20 % across; twist 3°' },
  { id: 'east-west', study: 's2', label: 'Fixed east-west low-tilt ridge, 1P each face',
    set: { layout: 'east-west', tiers: 1, orient: 'portrait', tableCols: null, posts: 2, tiltEw: 10, edge: 0.8, postMax: 3.0 },
    ranges: 'tilt 8-15°; gap between ridges 2-4 m; ridge gap 0.1-0.5 m; lowest edge 0.5-1.0 m piled; slope 20 % along, 15 % across' },
  { id: 'tracker-1p', study: 's3', label: 'Single-axis tracker, 1P portrait, independent rows',
    set: { layout: 'tracker', tiers: 1, orient: 'portrait', tableCols: null, trackerStrings: 2, gcr: 0.35, postMax: 3.0 },
    ranges: 'GCR 0.28-0.5; hub 1.2-1.6 m; rotation 45-60°; 2-4 strings a row; post spacing 6-12 m; 8.5-15 % along; across the row: maker review over 7 %, left out over 10 %' },
  { id: 'tracker-2p', study: 's4', label: 'Single-axis tracker, 2P portrait, independent rows',
    set: { layout: 'tracker', tiers: 2, orient: 'portrait', tableCols: null, trackerStrings: 4, gcr: 0.38, postMax: 3.0 },
    ranges: 'GCR 0.30-0.50; hub 2.1-2.6 m; rotation 50-60°; 4 strings a row; post spacing 7-10.5 m; 10 % along' },
  { id: 'high-clearance', study: 's5', label: 'High-clearance agrivoltaic, fixed tilt, 2P portrait (the special classes compared: dual-row tracker, vertical bifacial)',
    set: { layout: 'south', tiers: 2, orient: 'portrait', tableCols: null, posts: 2, tilt: 20, gcr: 0.3, edge: 2.5, postMax: 5.0 },
    ranges: 'clear height at least 2.1 m after tolerance (4-4.5 m for tractors); tilt 10-30°; GCR 0.2-0.35; post spacing 6-12 m; reveal warn 4.3 m, fail 5 m' }
]);
export const structureById = id => STRUCTURES.find(s => s.id === id) || null;
export const STRUCTURE_IDS = STRUCTURES.map(s => s.id);

/** The catalogue in words (typed "structure" alone). */
export function catalogueText() {
  return ['Structures (type structure <name>):', ...STRUCTURES.map(s => `${s.id}: ${s.label}. ${s.ranges}.`), STRUCTURE_NOTE].join('\n');
}

// ---- MPPT cap ----
/** Strings per inverter the MPPTs allow: inputs x strings per input. */
export const mpptCap = ({ mppts = 12, stringsPerMppt = 2 } = {}) => mppts * stringsPerMppt;

/**
 * The structure checks of a laid-out plant, for the HUD: facts { piles summary, rules, skipped, crossReview, table,
 * template counts and params, stretched }. Returns [{ id, failed, line, inputs, standard }].
 */
export function structureChecks(f = {}) {
  const out = [], s = f.piles, R = f.rules || {};
  if (s && Number.isFinite(s.revealFail)) {
    const max = R.revealFailM ?? 3;
    out.push({ id: 'post-height', failed: s.revealFail > 0, line: `${s.revealFail} POSTS OVER ${max.toFixed(1)} M${f.tiltDeg ? ` · TILT ${Math.round(f.tiltDeg)}°` : ''}`,
      inputs: [['Posts over the maximum', s.revealFail], ['Maximum reveal', `${max} m (editable: structure preset or piles rules)`],
        ['Tallest post once graded', `${(s.finishedP?.[2] ?? s.revealP?.[2] ?? NaN).toFixed(2)} m`], ['Posts in all', s.piles]],
      standard: 'EN 1993-5 and EN 1997-1 (piles in bending and embedment); lower tilt, fewer tiers or grading lower the posts' });
  }
  if (f.tracker && f.skipped) {
    const n = f.crossReview || 0, x = f.skipped.cross || 0;
    out.push({ id: 'tracker-cross', failed: n > 0 || x > 0, line: `TRACKER CROSS SLOPE: ${n} ROWS OVER ${f.crossReviewPct ?? 7}% (REVIEW) · ${x} LEFT OUT OVER ${f.crossMaxPct ?? 10}%`,
      inputs: [['Rows kept, over the review line', n], ['Rows left out', x], ['Review line', `${f.crossReviewPct ?? 7} %`], ['Exclusion line', `${f.crossMaxPct ?? 10} %`]],
      standard: 'Tracker maker\'s slope limits (manufacturer data, generic); slope-aware backtracking studied per site' });
  }
  const c = f.counts, P = f.params;
  if (c && P && P.inverterClass !== 'central') {      // central inverters take strings through combiner boxes: no MPPT cap
    const cap = mpptCap(P), stringKWp = c.modulesPerString * P.moduleWp / 1000, dcac = c.stringsPerInverter * stringKWp / P.inverterKVA;
    const capped = c.stringsPerInverter >= cap && dcac < (P.dcAcRatio ?? 1.25) - 0.05;
    out.push({ id: 'mppt-cap', failed: capped, line: `DC/AC ${dcac.toFixed(2)} · STRINGS PER INVERTER CAPPED AT ${cap} (${P.mppts ?? 12} MPPT × ${P.stringsPerMppt ?? 2})`,
      inputs: [['Strings per inverter', c.stringsPerInverter], ['MPPT inputs × strings each', `${P.mppts ?? 12} × ${P.stringsPerMppt ?? 2} = ${cap}`],
        ['String', `${c.modulesPerString} × ${P.moduleWp} W = ${stringKWp.toFixed(1)} kWp`], ['Inverter', `${P.inverterKVA} kVA`], ['DC/AC target', P.dcAcRatio ?? 1.25]],
      standard: 'IEC 62548-1 (array design: string and sub-array connection); inverter MPPT limits from the chosen inverter\'s data', quiet: !capped });
  }
  return out;
}

Substrate

A JavaScript module in the world folder of GlobalGrid2050 that sets origin (`setOrigin`), writes readout (`writeReadout`), opens panel (`openPanel`) and calculates planar distances (units: kV).

geodesyglobalgrid2050 / solar-design-studio/202609271853-site-world/world/substrate.mjs · lines 1–398 of 398 · version 2026-09-27 18:53 · Entry point · pattern groundSource (shared by 2 files)

What it does
It draws attribution, overhead lines (OHL), LiDAR terrain and substations. Defines 29 functions or classes, including $, fadeAt, tourPlaying, live, shown. Side effects: changes the web page (DOM); reads or writes files; 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: overhead lines (OHL), LiDAR terrain, substations.
Inputs & outputs
In: JSON file attribution.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/).
What it achieves
It sets origin (`setOrigin`), writes readout (`writeReadout`) and opens panel (`openPanel`). The substrate: an empty world you can move around in. It reads `./world/data/attribution.json`. It responds to click, resize and close events.
Why it matters
Loaded by the Site World page at https://globalgrid2050.com/solar-design-studio/202609271853-site-world/.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
Links (import), Camera (import), Views (import), Frame Gate (import), Device Budget (import), Lines (import), Input (import), Layers (import), and 15 more
Used by
preloaded by Solar Design Studio — Site World Page (modulepreload)
Produces
$, fadeAt, tourPlaying, live, shown, guarded, baseHeight, measuredAt, known, groundSource, heightAt, solids
Defines here
$, fadeAt, tourPlaying, live, shown, guarded, baseHeight, measuredAt, known, groundSource, heightAt, solids, invalidate, gridAssets, knownTowers, setOrigin, playing, target, moving, flyTo, draw, collect, chooseView, writeReadout, openPanel, writeCredits, skip, nearestSub, panelOpen
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/202609271853-site-world/world/substrate.mjs:1-398 · blob 5eed67b6906f71ca6b2928291113b00ff6522d2c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// The substrate: an empty world you can move around in. It owns the loop, the camera and the views;
// everything you see comes from layers listed in manifest.json, plus the design being drawn (trenches and cables).
// Positions are local metres from the site origin, which is held in float64 British National Grid metres
// (0, 0 until a site is chosen). setOrigin moves the origin and shifts the viewer so they stay put in the world;
// walking more than 600 m from the origin moves it to the nearest whole kilometre (origin.mjs).
// The design is kept in memory in national-grid metres, so it survives every move of the origin.

import { gridAtlasUrl } from './links.mjs';
import { perspective, view, multiply } from './camera.mjs';
import { VIEWS, fpsOf, step, look, setView, toggle, standOn, AERIAL_MIN_CLEARANCE } from './views.mjs';
import { createFrameGate } from './frame-gate.mjs';
import { initialBudget, adjust } from './device-budget.mjs';
import { createLines } from './lines.mjs';
import { attachInput } from './input.mjs';
import { loadLayers, statusLine } from './layers.mjs';
import { rebaseIfNeeded, toBng, toLocal } from './origin.mjs';
import { arrive } from './arrival.mjs';
import { gridRef } from './bng.mjs';
import { aboutList } from './attribution.mjs';
import { siteFromUrl } from './sites-ui.mjs';
import { sourceKeysFor, OPTIONAL_LAYERS } from './layers-panel.mjs';
import { createLiveTerrain } from './wcs-terrain.mjs';
import { attachLift, TAP_M } from './lift.mjs';
import { fadeFor, farPlane, FADE_M } from './fade.mjs';
// Design, Find, the project tools (file, print, tour, phases), the plan inset, the headset view and the layer
// panels load just after the first frame, not before it (review E, win 2): see "after the first frame" below.
const TOOLS = ['./design-ui.mjs', './find-mount.mjs', './plan-wire.mjs', './project-ui.mjs', './xr.mjs', './layers-ui.mjs',
  './sun-ui.mjs', './buffers-ui.mjs', './ground-readout.mjs', './sun-mode.mjs', './first-showing.mjs', './ohl-ui.mjs', './sld-hook.mjs', './help.mjs', './accuracy.mjs'];

const $ = id => document.getElementById(id);
const canvas = $('view'), where = $('where-line'), status = $('status');
// Layer diagnostics sit behind a closed "Layer details" in Controls; ?debug=1 opens them.
if (new URLSearchParams(location.search).get('debug') === '1') $('layer-details').open = true;
const fadeAt = () => fadeFor(state.view, state.pos[2] - heightAt(state.pos[0], state.pos[1]), layersUi?.rangeM() || 0, design.plantApi?.extentM() || 0) * mag; // x mag: binoculars
const FOV = 70 * Math.PI / 180, MAX_DT = 0.1, ARRIVAL_FPS = 30, ARRIVAL = { height: 80, seconds: 3 }, fov = () => 2 * Math.atan(Math.tan(FOV / 2) / mag);
const JUMP_M = 3000;      // further than this, Find moves the origin and drops in from above instead of flying across
const SITE_HALF_M = 1024; // half the staged site's side: terrain tiles exist within this of its centre
const OBLIQUE = { pitch: -35 * Math.PI / 180, back: 150 }; // arriving at a found place: 35 degrees down from 150 m out

let state = { view: 'standing', pos: [0, -25, 0], yaw: 0, pitch: -0.12 };
let budget = initialBudget(devicePixelRatio);
let loaded = { generation: '', layers: [] }, vertices = 0, readAt = -1e9; // readAt: the status line is written at most 4 times a second while moving
let origin = { e: 0, n: 0, id: 0 };
let groundVersion = 0; // bumped whenever a layer says new ground has arrived, or the origin moves
let lastGround = 0;    // the last ground height found near the viewer; used where no layer knows the height
let arrival = null;    // { pose, t0 } while the drone flies itself somewhere
const GROUND_MEMORY_M = 20;
// Hooks: before/after each frame; items: design-file items; open: each design opened; batches: extra lines (sld-mount.mjs); filter: last (xray-ui.mjs).
const hooks = { before: new Set(), after: new Set(), design: new Set(), items: new Set(), open: new Set(), batches: new Set(), filter: new Set(), commands: new Set() };
let lastBatches = [], driver = null; // commands: typed lines an extension answers; driver: buggy-ui.mjs moves the viewer instead of the walk step
let modules = null, legs = null, mag = 1, nav = null; // module-mount.mjs; jump.mjs (a walker's height), binoculars (mag); nav-flight.mjs
let sunMode = null, first = null; // after the first frame: sun-mode.mjs (plays at up to 30 fps), first-showing.mjs (cards, pin)
let tourPlaying = () => false; // set once the project tools are mounted: a playing tour draws at 30 fps

const live = () => loaded.layers.filter(l => l.layer);
let layersUi = null, groundReadout = null, ohl = null, accuracy = null; // accuracy.mjs, after the first frame; the Layers panel (dash button, layers-ui.mjs): an optional layer switched off is hidden
const shown = () => live().filter(l => !l.hidden);
// A layer that throws is switched off and named; it never takes the rest of the world down with it.
const guarded = (l, fn, fallback) => {
  try { return fn(); } catch (e) { l.layer = null; l.status = 'failed and switched off: ' + e.message; return fallback; }
};
// The ground the layers know, before any design cuts it.
const baseHeight = (x, y) => {
  for (const l of live()) {
    if (typeof l.layer.heightAt !== 'function') continue;
    const h = guarded(l, () => l.layer.heightAt(x, y), NaN);
    if (Number.isFinite(h)) {
      if (Math.hypot(x - state.pos[0], y - state.pos[1]) <= GROUND_MEMORY_M) lastGround = h;
      return h;
    }
  }
  return lastGround; // the empty world is flat at 0 m; past the edge of known ground, keep the last height
};
// Ground actually measured by a layer at (x, y), or NaN: engineering checks use this, never a guess.
const measuredAt = (x, y) => {
  for (const l of live()) if (typeof l.layer.heightAt === 'function') { const h = guarded(l, () => l.layer.heightAt(x, y), NaN); if (Number.isFinite(h)) return h; }
  return NaN;
};
// Whether a layer measured the ground at (x, y): off it, layers leave out what would stand there (water and roads
// past the LiDAR).
const known = (x, y) => Number.isFinite(measuredAt(x, y));
// Which layer the ground at (x, y) comes from, in words for the readout.
const GROUND_WORDS = { terrain: 'LiDAR', 'terrain-live': 'live EA LiDAR' }; // the Controls status spells out LIVE_LABEL
const groundSource = (x, y) => {
  for (const l of live()) {
    if (typeof l.layer.heightAt !== 'function') continue;
    if (Number.isFinite(guarded(l, () => l.layer.heightAt(x, y), NaN))) return l.id;
  }
  return null;
};
// The ground everyone stands on: the layers' ground with every finished trench cut into it (design-ui.mjs).
const heightAt = (x, y) => design.heightAt(x, y);
// Solids are what a person or drone cannot pass through; layers declare them as boxes in local metres.
const solids = () => shown().flatMap(l => (typeof l.layer.solids === 'function' ? guarded(l, () => l.layer.solids({ pos: state.pos }), []) : []))
  .concat([...(hooks.solids || [])].flatMap(f => { try { return f(state.pos); } catch { return []; } })); // + design tables (table-solids.mjs)

const lines = createLines(canvas, { onRestore: () => gate.invalidate() });
const gate = createFrameGate(draw);
// A layer asks for a redraw; { ground: true } (the default) also says new ground has arrived.
const invalidate = ({ ground = true } = {}) => { if (ground) groundVersion++; gate.invalidate(); };

// Grid equipment the design measures its routes against: substations and towers from the grid layer, if loaded.
function gridAssets() {
  const model = live().find(l => l.id === 'grid')?.layer?.debug?.()?.model;
  if (!model) return [];
  const subs = (model.substations || []).map(s => ({ kind: 'substation', label: `${s.cls} substation`, e: s.e, n: s.n,
    kv: s.kv ?? null, tier: s.tier ?? null, id: s.id })); // no operator: the screen shows the network tier only
  const towers = (model.lines || []).flatMap(l => l.towers.map(t => ({ kind: 'tower', label: `${l.cls} pylon`, e: t.e, n: t.n,
    kv: l.kv ?? null, id: t.id })));
  return [...subs, ...towers];
}
// Every known tower, national grid metres: the grid layer's and the national layer's near band (for the canopy mask).
const knownTowers = () => [...gridAssets().filter(a => a.kind === 'tower'),
  ...(live().find(l => l.id === 'national')?.layer?.towers?.() || [])];
// Until design-ui.mjs arrives (just after the first frame) the ground is the layers' own and nothing is designed.
let design = Object.freeze({ heightAt: (x, y) => baseHeight(x, y), batches: () => [], pickAt() {}, shift() {}, putDown() {},
  snapshot: () => ({ tool: null, trenches: [], cables: [], works: [], draft: [], readout: null }), lastFinished: () => null, replace() {}, animating: () => false });

// ---- moving -----------------------------------------------------------------------------------------
// Moves the site origin to (e, n) national-grid metres. The viewer and the route being drawn are shifted by the
// same amount the other way, so they stay in the same place in the world; layers read it via api.origin().
function setOrigin(e, n) {
  if (!Number.isFinite(e) || !Number.isFinite(n)) throw Error('setOrigin needs finite easting and northing');
  const dx = e - origin.e, dy = n - origin.n;
  state = { ...state, pos: [state.pos[0] - dx, state.pos[1] - dy, state.pos[2]] };
  origin = { e, n, id: origin.id + 1 };
  design.shift(dx, dy);
  invalidate();
  return { ...origin };
}

// Sun play and the solar block's build sequence (Design) both ask for frames at their own rate; paused, nothing.
const playing = () => !!sunMode?.playing() || design.animating() || !!driver?.moving();
const target = () => (arrival ? ARRIVAL_FPS : !input.active() && playing() ? (sunMode?.playing() ? sunMode.PLAY_FPS : ARRIVAL_FPS) : fpsOf(VIEWS[state.view], input.get().slow));
const moving = () => input.active() || !!arrival || playing() || !!legs?.busy();
const input = attachInput(canvas, $('pad'), {
  onChange: () => { if (input.active()) arrival = null; gate.setMoving(moving(), target()); gate.invalidate(); },
  onLook: (dy, dp) => { arrival = null; state = look(state, dy / mag, dp / mag); gate.invalidate(); },
  onView: v => chooseView(toggle(state.view, v)),
  onClick: (x, y) => { if (!modules?.tap(x, y)) design.pickAt(x, y); } // a tap on a detailed module inspects it
});

// Flies the drone smoothly to hover above local [x, y], looking down; any movement key takes over.
function flyTo(x, y, opts = {}) { // a far place moves the origin and drops in; across a plant the drone glides (nav-flight.mjs glides)
  if (state.view !== 'aerial') chooseView('aerial', { arrive: false });
  const pb = nav && design?.plantApi?.result?.() && design.plantApi.boundary(), box = pb && nav.boxOfPoints(pb.map(([e, n]) => toLocal(origin, e, n)));
  if (nav ? !nav.glides(state.pos, [x, y], box) : Math.hypot(x - state.pos[0], y - state.pos[1]) > JUMP_M) {
    const p = toBng(origin, x, y);
    setOrigin(Math.round(p.e / 1000) * 1000, Math.round(p.n / 1000) * 1000);
    [x, y] = toLocal(origin, p.e, p.n);
    state = { ...state, pos: [x, y, heightAt(x, y) + 400] };
  }
  // back: stand off this far behind the point (along the current heading), so a pitch above straight down still sees it.
  const { back = 0, ...rest } = opts, yaw = rest.yaw ?? state.yaw, g = heightAt(x, y), g0 = heightAt(state.pos[0], state.pos[1]);
  const at = [x - back * Math.sin(yaw), y - back * Math.cos(yaw), g], height = back && rest.pitch ? back * Math.tan(-rest.pitch) : (rest.height ?? ARRIVAL.height);
  // nav-flight.mjs descend eases through log(height) in 2-5 s; until it has loaded (after the first frame), arrival.mjs arrive.
  const pose = nav ? nav.descend(state, [x, y, g], { ...rest, back, yaw, groundFrom: g0 }) : arrive(state, at, { ...ARRIVAL, ...rest, yaw, height });
  arrival = { pose, t0: performance.now() }; gate.setMoving(true, ARRIVAL_FPS);
}
function draw(now, intervalMs) {
  for (const f of hooks.before) f(now);
  sunMode?.advance(intervalMs);
  if (arrival) {
    const t = (now - arrival.t0) / 1000;
    state = { ...state, ...arrival.pose(t) };
    if (arrival.pose.done(t)) { arrival = null; gate.setMoving(moving(), target()); }
  } else if (driver && state.view === 'standing') { state = driver.frame(state, input.get(), intervalMs); } else if (input.active() || legs?.busy()) {
    const i = input.get(), dt = Math.min(intervalMs / 1000, MAX_DT);
    if (i.turn) state = look(state, i.turn * dt / mag, 0);
    state = (legs || { step }).step(state, i, dt, heightAt, solids());
    budget = adjust(budget, intervalMs, 1000 / target());
  }
  const r = arrival ? null : rebaseIfNeeded(origin, state.pos);
  if (r) setOrigin(r.e, r.n);
  // Ground can arrive after the viewer does (tiles stream in): a walker's eye follows it (jump.mjs: or a top, or the air), a drone keeps clear.
  const v = VIEWS[state.view], g = heightAt(state.pos[0], state.pos[1]);
  if (!driver && v.eye !== null) state = legs ? legs.hold(state, heightAt, solids()) : Math.abs(state.pos[2] - (g + v.eye)) > 1e-6 ? { ...state, pos: [state.pos[0], state.pos[1], g + v.eye] } : state;
  if (v.eye === null && state.pos[2] < g + AERIAL_MIN_CLEARANCE) state = { ...state, pos: [state.pos[0], state.pos[1], g + AERIAL_MIN_CLEARANCE] };
  lines.resize(budget.scale);
  // The view is built at the eye; lines.draw moves each batch by (its origin - eye) in doubles.
  const fade = fadeAt(), mat = multiply(perspective(fov(), canvas.width / canvas.height, 0.05, farPlane(fade)), view([0, 0, 0], state.yaw, state.pitch));
  lastBatches = collect(state.pos);
  vertices = lines.draw(mat, state.pos, fade, lastBatches);
  if (now - readAt >= 250) { readAt = now; writeReadout(); } // the status line at most 4 times a second while moving (PERF.md 7)
  groundReadout?.update();
  sunMode?.afterDraw({ pos: state.pos, heightAt, groundVersion });
  for (const f of hooks.after) f(now);
}

// What the layers and the design draw around a position; the flat screen and the headset view both draw from this.
function collect(pos) {
  const ctx = { pos, heightAt, measuredAt, known, groundVersion, origin: { ...origin }, sun: sunMode?.sun(), view: state.view }; // view: imagery shows in Drone and Map, never Walk
  const batches = shown().flatMap(l => (typeof l.layer.lines === 'function' ? guarded(l, () => l.layer.lines(ctx), []) : []));
  const out = (sunMode ? sunMode.decorate(batches, ctx) : batches).concat(design.batches(), first?.batches() || [], modules?.batches() || [],
    [...hooks.batches].flatMap(f => f()));
  return [...hooks.filter].reduce((o, f) => f(o, ctx), out); // filters last, e.g. the as-built X-ray (xray-ui.mjs)
}

function chooseView(v, { arrive: fly = true } = {}) {
  const next = standOn(setView(state, v, heightAt), VIEWS[v], solids()); // over a table: stand on it (table-solids.mjs)
  if (!next) return; // e.g. no standing up inside a solid
  const from = state.view;
  state = next; arrival = null;
  for (const b of document.querySelectorAll('[data-view]')) b.setAttribute('aria-pressed', String(b.dataset.view === v));
  $('lift').hidden = v !== 'aerial';
  if (v !== 'aerial') input.setLift(0);
  if (fly && v === 'aerial' && from !== 'aerial') flyTo(state.pos[0], state.pos[1]);
  gate.setMoving(moving(), target());
  gate.invalidate();
}

function writeReadout() {
  const [x, y, z] = state.pos, g = heightAt(x, y), v = VIEWS[state.view], p = toBng(origin, x, y);
  // On screen: a grid reference and the ground (its height above sea level where measured); exact numbers in Layer details.
  let ref = '';
  try { ref = gridRef(p.e, p.n, 8) + ' · '; } catch { /* off the national grid */ }
  const src = groundSource(x, y), known = Number.isFinite(measuredAt(x, y)), up = v.eye === null ? ` · ${Math.round(z - g)} m up` : '';
  where.textContent = `${ref}${known ? `ground ${Math.round(g)} m above sea level` : src ? GROUND_WORDS[src] || src : 'flat, no LiDAR yet'}${up}`;
  $('where-detail').textContent = `${v.label} · ${src ? GROUND_WORDS[src] || src : 'flat, no LiDAR yet'} · easting ${p.e.toFixed(1)} m, ` +
    `northing ${p.n.toFixed(1)} m · ${typeof accuracy?.groundWords === "function" ? accuracy.groundWords(src, g, z - g, known) : `eye ${(z - g).toFixed(1)} m above the ground`}`;
  // When still, no frame is drawn, so the rate is 0 whatever the last second's counter still holds.
  status.textContent = `${moving() || tourPlaying() ? gate.fps() : 0} fps now (moving ${v.fps}, precise ${v.slowFps}, still 0) · ${budget.scale}× resolution · ` +
    `${vertices / 2} lines · ${loaded.layers.map(l => `${l.id}: ${statusLine(l)}`).join('; ') || 'no layers'}`;
}

// ---- page controls ----------------------------------------------------------------------------------
for (const b of document.querySelectorAll('[data-view]')) b.addEventListener('click', () => { chooseView(b.dataset.view); canvas.focus(); });
// One panel at a time: Find, Design, Layers and Controls share the space under the dash on a phone.
let search = null;
const panels = { 'help-toggle': 'help', 'design-toggle': 'design', 'find-toggle': 'find', 'layers-toggle': 'layers' };
// GridAtlas opens at the spot you are standing on (latitude, longitude and zoom only; no project reference).
$('to-gridatlas').addEventListener('click', () => {
  const url = gridAtlasUrl({ origin, pos: state.pos });
  if (url) open(url, '_blank', 'noopener');
});
function openPanel(btn, open) {
  if (btn === 'find-toggle') { if (search) (open ? search.open() : search.close()); }
  else $(panels[btn]).hidden = !open;
  $(btn).setAttribute('aria-expanded', String(open));
  if (btn === 'design-toggle' && !open) design.putDown(); // closing Design puts the tool down
  const shown = Object.keys(panels).find(b => $(b).getAttribute('aria-expanded') === 'true');
  if (shown) document.body.dataset.panel = panels[shown]; else delete document.body.dataset.panel;
  if (btn === 'find-toggle' && open) first?.dismissStart();
}
for (const btn of Object.keys(panels)) {
  $(btn).addEventListener('click', () => {
    const open = $(btn).getAttribute('aria-expanded') !== 'true';
    for (const o of Object.keys(panels)) if (o !== btn && $(o).getAttribute('aria-expanded') === 'true') openPanel(o, false);
    openPanel(btn, open);
  });
}
// Up and Down: hold to climb or sink; a quick tap moves the drone 10 m (lift.mjs).
attachLift(document.querySelectorAll('[data-lift]'), { setLift: d => input.setLift(d), tap: d => {
  if (state.view !== 'aerial') return;
  const [x, y, z] = state.pos, floor = heightAt(x, y) + AERIAL_MIN_CLEARANCE;
  state = { ...state, pos: [x, y, Math.max(floor, z + d * TAP_M)] }; gate.invalidate();
} });
addEventListener('resize', () => gate.invalidate());
setInterval(() => { if (!moving() && !tourPlaying()) { writeReadout(); groundReadout?.update(); } layersUi?.refresh(); ohl?.update(); }, 1000); // text only: no frame is drawn

// The full credit lines under Controls, for exactly the data on screen; the footer line is written by layers-ui.mjs.
let attribution = null;
function writeCredits() {
  if (!attribution) return;
  $('credits').replaceChildren(...aboutList(sourceKeysFor(shown().map(l => l.id)), attribution).map(c => {
    const li = document.createElement('li'), a = document.createElement('a');
    a.href = c.link || c.licence_url || '#'; a.target = '_blank'; a.rel = 'noopener';
    a.textContent = `${c.line} (${c.licence})`; li.append(a); return li;
  }));
}

try {
  // Optional layers that start off load on first switch-on (review E); the sun and buffer controls need theirs now.
  loaded = await loadLayers('./world/manifest.json', { invalidate, origin: () => origin, towers: knownTowers, site: await siteFromUrl(), started: item => item.layer?.mountControls?.(document.body),
    deferred: OPTIONAL_LAYERS.map(l => l.id).filter(id => !['grid', 'shade', 'buffers'].includes(id)), first: ['terrain', 'ground-grid'] }); // the ground first
} catch (e) {
  loaded = { generation: '', layers: [{ id: 'manifest', status: 'failed: ' + e.message }] };
}
// Live ground from the EA service wherever the staged tiles do not reach. It comes after the staged terrain
// layer, so staged, hash-checked tiles always win where both exist; boxes inside a staged site are not fetched.
{
  const staged = loaded.layers.find(l => l.id === 'terrain');
  const skip = (e0, n0, size) => {
    if (!staged?.layer || staged.layer.debug?.().indexState === 'failed' || !loaded.site) return false;
    const { centre_e: ce, centre_n: cn } = loaded.site;
    return e0 >= ce - SITE_HALF_M && n0 >= cn - SITE_HALF_M && e0 + size <= ce + SITE_HALF_M && n0 + size <= cn + SITE_HALF_M;
  };
  const layer = createLiveTerrain({ origin: () => origin, invalidate: () => invalidate(), skip });
  let failed = null; // set by guarded() if the layer throws; otherwise the status is the layer's own, live
  loaded.layers.push({ id: layer.id, layer, set status(t) { failed = t; },
    get status() { return failed || 'not hash-checked'; } }); // the Controls line adds the layer's own words in brackets
}
// A site places the world: its centre becomes the origin, so the viewer starts in the middle of the land.
if (loaded.site) origin = { e: loaded.site.centre_e, n: loaded.site.centre_n, id: origin.id + 1 };
chooseView('standing');

// ---- after the first frame ----------------------------------------------------------------------------
await new Promise(r => requestAnimationFrame(() => setTimeout(r, 0)));
const nearestSub = async (e, n) => live().find(l => l.id === 'grid')?.layer?.nearestSubstation?.(e, n) ?? null; // national index
const [{ createDesign }, { mountFind }, { mountPlan }, { mountProject }, { attachHeadset }, { mountLayersUi },
  { mountSunControl }, { mountBuffers }, { mountGroundReadout }, { attachSunMode }, { mountFirstShowing }, { attachOhl }, { sldHook }, , accuracyModule] = await Promise.all(TOOLS.map(p => import(p)));
accuracy = accuracyModule; await loaded.rest; // grid, shade and buffers start just after the first frame; their controls need them
design = createDesign({ doc: document, canvas, fov, baseHeight, origin: () => origin, viewer: () => state, extraItems: () => ohl?.layer.boqItems() ?? [],
  ohlZones: () => ohl?.layer.zonesEN() ?? null, // the plant layout keeps tables out of the overhead line zones
  invalidate, redraw: () => gate.invalidate(), release: key => lines.release(key), assets: gridAssets, measuredAt, nearest: nearestSub, onChange: () => hooks.design.forEach(f => f()),
  animate: () => gate.setMoving(moving(), target()) });
design.setGroundVersion(() => groundVersion);
await design.loadCatalogue();
invalidate(); // the ground now comes through the design (trenches, roads and pads cut into it)
try { attribution = await (await fetch('./world/data/attribution.json', { cache: 'no-cache' })).json(); } catch { /* the fixed footer stays */ }
// Layers panel, from the dash's Layers button; GridAtlas sits in its header. Grid starts on; the rest start off.
const shade = loaded.layers.find(l => l.id === 'shade' && l.layer); let sunUi = null; // the shadow's date and time (sun-ui.mjs)
const dv = { design: () => design.snapshot(), designVersion: () => design.version?.(), origin: () => origin }; // keyed on the version, copied on change
ohl = attachOhl(loaded.layers, { ...dv, measuredAt, invalidate: () => gate.invalidate() }); // overhead line zones, on whenever the grid is
const buffers = mountBuffers({ layer: loaded.layers.find(l => l.id === 'buffers' && l.layer)?.layer, ...dv });
try {
  layersUi = mountLayersUi({ items: loaded.layers, host: $('layers-slot'), footer: $('attribution'), attribution,
    invalidate: () => gate.invalidate(),
    onChange: ids => { sunUi?.show(ids.includes('shade') && !sunMode?.on()); buffers?.refresh(ids.includes('buffers')); writeCredits();
      ohl?.onChange(ids, () => layersUi?.panel); groundReadout?.reset(); groundReadout?.update(); } });
} catch (e) { console.warn('layers panel: not wired: ' + e.message); }
if (buffers) setInterval(() => buffers.refresh(layersUi?.panel.isOn('buffers')), 1000); // origin moves, new drawn items
ohl.mount($('layers-slot'), () => layersUi?.panel);
try { sunUi = mountSunControl($('layers-slot'), { layer: shade?.layer, site: loaded.site }); sunUi?.show(!!layersUi?.panel.isOn('shade')); }
catch (e) { console.warn('sun control: ' + e.message); }
// Sun mode (Sun switch in Layers): switches the terrain shadow on through the panel, shows its time bar, lights the grid.
try {
  sunMode = attachSunMode({ pos: () => state.pos, heightAt, origin: () => origin, site: () => loaded.site,
    layer: id => live().find(l => l.id === id)?.layer || null, base: new URL('./world/', location.href).href,
    setShade: on => { if (layersUi && layersUi.panel.isOn('shade') !== on) layersUi.panel.set('shade', on); },
    onToggle: on => sunUi?.show(!on && !!layersUi?.panel.isOn('shade')), redraw: () => gate.invalidate(),
    onPlay: () => { gate.setMoving(moving(), target()); gate.invalidate(); } });
} catch (e) { console.warn('sun mode: ' + e.message); }
// Escape inside the list closes the Layers panel and hands focus back to its dash button.
layersUi?.panel.element.addEventListener('close', () => { openPanel('layers-toggle', false); $('layers-toggle').focus(); });
// Ground readout: under the walker's feet, and along the last finished trench or cable (Design panel).
const panelOpen = () => Object.keys(panels).some(b => $(b).getAttribute('aria-expanded') === 'true');
groundReadout = mountGroundReadout({ doc: document, layer: () => live().find(l => l.id === 'ground')?.layer || null,
  on: () => !!layersUi?.panel.isOn('ground'), feet: $('ground-feet'), box: $('ground-readout'), finished: design.lastFinished,
  here: () => toBng(origin, state.pos[0], state.pos[1]), walking: () => state.view === 'standing' && !panelOpen() });
writeCredits();
first = mountFirstShowing({ canvas, redraw: () => gate.invalidate(), origin: () => origin, heightAt, groundVersion: () => groundVersion,
  assets: gridAssets, nearest: nearestSub, openFind: () => { if ($('find-toggle').getAttribute('aria-expanded') !== 'true') $('find-toggle').click(); } });
search = mountFind({ site: () => loaded.site, attribution, origin: () => origin, SITE_HALF_M, first: () => first, canvas,
  close: () => openPanel('find-toggle', false), flyTo: (x, y) => flyTo(x, y, OBLIQUE) }); // find-mount.mjs

// What extensions may read and change. The design stays in national-grid metres; replace swaps it whole.
const api = {
  canvas, gate, hooks, live, guarded, heightAt, invalidate, get FOV() { return fov(); }, FADE_M, VIEWS, flyTo, solids, measuredAt,
  state: () => state, origin: () => ({ ...origin }), site: () => loaded.site || null, generation: () => loaded.generation,
  batches: () => lastBatches, redraw: () => draw(performance.now(), 0), moving: () => input.active(), attribution: () => attribution,
  setPose(p) { arrival = null; state = { ...state, ...p }; gate.invalidate(); }, setMagnification(m) { mag = Math.max(1, Number(m) || 1); gate.invalidate(); }, setLegs(l) { legs = l; },
  setView: v => { if (state.view !== v) chooseView(v, { arrive: false }); }, setDriver: d => { driver = d; arrival = null; gate.setMoving(moving(), target()); gate.invalidate(); },
  resumeGate: () => gate.setMoving(moving(), target()), // after a tour pauses, the walk carries on at its own rate
  design: () => design.snapshot(), replaceDesign: d => design.replace(d), input, solids, measuredAt // input, solids, setDriver: the buggy
};
const plan = mountPlan(api), sld = sldHook({ api, design, doc: document }), project = mountProject(api); // sld: diagram and Follow
modules = (await import('./module-mount.mjs')).mountModules(api, { block: design.blockApi, plant: design.plantApi });
tourPlaying = project.playing;
// Headset view (in Controls): hidden where the browser cannot run it; on leaving, the flat screen carries on from there.
attachHeadset($('headset'), { lines, heightAt, solids, collect, fade: FADE_M, state: () => state,
  leave: next => { state = { ...state, ...next }; chooseView(state.view, { arrive: false }); } });

// Solid ground (GPU), in Controls: raycast.mjs, only where WebGL2 exists, off by default, fetched on the first switch-on; hides if WebGL2 fails.
let raycast = null;
if (typeof WebGL2RenderingContext !== 'undefined' && $('raycast')) {
  const b = $('raycast'); b.hidden = false;
  b.addEventListener('click', async () => {
    try {
      if (!raycast) raycast = (await import('./raycast.mjs')).mountRaycast({ lines, canvas, get FOV() { return fov(); }, measuredAt, invalidate, doc: document,
        state: () => state, groundVersion: () => groundVersion, origin: () => ({ ...origin }), sun: () => sunMode?.sun() });
    } catch (e) { console.warn('solid ground: ' + e.message); raycast = null; }
    if (!raycast) { b.hidden = true; return; }
    const on = !raycast.on(); raycast.set(on); b.setAttribute('aria-pressed', String(on));
  });
}
// For tests and the console. Read-only views of the live state, and the origin and arrival hooks.
window.world = Object.freeze({
  raycast: () => raycast?.debug() ?? null, raycastApi: () => raycast,
  origin: () => ({ ...origin }), groundVersion: () => groundVersion, setOrigin, heightAt, measuredAt, groundSource,
  liveTerrain: () => live().find(l => l.id === 'terrain-live')?.layer.debug() ?? null,
  state: () => state, budget: () => budget, fps: () => gate.fps(), generation: () => loaded.generation,
  layers: () => loaded.layers.map(({ id, status, layer }) => ({ id, status, detail: layer?.status ?? null })), // detail: the layer's own word
  // Flies the drone to national-grid (e, n): the arrival is smooth and capped at 30 fps.
  flyTo: (e, n, opts) => { const [x, y] = toLocal(origin, e, n); flyTo(x, y, opts); },
  plan, project, ohl: () => ohl?.layer.debug() ?? null, layerDebug: id => live().find(l => l.id === id)?.layer?.debug?.() ?? null, setRange: mi => layersUi?.range?.set(mi),
  layersOn: () => layersUi?.panel.onIds() || [], setLayer: (id, on) => layersUi?.panel.set(id, on),
  sun: () => sunMode?.debug() ?? null, place: () => first?.place() ?? null, // the place last found and pinned
  design: () => design.snapshot(), // the design in memory, in national-grid metres
  // Plant layout, Solar block, automatic piles, single-line diagram (world.sld), module detail on zoom (module-mount.mjs)
  plant: design.plantApi, block: design.blockApi, piles: design.pilesApi, sld, module: modules.api
});
// The command line (cmd-mount.mjs): a key and a dash button only; the bar and its engines load on first use. The Key (legend-ui.mjs).
import('./cmd-mount.mjs').then(m => { window.worldCmd = m.mountCommandLine({ api, world: window.world, project, ohl }); }).catch(e => console.warn('command line: ' + e.message));
import('./legend-ui.mjs').then(m => { window.worldLegend = m.mountLegend({ api }); }).catch(e => console.warn('key: ' + e.message)); // what the colours mean
// Buggy, check HUD, jump and binoculars, and more: extensions.mjs, each loaded after the first frame in its own chunk.
import('./extensions.mjs').then(m => m.mountExtensions({ api })).catch(e => console.warn('extensions: ' + e.message));
import('./nav-flight.mjs').then(m => { nav = m; }).catch(e => console.warn('flights: ' + e.message)); // glides and log-height descents