GLOBALGRID2050 / EXPLORE CODE

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

Plant Layout and 2 more files

A JavaScript module in the world folder of GlobalGrid2050 that maps solar and substations.

478 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 140 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. Places ingest · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/places.mjs lines 1–103
  2. Plant Feeders transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-feeders.mjs lines 1–114
  3. Plant Layout transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-layout.mjs lines 1–261

Places

A JavaScript module in the world folder of GlobalGrid2050 that fetches postcodes from postcodes.io.

ingestglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/places.mjs · lines 1–103 of 103 · version 2026-09-27 02:20 · pattern lookup (shared by 4 files)

What it does
It fetches postcodes. Defines 8 functions or classes, including foldName, looksLikePlace, english, whereOf, toPlaceRows. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: postcodes.
Inputs & outputs
In: data source: postcodes.io. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 2 files: Search UI (globalgrid2050); Search UI (globalgrid2050). Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
What it achieves
It creates place lookup (`createPlaceLookup`) and is built from the fold name helper (`foldName`) and the looks like place helper (`looksLikePlace`). Town and village search through postcodes.io /places, which serves OS Open Names (Open Government Licence v3.0; the service's code is MIT).
Why it matters
Imported by Search UI.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Postcodes (import)
Used by
imported by Search UI (import), imported by Search UI (import)
Produces
PLACES_API, PLACES_CREDIT, PLACE_TYPES, PLACE_SCORE, foldName, looksLikePlace, whereOf, toPlaceRows, createPlaceLookup
Defines here
foldName, looksLikePlace, english, whereOf, toPlaceRows, createPlaceLookup, remember, lookup
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/202609270220-site-world-v3/world/places.mjs:1-103 · blob 8f029e5647d5304e3ae3ac71b318a6c8cd309bd1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Town and village search through postcodes.io /places, which serves OS Open Names (Open Government Licence v3.0;
// the service's code is MIT). CORS is open (Access-Control-Allow-Origin: *) and no key is needed. Each place comes with
// national-grid eastings and northings as well as latitude and longitude, so the world is placed from OS's own figures.
// Only populated places are kept: City, Town, Village, Hamlet, Suburban Area. No Nominatim, no other geocoder.
// The pure parts are at the top; createPlaceLookup is the same polite client as postcodes.mjs: one request at a time,
// at least minGapMs apart, a newer query replaces one still waiting, answers are kept (least recently used out).

import { looksLikePostcode } from './postcodes.mjs';

export const PLACES_API = 'https://api.postcodes.io/places';

// Kept identical to data/attribution.json sources["os-open-names"].line with {year} filled (tests/places.test.mjs checks).
export const PLACES_CREDIT = Object.freeze({
  id: 'os-open-names',
  text: 'Contains OS data © Crown copyright and database right 2026.',
  link: 'https://www.ordnancesurvey.co.uk/customers/public-sector/public-sector-licensing/copyright-acknowledgments'
});

// Settlement types in rank order, and the word shown for each.
export const PLACE_TYPES = Object.freeze({ City: 'City', Town: 'Town', Village: 'Village', Hamlet: 'Hamlet', 'Suburban Area': 'Suburb' });
const TYPE_RANK = Object.keys(PLACE_TYPES);

// Scores on the scale of search.mjs SCORE (exact project name 2000, name prefix 500): an exact settlement name goes
// above every project name match, a settlement that starts with the text sits just above projects that do, and one
// that only holds the text further in ("Even Swindon") sits between project prefixes and other project matches.
export const PLACE_SCORE = Object.freeze({ exact: 3000, prefix: 550, other: 300 });

// Lower case, accents and punctuation off, spaces single: "Bishop's Stortford" and "bishops stortford" are one name.
export const foldName = s => String(s ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
  .replace(/['’.]/g, '').replace(/[^a-z0-9]+/g, ' ').trim();

// Worth asking for places: two letters or more, and not a postcode or a number.
export function looksLikePlace(text) {
  const q = foldName(text);
  return q.length >= 2 && /[a-z]/.test(q) && !looksLikePostcode(text);
}

// "Sir Ddinbych - Denbighshire" -> "Denbighshire": the English form closes the bilingual Welsh names.
const english = s => (s && s.includes(' - ') ? s.split(' - ').pop() : s || '').trim();

// Where a place is, for the detail line: county or unitary authority, else district, else region; never its own name.
export function whereOf(r) {
  for (const w of [r.county_unitary, r.district_borough, r.region, r.country].map(english)) {
    if (w && foldName(w) !== foldName(r.name_1)) return w;
  }
  return '';
}

// postcodes.io /places results -> Find rows, best first. Rows that are not settlements or have no point are left out.
// Order: exact name (either language), then names that start with the text, then the rest; within each,
// City > Town > Village > Hamlet > Suburb, then name, then south to north.
export function toPlaceRows(results, query) {
  const q = foldName(query);
  return (Array.isArray(results) ? results : [])
    .filter(r => r && PLACE_TYPES[r.local_type] && Number.isFinite(r.latitude) && Number.isFinite(r.longitude) && r.name_1)
    .map(r => {
      const names = [r.name_1, r.name_2].filter(Boolean).map(foldName);
      const score = names.includes(q) ? PLACE_SCORE.exact : names.some(n => n.startsWith(q)) ? PLACE_SCORE.prefix : PLACE_SCORE.other;
      const title = r.name_2 && foldName(r.name_2) === q && foldName(r.name_1) !== q ? `${r.name_2} (${r.name_1})` : r.name_1;
      const choice = { lat: r.latitude, lon: r.longitude, label: r.name_1 };
      if (Number.isFinite(r.eastings) && Number.isFinite(r.northings)) Object.assign(choice, { e: r.eastings, n: r.northings });
      return { key: `place-${r.code ?? `${r.name_1}-${r.latitude}-${r.longitude}`}`, source: PLACES_CREDIT.id, title,
        detail: [PLACE_TYPES[r.local_type], whereOf(r)].filter(Boolean).join(' · '),
        score, rank: TYPE_RANK.indexOf(r.local_type), choice };
    })
    .sort((a, b) => b.score - a.score || a.rank - b.rank || a.title.localeCompare(b.title, 'en') || a.choice.lat - b.choice.lat)
    .map(({ rank, ...row }) => row);
}

// fetchImpl, clock and sleep are injectable for tests. lookup(text) -> Promise of rows, or null when a newer query
// replaced this one before it was sent. Text that is not worth asking about resolves to [] with no request.
export function createPlaceLookup({ fetchImpl, limit = 30, minGapMs = 300, cacheSize = 60,
  clock = () => Date.now(), sleep = ms => new Promise(r => setTimeout(r, ms)) } = {}) {
  const get = fetchImpl || ((u, o) => fetch(u, o));
  const cache = new Map(), stats = { requests: 0, cached: 0, skipped: 0 };
  let chain = Promise.resolve(), last = -Infinity, latest = 0;
  const remember = (q, rows) => {
    cache.delete(q); cache.set(q, rows);
    while (cache.size > cacheSize) cache.delete(cache.keys().next().value);
  };
  function lookup(text) {
    const q = foldName(text);
    if (!looksLikePlace(text)) return Promise.resolve([]);
    if (cache.has(q)) { stats.cached++; const rows = cache.get(q); remember(q, rows); return Promise.resolve(rows); }
    const id = ++latest;
    const run = chain.then(async () => {
      if (id !== latest) { stats.skipped++; return null; }
      const wait = last + minGapMs - clock();
      if (wait > 0) await sleep(wait);
      if (id !== latest) { stats.skipped++; return null; }
      last = clock(); stats.requests++;
      const res = await get(`${PLACES_API}?q=${encodeURIComponent(String(text).trim())}&limit=${limit}`, { mode: 'cors' });
      if (!res.ok) throw Error(`postcodes.io HTTP ${res.status}`);
      const rows = toPlaceRows((await res.json())?.result, text);
      remember(q, rows);
      return rows;
    });
    chain = run.catch(() => {});
    return run;
  }
  lookup.stats = stats;
  return lookup;
}

Plant Feeders

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

transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-feeders.mjs · lines 1–114 of 114 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern routeFeeders (shared by 4 files)

What it does
It calculates cables, 33kV and A roads. Defines 9 functions or classes, including toSpine, roadPath, side, coverage, trenchFor.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV, A roads.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 2 files: Block MV (globalgrid2050); Plant Layout (globalgrid2050).
What it achieves
It routes feeders (`routeFeeders`) and is built from the to spine helper (`toSpine`) and the road path helper (`roadPath`). The 33kV feeders of a laid-out plant, routed along its roads, with their trenches and cables. Its code works with 33 kV.
Why it matters
Imported by Block MV and Plant Layout.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Cable Rating (import)
Used by
imported by Block MV (import), imported by Plant Layout (import)
Produces
SECTION_FOR, CABLE_ALLOW, roadPath, coverage, trenchFor, routeFeeders
Defines here
toSpine, roadPath, side, coverage, trenchFor, routeFeeders, onRoad, add, dropOf
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/202609270220-site-world-v3/world/plant-feeders.mjs:1-114 · blob 23de40bd7ea2dd21b039e9f2226fdcf848cc464f · 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-feeders.mjs: the 33 kV feeders of a laid-out plant, routed along its roads, with their trenches and cables.
//
// Each feeder of the plant template runs from its board in the substation compound along the access road, the
// spine and the branch tracks to its first station, then station to station. Routes stay on the road network
// (a comb: one spine, tracks off it), so every route is a set of intervals on a few straight lines. Where several
// circuits share a stretch they share a trench: one circuit in a single trefoil trench, two in a two-circuit
// trench, more in parallel trenches. Where a circuit turns across a road it goes in ducts.
// Cable lengths: route plus 3 % for snaking and 5 m at each end for terminations, three single cores a circuit.
// Voltage drop is worked out on the routed lengths (cable-rating.mjs), replacing the template's placeholder lengths;
// where it passes the limit, the segment that saves most drop per step is upsized, as the template does.
// Trench section ids are those of data/trench-sections.json. Pure: imports only the cable rating.

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

export const SECTION_FOR = Object.freeze({ one: '33kv-1-dno', two: '33kv-2', crossing: '33kv-1-ducted' });
export const CABLE_ALLOW = Object.freeze({ slack: 0.03, tailM: 5, cores: 3 });

// A point on the road network: on a track (k, u), on the access road (u), or on the spine (v).
function toSpine(pt, net) {
  if (pt.line === 'track') return { parts: [{ key: 't' + pt.k, a: pt.u, b: net.us }], v: net.tracks[pt.k] };
  if (pt.line === 'access') return { parts: [{ key: 'a', a: pt.u, b: net.us }], v: net.cv };
  return { parts: [], v: pt.v };
}

/** Intervals from A to B along the roads, and how many times the route turns across a road. */
export function roadPath(A, B, net) {
  const side = pt => Math.sign(pt.u - net.us);
  if (A.line === 'track' && B.line === 'track' && A.k === B.k && side(A) === side(B)) return { parts: [{ key: 't' + A.k, a: A.u, b: B.u }], turns: 0 };
  const a = toSpine(A, net), b = toSpine(B, net);
  const parts = [...a.parts, ...(a.v !== b.v ? [{ key: 's', a: a.v, b: b.v }] : []), ...b.parts];
  return { parts: parts.filter(q => q.a !== q.b), turns: (a.parts.length ? 1 : 0) + (b.parts.length ? 1 : 0) };
}

/** Sweep a line's intervals into stretches with a constant circuit count: [{ a, b, c }]. */
export function coverage(intervals) {
  const ev = [];
  for (const { a, b } of intervals) { ev.push([Math.min(a, b), 1], [Math.max(a, b), -1]); }
  ev.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
  const out = [];
  let c = 0, last = null;
  for (const [x, d] of ev) {
    if (c > 0 && last !== null && x > last) {
      const prev = out[out.length - 1];
      if (prev && prev.c === c && Math.abs(prev.b - last) < 1e-9) prev.b = x; else out.push({ a: last, b: x, c });
    }
    c += d; last = x;
  }
  return out;
}

/** Trench metres by section for a stretch of length L carrying c circuits. */
export function trenchFor(c, L, into) {
  const two = Math.floor(c / 2), one = c % 2;
  if (two) into[SECTION_FOR.two] = (into[SECTION_FOR.two] || 0) + two * L;
  if (one) into[SECTION_FOR.one] = (into[SECTION_FOR.one] || 0) + L;
  return into;
}

/**
 * routeFeeders(template, net, p) -> { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct, crossings }
 * net: { us, cv, spine, access, tracks, stations: [{ id, u, v, k, track }] } in the layout frame.
 */
export function routeFeeders(tpl, net, p) {
  const at = new Map(net.stations.map(s => [s.id, s]));
  const board = net.access ? { line: 'access', u: net.access.u0 } : { line: 'spine', v: net.cv };
  const onRoad = s => ({ line: 'track', k: s.k, u: s.u });
  const byKey = new Map(), stubs = new Map();
  const add = (key, a, b) => { if (!byKey.has(key)) byKey.set(key, []); byKey.get(key).push({ a, b }); };
  const opts = { pf: tpl.params.powerFactor, soilKmW: tpl.params.soilKmW, kv: 33 };
  const cableBySize = {}, trenchByType = {};
  let crossings = 0, cableM = 0, worst = 0, upsized = 0;
  const dropOf = hops => hops.reduce((t, h) => t + dropPercent(h.areaMm2, h.lengthM, h.loadMVA, opts), 0);
  const feeders = tpl.feeders.map((f, fi) => {
    let from = board, fromStub = 0, fromId = null;
    const hops = f.chain.map((st, k) => {
      const s = at.get(st.id), to = onRoad(s), path = roadPath(from, to, net), stub = Math.abs(s.v - s.track);
      for (const q of path.parts) add(q.key, q.a, q.b);
      stubs.set(s.id, (stubs.get(s.id) || 0) + 1);
      if (fromId) stubs.set(fromId, stubs.get(fromId) + 1);
      crossings += path.turns;
      const road = path.parts.reduce((t, q) => t + Math.abs(q.b - q.a), 0), seg = f.segments[k];
      const hop = { from: fromId || f.board, to: s.id, areaMm2: seg.area, loadMVA: seg.loadMVA, lengthM: road + stub + fromStub, parts: path.parts };
      from = to; fromStub = stub; fromId = s.id;
      return hop;
    });
    for (let guard = 0; dropOf(hops) > tpl.params.vdropLimitPct && guard < 60; guard++) {
      const can = hops.filter(h => h.areaMm2 < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
      if (!can) break;
      can.areaMm2 = SIZES[SIZES.indexOf(can.areaMm2) + 1]; upsized++;
    }
    for (const h of hops) {
      const cable = CABLE_ALLOW.cores * (h.lengthM * (1 + CABLE_ALLOW.slack) + 2 * CABLE_ALLOW.tailM);
      cableBySize[h.areaMm2] = (cableBySize[h.areaMm2] || 0) + cable; cableM += cable;
    }
    const drop = dropOf(hops);
    worst = Math.max(worst, drop);
    return { id: `F${fi + 1}`, board: f.board, hops, dropPct: drop, stations: f.chain.map(s => s.id) };
  });

  // Shared stretches: one trench per stretch, sized by the circuits in it.
  const pieces = [];
  let trenchM = 0;
  for (const [key, list] of byKey) for (const { a, b, c } of coverage(list)) {
    pieces.push({ key, a, b, c }); trenchFor(c, b - a, trenchByType); trenchM += b - a;
  }
  for (const [id, c] of stubs) {
    const s = at.get(id), L = Math.abs(s.v - s.track);
    if (L > 0) { pieces.push({ key: 'stub:' + id, a: s.track, b: s.v, c, u: s.u }); trenchFor(c, L, trenchByType); trenchM += L; }
  }
  const crossM = crossings * (p.spineWidthM + 2);
  if (crossM) { trenchByType[SECTION_FOR.crossing] = (trenchByType[SECTION_FOR.crossing] || 0) + crossM; trenchM += crossM; }
  return { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct: worst, crossings, upsized,
    dropOk: worst <= tpl.params.vdropLimitPct + 1e-9 };
}

Plant Layout

A JavaScript module in the world folder of GlobalGrid2050 that maps solar and substations.

transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/plant-layout.mjs · lines 1–261 of 261 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern layoutPlantAsync (shared by 4 files)

What it does
It maps solar and substations. Defines 17 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: solar, substations, 33kV.
Inputs & outputs
Out: interactive map. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Plant UI (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 Plant UI.
Application
globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
Uses
Plant Template (import), Plant Feeders (import)
Used by
imported by Plant UI (import)
Produces
LABEL, LAYOUTS, LAYOUT_DEFAULTS, tableGeometry, frameOf, inside, edgeDist, polyArea, waterIndex, layoutSteps, layoutPlant, layoutPlantAsync
Defines here
tableGeometry, frameOf, inside, segDist, edgeDist, polyArea, waterIndex, nearestEdge, layoutSteps, g, okPoint, inCompound, inAccess, need, 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/202609270220-site-world-v3/world/plant-layout.mjs:1-261 · blob eb47055ccfb0c88ddf4ac49798633cd6b8bac1a4 · 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-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, or east-west);
// 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):
//   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.
// 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';

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']]);
export const LAYOUT_DEFAULTS = Object.freeze({
  fenceSetbackM: 8, waterSetbackM: 10, slopeLimitPct: 15, hollowDepthM: 0.3, hollowRadiusM: 20, slopeStepM: 5,
  gcr: 0.4, 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: 300
});
const DEG = Math.PI / 180;

/** Table geometry for a layout: plan length along the row, plan depth across it, row pitch, modules and kWp. */
export function tableGeometry(layout, p, tpl) {
  const mps = tpl.counts.modulesPerString, lenU = mps * (p.moduleShortM + p.moduleGapM) - p.moduleGapM;
  const south = layout === 'south', tilt = (south ? p.tiltSouthDeg : p.tiltEwDeg) * DEG;
  // South: two modules portrait up the slope. East-west: one portrait module each side of a ridge.
  const slope = south ? 2 * p.moduleLongM + p.moduleGapM : p.moduleLongM;
  const depth = south ? slope * Math.cos(tilt) : 2 * slope * Math.cos(tilt) + p.ridgeGapM;
  const pitch = south ? slope / p.gcr : depth + p.ewGapM;
  const modules = 2 * mps, kWp = modules * tpl.params.moduleWp / 1000;
  return { lenU, depth, pitch, slope, tilt, modules, strings: 2, kWp, south, rise: slope * Math.sin(tilt) };
}

// ---- 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]...]...], options: {...} }
 */
export function* layoutSteps(input) {
  const p = { ...LAYOUT_DEFAULTS, ...(input.options || {}) }, layout = input.layout === 'east-west' ? 'east-west' : 'south';
  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');
  const F = frameOf(layout), poly = (input.boundary || []).map(([e, n]) => F.uv(e, n));
  if (poly.length < 3 || Math.abs(polyArea(poly)) < 100) throw new Error('plant layout: the boundary needs at least three corners around some land');
  const tplAsked = plantTemplate({ targetMW: asked }), T = tableGeometry(layout, p, tplAsked);
  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 us0 = Math.min(...poly.map(q => q[0])), us1 = Math.max(...poly.map(q => q[0]));
  const vs0 = Math.min(...poly.map(q => q[1])), vs1 = Math.max(...poly.map(q => q[1]));
  const notes = [];

  // Compound at the boundary point nearest the grid connection, 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 = nearestEdge(poly, gp[0], gp[1]), inset = p.fenceSetbackM + Math.hypot(p.compoundW, p.compoundD) / 2;
  const 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 = (u, v) => inside(poly, u, v) && edgeDist(poly, u, v) >= p.fenceSetbackM;

  // 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 = 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 = 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, band by band ----
  const skipped = { setback: 0, roads: 0, water: 0, unmeasured: 0, slope: 0, hollow: 0 };
  const acc = { ua: [], va: [], k: [], s: [], j: [], r: [], i: [], h: [] };
  const lim = p.slopeLimitPct / 100, d5 = p.slopeStepM, R = p.hollowRadiusM;
  let n = 0;
  for (let k = 0; k < tracks.length; k++) for (let r = 0; r < rows; r++) {
    const va = tracks[k] + trackHalf + r * T.pitch, vb = va + T.depth;
    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 (inside(poly, um, vm)) skipped.setback++;
          continue;
        }
        if (inCompound(ua, ub, va, vb) || inAccess(ua, ub, va, vb)) { skipped.roads++; continue; }
        if (waterAt(um, vm) < p.waterSetbackM + Math.hypot(T.lenU, T.depth) / 2) { skipped.water++; continue; }
        const h = [g(ua, va), g(ub, va), g(ub, vb), g(ua, vb)], hc = 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] + hc + e5 + w5 + n5 + s5)) { skipped.unmeasured++; continue; }
        const gu = (e5 - w5) / (2 * d5), gv = (n5 - s5) / (2 * d5), gl = (h[1] + h[2] - h[0] - h[3]) / (2 * T.lenU);
        if (Math.max(Math.hypot(gu, gv), Math.hypot(gl, gv)) > lim + 1e-12) { skipped.slope++; continue; }
        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 - hc >= p.hollowDepthM) { skipped.hollow++; continue; }
        acc.ua.push(ua); acc.va.push(va); acc.k.push(k); acc.s.push(s); acc.j.push(j); acc.r.push(r); acc.i.push(i);
        acc.h.push(h);
      }
    }
  }
  const found = acc.ua.length;
  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.');

  // ---- capacity: the asked plant, or the largest whole MW whose tables and station pads fit ----
  const need = tpl => tpl.nodes.filter(x => x.kind === 'station')
    .reduce((t, st) => t + Math.ceil(st.rating.strings / T.strings) + 1, 0);
  let tpl = tplAsked, fits = need(tplAsked) <= found;
  if (!fits) {
    let lo = 0, hi = Math.floor(asked);
    while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (need(plantTemplate({ targetMW: mid })) <= found) lo = mid; else hi = mid; yield { phase: 'capacity' }; }
    if (lo === 0 && need(plantTemplate({ targetMW: 1 })) <= found) lo = 1;
    tpl = lo ? plantTemplate({ targetMW: 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]);
  const stations = [], used = [];
  let at = 0;
  for (const st of tpl ? tpl.nodes.filter(x => x.kind === 'station') : []) {
    const take = order.slice(at, at + Math.ceil(st.rating.strings / T.strings) + 1); at += take.length;
    // 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 / 2, v: acc.va[pad] + T.depth / 2,
      k: acc.k[pad], track: tracks[acc.k[pad]], tables: take.length - 1 });
    for (const x of take) if (x !== pad) used.push(x);
  }

  // ---- 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 ? T.lenU : 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;
  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));
  const mwpAsked = tplAsked.ratings.dcMWp, mwpBuilt = used.length * T.kWp / 1000;
  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 },
    tables, stations, compound, spine, access, trackRoads, tracks, boundary: poly, gridPoint: gp, skipped, notes,
    template: tpl, electrical, rows, perRun
  };
}

/** 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;
  for (;;) {
    const t0 = now();
    let r;
    do r = it.next(); while (!r.done && now() - t0 < sliceMs);
    longest = Math.max(longest, now() - t0);
    if (r.done) return Object.assign(r.value, { longestSliceMs: longest });
    onProgress(r.value);
    await rest();
  }
}