GLOBALGRID2050 / EXPLORE CODE

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

Piles and 3 more files

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

659 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 124 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. Piles transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/piles.mjs lines 1–225
  2. Plan Wire transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/plan-wire.mjs lines 1–45
  3. Print Layout transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print-layout.mjs lines 1–191
  4. Print Sheet render · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print-sheet.mjs lines 1–198

Piles

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

transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/piles.mjs · lines 1–225 of 225 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern revealPercentiles (shared by 4 files)

What it does
It calculates solar. Defines 7 functions or classes, including pileStations, spreadAt, fitTopLine, clip, slopeAt.
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.
Downstream impact
Used directly by 1 file: Design Earthworks (globalgrid2050).
What it achieves
It fits top line (`fitTopLine`) and is built from the pile stations helper (`pileStations`) and the spread at helper (`spreadAt`). Where the piles of a row of solar tables go, how far each stands out of the ground, how deep it goes in, and what grading a row needs where the ground is too uneven for a straight table.
Why it matters
Imported by Design Earthworks.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Design Earthworks (import)
Produces
LIMITS, DEFAULTS, pileStations, fitTopLine, planPiles, revealPercentiles
Defines here
pileStations, spreadAt, fitTopLine, clip, slopeAt, planPiles, revealPercentiles
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/202609270005-site-world-v3/world/piles.mjs:1-225 · blob 1d3e25b6779b9bf2538ccdacd02d2d14941549dc · 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
// piles.mjs: where the piles of a row of solar tables go, how far each stands out of the ground, how deep it
// goes in, and what grading a row needs where the ground is too uneven for a straight table.
//
// Local metres: x east, y north, z up. The ground is any function groundAt(x, y).
// A row is a straight placement line on the ground, [[x0, y0], [x1, y1]]. Tables of tableLength are laid
// along it end to end with tableGap between them, the set centred on the line. Each table is straight and
// rigid, so the tops of its piles lie on one straight line in the vertical section along the row. Piles sit
// pileSpacing apart, centred on their table.
//
// The top-of-pile line of a table is either given (row.top = [zStart, zEnd], the target top level at the two
// ends of the placement line; every table on the row takes that line) or fitted:
//   1. slope b: the one that makes the spread of (ground - b s) over the table's piles smallest, within the
//      along-row slope limit. That spread is convex and piecewise linear in b, so its least value is at a
//      pairwise slope between two piles or at a limit; ties go to the slope nearest the least-squares slope.
//   2. level a: the allowed window [max(g - b s) + revealMin, min(g - b s) + revealMax]; within it, as near
//      the mean nominal reveal as the window allows; if the window is empty, its middle (excess split evenly).
// A pile whose reveal is above revealMax needs fill under it, below revealMin needs cut; the finished ground is
// then level with the allowed limit. Embedment is at least embedMin below the finished ground; with pileStep the
// pile length is rounded up to a stock step and the embedment grows to suit.
// Grading volume: each pile's cut or fill depth over its tributary length (one pile spacing) times the grading
// width (assumed). Slopes: ground gradient at each pile by central differences, split into north-south and
// east-west parts, and checked against the limits for the mounting system.
//
// No imports, no DOM. Pure functions of their inputs. Figures marked ASSUMED are defaults to be replaced by the
// chosen product's datasheet and the site's geotechnical report; they are not design values.

// Typical slope limits, as fractions (rise over run). Sources:
//  [1] K. Anderson, M. Mikofski, "Slope-Aware Backtracking for Single-Axis Trackers", NREL/TP-5K00-76626, 2020,
//      https://docs.nrel.gov/docs/fy20osti/76626.pdf (definitions of axis tilt and cross-axis slope).
//  [2] Sandia PV Performance Modeling Collaborative, "Single Axis Tracking",
//      https://pvpmc.sandia.gov/modeling-guide/1-weather-design-inputs/array-orientation/single-axis-tracking/
//  [3] Trade-press survey of tracker datasheets, 2023-2024 (standard products commonly 8.5-15 % along the axis,
//      terrain-following products more; cross-axis slope commonly 10-20 % with slope-aware backtracking),
//      https://www.solarpowerworldonline.com/2023/01/single-axis-trackers-upgrade-to-handle-uneven-land-sites/
// Single-axis tracker rows run north-south, so its north-south limit applies along the torque tube.
// Fixed-tilt rows run east-west, so its east-west limit applies along the table.
export const LIMITS = {
  tracker: {
    nsMax: 0.10, ewMax: 0.15, along: 'ns',
    note: 'typical single-axis tracker: 10 % along the axis (north-south), 15 % across (east-west) [1][2][3]; ASSUMED',
  },
  fixed: {
    nsMax: 0.20, ewMax: 0.15, along: 'ew',
    note: 'typical fixed tilt: 15 % along the row (east-west), 20 % north-south (changes the effective tilt) [3]; ASSUMED',
  },
};

// ASSUMED defaults, labelled as such in every result (result.assumed).
export const DEFAULTS = {
  tracker: { tableLength: 60, pileSpacing: 7, tableGap: 1, reveal: { min: 1.0, nominal: 1.4, max: 1.8 } },
  fixed: { tableLength: 25, pileSpacing: 5, tableGap: 0.5, reveal: { min: 0.6, nominal: 1.0, max: 1.6 } },
  embedMin: 1.5,       // minimum embedment, metres: in practice set by pile load tests
  gradingWidth: 2.0,   // width of ground graded along a row, metres
  pileStep: 0,         // stock length step, metres; 0 means piles cut to length
  gradStep: 1.0,       // central-difference half step for the ground gradient, metres
};

const EPS = 1e-9;

/** Pile chainages along a placement line of length len: [{ table, s }], and the table extents. */
export function pileStations(len, tableLength, pileSpacing, tableGap = 0) {
  if (!(tableLength > 0) || !(pileSpacing > 0)) throw new Error('piles: tableLength and pileSpacing must be positive');
  if (pileSpacing > tableLength + EPS) throw new Error('piles: pileSpacing is longer than the table');
  if (!(tableGap >= 0)) throw new Error('piles: tableGap must be zero or positive');
  const nt = Math.floor((len + tableGap + EPS) / (tableLength + tableGap));
  const used = nt * tableLength + Math.max(nt - 1, 0) * tableGap;
  const off = (len - used) / 2;
  const np = Math.floor(tableLength / pileSpacing + EPS) + 1;
  const over = (tableLength - (np - 1) * pileSpacing) / 2;
  const tables = [], stations = [];
  for (let t = 0; t < nt; t++) {
    const s0 = off + t * (tableLength + tableGap);
    tables.push({ table: t, s0, s1: s0 + tableLength });
    for (let k = 0; k < np; k++) stations.push({ table: t, s: s0 + over + k * pileSpacing });
  }
  return { tables, stations, pilesPerTable: np };
}

const spreadAt = (s, g, b) => {
  let hi = -Infinity, lo = Infinity;
  for (let i = 0; i < s.length; i++) { const d = g[i] - b * s[i]; if (d > hi) hi = d; if (d < lo) lo = d; }
  return { hi, lo, w: hi - lo };
};

/**
 * fitTopLine(s, g, { min, nominal, max }, maxSlope): the straight top-of-pile line z = a + b s for piles at
 * chainages s over ground g. Returns { a, b, spread, window, feasible }.
 */
export function fitTopLine(s, g, reveal, maxSlope = Infinity) {
  const n = s.length;
  if (n < 1 || g.length !== n) throw new Error('piles: fitTopLine needs matching s and g');
  const lim = Math.abs(maxSlope);
  let bls = 0;
  if (n > 1) {
    const ms = s.reduce((p, v) => p + v, 0) / n, mg = g.reduce((p, v) => p + v, 0) / n;
    let sxy = 0, sxx = 0;
    for (let i = 0; i < n; i++) { sxy += (s[i] - ms) * (g[i] - mg); sxx += (s[i] - ms) ** 2; }
    bls = sxx > 0 ? sxy / sxx : 0;
  }
  const clip = (b) => Math.max(-lim, Math.min(lim, b));
  const cand = [clip(bls)];
  if (Number.isFinite(lim)) cand.push(-lim, lim);
  for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
    if (Math.abs(s[j] - s[i]) > EPS) cand.push(clip((g[j] - g[i]) / (s[j] - s[i])));
  }
  let best = null;
  for (const b of cand) {
    const r = spreadAt(s, g, b);
    if (!best || r.w < best.w - 1e-9 || (r.w <= best.w + 1e-9 && Math.abs(b - bls) < Math.abs(best.b - bls))) best = { b, ...r };
  }
  const { b, hi, lo, w } = best;
  const winLo = hi + reveal.min, winHi = lo + reveal.max;
  let mean = 0;
  for (let i = 0; i < n; i++) mean += g[i] - b * s[i];
  const aNom = mean / n + reveal.nominal;
  const feasible = winLo <= winHi + EPS;
  const a = feasible ? Math.max(winLo, Math.min(winHi, aNom)) : (winLo + winHi) / 2;
  return { a, b, spread: w, window: [winLo, winHi], feasible };
}

function slopeAt(groundAt, x, y, h) {
  const gx = (groundAt(x + h, y) - groundAt(x - h, y)) / (2 * h);
  const gy = (groundAt(x, y + h) - groundAt(x, y - h)) / (2 * h);
  return { gx, gy };
}

/**
 * planPiles({ rows, groundAt, system, ...options }) -> { rows, piles, summary, limits, assumed }
 * rows: [{ id?, line: [[x0, y0], [x1, y1]], top?: [zStart, zEnd] }]
 * system: 'tracker' (default) or 'fixed'. Options override DEFAULTS[system] and DEFAULTS:
 *   tableLength, pileSpacing, tableGap, reveal { min, nominal, max }, embedMin, gradingWidth, pileStep, gradStep,
 *   limits { nsMax, ewMax } (override LIMITS[system]).
 */
export function planPiles(opts) {
  const { rows, groundAt } = opts;
  const system = opts.system || 'tracker';
  if (!LIMITS[system]) throw new Error(`piles: unknown system ${system}`);
  if (typeof groundAt !== 'function') throw new Error('piles: groundAt(x, y) is required');
  if (!Array.isArray(rows)) throw new Error('piles: rows must be an array');
  const D = DEFAULTS[system];
  const tableLength = opts.tableLength ?? D.tableLength, pileSpacing = opts.pileSpacing ?? D.pileSpacing;
  const tableGap = opts.tableGap ?? D.tableGap;
  const reveal = { ...D.reveal, ...(opts.reveal || {}) };
  const embedMin = opts.embedMin ?? DEFAULTS.embedMin, gradingWidth = opts.gradingWidth ?? DEFAULTS.gradingWidth;
  const pileStep = opts.pileStep ?? DEFAULTS.pileStep, gradStep = opts.gradStep ?? DEFAULTS.gradStep;
  const limits = { ...LIMITS[system], ...(opts.limits || {}) };
  if (!(reveal.min <= reveal.nominal && reveal.nominal <= reveal.max)) throw new Error('piles: need reveal min <= nominal <= max');
  if (!(embedMin > 0)) throw new Error('piles: embedMin must be positive');
  const alongMax = limits.along === 'ns' ? limits.nsMax : limits.ewMax;

  const outRows = [], allPiles = [];
  const sum = { rows: 0, tables: 0, piles: 0, revealHigh: 0, revealLow: 0, tablesNeedingGrading: 0,
    cutM3: 0, fillM3: 0, nsSlopeTables: 0, ewSlopeTables: 0, topSlopeTables: 0, localSlopeTables: 0, totalPileLengthM: 0 };
  rows.forEach((row, ri) => {
    const [[x0, y0], [x1, y1]] = row.line;
    const len = Math.hypot(x1 - x0, y1 - y0);
    if (!(len > EPS)) throw new Error(`piles: row ${row.id ?? ri} has no length`);
    const ux = (x1 - x0) / len, uy = (y1 - y0) / len;
    const { tables, stations } = pileStations(len, tableLength, pileSpacing, tableGap);
    const rowOut = { id: row.id ?? ri, length: len, bearingDeg: (Math.atan2(ux, uy) * 180 / Math.PI + 360) % 360,
      tables: [], flags: [], cutM3: 0, fillM3: 0 };
    if (!tables.length) rowOut.flags.push('row shorter than one table');
    for (const tb of tables) {
      const st = stations.filter((p) => p.table === tb.table);
      const s = st.map((p) => p.s);
      const xy = s.map((v) => [x0 + ux * v, y0 + uy * v]);
      const g = xy.map(([x, y]) => groundAt(x, y));
      if (g.some((v) => !Number.isFinite(v))) throw new Error(`piles: no ground under row ${rowOut.id}`);
      const fit = row.top
        ? { a: row.top[0], b: (row.top[1] - row.top[0]) / len, given: true }
        : fitTopLine(s, g, reveal, alongMax);
      const tOut = { table: tb.table, s0: tb.s0, s1: tb.s1, topLevelStart: fit.a + fit.b * tb.s0,
        topLevelEnd: fit.a + fit.b * tb.s1, topSlope: fit.b, given: !!fit.given, feasible: true,
        piles: [], cutM3: 0, fillM3: 0, maxNs: 0, maxEw: 0, nsSlope: 0, ewSlope: 0, flags: [] };
      st.forEach((p, k) => {
        const [x, y] = xy[k], ground = g[k], top = fit.a + fit.b * p.s, rev = top - ground;
        const fill = Math.max(rev - reveal.max, 0), cut = Math.max(reveal.min - rev, 0);
        const finished = ground + fill - cut, finRev = top - finished;
        let length = finRev + embedMin;
        if (pileStep > 0) length = Math.ceil(length / pileStep - 1e-9) * pileStep;
        const { gx, gy } = slopeAt(groundAt, x, y, gradStep);
        const flags = [];
        if (rev > reveal.max + EPS) flags.push('reveal-high');
        if (rev < reveal.min - EPS) flags.push('reveal-low');
        const pile = { row: rowOut.id, table: tb.table, index: k, s: p.s, x, y, ground, top, reveal: rev, cut, fill,
          finishedGround: finished, finishedReveal: finRev, embed: length - finRev, toe: top - length, length,
          slopeNs: gy, slopeEw: gx, slopeAlong: gx * ux + gy * uy, slopeCross: -gx * uy + gy * ux, flags };
        tOut.piles.push(pile); allPiles.push(pile);
        tOut.cutM3 += cut * pileSpacing * gradingWidth; tOut.fillM3 += fill * pileSpacing * gradingWidth;
        tOut.maxNs = Math.max(tOut.maxNs, Math.abs(gy)); tOut.maxEw = Math.max(tOut.maxEw, Math.abs(gx)); // local, 1 m
        tOut.nsSlope += gy / st.length; tOut.ewSlope += gx / st.length;                                   // table mean
        if (flags.length) { tOut.feasible = false; if (flags[0] === 'reveal-high') sum.revealHigh++; else sum.revealLow++; }
        sum.piles++; sum.totalPileLengthM += length;
      });
      if (!tOut.feasible) { tOut.flags.push('grading needed'); sum.tablesNeedingGrading++; }
      // Slope limits apply to the table: the mean ground gradient over its piles, so a ditch, a bank or LiDAR noise
      // under one pile does not flag the table. The worst 1 m point gradient is kept as maxNs / maxEw ("local").
      tOut.nsSlope = Math.abs(tOut.nsSlope); tOut.ewSlope = Math.abs(tOut.ewSlope);
      if (tOut.nsSlope > limits.nsMax + EPS) { tOut.flags.push('north-south slope over limit'); sum.nsSlopeTables++; }
      if (tOut.ewSlope > limits.ewMax + EPS) { tOut.flags.push('east-west slope over limit'); sum.ewSlopeTables++; }
      if (tOut.maxNs > limits.nsMax + EPS || tOut.maxEw > limits.ewMax + EPS) sum.localSlopeTables++;
      if (Math.abs(fit.b) > alongMax + EPS) { tOut.flags.push('table slope over limit'); sum.topSlopeTables++; }
      rowOut.cutM3 += tOut.cutM3; rowOut.fillM3 += tOut.fillM3;
      for (const f of tOut.flags) if (!rowOut.flags.includes(f)) rowOut.flags.push(f);
      rowOut.tables.push(tOut); sum.tables++;
    }
    sum.cutM3 += rowOut.cutM3; sum.fillM3 += rowOut.fillM3; sum.rows++;
    outRows.push(rowOut);
  });
  return {
    system, rows: outRows, piles: allPiles, summary: sum,
    limits: { nsMax: limits.nsMax, ewMax: limits.ewMax, alongMax, note: limits.note },
    assumed: { tableLength, pileSpacing, tableGap, reveal, embedMin, gradingWidth, pileStep, gradStep,
      note: 'ASSUMED defaults unless passed in: replace with the product datasheet and the geotechnical report. '
        + 'Embedment is the same for every pile, independent of reveal: set it from pile tests. Grading volumes are '
        + 'indicative: depth x pile spacing x grading width per pile.' },
  };
}

/** Reveal distribution of a set of piles: percentiles 0, 5, 25, 50, 75, 95, 100 (nearest-rank). */
export function revealPercentiles(piles) {
  const v = piles.map((p) => p.reveal).sort((a, b) => a - b);
  if (!v.length) return [];
  return [0, 5, 25, 50, 75, 95, 100].map((q) => v[Math.min(v.length - 1, Math.max(0, Math.ceil(q / 100 * v.length) - 1))]);
}

Plan Wire

A JavaScript module in the world folder of GlobalGrid2050 that works with cables.

transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/plan-wire.mjs · lines 1–45 of 45 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern drawn (shared by 2 files)

What it does
It calculates cables. Defines mountPlan, local, drawn, update.
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.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It is built from the mount plan helper (`mountPlan`), the local step (`local`) and the drawn step (`drawn`). Wires the plan inset (`plan-inset.mjs`) to the world: it is redrawn after each drawn frame, and only when what it shows has changed.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
Plan Inset (import), Origin (import)
Used by
none found
Produces
mountPlan
Defines here
mountPlan, local, drawn, update
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/202609270005-site-world-v3/world/plan-wire.mjs:1-45 · blob 3ad041c4d08fc89e27e49f6d864bddfb08bc6e62 · 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
// Wires the plan inset (plan-inset.mjs) to the world: it is redrawn after each drawn frame, and only when
// what it shows has changed. Layers may offer plan() -> { boundary?, tiles?, items? } in local metres.
// Tools that are not layers add items with setItems(key, items), points in national-grid metres [[e, n], ...],
// so they survive every move of the origin. The finished design (trenches and cables) is shown too.
// A tap on the plan flies there with the substrate's own flyTo.
import { createPlanInset } from './plan-inset.mjs';
import { toLocal } from './origin.mjs';

export function mountPlan(api, doc = document) {
  const extra = new Map(); // key -> items in national-grid metres
  const inset = createPlanInset(doc, { onFly: (x, y) => api.flyTo(x, y) });
  let cacheKey = '', cached = [], designVersion = 0;
  api.hooks.design.add(() => { designVersion++; });
  const local = (o, it) => ({ kind: it.kind, closed: !!it.closed, points: it.points.map(([e, n]) => toLocal(o, e, n)) });
  function drawn() {
    const o = api.origin(), key = `${o.id}:${designVersion}:${extra.size}`;
    if (key !== cacheKey) {
      const d = api.design(), line = kind => t => ({ kind, points: t.path.map(p => [p.e, p.n]) });
      const bng = [...d.trenches.map(line('trench')), ...d.cables.map(line('cable')), ...[...extra.values()].flat()];
      cached = bng.map(it => local(o, it));
      cacheKey = key;
    }
    return cached;
  }
  function update() {
    const parts = api.live().map(l => (typeof l.layer.plan === 'function' ? api.guarded(l, () => l.layer.plan(), null) : null))
      .filter(Boolean);
    const s = api.state();
    inset.set({
      viewer: { x: s.pos[0], y: s.pos[1], yaw: s.yaw },
      boundary: parts.find(p => Array.isArray(p.boundary) && p.boundary.length > 2)?.boundary || null,
      tiles: parts.flatMap(p => p.tiles || []),
      items: [...parts.flatMap(p => p.items || []), ...drawn()]
    });
  }
  api.hooks.after.add(update);
  return Object.freeze({
    collapsed: () => inset.collapsed(), setCollapsed: on => inset.setCollapsed(on), redraws: () => inset.redraws(),
    // items: [{ kind, closed?, points: [[e, n], ...] }] in national-grid metres; an empty list removes the key.
    setItems(key, items) {
      if (items && items.length) extra.set(key, items); else extra.delete(key);
      designVersion++; update();
    }
  });
}

Print Layout

A JavaScript module in the world folder of GlobalGrid2050 that scales bar (`scaleBar`), fits credit (`fitCredit`) and calculates angles. It wraps text (`wrapText`) and fits credit (`fitCredit`).

transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print-layout.mjs · lines 1–191 of 191 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern scaleBar (shared by 2 files)

What it does
It calculates its inputs. Defines 16 functions or classes, including rect, sheetLayout, niceBelow, chooseScale, batchBounds.
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.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 4 files: Print Sheet (globalgrid2050); Print SVG (globalgrid2050); Print (globalgrid2050); Print Sheet (globalgrid2050).
What it achieves
Print sheet layout: the pure parts.
Why it matters
Imported by 4 files, including Print Sheet, Print SVG and Print.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
Bng (import)
Used by
imported by Print Sheet (import), imported by Print SVG (import), imported by Print (import), imported by Print Sheet (import), mentioned in Standalone (comment link)
Produces
PAPER, SCALES, MONO_WIDTH, sheetLayout, niceBelow, chooseScale, batchBounds, planFrame, planToPaper, scaleBar, digitsFor, gridTicks
Defines here
rect, sheetLayout, niceBelow, chooseScale, batchBounds, planFrame, planToPaper, scaleBar, digitsFor, gridTicks, safeRef, refAt, trueNorthOffset, bearingText, wrapText, fitCredit
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/202609270005-site-world-v3/world/print-layout.mjs:1-191 · blob 153ae0bad2243a746dddf95dccb9c52a57e3dd7f · 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
// Print sheet layout: the pure parts. No DOM, no WebGL. Units are millimetres on the paper and
// metres in the world (local east, north, up from the site origin, as everywhere else in web/world).
// The sheet follows the GridAtlas print furniture: the drawing first, the credit for exactly the data
// shown beneath it, and a stamp; here the stamp grows into a title block beside the drawing.

import { gridRef, bngToWgs84 } from './bng.mjs';

export const PAPER = Object.freeze({
  A3: { name: 'A3', w: 420, h: 297 },
  A4: { name: 'A4', w: 297, h: 210 },
});

// Scales a surveyor would expect to read off a sheet, smallest denominator first.
export const SCALES = Object.freeze([100, 200, 250, 500, 1000, 1250, 2000, 2500, 5000, 10000, 25000, 50000, 100000]);

// Character width of the sheet's monospace face as a fraction of its size; used to wrap text.
export const MONO_WIDTH = 0.6;

const rect = (x, y, w, h) => ({ x, y, w, h });

// Where everything goes on the paper. Returns rectangles in mm:
//   frame     the drawing border
//   plan      the plan panel (left, the larger); planDraw its drawing area inside the band of grid figures
//   credit    under the plan: the credit for exactly the data shown
//   view      top right, at the screen's shape (aspect = height / width of the captured view)
//   title     the rest of the right-hand column: title block, layers, warning
export function sheetLayout(paperName = 'A3', { aspect = 10 / 16 } = {}) {
  const paper = PAPER[paperName];
  if (!paper) throw Error(`unknown paper ${paperName}; use ${Object.keys(PAPER).join(' or ')}`);
  const small = paper.name === 'A4';
  const m = small ? 8 : 10, gap = small ? 4 : 5, creditH = small ? 24 : 28, band = small ? 6 : 7, titleMin = small ? 92 : 120;
  const frame = rect(m, m, paper.w - 2 * m, paper.h - 2 * m);
  const inner = rect(frame.x + gap, frame.y + gap, frame.w - 2 * gap, frame.h - 2 * gap);
  const planW = Math.round(inner.w * 0.6), rightW = inner.w - planW - gap;
  const plan = rect(inner.x, inner.y, planW, inner.h - creditH - gap);
  const planDraw = rect(plan.x + band, plan.y + band, plan.w - 2 * band, plan.h - 2 * band);
  const credit = rect(inner.x, plan.y + plan.h + gap, planW, creditH);
  const a = Number.isFinite(aspect) && aspect > 0 ? aspect : 10 / 16;
  const viewH = Math.min(rightW * a, inner.h - titleMin - gap);
  const view = rect(inner.x + planW + gap, inner.y, rightW, viewH);
  const title = rect(view.x, view.y + viewH + gap, rightW, inner.h - viewH - gap);
  return { paper, margin: m, gap, band, frame, plan, planDraw, view, credit, title, small };
}

// A round number of the form 1, 2 or 5 x 10^k that is at most `v`.
export function niceBelow(v) {
  if (!(v > 0)) throw Error('niceBelow needs a positive value');
  const p = 10 ** Math.floor(Math.log10(v) + 1e-9);
  for (const f of [5, 2, 1]) if (f * p <= v * (1 + 1e-9)) return f * p;
  return p;
}

// The smallest standard scale at which `extentM` ([width, height] in metres) fits `drawMM`
// ([width, height] in mm). Past the last standard scale, the exact scale is returned.
export function chooseScale(extentM, drawMM) {
  const need = Math.max(extentM[0] * 1000 / drawMM[0], extentM[1] * 1000 / drawMM[1]);
  if (!(need > 0) || !Number.isFinite(need)) throw Error('chooseScale needs a positive extent and drawing area');
  return SCALES.find(s => s >= need - 1e-9) ?? Math.ceil(need);
}

// Bounds of the line batches in local metres, x and y only; z is ignored (the plan looks straight down).
// Each batch's positions are relative to its origin, if it has one. Non-finite points are skipped.
export function batchBounds(batches) {
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (const b of batches || []) {
    if (b.occluder || !b.positions) continue;
    const o = b.origin || [0, 0, 0], p = b.positions;
    for (let i = 0; i + 2 < p.length; i += 3) {
      const x = p[i] + o[0], y = p[i + 1] + o[1];
      if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
      if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y;
    }
  }
  return x0 <= x1 ? { x0, y0, x1, y1 } : null;
}

// The plan's framing: a centre (local metres), a standard scale and the visible extent.
// extent: optional { x0, y0, x1, y1 } in local metres; defaults to the batches' bounds, else 100 m round the centre.
// maxHalf caps the framing so a horizon-wide grid does not shrink the site to a dot.
export function planFrame(layout, { batches = [], extent = null, centre = null, maxHalf = 250, minHalf = 10 } = {}) {
  let e = extent || batchBounds(batches);
  const c = centre || (e ? [(e.x0 + e.x1) / 2, (e.y0 + e.y1) / 2] : [0, 0]);
  const half = [e ? (e.x1 - e.x0) / 2 : 50, e ? (e.y1 - e.y0) / 2 : 50]
    .map(h => Math.min(maxHalf, Math.max(minHalf, h)));
  const d = layout.planDraw;
  const scale = chooseScale([2 * half[0], 2 * half[1]], [d.w, d.h]);
  const mPerMM = scale / 1000;
  return { centre: c, scale, mPerMM, widthM: d.w * mPerMM, heightM: d.h * mPerMM };
}

// Local metres -> paper mm inside the plan's drawing area. North is up the sheet (grid north).
export function planToPaper(frame, layout, x, y) {
  const d = layout.planDraw;
  return [d.x + d.w / 2 + (x - frame.centre[0]) / frame.mPerMM,
          d.y + d.h / 2 - (y - frame.centre[1]) / frame.mPerMM];
}

// A scale bar up to about 0.3 of the plan's width (1-2-5 steps): its length in metres, in mm, and four divisions.
export function scaleBar(frame, layout, { fraction = 0.3 } = {}) {
  const m = niceBelow(layout.planDraw.w * fraction * frame.mPerMM);
  const mm = m / frame.mPerMM;
  const ticks = [0, 0.25, 0.5, 0.75, 1].map(t => ({ m: m * t, mm: mm * t }));
  return { m, mm, ticks, label: m >= 1000 ? `${m / 1000} km` : `${m} m` };
}

// Digits per grid reference that suit a tick spacing: 1 m -> 10 figures, 100 m -> 6, 1 km -> 4.
export const digitsFor = spacing => Math.max(2, Math.min(10, 2 * (5 - Math.floor(Math.log10(spacing) + 1e-9))));

// National Grid ticks along the plan's edges, every `spacing` metres (3 to 8 across the width).
// Each tick has its paper position and the grid-reference figures for that line, via gridRef.
// Lines that fall outside the National Grid are dropped rather than mislabelled.
export function gridTicks(frame, layout, origin, { target = 5 } = {}) {
  const spacing = niceBelow(frame.widthM / target);
  const digits = digitsFor(spacing), d = layout.planDraw;
  const half = [frame.widthM / 2, frame.heightM / 2];
  const ce = origin.e + frame.centre[0], cn = origin.n + frame.centre[1];
  const eastings = [], northings = [];
  for (let e = Math.ceil((ce - half[0]) / spacing) * spacing; e <= ce + half[0] + 1e-6; e += spacing) {
    const ref = safeRef(e, cn, digits);
    if (!ref) continue;
    eastings.push({ e, x: d.x + d.w / 2 + (e - ce) / frame.mPerMM, square: ref.square, label: ref.east });
  }
  for (let n = Math.ceil((cn - half[1]) / spacing) * spacing; n <= cn + half[1] + 1e-6; n += spacing) {
    const ref = safeRef(ce, n, digits);
    if (!ref) continue;
    northings.push({ n, y: d.y + d.h / 2 - (n - cn) / frame.mPerMM, square: ref.square, label: ref.north });
  }
  // The 100 km squares the plan covers, from its corners and centre (not only where ticks fall).
  const squares = [...new Set([[-1, 1], [1, 1], [0, 0], [-1, -1], [1, -1]]
    .map(([sx, sy]) => safeRef(ce + sx * half[0], cn + sy * half[1], 2)?.square).filter(Boolean))];
  return { spacing, digits, eastings, northings, squares };
}

function safeRef(e, n, digits) {
  try {
    const [square, east, north] = gridRef(e, n, digits).split(' ');
    return { square, east, north };
  } catch { return null; }
}

// Full grid reference for a local point, or null off the grid. 10 figures is a 1 m reference.
export function refAt(origin, x, y, digits = 10) {
  try { return gridRef(origin.e + x, origin.n + y, digits); } catch { return null; }
}

// Angle from grid north to true north at a grid point, degrees, east positive. The plan is drawn
// grid-north up; this says how far true north leans from it. Null off the grid.
export function trueNorthOffset(e, n) {
  if (!(e >= 0 && e < 700000 && n >= 0 && n < 1300000)) return null;
  const a = bngToWgs84(e, n), b = bngToWgs84(e, n + 1000);
  // Grid north's bearing (from true north) is the bearing of a 1 km step up the grid.
  const lat = a.lat * Math.PI / 180;
  const dx = (b.lon - a.lon) * Math.cos(lat), dy = b.lat - a.lat;
  return -Math.atan2(dx, dy) * 180 / Math.PI;
}

// Compass words for a view heading; yaw 0 is north, pi/2 east (as in camera.mjs).
export function bearingText(yaw) {
  const deg = ((yaw * 180 / Math.PI) % 360 + 360) % 360;
  const names = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
  return `${names[Math.round(deg / 45) % 8]} (${deg.toFixed(0).padStart(3, '0')}°)`;
}

// Word-wraps text to lines of at most `widthMM` at font size `sizeMM` in the monospace face.
// A word longer than a line is broken rather than allowed to spill past the frame.
export function wrapText(text, widthMM, sizeMM) {
  const max = Math.max(8, Math.floor(widthMM / (sizeMM * MONO_WIDTH)));
  const lines = [];
  let line = '';
  for (let word of String(text || '').split(/\s+/).filter(Boolean)) {
    while (word.length > max) { if (line) { lines.push(line); line = ''; } lines.push(word.slice(0, max)); word = word.slice(max); }
    if (!line) line = word;
    else if (line.length + 1 + word.length <= max) line += ' ' + word;
    else { lines.push(line); line = word; }
  }
  if (line) lines.push(line);
  return lines;
}

// The credit split into entries (footerText joins them with ' · '), each wrapped, then fitted to
// `maxLines`, shrinking the font down to `minSize` before it would ever drop a line. Returns
// { size, lines, fits }. fits is false only if even the smallest size overflows; the caller must say so.
export function fitCredit(text, widthMM, maxHeightMM, { size = 2.4, minSize = 1.6, lead = 1.3 } = {}) {
  const entries = String(text || '').split(' · ').filter(Boolean);
  for (let s = size; s >= minSize - 1e-9; s = Math.round((s - 0.1) * 10) / 10) {
    const lines = entries.flatMap(t => wrapText(t, widthMM, s));
    if (lines.length * s * lead <= maxHeightMM) return { size: s, lines, fits: true };
  }
  const lines = entries.flatMap(t => wrapText(t, widthMM, minSize));
  return { size: minSize, lines, fits: false };
}

Print Sheet

A JavaScript module in the world folder of GlobalGrid2050 that clips def (`clipDef`) and draws SVG graphics, using Helmert.

renderglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print-sheet.mjs · lines 1–198 of 198 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern buildSheet (shared by 2 files)

What it does
It draws its content. Defines 12 functions or classes, including sheetDate, f, t, rect, clipDef. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Out: SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Print (globalgrid2050).
What it achieves
It builds sheet (`buildSheet`) and is built from the sheet date helper (`sheetDate`) and the rect step (`rect`). The whole print sheet as one SVG string: plan, current view, north arrow, scale bar, National Grid references, title block and the credit for exactly the loaded layers.
Why it matters
Imported by Print.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
Attribution (import), Print Layout (import), Print SVG (import)
Used by
imported by Print (import), mentioned in Standalone (comment link)
Produces
NOT_FOR_CONSTRUCTION, CAVEAT, NO_CREDIT, sheetDate, buildSheet, legendOf
Defines here
sheetDate, f, t, rect, clipDef, stroke, tag, buildSheet, dateYear, viewerMark, legendOf, titleBlock
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/202609270005-site-world-v3/world/print-sheet.mjs:1-198 · blob 02d26b958ed83f8d9d505166a3fc47b463da0288 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// The whole print sheet as one SVG string: plan, current view, north arrow, scale bar, National Grid
// references, title block and the credit for exactly the loaded layers. Pure: no DOM, no WebGL.
// Style after the GridAtlas print furniture: monospace, letter-spaced heading, the credit beneath the
// drawing and a stamp; here the stamp grows into a title block with the layers shown and the warning.

import { footerText, unknownLayers } from './attribution.mjs';
import { sheetLayout, fitCredit, wrapText } from './print-layout.mjs';
import {
  FONT, INK, MUTED, RULE, esc, inkFor, planPaths, viewPaths, northArrow, scaleBarSvg, gridSvg,
  planFrame, scaleBar, gridTicks, refAt, trueNorthOffset, bearingText,
} from './print-svg.mjs';

export const NOT_FOR_CONSTRUCTION = 'NOT FOR CONSTRUCTION';
export const CAVEAT = 'Illustrative only. Positions are converted to the British National Grid by a Helmert transformation '
  + '(about 3.5 m); nothing here is surveyed, designed or checked.';
export const NO_CREDIT = 'No third-party data is shown on this sheet.';
// The viewer's own drawing (the design) needs no third-party credit.
const OWN_WORK = /^design(-|$)/;

// 26 September 2026 (British order, month in words so it cannot be misread).
export function sheetDate(date) {
  const d = date instanceof Date ? date : new Date(date ?? Date.now());
  if (Number.isNaN(d.getTime())) throw Error('sheetDate needs a valid date');
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
}

const f = v => (Math.round(v * 100) / 100).toString();
const t = (x, y, s, size, extra = '') => `<text x="${f(x)}" y="${f(y)}" font-size="${f(size)}"${extra}>${esc(s)}</text>`;
const rect = (r, extra = '') => `<rect x="${f(r.x)}" y="${f(r.y)}" width="${f(r.w)}" height="${f(r.h)}"${extra}/>`;
const clipDef = (id, r) => `<clipPath id="${id}">${rect(r)}</clipPath>`;
const stroke = (p, w) => `<path d="${p.d}" stroke="${p.stroke}" stroke-opacity="${f(p.opacity)}" stroke-width="${w}" fill="none" stroke-linecap="round"/>`;

// A small label with a white backing, so it reads over the drawing.
function tag(x, y, s, size = 2.1, extra = '') {
  const w = s.length * size * 0.6 + 2;
  return `<rect x="${f(x)}" y="${f(y)}" width="${f(w)}" height="${f(size + 1.6)}" fill="#fff" fill-opacity="0.9"/>`
    + t(x + 1, y + size + 0.5, s, size, ` fill="${INK}"${extra}`);
}

// opts:
//   paper        'A3' | 'A4'                 batches   the world's line batches (as given to lines.draw)
//   camera       { pos, yaw, pitch, fov?, label?, eyeHeight? }    origin  { e, n } National Grid metres
//   site         { name }  a neutral name      layerIds  ids of the loaded layers   attribution  data/attribution.json
//   date         Date or ISO string          generation  manifest generation stamp (optional)
//   viewImage    { href, width, height }: the captured frame; omit for a vector redraw of the view
//   extent       { x0, y0, x1, y1 } local metres to frame the plan (default: the batches' bounds, capped)
//   fade         metres at which lines vanish (the world's FADE_M)
// Returns { svg, meta }. meta repeats the facts on the sheet so a caller or a test can check them.
export function buildSheet(opts) {
  const { paper = 'A3', batches = [], camera, origin = { e: 0, n: 0 }, site = {}, layerIds = [], attribution,
    date, generation = '', viewImage = null, extent = null, fade = 450 } = opts || {};
  if (!camera || !Array.isArray(camera.pos)) throw Error('buildSheet needs the camera { pos, yaw, pitch }');
  if (!attribution) throw Error('buildSheet needs the attribution data; a sheet is never printed without its credit');
  const aspect = viewImage && viewImage.width > 0 ? viewImage.height / viewImage.width : camera.aspect;
  const L = sheetLayout(paper, { aspect });
  const frame = planFrame(L, { batches, extent, centre: extent ? null : [camera.pos[0], camera.pos[1]] });
  const ticks = gridTicks(frame, L, origin);
  const bar = scaleBar(frame, L);
  const ce = origin.e + frame.centre[0], cn = origin.n + frame.centre[1];
  const tn = trueNorthOffset(ce, cn);
  const centreRef = refAt(origin, frame.centre[0], frame.centre[1], 10);
  const eyeRef = refAt(origin, camera.pos[0], camera.pos[1], 10);
  // Credit what is loaded and what is drawn; anything drawn without a registered credit is named on the sheet.
  const legend = legendOf(batches);
  const creditIds = [...new Set([...layerIds, ...legend.map(e => e.name)])].filter(id => !OWN_WORK.test(id));
  const credit = footerText(creditIds, attribution, { year: dateYear(date) });
  const missing = unknownLayers(creditIds, attribution);
  const creditText = [credit || (missing.length ? '' : NO_CREDIT), missing.length ? `Credit missing for: ${missing.join(', ')}.` : '']
    .filter(Boolean).join(' · ');
  const name = String(site.name || 'Unnamed site');
  const dateText = sheetDate(date);
  const heightOk = Number.isFinite(camera.eyeHeight);

  const out = [
    `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${L.paper.w}mm" height="${L.paper.h}mm" `
      + `viewBox="0 0 ${L.paper.w} ${L.paper.h}" font-family="${esc(FONT)}" data-paper="${L.paper.name}" data-scale="${frame.scale}">`,
    `<title>${esc(`${name}: plan and view, ${L.paper.name} landscape`)}</title>`,
    `<defs>${clipDef('plan-clip', L.planDraw)}${clipDef('view-clip', L.view)}</defs>`,
    `<rect width="${L.paper.w}" height="${L.paper.h}" fill="#fff"/>`,
    rect(L.frame, ` fill="none" stroke="${INK}" stroke-width="0.5"`),
  ];

  // Plan
  out.push(rect(L.plan, ` fill="none" stroke="${INK}" stroke-width="0.3"`), rect(L.planDraw, ` fill="none" stroke="${INK}" stroke-width="0.2"`));
  out.push(gridSvg(ticks, L));
  out.push('<g clip-path="url(#plan-clip)">', ...planPaths(batches, frame, L).map(p => stroke(p, 0.15)));
  const [ex, ey] = [L.planDraw.x + L.planDraw.w / 2 + (camera.pos[0] - frame.centre[0]) / frame.mPerMM,
    L.planDraw.y + L.planDraw.h / 2 - (camera.pos[1] - frame.centre[1]) / frame.mPerMM];
  out.push(viewerMark(ex, ey, camera.yaw), '</g>');
  const d = L.planDraw;
  out.push(tag(d.x + 1.5, d.y + 1.5, 'PLAN · straight down, grid north up', 2.1, ' letter-spacing="0.15"'));
  out.push(`<rect x="${f(d.x + d.w - 17)}" y="${f(d.y + 2)}" width="15" height="${L.small ? 22 : 24}" fill="#fff" fill-opacity="0.9"/>`);
  out.push(northArrow(d.x + d.w - 9.5, d.y + 12, L.small ? 9 : 11, tn));
  out.push(`<rect x="${f(d.x + 2)}" y="${f(d.y + d.h - 12)}" width="${f(bar.mm + 10)}" height="10" fill="#fff" fill-opacity="0.9"/>`);
  out.push(scaleBarSvg(bar, d.x + 5, d.y + d.h - 8.5, frame.scale));

  // Current view
  const v = L.view;
  out.push(rect(v, ` fill="${viewImage ? '#0a0a0a' : '#fff'}" stroke="none"`), '<g clip-path="url(#view-clip)">');
  if (viewImage) {
    out.push(`<image x="${f(v.x)}" y="${f(v.y)}" width="${f(v.w)}" height="${f(v.h)}" preserveAspectRatio="xMidYMid meet" `
      + `href="${esc(viewImage.href)}" xlink:href="${esc(viewImage.href)}"/>`);
  } else {
    out.push(...viewPaths(batches, camera, v, { fade }).map(p => stroke(p, 0.18)));
  }
  out.push('</g>', rect(v, ` fill="none" stroke="${INK}" stroke-width="0.3"`));
  const how = viewImage ? 'the frame on screen when printed' : 'redrawn from the same lines; ground does not hide lines here';
  out.push(tag(v.x + 1.5, v.y + 1.5, 'CURRENT VIEW', 2.1, ' letter-spacing="0.15"'));
  const look = `${camera.label || 'View'} · looking ${bearingText(camera.yaw)}` + (heightOk ? ` · eye ${camera.eyeHeight.toFixed(1)} m above ground` : '');
  out.push(tag(v.x + 1.5, v.y + v.h - 9.2, look, 1.9), tag(v.x + 1.5, v.y + v.h - 4.8, how, 1.9));

  // Credit (under the plan): exactly the loaded layers' lines, never trimmed
  const c = L.credit, headSize = 2.2;
  out.push(rect(c, ` fill="none" stroke="${INK}" stroke-width="0.3"`));
  out.push(t(c.x + 2, c.y + 4, 'DATA SHOWN ON THIS SHEET', headSize, ` fill="${INK}" letter-spacing="0.4"`));
  const fit = fitCredit(creditText, c.w - 4, c.h - 7.5);
  fit.lines.forEach((line, i) => out.push(t(c.x + 2, c.y + 7 + fit.size * (1 + i * 1.3), line, fit.size, ` fill="${MUTED}"`)));

  // Title block (under the view)
  out.push(titleBlock(L, { name, dateText, frame, centreRef, eyeRef, generation, tn, legend }));
  out.push('</svg>');
  const meta = { paper: L.paper.name, scale: frame.scale, centreRef, eyeRef, credit, creditFits: fit.fits,
    creditComplete: missing.length === 0, creditMissing: missing, squares: ticks.squares,
    creditSize: fit.size, trueNorth: tn, gridSpacing: ticks.spacing, scaleBar: bar.label, date: dateText,
    view: viewImage ? 'image' : 'vector', layers: legend.map(e => e.name) };
  return { svg: out.join(''), meta };
}

function dateYear(date) {
  const d = date instanceof Date ? date : new Date(date ?? Date.now());
  return Number.isNaN(d.getTime()) ? undefined : d.getUTCFullYear();
}

// The viewer's position and heading on the plan: a small circle and a tick along the look direction.
function viewerMark(x, y, yaw) {
  const dx = Math.sin(yaw) * 4, dy = -Math.cos(yaw) * 4;
  return `<g stroke="#b00020" stroke-width="0.35" fill="none"><circle cx="${f(x)}" cy="${f(y)}" r="1.2"/>`
    + `<path d="M${f(x)} ${f(y)}L${f(x + dx)} ${f(y + dy)}"/></g>`;
}

// One legend entry per layer: batch keys are "layer/part", so the part before the slash names the layer.
export function legendOf(batches) {
  const seen = new Map();
  for (const b of batches || []) {
    if (b.occluder || !b.positions || !b.key) continue;
    const name = String(b.key).split('/')[0];
    if (!seen.has(name)) seen.set(name, inkFor(b.color));
  }
  return [...seen].map(([name, ink]) => ({ name, ...ink }));
}

function titleBlock(L, { name, dateText, frame, centreRef, eyeRef, generation, tn, legend }) {
  const r = L.title, out = [rect(r, ` fill="none" stroke="${INK}" stroke-width="0.3"`)];
  const x = r.x + 2.5, size = L.small ? 1.9 : 2.5, row = size * 1.5, cs = L.small ? 1.6 : 1.9;
  out.push(t(x, r.y + 4, 'SITE WORLD · PLAN AND VIEW', 1.9, ` fill="${MUTED}" letter-spacing="0.45"`));
  const nameSize = L.small ? 3.6 : 5.2;
  out.push(t(x, r.y + 5.5 + nameSize, wrapText(name, r.w - 5, nameSize)[0] || '', nameSize, ` fill="${INK}" font-weight="700"`));
  const rows = [
    ['Centre', centreRef || 'off the National Grid'],
    ['Viewer', eyeRef || 'off the National Grid'],
    ['Scale', `1:${frame.scale.toLocaleString('en-GB')} at ${L.paper.name} · grid north up`],
    ['North', tn === null ? 'off the National Grid' : Math.abs(tn) < 0.005 ? 'true north on grid north'
      : `true north ${Math.abs(tn).toFixed(2)}° ${tn >= 0 ? 'east' : 'west'} of grid north`],
    ['Date', dateText],
  ];
  if (generation) rows.push(['Data', generation]);
  let y = r.y + 7 + nameSize + 3.2;
  for (const [k, val] of rows) {
    out.push(t(x, y, k.toUpperCase(), size * 0.9, ` fill="${MUTED}" letter-spacing="0.25"`), t(x + size * 6.5, y, val, size, ` fill="${INK}"`));
    y += row;
  }
  // The warning: a boxed band across the foot of the block, the caveat above it
  const bandH = L.small ? 6 : 7, by = r.y + r.h - bandH - 1.5;
  const cav = wrapText(CAVEAT, r.w - 5, cs), cavTop = by - 1.2 - (cav.length - 1) * cs * 1.3 - cs;
  // Layers between the rows and the caveat, in two columns, as many as there is room for
  out.push(`<path d="M${f(r.x)} ${f(y - size + 0.6)}H${f(r.x + r.w)}" stroke="${RULE}" stroke-width="0.15"/>`);
  y += 1.6;
  out.push(t(x, y, 'LAYERS DRAWN', size * 0.9, ` fill="${MUTED}" letter-spacing="0.25"`));
  y += row;
  const colW = (r.w - 5) / 2, fit = Math.max(0, Math.floor((cavTop - 2 - (y - size)) / row)) * 2;
  const shown = legend.length > fit ? legend.slice(0, Math.max(0, fit - 1)) : legend;
  shown.forEach((e, i) => {
    const cx = x + (i % 2) * colW, cy = y + Math.floor(i / 2) * row;
    out.push(`<path d="M${f(cx)} ${f(cy - size * 0.35)}h5" stroke="${e.stroke}" stroke-opacity="${f(e.opacity)}" stroke-width="0.6"/>`,
      t(cx + 6.5, cy, e.name, size, ` fill="${INK}"`));
  });
  if (shown.length < legend.length) {
    const i = shown.length;
    out.push(t(x + (i % 2) * colW, y + Math.floor(i / 2) * row, `and ${legend.length - shown.length} more`, size, ` fill="${MUTED}"`));
  }
  if (!legend.length) out.push(t(x, y, 'none', size, ` fill="${MUTED}"`));
  cav.forEach((line, i) => out.push(t(x, by - 1.2 - (cav.length - 1 - i) * cs * 1.3, line, cs, ` fill="${MUTED}"`)));
  out.push(`<rect x="${f(r.x + 1.5)}" y="${f(by)}" width="${f(r.w - 3)}" height="${bandH}" fill="none" stroke="#b00020" stroke-width="0.5"/>`);
  out.push(t(r.x + r.w / 2, by + bandH / 2 + (L.small ? 1.3 : 1.5), NOT_FOR_CONSTRUCTION, L.small ? 3.4 : 4,
    ' fill="#b00020" font-weight="700" text-anchor="middle" letter-spacing="0.6"'));
  return out.join('');
}