In this section
- Postcodes ingest · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/postcodes.mjs lines 1–77
- Sites UI render · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/sites-ui.mjs lines 1–100
- Snap geodesy · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/snap.mjs lines 1–92
- Wcs Terrain geodesy · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/wcs-terrain.mjs lines 1–216
Postcodes
A JavaScript module in the world folder of GlobalGrid2050 that fetches postcodes from postcodes.io. It normalises postcode (`normalisePostcode`) and creates postcode lookup (`createPostcodeLookup`).
ingestglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/postcodes.mjs · lines 1–77 of 77 · version 2026-09-27 00:56 · pattern lookup (shared by 4 files)
- What it does
- It fetches postcodes. Defines 6 functions or classes, including normalisePostcode, looksLikePostcode, toPostcodeRows, createPostcodeLookup, remember. 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 3 files: Places (globalgrid2050); 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
- Postcode search through postcodes.io (code MIT; Great Britain postcode data under the OS OpenData licence, wording checked on postcodes.io 26 Sept 2026).
- Why it matters
- Imported by Places and Search UI.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Places (import), imported by Search UI (import), imported by Search UI (import)
- Produces
- POSTCODES_API, POSTCODES_CREDIT, normalisePostcode, looksLikePostcode, toPostcodeRows, createPostcodeLookup
- Defines here
- normalisePostcode, looksLikePostcode, toPostcodeRows, createPostcodeLookup, 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/202609270056-site-world-v3/world/postcodes.mjs:1-77 · blob 774b24cf3ea72ae705cc9af355f22e323f988b29 · 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
// Postcode search through postcodes.io (code MIT; Great Britain postcode data under the OS OpenData licence,
// wording checked on https://postcodes.io/docs/licences, 26 Sept 2026). The service sends
// Access-Control-Allow-Origin: *, and answers with national-grid eastings and northings as well as latitude
// and longitude, so the world is placed from the service's own grid figures.
// Northern Ireland postcodes (BT...) are left out: their data is licensed for non-commercial use only, and
// there is no EA LiDAR there anyway.
// The pure parts are at the top; createPostcodeLookup adds a polite client: one request at a time, at least
// minGapMs apart, a newer query replaces one still waiting, and answers are kept (least recently used out).
export const POSTCODES_API = 'https://api.postcodes.io/postcodes';
// Kept identical to data/attribution.json sources["postcodes-io"].line (tests/postcodes.test.mjs checks).
export const POSTCODES_CREDIT = Object.freeze({
id: 'postcodes-io',
text: 'Postcodes via postcodes.io. Contains Ordnance Survey data © Crown copyright and database right 2025. ' +
'Contains Royal Mail data © Royal Mail copyright and database right 2025. ' +
'Contains National Statistics data © Crown copyright and database right 2025. ' +
'Contains NRS data © Crown copyright and database right 2025.',
link: 'https://postcodes.io/docs/licences'
});
export const normalisePostcode = text => String(text ?? '').toUpperCase().replace(/\s+/g, ' ').trim();
// A whole postcode, or the start of one: an outward code ("HR2", "SW1A") with or without part of the inward.
const SHAPE = /^[A-Z]{1,2}\d[A-Z\d]?(?: ?\d[A-Z]{0,2})?$/;
export function looksLikePostcode(text) {
const q = normalisePostcode(text);
return SHAPE.test(q) && !q.startsWith('BT');
}
// postcodes.io results -> Find rows. Rows without a place, or in Northern Ireland, are left out.
export function toPostcodeRows(results) {
return (Array.isArray(results) ? results : [])
.filter(r => r && Number.isFinite(r.latitude) && Number.isFinite(r.longitude) && !String(r.postcode).startsWith('BT'))
.map(r => {
const where = [r.parish && !/unparished/i.test(r.parish) ? r.parish : null, r.admin_district].filter(Boolean).join(', ');
const choice = { lat: r.latitude, lon: r.longitude, label: r.postcode };
if (Number.isFinite(r.eastings) && Number.isFinite(r.northings)) Object.assign(choice, { e: r.eastings, n: r.northings });
return { key: `pc-${r.postcode}`, source: POSTCODES_CREDIT.id, title: r.postcode,
detail: ['Postcode', where, r.country].filter(Boolean).join(' · '), choice };
});
}
// 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. Non-postcode text resolves to [] with no request.
export function createPostcodeLookup({ fetchImpl, limit = 6, minGapMs = 250, 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 = normalisePostcode(text);
if (!looksLikePostcode(q)) 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(`${POSTCODES_API}?q=${encodeURIComponent(q)}&limit=${limit}`, { mode: 'cors' });
if (!res.ok) throw Error(`postcodes.io HTTP ${res.status}`);
const rows = toPostcodeRows((await res.json())?.result);
remember(q, rows);
return rows;
});
chain = run.catch(() => {});
return run;
}
lookup.stats = stats;
return lookup;
}Sites UI
A JavaScript module in the world folder of GlobalGrid2050 that creates site chooser (`createSiteChooser`) and mounts site select (`mountSiteSelect`), using SHA-256. It parses sites (`parseSites`) and creates site chooser (`createSiteChooser`).
renderglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/sites-ui.mjs · lines 1–100 of 100 · version 2026-09-27 00:56 · Entry point · pattern siteLabel (shared by 2 files)
- What it does
- It draws its content. Defines 6 functions or classes, including SAFE_PATH, parseSites, siteLabel, createSiteChooser, mountSiteSelect. 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.
- Inputs & outputs
- In: JSON file sites.json; form fields (user input).
- Downstream impact
- Used directly by 6 files: Project UI (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Project UI (globalgrid2050); and 2 more.
- What it achieves
- Site selector for the world viewer. It reads `./world/data/sites.json`. It responds to change events.
- 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 4 files, including Project UI and Substrate.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Project UI (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), imported by Project UI (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import), mentioned in Standalone (comment link)
- Produces
- SCHEMA, parseSites, siteLabel, createSiteChooser, mountSiteSelect, siteFromUrl
- Defines here
- SAFE_PATH, parseSites, siteLabel, createSiteChooser, mountSiteSelect, siteFromUrl
- 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/202609270056-site-world-v3/world/sites-ui.mjs:1-100 · blob 64775dd610958afc07cd352ddb7bef6587da7360 · 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
// Site selector for the world viewer. Reads web/world/data/sites.json (written by tools/stage-sites.mjs):
// { schema: 'world.sites.v1', sites: [ { name, centre_e, centre_n, relief_m, tiles, sha256, ... } ] }
// Pure logic (parseSites, siteLabel, createSiteChooser) plus one small DOM helper (mountSiteSelect) that
// takes the document as an argument, so everything runs under node:test without a browser.
// Site names are neutral ids (letters, digits, - and _); anything else is dropped, never shown.
export const SCHEMA = 'world.sites.v1';
const NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
const HEX64 = /^[0-9a-f]{64}$/i;
const SAFE_PATH = p => typeof p === 'string' && /^[\w./-]+\.json$/.test(p) && !p.includes('..') && !p.startsWith('/');
// Validates a sites.json object. Returns { sites, rejected } with sites sorted by name; bad entries are
// listed in rejected with the reason, never passed on.
export function parseSites(json) {
const rejected = [];
if (!json || json.schema !== SCHEMA || !Array.isArray(json.sites)) return { sites: [], rejected: [{ name: null, why: 'not a world.sites.v1 file' }] };
const seen = new Set(), sites = [];
for (const s of json.sites) {
const name = s?.name;
const why = !NAME.test(name ?? '') ? 'name is not a neutral id'
: seen.has(name) ? 'duplicate name'
: !Number.isFinite(s.centre_e) || !Number.isFinite(s.centre_n) ? 'no centre'
: !SAFE_PATH(s.tiles) ? 'unsafe tiles path'
: !HEX64.test(s.sha256 ?? '') ? 'no valid sha256'
: null;
if (why) { rejected.push({ name: typeof name === 'string' ? name : null, why }); continue; }
seen.add(name);
sites.push(Object.freeze({
name, centre_e: s.centre_e, centre_n: s.centre_n,
relief_m: Number.isFinite(s.relief_m) ? s.relief_m : null,
tiles: s.tiles, sha256: s.sha256.toLowerCase(),
tile_count: Number.isInteger(s.tile_count) ? s.tile_count : null
}));
}
sites.sort((a, b) => a.name.localeCompare(b.name, 'en', { numeric: true }));
return { sites, rejected };
}
// "open-land-01" -> "Open land 01"; the relief is added when known: "Open land 01 (40 m relief)".
export function siteLabel(site, { relief = true } = {}) {
const words = site.name.replace(/[-_]+/g, ' ').trim();
const base = words.charAt(0).toUpperCase() + words.slice(1);
return relief && Number.isFinite(site.relief_m) ? `${base} (${Math.round(site.relief_m)} m relief)` : base;
}
// Selection state. choose(name) calls onChoose(site) only for a known site that is not already current;
// it returns the chosen site, or null when nothing changed.
export function createSiteChooser(sites, { current = null, onChoose = () => {} } = {}) {
const byName = new Map(sites.map(s => [s.name, s]));
let cur = byName.has(current) ? current : null;
return {
get current() { return cur ? byName.get(cur) : null; },
options: () => sites.map(s => ({ value: s.name, label: siteLabel(s), selected: s.name === cur })),
choose(name) {
const site = byName.get(name);
if (!site || name === cur) return null;
cur = name;
onChoose(site);
return site;
},
// The viewer has left the current site (Find flew elsewhere): no site is current, so any can be chosen again.
leave() { cur = null; }
};
}
// Builds <label class="site-select">Site <select>...</select></label> into parent and wires it to the chooser.
// With no current site a disabled "Choose a site" placeholder is shown first. Returns the <select>.
export function mountSiteSelect(doc, parent, chooser) {
const label = doc.createElement('label');
label.className = 'site-select';
label.appendChild(doc.createTextNode('Site '));
const select = doc.createElement('select');
select.setAttribute('aria-label', 'Site');
const opts = chooser.options();
// The placeholder is always there, so after leaving a site (Find) the select can show "Choose a site" again.
const ph = doc.createElement('option');
ph.value = ''; ph.textContent = opts.length ? 'Choose a site' : 'No sites staged';
ph.disabled = true; ph.selected = !opts.some(o => o.selected);
select.appendChild(ph);
for (const o of opts) {
const el = doc.createElement('option');
el.value = o.value; el.textContent = o.label; el.selected = o.selected;
select.appendChild(el);
}
select.disabled = opts.length === 0;
select.addEventListener('change', () => chooser.choose(select.value));
label.appendChild(select);
parent.appendChild(label);
return select;
}
// The staged site named by ?site=<name>, or null. Read before the layers load, so terrain comes from that site.
export async function siteFromUrl(loc = location) {
const name = new URLSearchParams(loc.search).get('site');
if (!name) return null;
try {
const r = await fetch('./world/data/sites.json', { cache: 'no-cache' });
return r.ok ? parseSites(await r.json()).sites.find(s => s.name === name) || null : null;
} catch { return null; }
}Snap
A JavaScript module in the world folder of GlobalGrid2050 that works with substations. It snaps point (`snapPoint`) and snaps ring (`snapRing`).
geodesyglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/snap.mjs · lines 1–92 of 92 · version 2026-09-27 00:56 · Not reached from any entry point (candidate for review) · pattern nearestSubstation (shared by 4 files)
- What it does
- It calculates substations. Defines 11 functions or classes, including dist, snapPoint, bearingDeg, nearestSubstation, tierOf.
- 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: substations, 400kV, 200kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 400kV, 200kV.
- Downstream impact
- Used directly by 3 files: Design Ground (globalgrid2050); Design UI (globalgrid2050); Design UI (globalgrid2050).
- What it achieves
- Snapping a cable route to grid equipment, and what the readout says about where the route meets the grid. Its code works with 200 kV and 400 kV.
- Why it matters
- Imported by Design Ground and Design UI.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Design Ground (import), imported by Design UI (import), imported by Design UI (import), mentioned in Standalone (comment link)
- Produces
- SNAP_M, snapPoint, bearingDeg, nearestSubstation, tierOf, tierText, connectionText, draftToNearest, measuredShare, snapRing
- Defines here
- dist, snapPoint, bearingDeg, nearestSubstation, tierOf, tierText, km, connectionText, draftToNearest, measuredShare, snapRing
- 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/202609270056-site-world-v3/world/snap.mjs:1-92 · blob 1759972bdabf92df82c30ca48059dc8c6e7cbbf7 · 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
// Snapping a cable route to grid equipment, and what the readout says about where the route meets the grid.
// Pure: no imports, no DOM. Assets are in British National Grid metres:
// { kind: 'substation' | 'tower', e, n, kv?, tier?, id? } (any operator field is ignored: never shown)
// Route points are local metres [x, y, z] from origin { e, n }.
//
// A route point within SNAP_M (plan) of a substation or pylon moves onto it; the nearest wins. A route whose last
// point sits on a substation ends there. Distances are plan (horizontal) metres; bearings are from grid north,
// clockwise, in whole degrees.
export const SNAP_M = 25;
const dist = (a, b) => Math.hypot(a.e - b.e, a.n - b.n);
// The asset a local point snaps to, or null: { asset, x, y } with the asset's own position in local metres.
export function snapPoint(p, assets, origin, radius = SNAP_M) {
const at = { e: origin.e + p[0], n: origin.n + p[1] };
let best = null, bd = Infinity;
for (const a of assets || []) {
if (a.kind !== 'substation' && a.kind !== 'tower') continue;
const d = dist(a, at);
if (d <= radius && d < bd) { best = a; bd = d; }
}
return best ? { asset: best, x: best.e - origin.e, y: best.n - origin.n, d: bd } : null;
}
// Grid bearing from a to b, degrees 0-359 (0 = grid north, 90 = east).
export function bearingDeg(a, b) {
const deg = Math.atan2(b.e - a.e, b.n - a.n) * 180 / Math.PI;
return (Math.round(deg) + 360) % 360;
}
// The nearest substation to a point in national-grid metres: { asset, d, bearing } or null.
export function nearestSubstation(at, assets) {
let best = null, bd = Infinity;
for (const a of assets || []) if (a.kind === 'substation') { const d = dist(a, at); if (d < bd) { best = a; bd = d; } }
return best ? { asset: best, d: bd, bearing: bearingDeg(at, best) } : null;
}
// The network tier, never an operator's name or a voltage (owner's rule: the readout shows the tier only). The
// national index gives it; otherwise it follows the voltage: 200 kV and above is transmission (275 and 400 kV in
// England and Wales), below is distribution.
export function tierOf(a) {
if (a?.tier === 'transmission' || a?.tier === 'distribution') return a.tier;
const kv = Number(a?.kv);
return kv >= 200 ? 'transmission' : kv > 0 ? 'distribution' : null;
}
export const tierText = a => tierOf(a) || 'tier not recorded';
const km = d => (d / 1000).toFixed(d < 10000 ? 2 : 1);
// The readout's 'Grid connection' line for a route whose last point is `end`. near is the nearest substation to the
// end ({ asset, d, bearing } from nearestSubstation), 'pending' while the national index is being read, or null
// when there is none. endAsset is the asset the last point snapped to, if any.
export function connectionText(near, endAsset = null) {
if (endAsset?.kind === 'substation') return `ends at substation, ${tierText(endAsset)}`;
const sub = near === 'pending' ? 'finding the nearest substation…'
: near ? `nearest substation ${tierText(near.asset)}, ${km(near.d)} km, bearing ${near.bearing}°`
: 'no substation found in the national index';
return endAsset?.kind === 'tower' ? `ends at pylon, ${tierText(endAsset)} · ${sub}` : sub;
}
// The first draft of 'Route to nearest substation': the point to add after `last` (local [x, y]) for the substation
// `asset` (national-grid metres), or null. A straight line, nothing more: the user edits it.
export function draftToNearest(last, asset, origin) {
if (!asset) return null;
const at = { e: origin.e + last[0], n: origin.n + last[1] };
return { asset, x: asset.e - origin.e, y: asset.n - origin.n, d: dist(asset, at), bearing: bearingDeg(at, asset) };
}
// How much of a plan polyline (local [x, y]) stands on measured ground, sampled every `step` metres.
export function measuredShare(pts, measuredAt, step = 5) {
let total = 0, known = 0;
for (let i = 1; i < pts.length; i++) {
const [ax, ay] = pts[i - 1], [bx, by] = pts[i], L = Math.hypot(bx - ax, by - ay), n = Math.max(1, Math.ceil(L / step));
for (let k = 0; k < n; k++) {
const f = (k + 0.5) / n;
if (Number.isFinite(measuredAt(ax + (bx - ax) * f, ay + (by - ay) * f))) known += L / n;
}
total += L;
}
return { total, known };
}
// A snap ring: an octagon on the ground with a short post, as line pairs in local metres.
export function snapRing([x, y, z], r = 3, h = 4) {
const out = [];
for (let k = 0; k < 8; k++) {
const a0 = k * Math.PI / 4, a1 = (k + 1) * Math.PI / 4;
out.push(x + r * Math.cos(a0), y + r * Math.sin(a0), z + 0.3, x + r * Math.cos(a1), y + r * Math.sin(a1), z + 0.3);
}
out.push(x, y, z, x, y, z + h);
return out;
}Wcs Terrain
A JavaScript module in the world folder of GlobalGrid2050 that fetches LiDAR terrain, using EPSG:27700 from Environment Agency.
geodesyglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/wcs-terrain.mjs · lines 1–216 of 216 · version 2026-09-27 00:56 · Entry point · pattern decodeGeoTiff (shared by 2 files)
- What it does
- It fetches LiDAR terrain. Defines 14 functions or classes, including inExtent, wcsUrl, readTags, inflate, decodeGeoTiff. Side effects: makes network requests.
- 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: data source: Environment Agency. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 4 files: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It reads tags (`readTags`), decodes geo tiff (`decodeGeoTiff`) and creates live terrain (`createLiveTerrain`). Live terrain: Environment Agency LiDAR Composite DTM 1 m, fetched from the EA's public WCS 2.0.1 in the browser, for anywhere the staged (hash-checked) tiles do not reach.
- 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 Substrate.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- Terrain (import)
- Used by
- preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import)
- Produces
- WCS, EXTENT, inExtent, BOX_M, LIVE_LABEL, wcsUrl, decodeGeoTiff, toTile, sampleBox, boxesNear, createLiveTerrain
- Defines here
- inExtent, wcsUrl, readTags, inflate, decodeGeoTiff, toTile, isNo, sampleBox, boxesNear, createLiveTerrain, o, describe, request, pump
- 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/202609270056-site-world-v3/world/wcs-terrain.mjs:1-216 · blob d09a35534f973cd2c1d91a78e7cb96d613b10b94 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: production_core
// Live terrain: Environment Agency LIDAR Composite DTM 1 m, fetched from the EA's public WCS 2.0.1 in the
// browser, for anywhere the staged (hash-checked) tiles do not reach. The service sends
// Access-Control-Allow-Origin: *, so no proxy is needed.
//
// What the service actually returns (inspected 26 Sept 2026, see docs/integration/terrain-anywhere.md):
// a classic big-endian TIFF ("MM", 42), one band of 32-bit float (SampleFormat 3), no compression, no
// predictor, 256 x 256 internal tiles (small requests come back as strips), pixel-is-area with a
// ModelTransformation tag, and nodata -3.4028234663852886E38 in GDAL_NODATA. A box outside the survey but
// inside the service's extent (open sea) comes back as exact zeros with no nodata tag; a box outside its
// extent (Scotland) is answered with HTTP 500 and a JSON error. The decoder below reads exactly that and refuses anything else by
// name; deflate (compression 8 / 32946) is read with DecompressionStream in case the service ever switches.
//
// A 256 m box at 1 m is 256 x 256 pixels whose centres sit at e0 + 0.5 ... e0 + 255.5. It is held in the
// terrain layer's own tile shape ({ samples, spacing, baseCm, q: Uint16Array rows south to north }), and a
// point within half a metre of the box edge takes the edge pixel, so neighbouring boxes meet with no gap.
import { sampleTile, NODATA } from './layers/terrain.mjs';
export const WCS = Object.freeze({
url: 'https://environment.data.gov.uk/spatialdata/lidar-composite-digital-terrain-model-dtm-1m/wcs',
coverage: '13787b9a-26a4-4775-8523-806d13af58fc__Lidar_Composite_Elevation_DTM_1m'
});
// The coverage's envelope from DescribeCoverage (EPSG:27700). A box crossing it is answered with HTTP 500 and
// no CORS header, so only boxes wholly inside are asked for. Inside it, Wales and Scotland come back as zeros.
export const EXTENT = Object.freeze({ e0: 80000, n0: 4000, e1: 656000, n1: 665000 });
export const inExtent = (e0, n0, size = BOX_M) => e0 >= EXTENT.e0 && n0 >= EXTENT.n0 && e0 + size <= EXTENT.e1 && n0 + size <= EXTENT.n1;
export const BOX_M = 256, LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 36, RETRY_MS = 60000;
export const LIVE_LABEL = 'live from the EA service';
export function wcsUrl(e0, n0, size = BOX_M) {
return `${WCS.url}?service=WCS&version=2.0.1&request=GetCoverage&CoverageId=${WCS.coverage}` +
`&subset=E(${e0},${e0 + size})&subset=N(${n0},${n0 + size})&format=image/tiff`;
}
// ---- GeoTIFF: only what the EA service sends --------------------------------------------------
const TYPE_BYTES = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8 };
function readTags(dv, little) {
if (dv.byteLength < 8) throw Error('GeoTIFF shorter than its header');
const order = String.fromCharCode(dv.getUint8(0), dv.getUint8(1));
if (order !== (little ? 'II' : 'MM')) throw Error(`GeoTIFF byte order "${order}" not recognised`);
const magic = dv.getUint16(2, little);
if (magic === 43) throw Error('BigTIFF is not supported (the EA service sends classic TIFF)');
if (magic !== 42) throw Error(`TIFF magic ${magic} is not 42`);
const ifd = dv.getUint32(4, little), count = dv.getUint16(ifd, little), tags = new Map();
for (let i = 0; i < count; i++) {
const p = ifd + 2 + 12 * i, tag = dv.getUint16(p, little), type = dv.getUint16(p + 2, little), n = dv.getUint32(p + 4, little);
const bytes = (TYPE_BYTES[type] || 1) * n, at = bytes <= 4 ? p + 8 : dv.getUint32(p + 8, little);
if (at + bytes > dv.byteLength) throw Error(`TIFF tag ${tag} runs past the end of the file`);
const vals = [];
for (let k = 0; k < n; k++) {
const q = at + k * (TYPE_BYTES[type] || 1);
vals.push(type === 3 ? dv.getUint16(q, little) : type === 4 ? dv.getUint32(q, little)
: type === 12 ? dv.getFloat64(q, little) : type === 11 ? dv.getFloat32(q, little)
: type === 5 ? dv.getUint32(q, little) / dv.getUint32(q + 4, little) : dv.getUint8(q));
}
tags.set(tag, type === 2 ? String.fromCharCode(...vals).replace(/\0+$/, '') : vals);
}
return tags;
}
async function inflate(bytes) {
if (typeof DecompressionStream !== 'function') throw Error('this browser cannot inflate deflate-compressed GeoTIFF');
const s = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate'));
return new Uint8Array(await new Response(s).arrayBuffer());
}
// bytes -> { width, height, data: Float32Array rows north to south, nodata, west, north, res }.
export async function decodeGeoTiff(buffer) {
const ab = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
const dv = new DataView(ab), little = dv.byteLength > 1 && dv.getUint8(0) === 0x49;
const tags = readTags(dv, little), one = (t, d) => (tags.has(t) ? tags.get(t)[0] : d);
const width = one(256), height = one(257), bits = one(258, 1), comp = one(259, 1);
const spp = one(277, 1), fmt = one(339, 1), predictor = one(317, 1), planar = one(284, 1);
if (!(width > 0 && height > 0)) throw Error('GeoTIFF has no size');
if (bits !== 32 || fmt !== 3 || spp !== 1) throw Error(`GeoTIFF is ${spp} x ${bits}-bit format ${fmt}; expected one 32-bit float band`);
if (predictor !== 1 || planar !== 1) throw Error(`GeoTIFF predictor ${predictor} / planar ${planar} is not supported`);
if (![1, 8, 32946].includes(comp)) throw Error(`GeoTIFF compression ${comp} is not supported`);
const tiled = tags.has(322);
const bw = tiled ? one(322) : width, bh = tiled ? one(323) : one(278, height);
const offsets = tags.get(tiled ? 324 : 273), counts = tags.get(tiled ? 325 : 279);
if (!offsets || !counts || offsets.length !== counts.length) throw Error('GeoTIFF has no pixel blocks');
const across = tiled ? Math.ceil(width / bw) : 1, data = new Float32Array(width * height);
for (let b = 0; b < offsets.length; b++) {
if (offsets[b] + counts[b] > ab.byteLength) throw Error('GeoTIFF block runs past the end of the file');
let raw = new Uint8Array(ab, offsets[b], counts[b]);
if (comp !== 1) raw = await inflate(raw);
const bdv = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
const bx = (b % across) * bw, by = Math.floor(b / across) * bh, rows = Math.min(bh, height - by);
const need = (tiled ? bh : rows) * bw * 4;
if (raw.byteLength < Math.min(need, rows * bw * 4)) throw Error(`GeoTIFF block ${b} is ${raw.byteLength} bytes, expected ${need}`);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < bw && bx + c < width; c++) data[(by + r) * width + bx + c] = bdv.getFloat32((r * bw + c) * 4, little);
}
}
let west, north, res;
if (tags.has(34264)) { const m = tags.get(34264); [res, west, north] = [m[0], m[3], m[7]]; if (Math.abs(m[5] + res) > 1e-9) throw Error('GeoTIFF pixels are not square'); }
else if (tags.has(33550) && tags.has(33922)) { const s = tags.get(33550), t = tags.get(33922); [res, west, north] = [s[0], t[3] - t[0] * s[0], t[4] + t[1] * s[1]]; }
else throw Error('GeoTIFF has no georeference');
const nd = tags.has(42113) ? Number(tags.get(42113)) : NaN;
return { width, height, data, nodata: nd, hasNodata: tags.has(42113), west, north, res };
}
// A decoded box -> the terrain layer's tile shape. The first sample sits half a metre in from the south-west
// corner (pixel centre). Heights go to centimetres above the box's lowest point; no data becomes NODATA.
export function toTile(geo) {
const { width: w, height: h, data, res } = geo;
if (w !== h) throw Error(`live box is ${w} x ${h} pixels; expected a square`);
// Outside the survey (open sea, say) the service sends a box of exact zeros with no nodata tag at all.
const blank = !geo.hasNodata && data.every(v => v === 0);
const isNo = v => blank || !Number.isFinite(v) || v === geo.nodata || v < -1e30 || v > 1e5;
let min = Infinity, max = -Infinity, nodata = 0;
for (const v of data) { if (isNo(v)) { nodata++; continue; } if (v < min) min = v; if (v > max) max = v; }
const baseCm = Number.isFinite(min) ? Math.floor(min * 100) : 0;
if (max * 100 - baseCm > 0xfffe) throw Error('live box spans more than 655 m of height');
const q = new Uint16Array(w * h);
for (let r = 0; r < h; r++) { // TIFF rows run north to south; tile rows run south to north
for (let c = 0; c < w; c++) { const v = data[r * w + c]; q[(h - 1 - r) * w + c] = isNo(v) ? NODATA : Math.round(v * 100 - baseCm); }
}
return { version: 1, samples: w, spacing: res, flags: 0, e0: geo.west + res / 2, n0: geo.north - h * res + res / 2,
baseCm, minQ: 0, maxQ: Number.isFinite(max) ? Math.round(max * 100 - baseCm) : 0, nodata, q };
}
// Height inside a live box at (u, v) metres from its south-west corner: edge pixels hold out to the box edge.
export function sampleBox(tile, u, v) {
const s = (tile.samples - 1) * tile.spacing, half = tile.spacing / 2;
if (!(u >= 0 && v >= 0 && u <= s + tile.spacing && v <= s + tile.spacing)) return NaN;
return sampleTile(tile, Math.min(Math.max(u - half, 0), s), Math.min(Math.max(v - half, 0), s));
}
// Boxes (south-west corners on the 256 m national-grid lattice) within radius of (e, n), nearest first.
export function boxesNear(e, n, radius = LOAD_RADIUS, size = BOX_M) {
const out = [];
for (let i = Math.floor((e - radius) / size); i <= Math.floor((e + radius) / size); i++) {
for (let j = Math.floor((n - radius) / size); j <= Math.floor((n + radius) / size); j++) {
const e0 = i * size, n0 = j * size;
const d = Math.hypot(Math.max(e0 - e, 0, e - e0 - size), Math.max(n0 - n, 0, n - n0 - size));
if (d <= radius) out.push({ key: `${e0}_${n0}`, e0, n0, d, c: Math.hypot(e - e0 - size / 2, n - n0 - size / 2) });
}
}
return out.sort((a, b) => a.d - b.d || a.c - b.c);
}
// The live layer. opts: origin() -> { e, n }; invalidate(); skip(e0, n0, size) -> true where staged tiles
// cover the box; fetchImpl, clock (ms) for tests. It behaves like a manifest layer: status, heightAt, lines.
export function createLiveTerrain({ origin, invalidate = () => {}, skip = () => false, fetchImpl, clock = () => Date.now() } = {}) {
const get = fetchImpl || ((u, o) => fetch(u, o));
const loaded = new Map(), inFlight = new Set(), failed = new Map(); // failed: key -> retry-after ms
const stats = { requested: [], evicted: [], bytes: 0, ms: [], empty: 0 };
let used = 0, lastPos = null, lastError = '', outside = false;
const o = () => origin();
function describe() {
const n = loaded.size, fly = inFlight.size;
if (outside && !n && !fly) return 'outside the EA LiDAR coverage (England only); the ground here is shown flat';
if (lastError && !n) return `EA LiDAR service failed (${lastError}); the ground here is shown flat`;
if (!n && !fly) return 'no live EA LiDAR needed here yet';
const empty = [...loaded.values()].filter(b => b.tile.nodata === b.tile.q.length).length;
return `${n} box${n === 1 ? '' : 'es'} ${LIVE_LABEL}${fly ? `, ${fly} loading` : ''}` +
`${empty ? `; ${empty} with no survey (sea or not flown), shown flat` : ''}${lastError ? ` (last failure: ${lastError})` : ''}`;
}
function request(b) {
inFlight.add(b.key); stats.requested.push(b.key);
const t0 = clock();
layer.status = describe();
Promise.resolve().then(() => get(wcsUrl(b.e0, b.n0), { mode: 'cors' })).then(async res => {
if (!res.ok) throw Error(`HTTP ${res.status}${res.status >= 500 ? ', outside England or the service is down' : ''}`);
const buf = await res.arrayBuffer();
stats.bytes += buf.byteLength;
const tile = toTile(await decodeGeoTiff(buf));
stats.ms.push(clock() - t0);
if (tile.nodata === tile.q.length) stats.empty++;
loaded.set(b.key, { tile, e0: b.e0, n0: b.n0, size: BOX_M, used: ++used });
lastError = '';
while (loaded.size > MAX_TILES) {
let old = null;
for (const [k, v] of loaded) if (!old || v.used < loaded.get(old).used) old = k;
loaded.delete(old); stats.evicted.push(old);
}
invalidate();
}).catch(e => { lastError = e instanceof TypeError ? `network: ${e.message}` : e.message; failed.set(b.key, clock() + RETRY_MS); })
.finally(() => { inFlight.delete(b.key); layer.status = describe(); pump(); });
}
function pump() {
if (!lastPos) return;
const { e, n } = o(), now = clock(), near = boxesNear(e + lastPos[0], n + lastPos[1]);
const wasOutside = outside;
outside = !near.some(b => inExtent(b.e0, b.n0));
if (outside !== wasOutside) layer.status = describe();
for (const b of near) {
if (!inExtent(b.e0, b.n0)) continue;
if (inFlight.size >= MAX_IN_FLIGHT) break;
if (loaded.has(b.key)) { loaded.get(b.key).used = ++used; continue; }
if (inFlight.has(b.key) || (failed.get(b.key) ?? 0) > now || skip(b.e0, b.n0, BOX_M)) continue;
request(b);
}
}
const layer = {
id: 'terrain-live',
status: 'waiting',
// Local metres in, metres above datum out; NaN where no live box is held or the box has no data there.
heightAt(x, y) {
const { e, n } = o(), pe = e + x, pn = n + y;
const b = loaded.get(`${Math.floor(pe / BOX_M) * BOX_M}_${Math.floor(pn / BOX_M) * BOX_M}`);
if (!b) return NaN;
b.used = ++used;
return sampleBox(b.tile, pe - b.e0, pn - b.n0);
},
lines(ctx) { lastPos = ctx.pos; pump(); return []; },
debug: () => ({ loaded: [...loaded.keys()], inFlight: [...inFlight], failed: [...failed.keys()], lastError, ...stats })
};
return layer;
}