GLOBALGRID2050 / EXPLORE CODE

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

Layers and 4 more files

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

677 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 150 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. Design Sections interaction · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/design-sections.mjs lines 1–166
  2. Find Mount render · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/find-mount.mjs lines 1–39
  3. Layers render · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/layers.mjs lines 1–224
  4. Terrain geodesy · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/layers/terrain.mjs lines 1–114
  5. Tiles ingest · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/lib/tiles.mjs lines 1–134

Design Sections

A JavaScript module in the world folder of GlobalGrid2050 that lists and searches cables and solar. It creates sections (`createSections`), loads options (`loadOptions`) and loads plant (`loadPlant`).

interactionglobalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/design-sections.mjs · lines 1–166 of 166 · version 2026-09-27 04:02 · Not reached from any entry point (candidate for review) · pattern createSections (shared by 2 files)

What it does
It lists and searches cables and solar. Defines 10 functions or classes, including createSections, $, once, loadOptions, loadPlant. 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: cables, solar, 400kV, 275kV, 132kV, 33kV.
Inputs & outputs
In: user-supplied file (file picker); form fields (user input). Voltage levels named: 400kV, 275kV, 132kV, 33kV.
Downstream impact
Used directly by 1 file: Design UI (globalgrid2050).
What it achieves
The parts of the Design panel that follow a specification, kept out of `design-ui.mjs`. Its code works with 10 MVA, 10 MW and 100 MW. It responds to click and toggle events.
Why it matters
Imported by Design UI.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world · JavaScript module
Uses
Spec Rules (import), Trench Section (import), Trench (import), Measure Format (import), Design Tabs (import), Design Options (dynamic import), Plant UI (dynamic import), Block UI (dynamic import), and 1 more
Used by
imported by Design UI (import)
Produces
createSections
Defines here
createSections, $, once, loadOptions, loadPlant, loadBlock, loadCables, spec, effOf, cross
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/202609270402-site-world-v3/world/design-sections.mjs:1-166 · blob 66a018f5a3845e17f8353af113b7fda40c253b4c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// design-sections.mjs: the parts of the Design panel that follow a specification, kept out of design-ui.mjs.
//   Options        specification, ground condition (alluvium) and the generic MV network (design-options.mjs)
//   Plant layout   a plant laid out inside a drawn boundary on the measured ground (plant-ui.mjs)
//   Solar block    the 10 MVA station block, built in sequence and ringed to the grid (block-ui.mjs)
// Each loads the first time its section opens (or its world.plant / world.block call is made), so none of it is on
// the first frame. Until Options loads, trenches are dug to the network operator spec in normal ground.
// Close to the viewer every trench shows its true cross-section and every cable its outside diameter.

import { OPERATOR_SPEC, applyGround, looseSpoil } from './spec-rules.mjs';
import { crossSection, sectionLines, tubeLines } from './trench-section.mjs';
import { createTrench } from './trench.mjs';
import { formatLength, formatVolume } from './measure-format.mjs';
import { mountDesignTabs } from './design-tabs.mjs';

// The sections' markup, put into the Design panel when this module loads (after the first frame), so world.html
// stays light: the Plant tab gains the specification, ground and MV network, and Plant layout and Solar block folds.
const OPTIONS_HTML = `
    <label>Specification <select id="spec-source">
      <option value="operator">Network operator spec</option>
      <option value="project">Project specification (local file)</option>
      <option value="example">Example specification (made-up values)</option>
    </select></label>
    <input type="file" id="spec-file" accept=".json,application/json" hidden>
    <label>Ground condition <select id="ground-condition"><option value="normal">Normal ground</option></select></label>
    <details class="fold" id="mv-fold"><summary>MV network (generic)</summary>
      <label>Plant size (MW) <input type="number" id="mv-mw" min="1" max="5000" step="1" value="50"></label>
      <label>Route file, drawing coordinates (optional) <input type="file" id="mv-routes-file" accept=".json,application/json"></label>
      <label>Metres per drawing unit <input type="number" id="mv-scale" min="0.001" step="any" value="1"></label>
      <div class="row">
        <button type="button" id="mv-place">Place MV network here</button>
        <button type="button" id="mv-clear">Clear network</button>
      </div>
    </details>
    <p id="spec-status" role="status"></p>`;
const SECTIONS_HTML = `
  <details class="fold" id="plant"><summary>Plant layout</summary>
    <div class="row" id="plant-presets" hidden role="group" aria-label="Capacity presets">
      <button type="button" data-mw="10">10 MW</button><button type="button" data-mw="100">100 MW</button><button type="button" data-mw="1000">1000 MW</button>
    </div>
    <label>Capacity, export (MW) <input type="number" id="plant-mw" min="1" max="5000" step="1" value="100"></label>
    <label>Layout <select id="plant-layout"></select></label>
    <label>Slope limit (%) <input type="number" id="plant-slope" min="1" max="40" step="1" value="15"></label>
    <label>Tables inside the fence (m, 5 to 10) <input type="number" id="plant-fence" min="5" max="10" step="0.5" value="8"></label>
    <div class="row" role="group" aria-label="Plant boundary">
      <button type="button" data-tool="boundary" aria-pressed="false">Draw boundary</button>
      <button type="button" id="plant-open">Use the open land around me</button>
    </div>
    <div class="row">
      <button type="button" id="plant-run">Lay out</button>
      <button type="button" id="plant-clear">Clear layout</button>
    </div>
    <p id="plant-status" role="status"></p>
    <dl id="plant-readout" aria-live="polite"></dl>
  </details>
  <details class="fold" id="block"><summary>Solar block (10 MVA station)</summary>
    <label>Stations on the 33 kV rings (1 to 10) <input type="number" id="block-stations" min="1" max="10" step="1" value="4"></label>
    <label>Grid connection <select id="block-poc"><option value="400" selected>400 kV</option><option value="275">275 kV</option>
      <option value="132">132 kV</option></select></label>
    <div class="row">
      <button type="button" id="block-place">Place block here</button>
      <button type="button" id="block-clear">Clear block</button>
    </div>
    <div class="row"><button type="button" id="block-gpu" title="The GPU study's placement on open-land-01, illustrative">GPU-checked placement</button></div>
    <div class="row" role="group" aria-label="Build sequence">
      <button type="button" id="block-play">Play</button><button type="button" id="block-pause">Pause</button>
      <button type="button" id="block-step">Step</button>
    </div>
    <p id="block-stage" aria-live="polite"></p>
    <p id="block-status" role="status"></p>
    <dl id="block-readout" aria-live="polite"></dl>
    <details class="fold" id="block-cables"><summary>Cable checks (illustrative)</summary><div id="cables-box"></div></details>
  </details>`;
const NEAR_M = 25; // full cross-sections within this distance of the viewer; beyond, only the trench outline
const COLOUR = { section: [0.95, 0.9, 0.7, 1], cable: [0.55, 1, 0.62, 1] };

// deps: { doc, origin(), viewer(), measuredAt(x, y), heightAt(x, y) designed ground, baseHeight(x, y) layers' ground,
//   assets() -> grid equipment in reach, nearest(e, n) -> Promise<substation | null> (national index), redraw(),
//   animate() (the block's build sequence started or stopped), onChange() (the specification or ground changed) }
export function createSections({ doc, origin, viewer, measuredAt, heightAt, baseHeight, assets = () => [], nearest = null,
  redraw, animate = () => {}, onChange = () => {} }) {
  const $ = id => doc.getElementById(id);
  if (!$('spec-source')) ($('design-spec') || $('design-options'))?.insertAdjacentHTML('beforeend', OPTIONS_HTML);
  if (!$('plant')) ($('design-spec') ? $('design-spec').insertAdjacentHTML('afterend', SECTIONS_HTML)
    : ($('phases-fold') || $('design-profile-box'))?.insertAdjacentHTML('beforebegin', SECTIONS_HTML));
  let options = null, plant = null, block = null;
  const loading = {};
  const once = (name, load) => (loading[name] ||= load().catch(e => { loading[name] = null; console.warn(`${name}: ${e.message}`); return null; }));
  const loadOptions = () => once('options', async () => {
    const { createOptions } = await import('./design-options.mjs');
    options = createOptions({ doc, viewer, heightAt, redraw, onChange });
    onChange();
    return options;
  });
  const loadPlant = () => once('plant', async () => {
    const { createPlant } = await import('./plant-ui.mjs');
    return (plant = createPlant({ doc, origin, viewer, measuredAt: measuredAt || baseHeight, heightAt, assets, nearest, redraw }));
  });
  const loadBlock = () => once('block', async () => {
    const { createBlock } = await import('./block-ui.mjs');
    block = createBlock({ doc, origin, viewer, measuredAt: measuredAt || baseHeight, heightAt: baseHeight, redraw, animate,
      towers: () => assets().filter(a => a.kind === 'tower' && Number.isFinite(a.kv)) });
    return block;
  });
  $('design-options-toggle')?.addEventListener('click', () => loadOptions());
  // Build, Measure, Plant, Share (design-tabs.mjs): the specification and ground load when Plant first opens.
  const tabs = mountDesignTabs(doc, { onFirstOpen: { plant: () => loadOptions() } });
  $('plant')?.addEventListener('toggle', e => { if (e.target.open) loadPlant(); });
  $('block')?.addEventListener('toggle', e => { if (e.target.open) loadBlock(); });
  // The cable schedule as illustrative checks (cable-checks-ui.mjs): loaded the first time its fold opens.
  let cables = null;
  const loadCables = () => once('cables', async () => (cables = await (await import('./cable-checks-ui.mjs')).mountCableChecks({ doc, box: $('cables-box') })));
  $('block-cables')?.addEventListener('toggle', e => { if (e.target.open) loadCables(); });

  const spec = () => options?.spec() || OPERATOR_SPEC, ground = () => options?.ground() || 'normal';
  // The trench as it will be dug: the section, under the chosen specification and ground condition.
  const effOf = section => applyGround(section, spec(), ground());
  const cross = (section, eff, cableOdMm) => crossSection(section, eff, { cableOdMm, tapeAboveM: spec().marker.tape_above_service_m });

  return {
    effOf, cross,
    // Readout rows for the specification and ground, and the loose spoil once the bank volume is known.
    rows: eff => [['Specification', eff.specLabel], ['Ground', eff.groundLabel], ['Support', eff.support],
      ['Working width', formatLength(eff.workingWidth)], ...eff.notes.map((n, i) => [i ? '' : 'Notes', n])],
    spoilRows: (spoil, eff) => (eff.bulking > 1 && spoil ? [['Spoil, loose', formatVolume(looseSpoil(spoil, eff), 2)]] : []),
    // The solar block's open trenches (they cut the ground like any other) and a key that changes when they do.
    key: () => block?.key() || '',
    extra(toLocalPts) {
      const list = block?.trenchItems() || [];
      const eff = list.map(t => effOf(t.section));
      return { trenches: list.map((t, i) => createTrench({ path: toLocalPts(t.path), width: eff[i].width, depth: eff[i].depth,
        benchSlope: eff[i].benchSlope })), sections: list.map((t, i) => cross(t.section, eff[i], t.cableOdMm)) };
    },
    // Close up: true cross-sections and cable tubes, rebuilt when the viewer moves a few metres.
    // b: design-ui's build ({ key, trenches, sections, cables, near }); batch(key, version, positions, colour).
    detail(b, batch) {
      const out = [], eye = viewer().pos, k = `${b.key}:${Math.round(eye[0] / 4)}:${Math.round(eye[1] / 4)}:${Math.round(eye[2] / 4)}`;
      b.trenches.forEach((t, i) => {
        const x = t.bbox;
        if (!x || !b.sections[i] || eye[0] < x.minX - NEAR_M || eye[0] > x.maxX + NEAR_M || eye[1] < x.minY - NEAR_M || eye[1] > x.maxY + NEAR_M) return;
        if (b.near[i]?.k !== k) b.near[i] = { k, v: sectionLines({ trench: t, groundAt: baseHeight, cs: b.sections[i], eye, near: NEAR_M }) };
        out.push(batch('design-section-' + i, k, b.near[i].v, COLOUR.section));
      });
      b.cables.forEach((c, i) => {
        if (b.near['c' + i]?.k !== k) {
          const v = [];
          for (const core of c.cores) v.push(...tubeLines(core.polyline, c.spec.od_mm / 1000, { eye, near: NEAR_M }));
          b.near['c' + i] = { k, v };
        }
        out.push(batch('design-cable-' + i, k, b.near['c' + i].v, COLOUR.cable));
      });
      return out;
    },
    batches: () => [...(options?.batches() || []), ...(plant?.batches() || []), ...(block?.batches() || [])],
    // The Boundary tool (in Plant layout) hands its closed outline over on Done.
    setBoundary: async path => !!(await loadPlant())?.setBoundary(path),
    animating: () => !!block?.animating(),
    snapshot: () => ({ options: options?.snapshot() || { spec: spec().label, source: spec().source, ground: ground(), network: null },
      plant: plant?.snapshot() || null, block: block?.snapshot() || null }),
    plantApi: Object.freeze({ run: async () => (await loadPlant())?.run() ?? null, openLand: async () => (await loadPlant())?.useOpenLand(),
      summary: () => plant?.snapshot() || null }),
    tabs,
    blockApi: Object.freeze({ place: async () => (await loadBlock())?.place(), placeGpu: async () => (await loadBlock())?.placeGpu(), play: () => block?.play() ?? false, pause: () => block?.pause(),
      step: () => block?.step(), clear: () => block?.clear(), counts: () => block?.counts() ?? null, state: () => block?.snapshot() ?? null,
      cables: async () => { await loadCables(); return cables; } })
  };
}

Find Mount

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

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

What it does
It draws projects and postcodes. Defines mountFind, siteNear, loadIndex. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: postcodes.
Inputs & outputs
In: JSON file projects.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It loads index (`loadIndex`) and is built from the mount find helper (`mountFind`) and the site near helper (`siteNear`). Find in the dash: a Renewable Energy Planning Database (REPD) project, postcode or "lat, lon"; the drone flies there. It reads `./world/data/projects.json`. It responds to keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world · JavaScript module
Uses
Search UI (import), Bng (import), Origin (import)
Used by
none found
Produces
mountFind
Defines here
mountFind, siteNear, loadIndex
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270402-site-world-v3/world/find-mount.mjs:1-39 · blob 47509f3aae837af67cbca42960ad45c4f84da084 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// Find in the dash: a REPD project, postcode or "lat, lon"; the drone flies there. Near the staged site there is terrain.
// Loaded just after the first frame with the other tools (review E). ctx: { site(), attribution, origin(), SITE_HALF_M,
// first(), canvas, close(), flyTo(x, y) }. Returns the search panel ({ element, open, close }).
import { createSearchPanel, arrivalNote } from './search-ui.mjs';
import { wgs84ToBng } from './bng.mjs';
import { toLocal } from './origin.mjs';

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

Layers

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

Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609270439-site-world/world/layers.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Layers; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9787 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/layers.mjs:1-226 c5cee451f0c37eabf7fc8d7fd1240de196f66ef6
  • sha256 b45d592cbff1ad39443618d256443d0ff5be2a6cae35636d2d817a30426bd033
  • target sha256 86fb573c7bf4714ce9a31d7b9514c0443ef111cec7d3952d6dcd81527de7ff61
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

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

What it does
It fetches data. Defines 20 functions or classes, including loadBase, withBase, loadLib, no, libRefusal. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 7 files: Cable Checks UI (globalgrid2050); Buffers UI (globalgrid2050); Sun Mode (globalgrid2050); Layers UI (globalgrid2050); and 3 more.
What it achieves
It loads base (`loadBase`), loads lib (`loadLib`) and imports text (`importText`). The manifest lists layers in order; each layer file is fetched, its SHA-256 compared with the manifest, and only then imported.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/. Also imported by 6 files, including Cable Checks UI, Buffers UI and Sun Mode.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world · JavaScript module
Uses
Site World V3 — World (import), Overhead (dynamic import), Trench (dynamic import), Cable Route (dynamic import)
Used by
imported by Cable Checks UI (import), imported by Buffers UI (import), imported by Sun Mode (import), imported by Layers UI (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Plant Ground (import), imported by Substrate (import), mentioned in Standalone (comment link)
Produces
loadBase, loadLib, libRefusal, loadLayers, REFUSED, statusLine, startLayer, makeApi, normalise, sha256, sha256Bytes
Defines here
loadBase, withBase, loadLib, no, libRefusal, earlyFetch, importText, loadLayers, fetchChecked, start, fetchOne, statusLine, startLayer, off, makeApi, fetchVerified, fetchJSON, normalise, sha256, sha256Bytes
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270402-site-world-v3/world/layers.mjs:1-224 · blob ac41329a08e45c0d6b9388dff529812f5adce9df · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Layer loader. The manifest lists layers in order; each layer file is fetched, its SHA-256 compared
// with the manifest, and only then imported. A layer whose hash differs is refused and named, never run.
// A layer is a module whose default export may offer:
//   init(api)        -> called once after the layer is verified and imported (may return a promise)
//   lines(ctx)       -> [{ key, version, positions: Float32Array, color: [r,g,b,a], origin?: [x,y,z] }]
//   heightAt(x, y)   -> ground height in metres (the first layer offering a finite height is the ground)
//   solids(ctx)      -> [{ min: [x,y,z], max: [x,y,z] }] boxes nobody can walk or fly through
// Layers are self-contained: no imports (they run from a blob URL). Positions are in local metres
// from the site origin, never national-grid coordinates: the GPU pair (tools/gpu/world_pair.py) measured
// 32-bit drawing error passing 0.1 px about 200 m from the origin and 0.5 px about 1 km out.
// A batch may carry an origin (local metres) with its positions relative to it, so it stays sharp far out.
//
// The api handed to init(api):
//   base                         absolute URL of the manifest's folder
//   fetchVerified(path, sha256)  -> Promise<ArrayBuffer>; the raw bytes are hashed as sent, nothing normalised
//   fetchJSON(path, sha256)      -> Promise<any>; the same check, then the text is decoded and parsed
//   invalidate({ ground })       asks for a redraw; ground (default true) says new ground has arrived
//   origin()                     -> { e, n, id }: the site origin in national-grid metres and its change count
//   lib                          pure helpers a self-contained layer may call: lib.overhead (buildOverhead, catenarySpan...),
//                                lib.trench (createTrench, composeGround), lib.cableRoute (routeCable), and the shared
//                                world library (web/world/lib): lib.version, lib.tiles, lib.drape, lib.earthworks
// The shared library's files are in the manifest (manifest.lib: { version, files: [{ id, path, sha256 }] }) and are
// hash-checked and imported like layers before any layer starts. A layer written for it declares the version
// (export const LIB_VERSION; the manifest repeats it as the entry's lib) and is refused unless it is the one served.

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

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

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

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

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

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

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

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

// Runs a layer's init. A layer whose init throws, or whose promise rejects, is switched off and named.
export function startLayer(item, api) {
  const off = e => {
    item.layer = null; item.status = 'failed to start and switched off: ' + (e?.message || e);
    api.invalidate({ ground: false });
  };
  try {
    const r = item.layer?.init?.(api);
    if (r && typeof r.then === 'function') r.then(null, off);
  } catch (e) { off(e); }
}

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

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

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

export async function sha256Bytes(bytes) {
  if (!globalThis.crypto?.subtle) return null;
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
}

Terrain

A JavaScript module in the layers folder of GlobalGrid2050 that works with tiles and LiDAR terrain, using SHA-256. It sets index sha (`setIndexSha`) and decodes tile (`decodeTile`).

geodesyglobalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/layers/terrain.mjs · lines 1–114 of 114 · version 2026-09-27 04:02 · Entry point · pattern createTerrain (shared by 2 files)

What it does
It calculates tiles and LiDAR terrain. Defines setIndexSha, decodeTile, sampleTile, createTerrain.
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'terrain'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: JSON file tiles.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 3 files: Wcs Terrain (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Plant Ground (globalgrid2050). Reached from 3 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050); Substrate (globalgrid2050).
What it achieves
Ground heights from LiDAR tiles (.ght, written by the LiDAR pipeline).
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/. Also imported by Wcs Terrain and Plant Ground.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world/layers · JavaScript module
VEDIC
DECODE (GG2050-VEDIC-000009): Solar Design Studio / 3D terrain · Computer science / Binary decoding. terrain_tile_bytes → terrain_grid
VEDIC
SAMPLE (GG2050-VEDIC-000010): Solar Design Studio / 3D terrain · Mathematics / Bilinear interpolation. terrain_grid, local_x_m, local_y_m → height_m_or_nan
Uses
none found
Used by
imported by Wcs Terrain (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Plant Ground (import)
Produces
setIndexSha, HEADER_BYTES, NODATA, LOAD_RADIUS, decodeTile, sampleTile, LIB_VERSION, createTerrain
Defines here
setIndexSha, decodeTile, sampleTile, createTerrain
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/202609270402-site-world-v3/world/layers/terrain.mjs:1-114 · blob 4a2fe8c7d5b566440037e6acfd3c6cef700c74de · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: production_core
// Layer: terrain. Ground heights from LiDAR tiles (.ght, written by the lidar pipeline). It draws no lines
// of its own: the ground grid drapes on heightAt. Each frame's lines(ctx) call only asks for the tiles
// within LOAD_RADIUS of the viewer, nearest first, a couple at a time, and forgets the least recently used
// when it holds too many. Every file is fetched through the substrate's hash check (api.fetchVerified).
// Heights are in local metres from the site origin; tiles are placed in British National Grid metres.
//
// Tile format (.ght, little-endian). 32-byte header:
//   0 magic "GGH1" | 4 u16 version=1 | 6 u16 samples=257 | 8 u16 spacing_mm | 10 u16 flags
//   12 i32 origin_e_m | 16 i32 origin_n_m (south-west corner) | 20 i32 base_cm | 24 u16 min_q | 26 u16 max_q
//   28 u32 nodata_count. Body: samples*samples u16, rows south to north, each row west to east.
//   height_m = (base_cm + q) / 100; q = 0xFFFF is no data.

const INDEX_PATH = 'terrain/tiles.json';
// Filled by the build tool with the SHA-256 of tiles.json. Until then the layer loads nothing.
let INDEX_SHA256 = '__TERRAIN_TILES_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }

export const HEADER_BYTES = 32;
export const NODATA = 0xffff;
export const LOAD_RADIUS = 350, MAX_IN_FLIGHT = 2, MAX_TILES = 48;

// Pure: bytes -> { version, samples, spacing, flags, e0, n0, baseCm, minQ, maxQ, nodata, q: Uint16Array }.
export function decodeTile(buffer) {
  const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  if (bytes.byteLength < HEADER_BYTES) throw Error('terrain tile shorter than its header');
  const dv = new DataView(bytes);
  const magic = String.fromCharCode(dv.getUint8(0), dv.getUint8(1), dv.getUint8(2), dv.getUint8(3));
  if (magic !== 'GGH1') throw Error(`terrain tile magic "${magic}" is not GGH1`);
  const version = dv.getUint16(4, true);
  if (version !== 1) throw Error(`terrain tile version ${version} is not 1`);
  const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true);
  if (samples < 2 || spacingMm === 0) throw Error('terrain tile has no usable grid');
  const need = HEADER_BYTES + samples * samples * 2;
  if (bytes.byteLength !== need) throw Error(`terrain tile is ${bytes.byteLength} bytes, expected ${need}`);
  const q = new Uint16Array(samples * samples);
  for (let i = 0; i < q.length; i++) q[i] = dv.getUint16(HEADER_BYTES + 2 * i, true); // endian-safe copy
  return {
    version, samples, spacing: spacingMm / 1000, flags: dv.getUint16(10, true),
    e0: dv.getInt32(12, true), n0: dv.getInt32(16, true), baseCm: dv.getInt32(20, true),
    minQ: dv.getUint16(24, true), maxQ: dv.getUint16(26, true), nodata: dv.getUint32(28, true), q
  };
}

// Pure: bilinear height at a point given in the tile's own metres (0..size from the south-west corner).
// NaN outside the tile, or where a sample that carries weight has no data.
export function sampleTile(t, u, v) {
  const s = t.samples - 1, gx = u / t.spacing, gy = v / t.spacing;
  if (!(gx >= 0 && gy >= 0 && gx <= s && gy <= s)) return NaN;
  const i = Math.min(Math.floor(gx), s - 1), j = Math.min(Math.floor(gy), s - 1);
  const fx = gx - i, fy = gy - j;
  const w = [(1 - fx) * (1 - fy), fx * (1 - fy), (1 - fx) * fy, fx * fy];
  const k = [j * t.samples + i, j * t.samples + i + 1, (j + 1) * t.samples + i, (j + 1) * t.samples + i + 1];
  let sum = 0;
  for (let c = 0; c < 4; c++) {
    if (w[c] === 0) continue;
    const q = t.q[k[c]];
    if (q === NODATA) return NaN;
    sum += w[c] * q;
  }
  return (t.baseCm + sum) / 100;
}

// The layer: tiles come through the shared loader (api.lib.tiles), which the substrate hash-checks.
export const LIB_VERSION = 1;

export function createTerrain() {
  let api = null, tl = null;
  const layer = {
    id: 'terrain',
    status: 'waiting for init',
    init(a) {
      api = a;
      if (!a.lib?.tiles) { layer.status = 'refused: api.lib.tiles not provided'; api = null; return; }
      tl = a.lib.tiles.createTileLoader(a, {
        file: 'tiles.json', path: INDEX_PATH, sha: () => INDEX_SHA256, tileNoun: 'tile', decode: decodeTile,
        radius: LOAD_RADIUS, maxInFlight: MAX_IN_FLIGHT, maxTiles: MAX_TILES, tieCentre: true, ground: true, pumpOnReady: false,
        say: t => { layer.status = t; }, onReady: () => { layer.status = `index: ${tl.index.length} tiles`; },
        onIndexError: e => { layer.status = `index failed, no ground: tiles.json refused (${e.message})`; }
      });
      layer.status = 'ready to load';
      tl.load();
    },
    // Finest loaded tile containing the point wins; NaN where no tile is loaded (the substrate falls back).
    heightAt(x, y) {
      if (!tl) return NaN;
      tl.follow();
      let best = null;
      for (const t of tl.loaded.values()) {
        if (x < t.x0 || y < t.y0 || x > t.x0 + t.size || y > t.y0 + t.size) continue;
        if (!best || t.tile.spacing < best.tile.spacing) best = t;
      }
      if (!best) return NaN;
      tl.touch(best);
      return sampleTile(best.tile, x - best.x0, y - best.y0);
    },
    lines(ctx) {
      if (!api) return [];
      tl.frame(ctx.pos);
      return [];
    },
    // For the plan inset: every 1 m tile in the index (not the far ring: the inset is the site), and whether it is
    // loaded now. Local metres.
    plan() {
      if (!tl?.index) return null;
      tl.follow();
      return { tiles: tl.index.filter(t => !t.ring).map(t => ({ x0: t.x0, y0: t.y0, size: t.size, loaded: tl.loaded.has(t.key) })) };
    },
    // For tests and the console.
    debug: () => ({ ...tl?.debug(), ...tl?.stats })
  };
  return layer;
}

export default createTerrain();

Tiles

A JavaScript module in the world folder of GlobalGrid2050 that creates tile loader (`createTileLoader`) and calculates planar distances, covering slope tiles, using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/lib/tiles.mjs · lines 1–134 of 134 · version 2026-09-27 04:02 · Entry point · pattern rectDist (shared by 4 files)

What it does
It lists and searches slope tiles. Defines 10 functions or classes, including rectDist, createTileLoader, invalidate, place, follow.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file slope-tiles.json.
Downstream impact
Used directly by 3 files: Site World V3 — World (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/). Reached from 4 other entry points, including Layers (globalgrid2050); Layers (globalgrid2050); Substrate (globalgrid2050).
What it achieves
It creates tile loader (`createTileLoader`) and is built from the rect dist helper (`rectDist`) and the invalidate step (`invalidate`). The tile loader every tiled layer shares (terrain, slope, flow, contours, shade, visibility, canopy).
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by Site World V3 — World.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world/lib · JavaScript module
Uses
none found
Used by
imported by Site World V3 — World (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), preloaded by Solar Design Studio — Site World Page (modulepreload)
Produces
rectDist, createTileLoader
Defines here
rectDist, createTileLoader, invalidate, place, follow, load, wanted, request, pump, evict
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/202609270402-site-world-v3/world/lib/tiles.mjs:1-134 · blob c5fca58f22d9bfd4ec797f6c0187de767fd108b2 · 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
// lib/tiles.mjs: the tile loader every tiled layer shares (terrain, slope, flow, contours, shade, visibility,
// canopy). A layer cannot import, so it reaches this through api.lib.tiles; the substrate hash-checks this file
// against the manifest before any layer sees it. No imports, no DOM.
//
// The loader reads a tile index (fetched with the layer's configured hash), asks for the tiles within `radius`
// metres of the viewer, nearest first, `maxInFlight` at a time, never twice after a failure, and forgets the
// least recently used above `maxTiles`. Every tile is placed in local metres from the live site origin; when the
// origin moves, index entries and loaded tiles are re-placed and each loaded tile's `cache` is cleared.

// Distance from a point to an axis-aligned rectangle (0 inside).
export const rectDist = (x, y, x0, y0, x1, y1) => Math.hypot(Math.max(x0 - x, 0, x - x1), Math.max(y0 - y, 0, y - y1));

/**
 * createTileLoader(api, o) -> loader
 * api: the layer's api (config.index / config.sha256 win over the defaults, origin(), fetchJSON, fetchVerified,
 *      invalidate).
 * o:   file        index name in messages ('slope-tiles.json')
 *      path, sha() default index path and hash (the build tool may set the hash later)
 *      tileNoun    'slope tile': "slope tile 3_4 failed: ..."
 *      decode(data) -> tile with e0, n0 (national-grid metres); data is bytes, or parsed JSON when o.json
 *      size(tile)  tile side in metres (default (samples - 1) * spacing)
 *      radius, maxInFlight, maxTiles
 *      active()    loads only while it is true (default: always)
 *      keep(entry) index entries worth fetching (default: all)
 *      tieCentre   break distance ties by distance to the tile centre
 *      ground      new tiles are new ground: invalidate() says so; else invalidate({ ground: false })
 *      pumpOnReady ask for tiles as soon as the index arrives (default true)
 *      say(text)   status sink
 *      onIndex(j)  before the index is built; onReady(j, dir) once it is
 *      onIndexError(e, whileLoading)  default: say("<file> failed: <message>")
 *      afterReady(j, dir)  after the first ask for tiles (a returned promise is chained)
 *      onMove()    after the origin moved and every tile was re-placed; keepCaches leaves each tile's cache alone
 */
export function createTileLoader(api, o) {
  const active = o.active || (() => true), size = o.size || (t => (t.samples - 1) * t.spacing);
  const loaded = new Map();   // key -> { tile, x0, y0, size, used, cache }
  const inFlight = new Set(), failed = new Set(), stats = { requested: [], evicted: [] };
  let index = null, state = 'idle', clock = 0, lastPos = null; // state: idle | loading | ready | failed
  const o0 = typeof api.origin === 'function' ? api.origin() : null;
  let origin = o0 ? { e: o0.e, n: o0.n } : { e: 0, n: 0 };
  const invalidate = () => (o.ground ? api.invalidate() : api.invalidate({ ground: false }));
  const place = t => { t.x0 = t.e0 - origin.e; t.y0 = t.n0 - origin.n; return t; };

  // Re-places everything when the site origin has moved; true if it had.
  function follow() {
    const g = typeof api.origin === 'function' ? api.origin() : null;
    if (!g || (g.e === origin.e && g.n === origin.n)) return false;
    origin = { e: g.e, n: g.n };
    for (const t of index || []) place(t);
    for (const t of loaded.values()) { t.x0 = t.tile.e0 - origin.e; t.y0 = t.tile.n0 - origin.n; if (!o.keepCaches) t.cache = null; }
    o.onMove?.();
    return true;
  }

  function load() {
    if (state !== 'idle' || !active()) return;
    follow();
    const sha = api.config?.sha256 || o.sha(), path = api.config?.index || o.path;
    if (!sha || sha.startsWith('__')) { state = 'failed'; o.say(`no ${o.file} hash configured`); return; }
    state = 'loading';
    const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '';
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      if (!j || !Array.isArray(j.tiles)) throw Error(`${o.file} has no tiles list`);
      o.onIndex?.(j);
      index = j.tiles.map(t => place({ ...t, path: dir + t.file, size: t.tile_m || j.tile_m || 256 })); // a far-ring tile (8 or 16 m nodes) carries its own size
      state = 'ready';
      o.onReady?.(j, dir);
      if (o.pumpOnReady !== false) pump();
      invalidate();
      return o.afterReady?.(j, dir);
    }).catch(e => {
      const whileLoading = state === 'loading';
      if (whileLoading) state = 'failed';
      if (o.onIndexError) o.onIndexError(e, whileLoading); else o.say(`${o.file} failed: ${e.message}`);
    });
  }

  // Index entries within radius of (x, y) worth fetching, nearest first.
  function wanted(x, y) {
    if (!index) return [];
    return index
      .filter(t => !o.keep || o.keep(t))
      .map(t => ({ t, d: rectDist(x, y, t.x0, t.y0, t.x0 + t.size, t.y0 + t.size),
        c: o.tieCentre ? Math.hypot(x - t.x0 - t.size / 2, y - t.y0 - t.size / 2) : 0 }))
      .filter(v => v.d <= o.radius)
      .sort((a, b) => a.d - b.d || a.c - b.c)
      .map(v => v.t);
  }

  function request(entry) {
    inFlight.add(entry.key);
    stats.requested.push(entry.key);
    Promise.resolve().then(() => (o.json ? api.fetchJSON(entry.path, entry.sha256) : api.fetchVerified(entry.path, entry.sha256))).then(data => {
      const tile = o.decode(data);
      loaded.set(entry.key, { tile, x0: tile.e0 - origin.e, y0: tile.n0 - origin.n, size: size(tile), used: ++clock, cache: null });
      evict();
      invalidate();
    }).catch(e => { failed.add(entry.key); o.say(`${o.tileNoun} ${entry.key} failed: ${e.message}`); })
      .finally(() => { inFlight.delete(entry.key); pump(); });
  }

  function pump() {
    if (!lastPos || state !== 'ready' || !active()) return;
    follow();
    for (const t of wanted(lastPos[0], lastPos[1])) {
      if (inFlight.size >= o.maxInFlight) break;
      if (loaded.has(t.key)) { loaded.get(t.key).used = ++clock; continue; }
      if (inFlight.has(t.key) || failed.has(t.key)) continue;
      request(t);
    }
  }

  function evict() {
    while (loaded.size > o.maxTiles) {
      let oldest = null;
      for (const [k, v] of loaded) if (!oldest || v.used < loaded.get(oldest).used) oldest = k;
      loaded.delete(oldest);
      stats.evicted.push(oldest);
    }
  }

  return {
    loaded, stats, load, pump, follow, wanted,
    get state() { return state; },
    get index() { return index; },
    get origin() { return origin; },
    // One frame: follow the origin, remember the viewer, load the index if it is due, ask for tiles.
    frame(pos) { follow(); lastPos = pos; if (state === 'idle') load(); pump(); },
    // Loaded tiles within radius of pos, as [key, tile] pairs.
    near: pos => [...loaded].filter(([, t]) => rectDist(pos[0], pos[1], t.x0, t.y0, t.x0 + t.size, t.y0 + t.size) <= o.radius),
    touch: t => { t.used = ++clock; },
    debug: () => ({ loaded: [...loaded.keys()], inFlight: [...inFlight], failed: [...failed], indexState: state })
  };
}