GLOBALGRID2050 / EXPLORE CODE

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

Plant Layout and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that maps overhead lines (OHL), solar and substations.

635 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 190 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. Pile Rules render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/pile-rules.mjs lines 1–120
  2. Plant Central transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-central.mjs lines 1–46
  3. Plant Ground geodesy · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-ground.mjs lines 1–95
  4. Plant Layout transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-layout.mjs lines 1–374

Pile Rules

A JavaScript module in the world folder of GlobalGrid2050 that works with tracker hub (`trackerHub`) and reveal band (`revealBand`), covering solar.

renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/pile-rules.mjs · lines 1–120 of 120 · version 2026-09-27 18:53 · pattern heightFlags (shared by 3 files)

What it does
Defines 8 functions or classes, including rulesFor, revealAt, trackerHub, revealBand, heightFlags. 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. Domain terms in the code: solar.
Downstream impact
Used directly by 6 files: Block Build (globalgrid2050); Piles (globalgrid2050); Plant Pack (globalgrid2050); Plant Piles (globalgrid2050); and 2 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 is built from the rules for helper (`rulesFor`), the reveal at helper (`revealAt`) and the tracker hub helper (`trackerHub`). The one set of pile rules shared by the pile row tool (`piles.mjs`), the plant layout (`plant-piles.mjs`) and the solar block (`block-build.mjs`), with two profiles: fixed tilt and single-axis tracker.
Why it matters
Imported by 6 files, including Block Build, Piles and Plant Pack.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Block Build (import), imported by Piles (import), imported by Plant Pack (import), imported by Plant Piles (import), imported by Plant UI (import), imported by Table Solids (import)
Produces
SOILS, PROFILES, PILE_RULES, TRACKER_RULES, rulesFor, revealAt, trackerHub, revealBand, heightFlags, withSoil, tableLines, twistDeg
Defines here
rulesFor, revealAt, trackerHub, revealBand, heightFlags, withSoil, tableLines, twistDeg
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/pile-rules.mjs:1-120 · blob 16c3cea0ee098709b4cf32073c6ea7b32fc1ded3 · 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: production_core
// pile-rules.mjs: the one set of pile rules shared by the pile row tool (piles.mjs), the plant layout (plant-piles.mjs)
// and the solar block (block-build.mjs), with two profiles: fixed tilt and single-axis tracker.
//
// Every figure here is ILLUSTRATIVE and EDITABLE (world.piles.auto({ rules }) and the typed "piles" command): a generic
// starting point to be replaced by the chosen product's datasheet, the project spec and the site's
// geotechnical report (pile load tests set the embedment). None is a design value. Values follow the generic piling
// rules study (pile-rules.json v1, ids as PILING-RULES.md: R reveal, F fixed and K tracker tolerances, S slopes,
// E embedment by soil, L testing); the head adjustment (0.25 m) is the GPU prototype's.
//
// FIXED TILT. Reveal (how far a post stands out of the ground) is DERIVED from the table:
//   module surface at a fraction f up the slope = lowEdge + rise * f; rails hang railDepth below the modules, so
//   reveal = lowEdge + rise * f - railDepth.
// One post at mid-slope: 0.8 m low edge, 2P portrait at 25 deg (rise 2.02 m), 0.3 m rails -> 1.51 m. Two posts at 0.2
// and 0.8 of the depth: 0.90 m front, 2.12 m rear. A fixed rafter keeps its tilt: front and rear are fitted as one rigid
// frame (rear top = front top + the difference in nominal reveal) and the posts take the cross slope.
// Tolerances: a post more than revealAdjust from its nominal is outside the head adjustment (flagged); outside the band
// [nominal - below, nominal + above] the ground is graded. Twist: the change of the rafter angle from one end of the
// table to the other that the ground under the front and rear lines asks for (their least-squares slopes); over
// twistTolDeg the table cannot be warped to follow, so the posts and grading take it.
//
// TRACKER. Posts stand along the torque tube, one line per row, running north-south. The tube height clears the
// ground by clearance at the largest rotation: hub = clearance + (module length / 2) sin(maxRotation); the post reveal is
// the axis height less the bearing offset (R5, R7). A terrain-following tracker bends at its bearings: the tube may
// change slope from bay to bay by at most bayChangeMaxDeg (S5) and slope along the row by at most alongMaxPct (S3).
// Post reveals must sit inside the hard reveal window (R7); head height and plumb are installation tolerances (K1-K6),
// tighter than fixed tilt, stated, not computed.
// A row the tube cannot follow within those limits is flagged: it needs grading.
// Pure: no imports, no DOM.

// Embedment by soil (E, default of each range), fixed and tracker; the soil is chosen per site (default stiff clay).
export const SOILS = Object.freeze({ stiff_clay: [1.6, 2.3], soft_clay_alluvium: [2.6, 3.2], peat_organic: [4.0, 4.5], dense_sand: [1.8, 2.4],
  loose_sand: [2.4, 3.0], gravel_till: [1.6, 2.2], chalk: [1.7, 2.3], weak_rock: [1.2, 1.8] });
const COMMON = {
  label: 'Illustrative pile rules (editable): replace with the product datasheet, the project spec and the geotechnical report.',
  soil: 'stiff_clay',
  embedGpuM: Object.freeze({ min: 1.2, nominal: 1.6 }), // the GPU prototype's figures, for comparison
  proofTestPct: 1.0,       // production proof tests, % of piles (L3, range 0.5-2)
  revealAdjustM: 0.25,     // head adjustment: +/- from nominal without a different post
  embedToReveal: 0.75,     // lateral load, a rule of thumb: embedment at least 0.75 x the post's reveal (longer post)
  gradingWidthM: 2.0,      // width graded along a pile line
  lowEdgeClearM: 0.5,      // lowest module edge over the ground: flagged below this
  pileSpacingM: Object.freeze({ fixed: 5, tracker: 7 }),
  grading: Object.freeze({ dropOverM: 0.6, mergeGapM: 2 }) // deeper than 0.6 m of grading: suggest dropping the table
};

export const PROFILES = Object.freeze({
  fixed: Object.freeze({ ...COMMON, system: 'fixed', embedM: SOILS.stiff_clay[0], embedMinM: 1.0, // E, E-min
    revealBelowM: 0.4, revealAboveM: 0.6,  // band about nominal; outside it the ground is graded
    // R4, relative: warn when a post stands more than revealWarnAboveM over ITS design height (the rear posts of a 2P
    // table stand 2.12 m by design, so a fixed 2.0 m line flagged every one); revealFailM is a hard maximum for any post.
    revealWarnAboveM: 0.5, revealFailM: 3.0,
    twistTolDeg: 3.0,                      // F6: rafter angle change end to end the table can take
    headTolMm: 30, plumbTolDeg: 2.0,       // F4, F3: installation, stated
    railDepthM: 0.3, pivot: 0.5, twoPost: Object.freeze([0.2, 0.8]) }),
  tracker: Object.freeze({ ...COMMON, system: 'tracker', embedM: SOILS.stiff_clay[1], embedMinM: 1.5,
    axisHeightM: 1.4, bearingDropM: 0.15,  // R5, R7: 1P axis height, bearing offset
    revealWindowM: Object.freeze([0.95, 1.45]), // R7: hard window for every post
    headTolMm: 20, plumbTolDeg: 1.5,       // K: standard pile (drive piles 10 mm, 0.5 deg east-west), installation, stated
    alongMaxPct: 15, crossMaxPct: 7, bayChangeMaxDeg: 0.5, // S3, S4, S5
    maxRotationDeg: 60, moduleLongM: 2.384, lowEdgeFullTiltM: 0.5, twistTolDeg: Infinity })
});
export const PILE_RULES = PROFILES.fixed; // the fixed-tilt profile, the default everywhere
export const TRACKER_RULES = PROFILES.tracker;
export const rulesFor = system => PROFILES[system === 'tracker' ? 'tracker' : 'fixed'];

/** Nominal reveal of a fixed-tilt post at fraction f up the slope of a table: lowEdge + rise f - railDepth. */
export function revealAt({ lowEdgeM, rise, f, railDepthM = PILE_RULES.railDepthM }) {
  if (!(lowEdgeM >= 0) || !(rise >= 0) || !(f >= 0 && f <= 1)) throw new Error('pile rules: need lowEdge >= 0, rise >= 0 and 0 <= f <= 1');
  return lowEdgeM + rise * f - railDepthM;
}

/** Tracker: axis (hub) height, post reveal, and the lowest module edge at full tilt. */
export function trackerHub(R = TRACKER_RULES) {
  const hub = R.axisHeightM;
  return { hub, reveal: hub - R.bearingDropM, lowEdgeFullTilt: hub - R.moduleLongM / 2 * Math.sin(R.maxRotationDeg * Math.PI / 180) };
}

/** The reveal band about a nominal: { min, nominal, max }; a tracker's is its hard window. */
export function revealBand(nominal, rules = PILE_RULES) {
  if (rules.revealWindowM) return { min: rules.revealWindowM[0], nominal, max: rules.revealWindowM[1] };
  return { min: nominal - rules.revealBelowM, nominal, max: nominal + rules.revealAboveM };
}

/**
 * Height checks of one post against its design (nominal) reveal: { high: stands more than revealWarnAboveM above its design
 * height, overMax: stands over the hard maximum revealFailM }. A rule left out never fires.
 */
export function heightFlags(reveal, design, rules = PILE_RULES) {
  const up = rules.revealWarnAboveM, max = rules.revealFailM;
  return { high: Number.isFinite(up) && reveal > design + up + 1e-9, overMax: Number.isFinite(max) && reveal > max + 1e-9 };
}

/** Rules with the embedment of a soil (SOILS) in place of the default. */
export function withSoil(rules, soil) {
  const e = SOILS[soil];
  return e ? { ...rules, soil, embedM: e[rules.system === 'tracker' ? 1 : 0] } : rules;
}

/**
 * Pile lines of a table: [{ f (fraction of the plan depth from the low edge), nominal }].
 * fixed: posts 1 (the pivot) or 2 (front and rear); east-west (ridge): one line per face at the face's pivot;
 * tracker: one line under the tube (f = 0.5).
 */
export function tableLines({ lowEdgeM, rise, posts = 2, eastWest = false, tracker = false, rules = PILE_RULES }) {
  if (tracker) return [{ f: 0.5, nominal: trackerHub(rules.system === 'tracker' ? rules : TRACKER_RULES).reveal }];
  const rd = rules.railDepthM;
  if (eastWest) return [0.25, 0.75].map(f => ({ f, nominal: revealAt({ lowEdgeM, rise, f: rules.pivot, railDepthM: rd }) }));
  const fs = posts === 1 ? [rules.pivot] : rules.twoPost;
  return fs.map(f => ({ f, nominal: revealAt({ lowEdgeM, rise, f, railDepthM: rd }) }));
}

/**
 * Twist, degrees: the change of the rafter angle from one end of a table of length len to the other, when the rear line
 * is dz above the front across the plan distance depth at the first end and the lines' slopes differ by bRear - bFront.
 * With dz = 0 it is the rotation of a flat section.
 */
export function twistDeg(bFront, bRear, len, depth, dz = 0) {
  if (!(depth > 0)) return 0;
  return Math.abs(Math.atan((dz + (bRear - bFront) * len) / depth) - Math.atan(dz / depth)) * 180 / Math.PI;
}

Plant Central

A JavaScript module in the world folder of GlobalGrid2050 that works with transformers. It is built from the central items helper (`centralItems`) and the item solids helper (`itemSolids`).

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

Evidence
  • line-jaccard 0.9429 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/plant-central.mjs:1-48 09ec548bac499df53242bd0d85fc3740da67b0ab
  • sha256 b7a287e4b8471e0d115bb6d061cb3c5f19d6f5d94e606b3d2f4b74e6e025f667
  • target sha256 ef8c8f373f0154e5566a51717827ba7b71719818657138e56849587a4c8d9d33
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-central.mjs · lines 1–46 of 46 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern centralItems (shared by 3 files)

What it does
It calculates transformers. Defines centralItems, itemSolids.
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: transformers.
Downstream impact
Used directly by 1 file: Plant UI (globalgrid2050).
What it achieves
What a central-inverter plant adds to the drawing.
Why it matters
Imported by Plant UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Station (import)
Used by
imported by Plant UI (import)
Produces
CENTRAL_EQUIPMENT, centralItems, itemSolids
Defines here
centralItems, itemSolids
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/plant-central.mjs:1-46 · blob 6dd8bd6e211f9a386eb0280dbebf589c89c9524c · 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
// plant-central.mjs: what a central-inverter plant adds to the drawing. Each central station (plant-template.mjs,
// inverterClass 'central') is one container on its pad: the central inverters, the MV transformer and switchgear
// together (a 40 ft container, the generic class; a skid is drawn the same size). Its strings reach it through DC
// combiner boxes, one per group of tables: the station's tables in layout order are split into as many groups as it
// has boxes, and each box stands on a post just south of the low edge of its group's middle table.
// Sizes are generic and rounded, not any product; illustrative only. Pure: imports only the placer.

import { placer } from './station.mjs';

export const CENTRAL_EQUIPMENT = Object.freeze({
  skid: { w: 12.2, d: 2.5, h: 2.9, label: 'central inverter station: inverters, MV transformer and switchgear in a 40 ft container (generic)' },
  combiner: { w: 0.9, d: 0.35, h: 1.1, label: 'DC combiner box on a post (generic)' }
});

/**
 * Items of a laid-out plant's central stations in the layout frame: [{ kind: 'skid' | 'combiner', u, v, id, station }].
 * r: plant-layout.mjs result. Tables are stored station by station (each station's r.stations[k].tables in turn).
 */
export function centralItems(r) {
  const out = [], T = r?.table, t = r?.tables;
  if (!T || !t) return out;
  let q0 = 0;
  for (const st of r.stations || []) {
    const n = st.tables || 0;
    if (st.central) {
      out.push({ kind: 'skid', u: st.u, v: st.v, id: st.id, station: st.id });
      const boxes = Math.max(1, Math.min(st.combiners || 1, n));
      for (let b = 0; b < boxes && n; b++) {
        const a = q0 + Math.floor(b * n / boxes), z = q0 + Math.floor((b + 1) * n / boxes) - 1, m = Math.floor((a + z) / 2);
        const L = r.tableLen?.[m] ?? T.lenU;
        out.push({ kind: 'combiner', u: t[m * 6] + L / 2, v: t[m * 6 + 1] - 0.6, id: `${st.id}-CB${b + 1}`, station: st.id });
      }
    }
    q0 += n;
  }
  return out;
}

/** Solids of one item at a placed point (national-grid offsets and ground height), as mv-network.mjs draws them. */
export function itemSolids(kind, at = [0, 0, 0], id = kind, heading = 0) {
  const e = CENTRAL_EQUIPMENT[kind];
  if (!e) throw new Error(`plant central: unknown item ${kind}`);
  const P = placer(at, heading), out = [P.box({ kind, part: 'body', id, min: [-e.w / 2, -e.d / 2, kind === 'combiner' ? 0.5 : 0], max: [e.w / 2, e.d / 2, e.h] })];
  if (kind === 'combiner') out.push(P.box({ kind, part: 'post', id, min: [-0.04, -0.04, 0], max: [0.04, 0.04, 0.5] }));
  return out;
}

Plant Ground

A JavaScript module in the world folder of GlobalGrid2050 that creates site ground (`createSiteGround`), using SHA-256.

geodesyglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-ground.mjs · lines 1–95 of 95 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern createSiteGround (shared by 2 files)

What it does
It calculates its inputs. Defines 12 functions or classes, including createSiteGround, start, site, extent, loadFor.
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 2 files: Block UI (globalgrid2050); Plant UI (globalgrid2050).
What it achieves
It creates site ground (`createSiteGround`) and is built from the start step (`start`) and the site step (`site`). The measured ground under a whole plant boundary, and the mapped water beside it. Its code works with 500 MW.
Why it matters
Imported by Block UI and Plant UI.
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
Layers (import), Terrain (import)
Used by
imported by Block UI (import), imported by Plant UI (import)
Produces
createSiteGround
Defines here
createSiteGround, start, site, extent, loadFor, hit, ringAt, heightAt, sampler, ringShare, water, survey
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/plant-ground.mjs:1-95 · blob a50c47d8d01e84b9239e29d75224871f37dc7780 · 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
// plant-ground.mjs: the measured ground under a whole plant boundary, and the mapped water beside it.
//
// The terrain layer keeps only the LiDAR tiles near the viewer. A plant boundary is far bigger, so this reads the
// same tiles for the boundary's extent, through the same hash checks (the manifest pins tiles.json, tiles.json
// pins every tile), and answers heights in national-grid metres. Where no tile covers a point the answer is NaN,
// never a guess; the page falls back to the world's own measuredAt there. Water comes from the manifest's water
// layer file when it has one (OS Open Rivers), else there is none and the layout says so.
// A plant bigger than the 1 m tiles (500 MW needs about 3.3 km square) may also read the far ring (8 m, v06) where the
// 1 m tiles stop: loadFor(box, onTile, { ring: true }). The 1 m tile always wins where both exist, and ringShare()
// says how much of what was read came from the ring, so the layout can say so (hollows under 8 m are not seen there).

import { makeApi } from './layers.mjs';
import { decodeTile, sampleTile } from './layers/terrain.mjs';

export function createSiteGround({ manifestUrl = './world/manifest.json', fetchImpl } = {}) {
  let manifest = null, api = null, index = null, ringIndex = [], dir = '', size = 256, surveyDate = null, reads = 0, ringReads = 0;
  const tiles = new Map(), rings = new Map(); // key -> decoded tile (1 m), key -> decoded far-ring tile
  async function start() {
    if (manifest) return manifest;
    const base = new URL(manifestUrl, location.href);
    const res = await (fetchImpl || fetch)(base.href, { cache: 'no-cache' });
    if (!res.ok) throw Error(`manifest HTTP ${res.status}`);
    manifest = await res.json();
    api = makeApi(new URL('./', base).href, { fetchImpl });
    const cfg = (manifest.layers || []).find(l => l.id === 'terrain')?.config;
    if (cfg?.index && cfg?.sha256) {
      const j = await api.fetchJSON(cfg.index, cfg.sha256);
      dir = cfg.index.includes('/') ? cfg.index.slice(0, cfg.index.lastIndexOf('/') + 1) : '';
      size = j.tile_m || 256; surveyDate = j.survey_date || null; index = (j.tiles || []).filter(t => !t.ring); // the 1 m tiles: a far ring (v06) is for the view only
      ringIndex = (j.tiles || []).filter(t => t.ring);                      // unless a large plant asks for it (loadFor ring)
    }
    return manifest;
  }
  const site = () => manifest?.site || null;
  // The tiles' outer extent in national-grid metres, or null with no terrain.
  // ring: true takes in the far ring as well.
  const extent = ({ ring = false } = {}) => {
    const all = [...(index || []).map(t => [t.e0, t.n0, size]), ...(ring ? ringIndex.map(t => [t.e0, t.n0, t.tile_m || size]) : [])];
    return all.length ? { e0: Math.min(...all.map(t => t[0])), n0: Math.min(...all.map(t => t[1])),
      e1: Math.max(...all.map(t => t[0] + t[2])), n1: Math.max(...all.map(t => t[1] + t[2])) } : null;
  };

  /** Loads (verified) every tile touching the box; returns how many cover it and how many failed. */
  async function loadFor({ e0, n0, e1, n1 }, onTile = () => {}, { ring = false } = {}) {
    await start();
    if (!index) return { tiles: 0, failed: 0 };
    const hit = s => t => t.e0 < e1 && t.e0 + (s || t.tile_m) > e0 && t.n0 < n1 && t.n0 + (s || t.tile_m) > n0;
    const want = [...index.filter(hit(size)).map(t => [t, tiles]), ...(ring ? ringIndex.filter(hit(0)).map(t => [t, rings]) : [])];
    let failed = 0;
    for (const [t, into] of want) {
      if (into.has(t.key)) continue;
      try { into.set(t.key, decodeTile(await api.fetchVerified(dir + t.file, t.sha256))); } catch { failed++; }
      onTile(tiles.size + rings.size);
    }
    return { tiles: want.length, failed };
  }
  const ringAt = (e, n) => {
    for (const t of rings.values()) { const h = sampleTile(t, e - t.e0, n - t.n0); if (Number.isFinite(h)) return h; }
    return NaN;
  };
  function heightAt(e, n) {
    for (const t of tiles.values()) {
      const s = (t.samples - 1) * t.spacing;
      if (e >= t.e0 && n >= t.n0 && e <= t.e0 + s && n <= t.n0 + s) return sampleTile(t, e - t.e0, n - t.n0);
    }
    return ringAt(e, n);
  }
  // A faster lookup for the tight loop: tiles on a map keyed by their south-west corner.
  function sampler() {
    const byCorner = new Map([...tiles.values()].map(t => [t.e0 + ',' + t.n0, t]));
    reads = ringReads = 0;
    return (e, n) => {
      const t = byCorner.get(Math.floor(e / size) * size + ',' + Math.floor(n / size) * size);
      reads++;
      if (t) { const h = sampleTile(t, e - t.e0, n - t.n0); if (Number.isFinite(h)) return h; }
      const h = rings.size ? ringAt(e, n) : NaN;                      // no scan of every 1 m tile on a miss (review 3)
      if (Number.isFinite(h)) ringReads++;
      return Number.isFinite(h) || rings.size ? h : heightAt(e, n); // without the ring, as before: the edge of the last tile
    };
  }
  // The share of heights read by the last sampler that came from the far ring (8 m), 0 to 1.
  const ringShare = () => (reads ? ringReads / reads : 0);
  /** Mapped watercourse lines ([[e, n]...]) from the manifest's water layer, or [] when there is none. */
  async function water() {
    await start();
    const cfg = (manifest.layers || []).find(l => l.id === 'water')?.config;
    if (!cfg?.index || !cfg?.sha256) return [];
    try { return ((await api.fetchJSON(cfg.index, cfg.sha256)).lines || []).map(l => l.points).filter(p => p && p.length > 1); }
    catch { return []; }
  }
  // Dates for the survey check (site-checks.mjs): the terrain index's survey date, else the site's; planning and commissioning.
  const survey = () => ({ groundDate: surveyDate || manifest?.site?.lidar_date || null, planningDate: manifest?.site?.planning_date || null,
    commissionedDate: manifest?.site?.commissioned || null });
  return { start, site, extent, loadFor, heightAt, sampler, water, survey, ringShare, loaded: () => tiles.size + rings.size };
}

Plant Layout

A JavaScript module in the world folder of GlobalGrid2050 that maps overhead lines (OHL), solar and substations.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-layout.mjs · lines 1–374 of 374 · version 2026-09-27 18:53 · pattern stretchAt (shared by 3 files)

What it does
It maps overhead lines (OHL), solar and substations. Defines 23 functions or classes, including tableGeometry, frameOf, inside, segDist, edgeDist.
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), solar, substations, 33kV.
Inputs & outputs
Out: interactive map. Voltage levels named: 33kV.
Downstream impact
Used directly by 3 files: Build Rules (globalgrid2050); Cmd Model (globalgrid2050); Plant UI (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 table geometry helper (`tableGeometry`), the frame of helper (`frameOf`) and the inside step (`inside`). A solar plant laid out on measured ground inside a drawn boundary, from generic rules. Its code works with 33 kV and 5000 MW.
Why it matters
Imported by Build Rules, Cmd Model and Plant UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Plant Template (import), Plant Feeders (import), Plant Piles (import), Structures (import), Plant Packing (import), Site Checks (import)
Used by
imported by Build Rules (import), imported by Cmd Model (import), imported by Plant UI (import)
Produces
LABEL, LAYOUTS, LAYOUT_DEFAULTS, V09_PACKING, tableGeometry, frameOf, inside, edgeDist, polyArea, waterIndex, layoutSteps, layoutPlant
Defines here
tableGeometry, frameOf, inside, segDist, edgeDist, polyArea, waterIndex, nearestEdge, layoutSteps, tplOf, g, inOhl, inCompound, inAccess, alongPts, stretchAt, consider, need, room, lenOf, stretch, layoutPlant, layoutPlantAsync
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/plant-layout.mjs:1-374 · blob 4caf81938deab9fe9b23843456eda9109614487e · 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
// plant-layout.mjs: a solar plant laid out on measured ground inside a drawn boundary, from generic rules.
//
// Give it a boundary (national-grid metres), a capacity and a layout (south-facing fixed tilt, east-west, or single-axis
// tracker rows north-south, 1P portrait, pitch from their own ground cover ratio, 0.35 by default);
// it keeps tables inside the fence setback and away from mapped water, drops any table on ground that is not
// measured (NaN), steeper than the slope limit, or in a closed hollow, then groups the tables into blocks with a
// station at the block end beside a branch track off a spine road, and routes each 33 kV feeder of the plant
// template (plant-template.mjs) along the tracks to a substation compound at the boundary point nearest the grid.
//
// Rules used (general practice and public standards; the defaults sit inside the ranges):
//   ground cover ratio 0.5 by default: UK plants measured as built from open LiDAR run 0.41-0.52 with 2 portrait
//   tables and 0.63-0.70 with 6-high landscape tables (row pitch 8.0-9.3 m); the v09 default of 0.4 sat below them all;
//   the boundary may be several hedged fields packed as one set (plant-packing.mjs, packing 'fields' by default);
//   tables stand 5-10 m inside the fence; watercourse stand-off 10 m (common Environment Agency byelaw figure;
//   drainage-board strips are typically 8-9 m); south-facing row gap from a ground cover ratio of 0.35-0.5;
//   east-west 2-4 m between tables, ridge gap 0.1-0.5 m; lowest module edge 0.6-1.2 m; table runs 100-200 m with
//   4-6 m cross lanes; stations at the end of a block beside a road; a stone spine road with branch tracks.
// Module and table sizes are a generic 600 W class (2.38 x 1.13 m), two strings per table; not any product.
// Every table then gets its piles automatically (plant-piles.mjs): nobody places a pile.
// Work is done in chunks (a generator), so a page can run it between frames. Pure: no DOM.

import { plantTemplate } from './plant-template.mjs';
import { routeFeeders } from './plant-feeders.mjs';
import { pilesForLayout } from './plant-piles.mjs';
import { tableShape, pitchStretch, winterNoonDeg, halfCols } from './structures.mjs';
import { fieldsOf, fieldSet, packFields, FIELD_DEFAULTS, PACKINGS } from './plant-packing.mjs';
import { surveyNote } from './site-checks.mjs';

export const LABEL = 'Illustrative layout from generic rules, not a design for any site.';
export const LAYOUTS = Object.freeze([['south', 'South-facing, fixed tilt'], ['east-west', 'East-west'], ['tracker', 'Single-axis tracker']]);
export const LAYOUT_DEFAULTS = Object.freeze({
  fenceSetbackM: 8, waterSetbackM: 10, ohlMarginM: 5, slopeLimitPct: 15, twistTolDeg: 3, hollowDepthM: 0.3, hollowRadiusM: 20, slopeStepM: 5,
  gcr: 0.5, gcrTracker: 0.35, ewGapM: 3, ridgeGapM: 0.3, tiltSouthDeg: 25, tiltEwDeg: 10, lowEdgeM: 0.8,
  moduleLongM: 2.384, moduleShortM: 1.134, moduleGapM: 0.02, tableGapM: 0.5, runTargetM: 150, crossLaneM: 5,
  bandTargetM: 150, spineWidthM: 6, trackWidthM: 4, roadClearM: 3, compoundW: 60, compoundD: 40, chunk: 100,
  packing: 'fields', halfTables: true, hedgeSetbackM: 5,
  // Structure (structures.mjs): table format, tracker strings a row, the row gap rule and the tracker cross-slope lines.
  tiers: null, orient: 'portrait', tableCols: null, trackerStrings: 2, rowGap: 'flat', latDeg: 52, maxStretch: 2,
  trackerCrossReviewPct: 7, trackerCrossMaxPct: 10
});
// The v09 rules (one band grid, GCR 0.4), kept typed (packing bands, gcr 0.4) and used by the closed-form witnesses.
export const V09_PACKING = Object.freeze({ packing: 'bands', gcr: 0.4 });
const DEG = Math.PI / 180, AVOID_STEP_M = 10;   // AVOID_STEP_M: test points along a table or row for an area kept clear

/** Table geometry for a layout: plan length along the row, plan depth across it, row pitch, modules and kWp. The format
 * (structures.mjs tableShape): south 2P (default), 3P, 3L or 4L; east-west 1P each side of a ridge; tracker 1P or 2P across
 * one north-south torque tube carrying trackerStrings strings. strings = modules / modules per string (a string may run on
 * into the next table when the counts do not divide). */
export function tableGeometry(layout, p, tpl) {
  const mps = tpl.counts.modulesPerString, S = tableShape(p, mps, layout), lenU = S.cols * (S.along + p.moduleGapM) - p.moduleGapM;
  const fmt = { tiers: S.tiers, orient: S.orient, cols: S.cols }, kWp = S.modules * tpl.params.moduleWp / 1000;
  if (layout === 'tracker') {       // single-axis: rows north-south, the modules across the tube
    return { lenU, depth: S.slope, pitch: S.slope / p.gcrTracker, slope: S.slope, tilt: 0, modules: S.modules, strings: S.modules / mps,
      kWp, south: false, tracker: true, rise: 0, ...fmt };
  }
  const south = layout === 'south', tilt = (south ? p.tiltSouthDeg : p.tiltEwDeg) * DEG, slope = S.slope;
  const depth = south ? slope * Math.cos(tilt) : 2 * slope * Math.cos(tilt) + p.ridgeGapM;
  const pitch = south ? slope / p.gcr : depth + p.ewGapM;
  return { lenU, depth, pitch, slope, tilt, modules: S.modules, strings: S.modules / mps, kWp, south, rise: slope * Math.sin(tilt), ...fmt };
}

// ---- plane helpers (u, v: the layout frame; south-facing u = east, v = north; east-west u = north, v = east) ----
export function frameOf(layout) {
  const swap = layout !== 'south';
  return { swap, uv: (e, n) => (swap ? [n, e] : [e, n]), en: (u, v) => (swap ? [v, u] : [u, v]) };
}
export function inside(poly, x, y) {
  let c = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
  }
  return c;
}
const segDist = (x, y, ax, ay, bx, by) => {
  const dx = bx - ax, dy = by - ay, d2 = dx * dx + dy * dy, t = d2 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / d2)) : 0;
  return Math.hypot(x - ax - t * dx, y - ay - t * dy);
};
export function edgeDist(poly, x, y) {
  let d = Infinity;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) d = Math.min(d, segDist(x, y, poly[j][0], poly[j][1], poly[i][0], poly[i][1]));
  return d;
}
export const polyArea = poly => poly.reduce((s, [x, y], i) => { const [x2, y2] = poly[(i + 1) % poly.length]; return s + x * y2 - x2 * y; }, 0) / 2;

// Nearest distance to any mapped water line, bucketed on a coarse grid (only the nearby cells are searched).
export function waterIndex(lines, reach, cell = 64) {
  const grid = new Map(), key = (i, j) => i + ',' + j;
  for (const pts of lines) for (let k = 1; k < pts.length; k++) {
    const [ax, ay] = pts[k - 1], [bx, by] = pts[k];
    const i0 = Math.floor((Math.min(ax, bx) - reach) / cell), i1 = Math.floor((Math.max(ax, bx) + reach) / cell);
    const j0 = Math.floor((Math.min(ay, by) - reach) / cell), j1 = Math.floor((Math.max(ay, by) + reach) / cell);
    for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) {
      const k2 = key(i, j); if (!grid.has(k2)) grid.set(k2, []); grid.get(k2).push([ax, ay, bx, by]);
    }
  }
  return (x, y) => {
    let d = Infinity;
    for (const s of grid.get(key(Math.floor(x / cell), Math.floor(y / cell))) || []) d = Math.min(d, segDist(x, y, ...s));
    return d;
  };
}

// Nearest point on the boundary to (x, y), with the inward normal of that edge.
function nearestEdge(poly, x, y) {
  const ccw = polyArea(poly) > 0;
  let best = null;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [ax, ay] = poly[j], [bx, by] = poly[i], dx = bx - ax, dy = by - ay, d2 = dx * dx + dy * dy || 1;
    const t = Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / d2)), px = ax + t * dx, py = ay + t * dy;
    const d = Math.hypot(x - px, y - py), l = Math.sqrt(d2), n = ccw ? [-dy / l, dx / l] : [dy / l, -dx / l];
    if (!best || d < best.d) best = { d, p: [px, py], n };
  }
  return best;
}

/**
 * layoutSteps(input) -> generator; its return value is the layout.
 * input: { boundary: [[e, n]...], targetMW, layout: 'south' | 'east-west', groundAt(e, n) -> m or NaN,
 *          grid: [e, n] | null (the connection the compound faces), water: [[[e, n]...]...],
 *          ohl: [{ pts: [[e, n]...], closed, reachM }] | null (overhead line zones: no tables within reach + ohlMarginM),
 *          options: {...} }
 */
export function* layoutSteps(input) {
  const layout = ['east-west', 'tracker'].includes(input.layout) ? input.layout : 'south', o = input.options || {};
  const byFields = (o.packing ?? LAYOUT_DEFAULTS.packing) === 'fields' && layout !== 'tracker'; // tracker rows keep the band rule
  const p = { ...LAYOUT_DEFAULTS, ...(byFields ? FIELD_DEFAULTS : {}), ...o, packing: byFields ? 'fields' : 'bands' };
  const asked = Number(input.targetMW);
  if (!(asked >= 1 && asked <= 5000)) throw new Error('plant layout: capacity must be 1 to 5000 MW');
  if (!(p.fenceSetbackM >= 5 && p.fenceSetbackM <= 10)) throw new Error('plant layout: fence setback must be 5 to 10 m');
  if (!PACKINGS.includes(o.packing ?? 'fields')) throw new Error(`plant layout: packing must be ${PACKINGS.join(' or ')}`);
  const F = frameOf(layout), polys = fieldsOf(input.boundary).map(f => f.map(([e, n]) => F.uv(e, n))).filter(f => f.length >= 3 && Math.abs(polyArea(f)) >= 100);
  if (!polys.length) throw new Error('plant layout: the boundary needs at least three corners around some land');
  const FS = fieldSet(polys, p), poly = polys[0];
  const tplOf = mw => plantTemplate({ ...(input.template || {}), targetMW: mw }); // input.template: typed module and string choices
  const tplAsked = tplOf(asked), T = tableGeometry(layout, p, tplAsked);
  const hc = halfCols(T.cols), halfUnits = hc / T.cols, halfLen = hc * (T.lenU + p.moduleGapM) / T.cols - p.moduleGapM;
  const g = (u, v) => { const [e, n] = F.en(u, v); const h = input.groundAt(e, n); return Number.isFinite(h) ? h : NaN; };
  const water = (input.water || []).map(l => l.map(([e, n]) => F.uv(e, n)));
  const waterAt = water.length ? waterIndex(water, p.waterSetbackM + T.lenU) : () => Infinity;
  const half = Math.hypot(T.lenU, T.depth) / 2, ohlZones = (input.ohl || []).map(z => {
    const pts = z.pts.map(([e, n]) => F.uv(e, n)), r = z.reachM + p.ohlMarginM + half;
    return { pts, closed: !!z.closed && pts.length > 2, r, box: [Math.min(...pts.map(q => q[0])) - r, Math.max(...pts.map(q => q[0])) + r,
      Math.min(...pts.map(q => q[1])) - r, Math.max(...pts.map(q => q[1])) + r] };
  });
  // Inside an overhead line zone grown by the margin and the table's half diagonal (GS6 planning zone, illustrative).
  const inOhl = (u, v) => ohlZones.some(z => u > z.box[0] && u < z.box[1] && v > z.box[2] && v < z.box[3]
    && ((z.closed && inside(z.pts, u, v)) || z.pts.some((q, i) => (i || z.closed) && segDist(u, v, ...z.pts[(i || z.pts.length) - 1], ...q) < z.r)));
  const [us0, us1, vs0, vs1] = FS.box;
  const notes = [];
  const survey = surveyNote(input.survey);
  if (survey) notes.push(survey);

  // Compound at the boundary point nearest the grid connection (one for every field), set in by the fence setback.
  let gp = input.grid ? F.uv(...input.grid) : null;
  if (!gp) { gp = [(us0 + us1) / 2, vs0 - 1]; notes.push('No grid connection given: the compound is placed on the south side.'); }
  const ne = polys.map(f => nearestEdge(f, gp[0], gp[1])).reduce((a, b) => (b.d < a.d ? b : a));
  const inset = p.fenceSetbackM + Math.hypot(p.compoundW, p.compoundD) / 2, cu = ne.p[0] + ne.n[0] * inset, cv = ne.p[1] + ne.n[1] * inset;
  const compound = { u: cu, v: cv, w: p.compoundW, d: p.compoundD };
  const okPoint = FS.ok;

  // Spine along v through the middle; the access road runs along v = cv from the compound to it.
  const us = (us0 + us1) / 2;
  let vLo = Infinity, vHi = -Infinity;
  for (let v = vs0; v <= vs1; v += 5) if (okPoint(us, v)) { vLo = Math.min(vLo, v); vHi = Math.max(vHi, v); }
  if (!Number.isFinite(vLo)) { vLo = cv; vHi = byFields ? vs1 : cv; notes.push('The spine road line through the middle is outside the boundary.'); }
  const accessU0 = Math.abs(us - cu) > p.compoundW / 2 ? cu + Math.sign(us - cu) * p.compoundW / 2 : null;
  const rows = Math.max(2, Math.round(p.bandTargetM / T.pitch));
  const band = byFields ? p.bandTargetM : p.trackWidthM + 2 * p.roadClearM + (rows - 1) * T.pitch + T.depth;
  const tracks = [];
  for (let v = Math.min(vLo, cv) + p.trackWidthM / 2; v <= vHi; v += band) tracks.push(v);
  const perRun = Math.max(1, Math.round(p.runTargetM / (T.lenU + p.tableGapM)));
  const runLen = perRun * T.lenU + (perRun - 1) * p.tableGapM, runStep = runLen + p.crossLaneM;
  const spineHalf = p.spineWidthM / 2 + p.roadClearM, trackHalf = p.trackWidthM / 2 + p.roadClearM;
  const inCompound = (ua, ub, va, vb) => ub > cu - p.compoundW / 2 - p.roadClearM && ua < cu + p.compoundW / 2 + p.roadClearM
    && vb > cv - p.compoundD / 2 - p.roadClearM && va < cv + p.compoundD / 2 + p.roadClearM;
  const inAccess = (ua, ub, va, vb) => accessU0 !== null && vb > cv - trackHalf && va < cv + trackHalf
    && ub > Math.min(accessU0, us) && ua < Math.max(accessU0, us);

  // ---- candidate tables ----
  const skipped = { setback: 0, roads: 0, water: 0, ohl: 0, unmeasured: 0, slope: 0, twist: 0, hollow: 0, ...(T.tracker ? { cross: 0 } : {}) };
  const avoid = (input.avoid || []).filter(a => a && typeof a.test === 'function' && a.id);
  const alongPts = (ua, ub, vs) => { const k = Math.max(2, Math.ceil((ub - ua) / AVOID_STEP_M)); return vs.flatMap(v => Array.from({ length: k + 1 }, (_, i) => [ua + (ub - ua) * i / k, v])); };
  for (const a of avoid) skipped[a.id] = skipped[a.id] || 0;
  const acc = { ua: [], va: [], k: [], s: [], j: [], r: [], i: [], h: [], x: [], w: [] };
  // Slope-aware row gap (south, rowGap 'slope'): the gap behind a row is stretched on ground falling to the north
  // (structures.mjs pitchStretch at winter noon), read along the row every 25 m over the flat-ground gap; 80th percentile.
  // The fields packing reads each field on its own, so the pitch follows each field's own fall.
  const aware = layout === 'south' && p.rowGap === 'slope', elev = winterNoonDeg(p.latDeg), gap0 = T.pitch - T.depth;
  const stretchAt = (va, vb, fi = -1) => {
    if (!aware) return 1;
    const f = [], [a0, a1] = fi < 0 ? [us0, us1] : FS.list[fi].box;
    for (let u = a0 + 12.5; u < a1; u += 25) {
      const a = g(u, vb), b = g(u, vb + gap0);
      if (Number.isFinite(a + b) && (fi < 0 ? FS.inAny(u, va) : inside(FS.list[fi].poly, u, va))) f.push((a - b) / gap0);
    }
    if (!f.length) return 1;
    f.sort((x, y) => x - y);
    return pitchStretch({ depth: T.depth, rise: T.rise, elevDeg: elev, fallN: f[Math.floor(0.8 * (f.length - 1))], maxStretch: p.maxStretch });
  };
  const gapStats = { rowsStretched: 0, rowsDropped: 0, maxStretch: 1 };
  const crossRev = p.trackerCrossReviewPct / 100, crossMax = p.trackerCrossMaxPct / 100;
  const lim = p.slopeLimitPct / 100, d5 = p.slopeStepM, R = p.hollowRadiusM;
  // One table position through every check: kept (true), or counted under the check that left it out.
  const consider = (ua, ub, va, vb, m) => {
    const um = (ua + ub) / 2, vm = (va + vb) / 2, L = ub - ua;
    if (inCompound(ua, ub, va, vb) || inAccess(ua, ub, va, vb)) { skipped.roads++; return false; }
    if (waterAt(um, vm) < p.waterSetbackM + Math.hypot(L, T.depth) / 2) { skipped.water++; return false; }
    if (ohlZones.length && inOhl(um, vm)) { skipped.ohl++; return false; }
    // input.avoid: [{ id, test(e, n) }] areas kept clear (overhead line zones); each counts what it kept out in skipped[id].
    // Tested along both long edges and the middle at most AVOID_STEP_M apart, so a long tracker row cannot straddle a zone.
    const av = avoid.length ? avoid.find(a => alongPts(ua, ub, [va, vm, vb]).some(([u, v]) => a.test(...F.en(u, v)))) : null;
    if (av) { skipped[av.id] = (skipped[av.id] || 0) + 1; return false; }
    const h = [g(ua, va), g(ub, va), g(ub, vb), g(ua, vb)], hm = g(um, vm);
    const e5 = g(um + d5, vm), w5 = g(um - d5, vm), n5 = g(um, vm + d5), s5 = g(um, vm - d5);
    if (!Number.isFinite(h[0] + h[1] + h[2] + h[3] + hm + e5 + w5 + n5 + s5)) { skipped.unmeasured++; return false; }
    const gu = (e5 - w5) / (2 * d5), gv = (n5 - s5) / (2 * d5), gl = (h[1] + h[2] - h[0] - h[3]) / (2 * L);
    if (Math.max(Math.hypot(gu, gv), Math.hypot(gl, gv)) > lim + 1e-12) { skipped.slope++; return false; }
    // Per table, before piling (user test H5): the slope along each edge and across each end within the limit, and the
    // twist (the change of cross slope from one end to the other) within the table's tolerance (trackers follow it).
    const edge = Math.max(Math.abs(h[1] - h[0]), Math.abs(h[2] - h[3])) / L, end = Math.max(Math.abs(h[3] - h[0]), Math.abs(h[2] - h[1])) / T.depth;
    if (Math.max(edge, end) > lim + 1e-12) { skipped.slope++; return false; }
    // Tracker rows: the slope across the row (east-west, frame v) over a 10 m base and across each end. Over the
    // exclusion line the row is left out; over the review line it is kept and flagged for the maker's review.
    const cross = T.tracker ? Math.max(Math.abs(gv), end) : 0;
    if (T.tracker && cross > crossMax + 1e-12) { skipped.cross++; return false; }
    const tw = Math.abs(Math.atan((h[3] - h[0]) / T.depth) - Math.atan((h[2] - h[1]) / T.depth)) * 180 / Math.PI;
    if (!T.tracker && tw > p.twistTolDeg + 1e-9) { skipped.twist++; return false; }
    let lowest = Infinity;
    for (let q = 0; q < 8; q++) lowest = Math.min(lowest, g(um + R * Math.cos(q * Math.PI / 4), vm + R * Math.sin(q * Math.PI / 4)));
    if (Number.isFinite(lowest) && lowest - hm >= p.hollowDepthM) { skipped.hollow++; return false; }
    acc.ua.push(ua); acc.va.push(va); acc.k.push(m.k); acc.s.push(m.s); acc.j.push(m.j); acc.r.push(m.r); acc.i.push(m.i);
    acc.h.push(h); acc.x.push(cross > crossRev + 1e-12); acc.w.push(m.units);
    return true;
  };
  let n = 0, packed = null;
  if (byFields) {
    packed = yield* packFields({ fields: FS, T, p, us, spineHalf, tracks, trackHalf, halfLen, halfUnits, consider, accepted: () => acc.ua.length,
      stretch: (fi, va, vb) => stretchAt(va, vb, fi) });
    n = packed.candidates;
    if (aware) Object.assign(gapStats, { rowsStretched: packed.stretched, maxStretch: packed.maxStretch });
  } else {
    for (let k = 0, va = 0; k < tracks.length; k++) for (let r = 0; r < rows; r++) {
      if (!r) va = tracks[k] + trackHalf;
      else if (aware) { const x = stretchAt(va, va + T.depth); va += T.pitch * x; if (x > 1 + 1e-6) gapStats.rowsStretched++; gapStats.maxStretch = Math.max(gapStats.maxStretch, x); }
      else va += T.pitch;
      const vb = va + T.depth;
      if (vb > tracks[k] + band - trackHalf + 1e-6) { gapStats.rowsDropped += rows - r; break; } // stretched past the next track
      if (va > vs1) continue;
      for (const s of [1, -1]) for (let j = 0; ; j++) {
        const near = us + s * (spineHalf + j * runStep);
        if ((s > 0 && near > us1) || (s < 0 && near < us0)) break;
        for (let i = 0; i < perRun; i++) {
          const a = near + s * i * (T.lenU + p.tableGapM), b = a + s * T.lenU, ua = Math.min(a, b), ub = Math.max(a, b);
          if (++n % p.chunk === 0) yield { phase: 'tables', candidates: n, accepted: acc.ua.length };
          const um = (ua + ub) / 2, vm = (va + vb) / 2;
          if (!(okPoint(ua, va) && okPoint(ub, va) && okPoint(ua, vb) && okPoint(ub, vb) && okPoint(um, va) && okPoint(um, vb))) {
            if (FS.inAny(um, vm)) skipped.setback++;
            continue;
          }
          consider(ua, ub, va, vb, { k, s, j, r, i, units: 1 });
        }
      }
    }
  }
  const found = acc.ua.length, foundUnits = acc.w.reduce((t, w) => t + w, 0);
  if (skipped.cross) notes.push(`${skipped.cross} tracker rows left out: more than ${p.trackerCrossMaxPct} % across the row.`);
  if (gapStats.rowsStretched) notes.push(`${gapStats.rowsStretched} row gaps stretched on ground falling to the north (up to ${gapStats.maxStretch.toFixed(2)} x) `
    + `so the winter-noon shadow reaches no further than on flat ground${gapStats.rowsDropped ? `; ${gapStats.rowsDropped} rows no longer fit their bands` : ''}.`);
  if (skipped.twist) notes.push(`${skipped.twist} table positions left out: the ground twists more than ${p.twistTolDeg}° across the table.`);
  if (skipped.unmeasured) notes.push(`${skipped.unmeasured} table positions skipped: the ground there is not measured.`);
  if (!water.length) notes.push('No mapped water loaded here: the watercourse setback is not applied.');
  if (skipped.ohl) notes.push(`${skipped.ohl} table positions kept out of overhead line zones (GS6 planning zone + ${p.ohlMarginM} m, illustrative).`);
  else if (input.ohl == null && !avoid.some(a => a.id === 'ohl')) notes.push('No overhead line zones given: tables are not kept clear of overhead lines.');
  const halves = acc.w.filter(w => w < 1).length;
  if (halves) notes.push(`${halves} half tables close row ends where a full table does not fit.`);

  // ---- capacity: the asked plant, or the largest whole MW whose tables and station pads fit (in whole-table units) ----
  const need = tpl => tpl.nodes.filter(x => x.kind === 'station')
    .reduce((t, st) => t + Math.ceil(st.rating.strings / T.strings) + 1, 0);
  const room = tpl => need(tpl) <= foundUnits + 1e-9;
  let tpl = tplAsked, fits = room(tplAsked);
  if (!fits) {
    let lo = 0, hi = Math.floor(asked);
    while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (room(tplOf(mid))) lo = mid; else hi = mid; yield { phase: 'capacity' }; }
    if (lo === 0 && room(tplOf(1))) lo = 1;
    tpl = lo ? tplOf(lo) : null;
  }
  const builtMW = tpl ? tpl.params.targetMW : 0;
  yield { phase: 'blocks' };

  // ---- blocks: bands nearest the compound first, then side, run column, row; station at the block end ----
  const order = Array.from({ length: found }, (_, x) => x);
  const bandRank = tracks.map((v, k) => k).sort((a, b) => Math.abs(tracks[a] - cv) - Math.abs(tracks[b] - cv));
  const rank = new Array(tracks.length); bandRank.forEach((k, x) => { rank[k] = x; });
  order.sort((a, b) => rank[acc.k[a]] - rank[acc.k[b]] || acc.s[b] - acc.s[a] || acc.j[a] - acc.j[b] || acc.r[a] - acc.r[b] || acc.i[a] - acc.i[b]
    || acc.va[a] - acc.va[b] || acc.ua[a] - acc.ua[b]);
  const stations = [], used = [];
  let at = 0;
  for (const st of tpl ? tpl.nodes.filter(x => x.kind === 'station') : []) {
    const want = Math.ceil(st.rating.strings / T.strings) + 1, take = [];
    for (let got = 0; at < found && got < want - 1e-9; at++) { take.push(order[at]); got += acc.w[order[at]]; }
    if (!take.length) break;
    // The pad takes the table nearest the track, nearest the spine: the block end beside the road.
    const pad = take.reduce((b, x) => (acc.r[x] < acc.r[b] || (acc.r[x] === acc.r[b] && Math.abs(acc.ua[x] - us) < Math.abs(acc.ua[b] - us)) ? x : b));
    stations.push({ id: st.id, mva: st.rating.mva, inverters: st.rating.inverters, u: acc.ua[pad] + T.lenU * acc.w[pad] / 2, v: acc.va[pad] + T.depth / 2,
      k: acc.k[pad], track: tracks[acc.k[pad]], tables: take.length - 1,
      ...(st.rating.inverterClass === 'central' ? { central: true, combiners: st.rating.combiners } : {}) });
    for (const x of take) if (x !== pad) used.push(x);
  }
  const lenOf = x => (acc.w[x] < 1 ? halfLen : T.lenU);

  // ---- roads cut to the tables they serve ----
  const reach = new Map();
  const stretch = (k, s, d) => { const key = k + ':' + s; reach.set(key, Math.max(reach.get(key) || 0, d)); };
  for (const x of used) stretch(acc.k[x], acc.s[x], Math.abs(acc.ua[x] + (acc.s[x] > 0 ? lenOf(x) : 0) - us));
  for (const st of stations) stretch(st.k, st.u >= us ? 1 : -1, Math.abs(st.u - us) + T.lenU / 2);
  const trackRoads = [...reach].map(([key, d]) => { const [k, s] = key.split(':').map(Number); return { k, v: tracks[k], s, u0: us, u1: us + s * d }; });
  const vUsed = [cv, ...trackRoads.map(t => t.v)];
  const spine = { u: us, v0: Math.min(...vUsed), v1: Math.max(...vUsed) };
  const access = accessU0 === null ? null : { v: cv, u0: accessU0, u1: us };
  const roadM = (spine.v1 - spine.v0) + trackRoads.reduce((t, r) => t + Math.abs(r.u1 - r.u0), 0) + (access ? Math.abs(access.u1 - access.u0) : 0);
  yield { phase: 'feeders' };

  const net = { us, cv, spine, access, tracks, stations, compound };
  const electrical = tpl ? routeFeeders(tpl, net, p) : null;
  yield { phase: 'routes' };                                       // a slice boundary: routing and piling apart (PERF.md 3)
  if (electrical && !electrical.dropOk) {
    const over = electrical.feeders.filter(f => f.dropPct > tpl.params.vdropLimitPct + 1e-9).length;
    notes.push(`${over} feeder(s) over the ${tpl.params.vdropLimitPct} % MV drop at routed lengths (worst ${electrical.worstDropPct.toFixed(2)} %), `
      + 'even at the largest size: a plant this spread is usually split between two or more collector substations.');
  }
  const tables = new Float64Array(used.length * 6);
  used.forEach((x, q) => tables.set([acc.ua[x], acc.va[x], ...acc.h[x]], q * 6));
  // Half tables: each table's plan length along the row (null when every table is whole).
  const tableLen = used.some(x => acc.w[x] < 1) ? Float64Array.from(used, lenOf) : null;
  const units = used.reduce((t, x) => t + acc.w[x], 0);
  const mwpAsked = tplAsked.ratings.dcMWp, mwpBuilt = units * T.kWp / 1000;
  // Piles: automatic from every table (plant-piles.mjs), on the same measured ground; input.piles = false skips them.
  const piles = input.piles === false || !used.length ? null
    : yield* pilesForLayout({ frame: F, table: T, params: p, tables, tableLen }, input.groundAt, { ...(input.piles || {}), mwp: mwpBuilt });
  if (!fits) notes.unshift(builtMW ? `The boundary fits about ${builtMW} MW of the ${asked} MW asked.` : `Nothing fits: ${found} table positions for a ${asked} MW ask.`);
  return {
    label: LABEL, layout, frame: F, table: T, params: p, asked: { mw: asked, mwp: mwpAsked }, fits,
    built: { mw: builtMW, mwp: Math.round(mwpBuilt * 1000) / 1000, tables: used.length, stations: stations.length,
      feeders: tpl ? tpl.counts.feeders : 0, roadM, candidates: n, found, halfTables: tableLen ? used.filter(x => acc.w[x] < 1).length : 0,
      landMWp: Math.round(foundUnits * T.kWp) / 1000 },
    tables, tableLen, stations, compound, spine, access, trackRoads, tracks, boundary: poly, fields: FS.list.map(f => f.poly), gridPoint: gp, skipped,
    notes, template: tpl, electrical, rows, perRun, piles, rowGap: aware ? gapStats : null, packing: p.packing, survey: survey || null,
    crossReview: T.tracker ? used.filter(x => acc.x[x]).length : 0
  };
}

/** Runs the layout to the end in one go (tests, workers). */
export function layoutPlant(input) {
  const it = layoutSteps(input);
  for (;;) { const r = it.next(); if (r.done) return r.value; }
}

/** Runs the layout in slices of at most sliceMs between yields to the page, so no frame waits on it. */
export async function layoutPlantAsync(input, { sliceMs = 12, onProgress = () => {}, now = () => performance.now(), pause } = {}) {
  const it = layoutSteps(input), rest = pause || (() => new Promise(r => setTimeout(r, 0)));
  let longest = 0, slowest = '', at = 'start';
  for (;;) {
    const t0 = now();
    let r, from = at, s0 = t0, step = 0;
    do { r = it.next(); const t = now(); if (t - s0 > step) { step = t - s0; from = at; } s0 = t; at = r.done ? 'done' : r.value.phase; }
    while (!r.done && now() - t0 < sliceMs);
    if (now() - t0 > longest) { longest = now() - t0; slowest = `${from} > ${at} (one step ${step.toFixed(1)} ms)`; }
    if (r.done) return Object.assign(r.value, { longestSliceMs: longest, slowestStep: slowest });
    onProgress(r.value);
    await rest();
  }
}