GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / energy-transition-simulator / prototype/mod/lidar-onsite

LiDAR Stream and 2 more files (part 1)

A JavaScript file in the prototype folder of Energy Transition Simulator that maps LiDAR terrain, using EPSG:27700 and OSTN15. It saves day (`saveDay`), sets open (`setOpen`) and shows text (`showText`).

577 lines of JavaScript and Python from energy-transition-simulator, in 3 files. Topic: Maps, GIS and field navigation. Section 485 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. Bake storage · energy-transition-simulator / prototype/mod/lidar-onsite/bake.py lines 1–47
  2. LiDAR Stream geodesy · energy-transition-simulator / prototype/mod/lidar-stream.js lines 1–344
  3. R5 ingest · energy-transition-simulator / prototype/mod/lidar-stream/r5.mjs lines 1–186

Bake

A Python module in the LiDAR onsite folder of Energy Transition Simulator that reads LiDAR terrain.

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

Evidence
  • line-jaccard 0.9545 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/lidar-onsite/bake.py:1-47 7fd7b876e7ec28f3474bf628919fe10d68ec3607
  • sha256 f8134b76fe16d5d04157e22b48213087e68e074a46c371a6773207b8dd742c77
  • target sha256 0baee758be5d15a6cc861888bdff041cce8319ea1a7e198764c05093b76adb16
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

storageenergy-transition-simulator / prototype/mod/lidar-onsite/bake.py · lines 1–47 of 47 · Not reached from any entry point (candidate for review)

What it does
It loads LiDAR terrain. Uses libraries sys, json, base64, os, numpy. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: JSON file index.json; command-line arguments. Out: JSON file.
What it achieves
Bake cached EA LiDAR 1 m DTM around a point into a small file the LiDAR-onsite module draws.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/mod/lidar-onsite · Python module
Uses
sys, json, base64, os, numpy, mirror_store
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/lidar-onsite/bake.py:1-47 · blob 1f02059f897c89ea9fb50ae1a1bae38c5157bc25 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Bake cached EA LiDAR 1 m DTM around a point into a small file the lidar-onsite module draws.

Reads ONLY the local mirror E:/lidar-mirror (built from the local caches E:/lidar-cache, E:/world-cache and the
bulk zips; no network, never the EA WCS). Writes mod/lidar-onsite/<name>.json: every 1 km tile within `search`
metres that holds data, cropped to its data, sampled every `step` metres as int16 centimetres (-32768 = no data).
Usage: python bake.py <name> <E> <N> [search_m=3000] [step_m=5]
"""
import sys, json, base64, os
import numpy as np
sys.path.insert(0, os.environ.get('LIDAR_MIRROR_SRC', 'lidar-mirror/src'))  # the private mirror store, set by the operator
import mirror_store as ms

ROOT = 'E:/lidar-mirror'
name, E, N = sys.argv[1], float(sys.argv[2]), float(sys.argv[3])
search = float(sys.argv[4]) if len(sys.argv) > 4 else 3000.0
step = int(sys.argv[5]) if len(sys.argv) > 5 else 5
patches = []
for te in range(int((E - search) // 1000) * 1000, int(E + search) + 1, 1000):
    for tn in range(int((N - search) // 1000) * 1000, int(N + search) + 1, 1000):
        tid = ms.tile_id(te, tn)
        meta, h = ms.read_tile(ROOT, tid, 'dtm')
        if meta is None:
            continue
        h = np.asarray(h)                                  # rows south->north, cell SW corner (e0+c, n0+r)
        ok = np.isfinite(h)
        if not ok.any():
            continue
        rows, cols = np.where(ok)
        r0, r1 = rows.min() // step * step, rows.max() // step * step
        c0, c1 = cols.min() // step * step, cols.max() // step * step
        sub = h[r0:r1 + 1:step, c0:c1 + 1:step]           # sample the cell at every step-th SW corner
        q = np.where(np.isfinite(sub), np.round(sub * 100), -32768).astype('<i2')
        patches.append(dict(tile=tid, e0=int(meta['e0'] + c0), n0=int(meta['n0'] + r0), step=step,
                            w=int(sub.shape[1]), h=int(sub.shape[0]), valid=int(ok.sum()),
                            min=float(np.nanmin(sub)), max=float(np.nanmax(sub)),
                            source=meta['source'].split(':')[0], survey_year=meta.get('survey_year'),
                            cm=base64.b64encode(q.tobytes()).decode()))
out = dict(name=name, E=E, N=N, search=search, step=step, product='dtm',
           credit='Contains Environment Agency LiDAR 1 m DTM, OGL v3 (local cache)', patches=patches)
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, name + '.json'), 'w') as f:
    json.dump(out, f)
idx = os.path.join(here, 'index.json')
lst = json.load(open(idx)) if os.path.exists(idx) else []
lst = [a for a in lst if a['name'] != name] + [dict(name=name, E=E, N=N, search=search)]
json.dump(lst, open(idx, 'w'))
print(name, len(patches), 'patches', [(p['tile'], p['w'], p['h'], p['valid']) for p in patches])

LiDAR Stream

A JavaScript file in the prototype folder of Energy Transition Simulator that maps LiDAR terrain, using EPSG:27700 and OSTN15. It saves day (`saveDay`), sets open (`setOpen`) and shows text (`showText`).

geodesyenergy-transition-simulator / prototype/mod/lidar-stream.js · lines 1–344 of 344 · Not reached from any entry point (candidate for review) · pattern fetchProduct (shared by 2 files)

What it does
It maps LiDAR terrain. Defines 29 functions or classes, including PF, wait, today, dayUsed, saveDay. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
What it achieves
Rule R5 (the site tile) in the browser. It responds to click, resize and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/mod · script
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
PF, wait, today, dayUsed, saveDay, panel, setOpen, summary, show, showText, frame, hAt
Defines here
PF, wait, today, dayUsed, saveDay, panel, setOpen, summary, show, showText, frame, hAt, exag, elevNow, terrainAt, demAt, heightAt, probe, walker, draw, X, ghost, satMode, sync, captions, place, fetchProduct, step, arrive
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/lidar-stream.js:1-344 · blob 8679b98c6ecc9a5f5056469a6d4d53991cb5d419 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: experimental · users: none · canonical: unreached_review
// lidar-stream: rule R5 (the site tile) in the browser. On ARRIVAL (a find or go ends, or Walk, Drone or Build here
// starts, or the "Stream ground" button), the 2,048 m lattice tile under the view centre is streamed from the
// Environment Agency WCS: the DTM first, the DSM at least 40 s later. Each is decoded in memory, turned into a
// wireframe and a receipt; the heights stay in memory only (for heightAt) and are never stored. Moving (walk, fly, pan, zoom) never asks the service.
// Ground: an 8 m wire grid of measured DTM heights, each node drawn at its own DTM height (ODN), not one anchor height. Above ground: DSM minus DTM over 1 m, as wire posts (derived).
// Coordinates: every node is a British National Grid cell centre (e0 + k + 0.5) turned into WGS84 by the
// overlay's one conversion (place-frame fromBng: OSTN15 where loaded, Helmert otherwise, and the label says which).
// Outside coverage the module says "no measured ground here" and draws nothing (never 0 m).
(function () {
  const HERE = document.currentScript ? document.currentScript.src : location.href;
  const STEP = 8, ABOVE_M = 1, DAY_KEY = 'lidarStream.day';
  const PF = () => window.__pf && window.__pf.PF;
  let R5 = null, pacer = null, fetchImpl = null, on = true, btn = null, box = null, gapOverride = null;
  const tiles = new Map(); // tile key -> { tile, dtm: {..}|null, dsm: {..}|null, blocks: [], status }
  let current = null, timer = null, arriving = false;
  function wait(f) { if (window.SIM && PF()) f(); else setTimeout(() => wait(f), 200); }
  const today = () => new Date().toISOString().slice(0, 10);
  function dayUsed() { try { const d = JSON.parse(localStorage.getItem(DAY_KEY) || '{}'); return d.date === today() ? d.used | 0 : 0; } catch (e) { return 0; } }
  function saveDay() { try { localStorage.setItem(DAY_KEY, JSON.stringify({ date: today(), used: pacer.state.used })); } catch (e) { /* private window */ } }

  // The receipt collapses to ONE dim line (tile + receipt sha8); a click on it opens the full receipt, licence and
  // attribution above it, a second click closes it. The line is placed clear of every visible caption (place()).
  let line = null, full = null, open = false;
  function panel() {
    if (box) return full;
    box = document.createElement('div'); box.id = 'lidar-stream-receipt';
    box.style.cssText = 'position:fixed;left:10px;bottom:8px;z-index:5;display:flex;flex-direction:column-reverse;align-items:flex-start;gap:4px;max-width:calc(100vw - 120px)';
    line = document.createElement('div'); line.id = 'lidar-stream-line'; line.title = 'Measured ground: click for the full receipt, licence and attribution';
    line.style.cssText = 'font:11px/15px system-ui,sans-serif;color:var(--dim,#8a9a9a);text-shadow:0 0 3px #000,0 0 1px #000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;cursor:pointer';
    full = document.createElement('div'); full.id = 'lidar-stream-full'; full.hidden = true;
    full.style.cssText = 'max-width:min(560px,calc(100vw - 32px));max-height:50vh;overflow:auto;font:11px/1.35 monospace;color:#dfe;background:rgba(0,0,0,.8);padding:6px 8px;border-radius:6px;white-space:pre-wrap;word-break:break-all';
    line.addEventListener('click', () => setOpen(!open));
    box.append(line, full); document.body.appendChild(box); return full;
  }
  function setOpen(v) { panel(); open = !!v; full.hidden = !open; place(); }
  function summary(t) {
    if (!t) return 'measured ground: arrive somewhere to stream its tile';
    const at = `tile ${t.tile.e0}/${t.tile.n0}`, d = t.dtm;
    if (d && d.sha) return `measured ground: EA LiDAR 1 m, ${at}, receipt ${d.sha.slice(0, 8)}${t.dsm && t.dsm.sha ? '' : t.status && t.status !== 'complete' ? ` (${t.status})` : ''}`;
    return `measured ground: ${at}, ${t.status || (d && d.none) || 'waiting'}`;
  }
  function show() { showText(); place(); }
  function showText() {
    const t = current && tiles.get(current), P = PF();
    panel(); line.textContent = summary(t);
    if (!t) { full.textContent = 'Measured ground (R5): arrive somewhere to stream its 2,048 m tile.'; return; }
    const eng = P && P.engine ? P.engine : (t.engine || '');
    const L = t.arrived ? [t.arrived] : [];
    L.push(`Measured ground, tile ${t.tile.e0} E ${t.tile.n0} N (2,048 m, EPSG:27700): ${t.status}`);
    for (const k of ['dtm', 'dsm']) {
      const r = t[k];
      if (!r) continue;
      if (r.none) { L.push(r.failed ? r.none : `${k.toUpperCase()}: no measured ground here (${r.none})`); continue; }
      if (r.pending) { L.push(`${k.toUpperCase()}: ${r.pending}`); continue; }
      L.push(`${k.toUpperCase()} receipt ${r.sha.slice(0, 12)}: ${r.src.product}, ${r.src.release}; survey year not read yet, so these heights count as pre-construction ground (R5 rule 9); ` +
        `box E ${r.box.e0}-${r.box.e1} N ${r.box.n0}-${r.box.n1}; fetched ${r.at}; ${(r.valid * 100).toFixed(1)}% cells measured; sha256(cells) ${r.sha}`);
    }
    if (t.lifted) L.push(`Near the walker (${LIFT_M} m): ${t.lifted} nodes lie under the coarser map DEM and are drawn at the DEM surface, DOTTED (estimated); solid = measured height.`);
    if (t.objects != null) L.push(`Above ground (DSM - DTM > ${ABOVE_M} m, derived): ${t.objects} posts on the ${STEP} m grid.`);
    L.push(`Placed by ${t.engine || eng || 'place-frame'}. ${R5 ? R5.LICENCE : ''} Source: Environment Agency.`);
    panel().textContent = L.join('\n');
  }

  // Tile -> local wire frame: exact at three control nodes, affine between them (OSTN15 varies by mm over 2 km).
  function frame(t) {
    const P = PF(), g = P.fromBng(t.e0 + 1024, t.n0 + 1024), anchor = P.placeKey(g.lat, g.lon);
    const o = P.bngToWire(anchor, t.e0, t.n0), ex = P.bngToWire(anchor, t.e0 + 2048, t.n0), ny = P.bngToWire(anchor, t.e0, t.n0 + 2048);
    const ax = (ex.x - o.x) / 2048, ay = (ex.y - o.y) / 2048, bx = (ny.x - o.x) / 2048, by = (ny.y - o.y) / 2048;
    return { anchor, engine: g.engine || '', xy: (e, n) => { const de = e - t.e0, dn = n - t.n0; return [o.x + ax * de + bx * dn, o.y + ay * de + by * dn]; } };
  }
  // Height at cell (i, j) counted from the tile's SW corner, or NaN (unmeasured or outside the box).
  function hAt(r, i, j) {
    if (!r || r.none || r.pending) return NaN;
    const c = r.tile.e0 + i - r.geo.west, rr = r.geo.north - (r.tile.n0 + j) - 1;
    if (c < 0 || rr < 0 || c >= r.geo.width || rr >= r.geo.height) return NaN;
    const k = rr * r.geo.width + c; return r.mask[k] ? r.geo.data[k] : NaN;
  }
  // Terrain exaggeration: MapLibre 4.7 returns queryTerrainElevation multiplied by the exaggeration and relative to the
  // centre's elevation (transform.elevation, also exaggerated). terrainAt is the RENDER lift in that same frame, so it
  // must stay exactly what perf.js adds (the per-node cancellation H - gz + gz = H needs the same number on both sides).
  // demAt is the map DEM in true metres (ODN), divided by the exaggeration like coords-readout.js, for DEM vs DTM.
  const exag = () => { const m = window.SIM.map, t = m.getTerrain && m.getTerrain(); return (t && t.exaggeration) || 1; };
  const elevNow = () => (window.SIM.map.transform && window.SIM.map.transform.elevation) || 0;
  function terrainAt(lon, lat) { const m = window.SIM.map; return (m.queryTerrainElevation && m.queryTerrainElevation([lon, lat])) || 0; }
  function demAt(lon, lat) {
    const m = window.SIM.map; if (!(m.getTerrain && m.getTerrain() && m.queryTerrainElevation)) return null;
    const v = m.queryTerrainElevation([lon, lat]); return v == null ? null : (v + (m.transform.elevation || 0)) / exag();
  }
  // The measured DTM height (m, ODN) of the 1 m cell holding (e, n), with the receipt it came from; null outside.
  function heightAt(e, n) {
    for (const t of tiles.values()) {
      const r = t.dtm; if (!r || r.none || r.pending) continue;
      const i = Math.floor(e - t.tile.e0), j = Math.floor(n - t.tile.n0);
      if (i < 0 || j < 0 || i >= 2048 || j >= 2048) continue;
      const h = hAt(r, i, j);
      return Number.isFinite(h) ? { h, receipt: r.sha.slice(0, 12), prov: 'measured', cell: [t.tile.e0 + i, t.tile.n0 + j] } : { h: null, receipt: r.sha.slice(0, 12), why: 'cell not measured' };
    }
    return { h: null, why: 'no streamed tile here' };
  }
  // Datum probe: for up to n wire nodes, the height the GPU draws (buffer z + the overlay's live anchor lift, in
  // metres at the node) minus heightAt at the node. Also the map DEM at the node minus heightAt (for information).
  function probe(n = 200) {
    const P = PF(), out = [];
    for (const [key, t] of tiles) {
      if (!t.H) continue;
      const blk = (t.blks || []).find(b => b.kind === 'ground'); if (!blk) continue;
      const idx = []; for (let k = 0; k < t.N * t.N; k++) if (t.seg[k] >= 0) idx.push(k);
      const gzNow = terrainAt(t.anchor.lon, t.anchor.lat), stride = Math.max(1, Math.floor(idx.length / n));
      for (let q = 0; q < idx.length && out.length < n; q += stride) {
        const k = idx[q], a = k % t.N, b = (k - a) / t.N, e = t.tile.e0 + a * STEP + STEP / 2 + 0.5, nn = t.tile.n0 + b * STEP + STEP / 2 + 0.5;
        const g = P.fromBng(e, nn), mz = blk.buf[6 * t.seg[k] + 2] + P.toMercator(t.anchor.lat, t.anchor.lon, gzNow + elevNow()).z; // back to ODN
        const drawn = mz / P.toMercator(g.lat, g.lon, 1).z, truth = heightAt(e, nn);
        out.push({ e, n: nn, drawn, truth: truth.h, D: drawn - truth.h, demD: demAt(g.lon, g.lat) == null ? null : demAt(g.lon, g.lat) - truth.h, receipt: truth.receipt });
      }
    }
    const D = out.map(o => Math.abs(o.D)), exaggeration = exag(), dm = out.filter(o => o.demD != null), M = dm.map(o => Math.abs(o.demD));
    return { nodes: out.length, maxAbsD: Math.max(...D), meanD: out.reduce((s, o) => s + o.D, 0) / (out.length || 1),
      demNodes: dm.length, maxAbsDemD: M.length ? Math.max(...M) : null, meanDemD: dm.length ? dm.reduce((s, o) => s + o.demD, 0) / dm.length : null, receipt: out[0] && out[0].receipt, exaggeration, sample: out.slice(0, 3) };
  }
  // The walker: the camera's ground point in BNG (Walk and Drone stand the camera there), or null before a map frame.
  const LIFT_M = 150, DOTS = 4, LIFT_CLEAR = 0.25; // 0.25 m over the DEM: a line lying exactly on the DEM mesh z-fights it (seen r8)
  function walker() {
    const T = window.SIM.map.transform, cp = T.getCameraPosition && T.getCameraPosition();
    if (!cp || !cp.lngLat) return null; const g = PF().toBng(cp.lngLat.lat, cp.lngLat.lng); return { e: g.e, n: g.n };
  }
  function draw(key) {
    const t = tiles.get(key), S = window.SIM, P = PF();
    S.removeWhere(b => b.lidarStream === key); if (t) t.blks = [];
    if (!t || !t.dtm || t.dtm.none || t.dtm.pending) return;
    const f = frame(t.tile); t.engine = f.engine;
    const N = 2048 / STEP;
    // HEIGHT DATUM: the overlay lifts every block by the map terrain at its anchor (gz). Each vertex is written as
    // (its own DTM height - gz), so on screen every node sits at its own measured height (ODN), never at one anchor
    // height per block. gz is re-read when the map goes idle and the block is rebuilt if it moved (terrain loading).
    // FRAME (r3): MapLibre 4.7 custom layers draw in a frame whose zero is the centre's elevation (transform.elevation,
    // E), and gz is relative to E too. So a vertex is (H - gz - E): drawn = H - gz - E + gz = H - E, the node at its
    // own measured height in the map's frame. Without E the wire floated E metres up once E was set (Walk: a band overhead).
    const gz = terrainAt(f.anchor.lon, f.anchor.lat), E = elevNow(), base = gz + E;
    const H = new Float32Array(N * N), seg = new Int32Array(N * N).fill(-1);
    for (let b = 0; b < N; b++) for (let a = 0; a < N; a++) H[b * N + a] = hAt(t.dtm, a * STEP + STEP / 2, b * STEP + STEP / 2);
    // NEAR LIFT (r8): within LIFT_M of the walker, a node the map DEM covers is drawn at max(DTM, DEM), because the
    // coarse DEM mesh sits up to ~2 m over the 1 m DTM there and at eye height no depth bias can see under it (r6, r7).
    // (plus LIFT_CLEAR, so the lifted line is not coplanar with the DEM mesh)
    // Every segment touching a lifted node is ESTIMATED (drawn at the DEM, not where it was measured), so it goes to a
    // separate ghost block drawn DOTTED; nodes at their measured height stay in the solid measured block.
    const Z = new Float32Array(H), lift = new Uint8Array(N * N), wk = walker(); let nLift = 0;
    if (wk) {
      const a0 = Math.max(0, Math.floor((wk.e - t.tile.e0 - LIFT_M) / STEP)), a1 = Math.min(N - 1, Math.ceil((wk.e - t.tile.e0 + LIFT_M) / STEP));
      const b0 = Math.max(0, Math.floor((wk.n - t.tile.n0 - LIFT_M) / STEP)), b1 = Math.min(N - 1, Math.ceil((wk.n - t.tile.n0 + LIFT_M) / STEP));
      for (let b = b0; b <= b1; b++) for (let a = a0; a <= a1; a++) {
        const k = b * N + a, e = t.tile.e0 + a * STEP + STEP / 2 + 0.5, n = t.tile.n0 + b * STEP + STEP / 2 + 0.5;
        if (!Number.isFinite(H[k]) || Math.hypot(e - wk.e, n - wk.n) > LIFT_M) continue;
        const g = P.fromBng(e, n), d = demAt(g.lon, g.lat);
        if (d != null && d + LIFT_CLEAR > H[k]) { Z[k] = Math.max(H[k], d + LIFT_CLEAR); lift[k] = 1; nLift++; }
      }
    }
    const X = (a, b) => { const c = STEP / 2, p = f.xy(t.tile.e0 + a * STEP + c + 0.5, t.tile.n0 + b * STEP + c + 0.5); return [p[0], p[1], Z[b * N + a] - base]; };
    const L = [], G = []; let gSegs = 0;
    const ghost = (p, q) => { gSegs++; for (let s = 0; s < DOTS; s++) { const u = s / DOTS, v = (s + 0.5) / DOTS; // dotted: half of each 1/DOTS step drawn
      G.push([p[0] + (q[0] - p[0]) * u, p[1] + (q[1] - p[1]) * u, p[2] + (q[2] - p[2]) * u, p[0] + (q[0] - p[0]) * v, p[1] + (q[1] - p[1]) * v, p[2] + (q[2] - p[2]) * v]); } };
    for (let b = 0; b < N; b++) for (let a = 0; a < N; a++) {
      if (!Number.isFinite(H[b * N + a])) continue; const p = X(a, b), k0 = L.length, lp = lift[b * N + a];
      if (a + 1 < N && Number.isFinite(H[b * N + a + 1])) { const q = X(a + 1, b); if (lp || lift[b * N + a + 1]) ghost(p, q); else L.push([p[0], p[1], p[2], q[0], q[1], q[2]]); }
      if (b + 1 < N && Number.isFinite(H[(b + 1) * N + a])) { const q = X(a, b + 1); if (lp || lift[(b + 1) * N + a]) ghost(p, q); else L.push([p[0], p[1], p[2], q[0], q[1], q[2]]); }
      if (L.length > k0) seg[b * N + a] = k0;
    }
    t.gz = gz; t.E = E; t.H = H; t.seg = seg; t.N = N; t.anchor = f.anchor; t.wk = wk; t.lifted = nLift;
    t.blks.push({ lon: f.anchor.lon, lat: f.anchor.lat, anchor: f.anchor, lines: L, buf: P.wireBuffer(f.anchor, L), lidarStream: key,
      prov: 'measured', receipt: t.dtm.sha, kind: 'ground', gz, E });
    if (G.length) t.blks.push({ lon: f.anchor.lon, lat: f.anchor.lat, anchor: f.anchor, lines: G, buf: P.wireBuffer(f.anchor, G), lidarStream: key,
      prov: 'estimated', style: 'ghost', segs: gSegs, receipt: t.dtm.sha, kind: 'ground', lifted: nLift, gz, E });
    t.segs = L.length + gSegs;
    if (t.dsm && !t.dsm.none && !t.dsm.pending) {
      const O = []; let n = 0;
      for (let b = 0; b < N; b++) for (let a = 0; a < N; a++) {
        let top = -Infinity, gi = NaN;
        for (let v = 0; v < STEP; v++) for (let u = 0; u < STEP; u++) {
          const i = a * STEP + u, j = b * STEP + v, s = hAt(t.dsm, i, j), g = hAt(t.dtm, i, j);
          if (Number.isFinite(s) && Number.isFinite(g) && s - g > top) { top = s - g; gi = g; }
        }
        if (!(top > ABOVE_M)) continue;
        n++;
        const p = f.xy(t.tile.e0 + a * STEP + STEP / 2 + 0.5, t.tile.n0 + b * STEP + STEP / 2 + 0.5), z0 = gi - base, z1 = z0 + top, d = 2;
        O.push([p[0], p[1], z0, p[0], p[1], z1],
          [p[0] - d, p[1] - d, z1, p[0] + d, p[1] - d, z1], [p[0] + d, p[1] - d, z1, p[0] + d, p[1] + d, z1],
          [p[0] + d, p[1] + d, z1, p[0] - d, p[1] + d, z1], [p[0] - d, p[1] + d, z1, p[0] - d, p[1] - d, z1]);
      }
      t.objects = n;
      if (O.length) t.blks.push({ lon: f.anchor.lon, lat: f.anchor.lat, anchor: f.anchor, lines: O, buf: P.wireBuffer(f.anchor, O), lidarStream: key,
        prov: 'derived', receipt: t.dsm.sha, kind: 'above-ground', gz, E });
    }
    sync();
  }

  // LAYER ORDER. Wire and Dark: the blocks ride the overlay's solid wire layer, as before. Satellite: they move to this
  // module's own layer, drawn above the imagery in the same colour (still solid, continuous lines = measured) but at
  // alpha SAT_ALPHA with no depth write, so the satellite stays visible through the 8 m grid at close range.
  // DEPTH_BIAS (r3): the map DEM is coarser than the 1 m DTM and sits up to ~2 m above measured nodes at the walker, so
  // a plain depth test hid the near wire at grazing angles. The bias moves only the depth (NDC z, same for x and y, so
  // every line stays exactly where it was measured on screen); in metres it grows with distance, and hills still hide.
  // r5: 0.0006 let 60/3,993 nodes behind a synthetic 180 m ridge show at the crest (1.5 %); 0.0005 draws 2 (0.05 %),
  // with 2,288/2,301 visible far nodes still drawn (tests/lidar-stream.cjs, ridge check).
  // r6 (near check, DEM 2 m over DTM, eye ~3.4 m over DTM): nodes 20-300 m that clear the DTM by >= 3 m are all drawn
  // (70/70 at 0.0004-0.0006, 0/70 with no bias), but only ~56 % of the foreground (716/1,274) is drawn at 0.0005: a
  // constant NDC bias is a few cm near the eye, so the nearest wire under a raised DEM is still lost (fixed r8: NEAR LIFT).
  // r7: a metric pull (depth taken 2.5 m toward the eye, x/y unpulled) was tried and REVERTED: ridge 0/3,993 hidden and
  // 2,285/2,301 visible, but near 0/70 visible and 0/1,274 foreground. At eye height the ray meets a DEM 2 m high tens
  // of metres before the node, so any fixed pull along the ray is far too short; the fix is geometry, not depth.
  const SAT_ALPHA = 0.35, sat = [], DEPTH_BIAS = 0.0005;
  const satMode = () => { const m = window.SIM.map; return !!(m.getSource && m.getSource('sat')); };
  const layer = { id: 'lidar-stream-sat', type: 'custom', renderingMode: '3d',
    onAdd(m, gl) { const sh = (ty, src) => { const o = gl.createShader(ty); gl.shaderSource(o, src); gl.compileShader(o); return o; };
      this.pr = gl.createProgram();
      gl.attachShader(this.pr, sh(gl.VERTEX_SHADER, 'uniform mat4 u; uniform float k; attribute vec3 p; void main(){ gl_Position = u * vec4(p, 1.0); gl_Position.z -= k * gl_Position.w; }'));
      gl.attachShader(this.pr, sh(gl.FRAGMENT_SHADER, 'precision mediump float; uniform vec4 c; void main(){ gl_FragColor = c; }'));
      gl.linkProgram(this.pr); this.vbo = new WeakMap(); },
    render(gl, args) {
      if (!sat.length) return;
      const m = (args && args.defaultProjectionData && args.defaultProjectionData.mainMatrix) || args, P = PF(), loc = gl.getAttribLocation(this.pr, 'p');
      gl.useProgram(this.pr); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
      gl.uniform4f(gl.getUniformLocation(this.pr, 'c'), 0.55, 0.9, 1.0, SAT_ALPHA); gl.uniform1f(gl.getUniformLocation(this.pr, 'k'), DEPTH_BIAS);
      for (const b of sat) {
        let v = this.vbo.get(b); if (!v) { v = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, v); gl.bufferData(gl.ARRAY_BUFFER, b.buf, gl.STATIC_DRAW); this.vbo.set(b, v); }
        const o = P.toMercator(b.anchor.lat, b.anchor.lon, b.gz + (b.E || 0) - elevNow()), r = new Float32Array(m); // build lift, kept in the live frame as E moves
        for (let k = 0; k < 4; k++) r[12 + k] = m[k] * o.x + m[4 + k] * o.y + m[8 + k] * o.z + m[12 + k];
        gl.bindBuffer(gl.ARRAY_BUFFER, v); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
        gl.uniformMatrix4fv(gl.getUniformLocation(this.pr, 'u'), false, r); gl.drawArrays(gl.LINES, 0, b.buf.length / 3);
      }
      gl.depthMask(true);
    } };
  function sync() {
    const S = window.SIM, s = satMode();
    S.removeWhere(b => b.lidarStream); sat.length = 0;
    for (const t of tiles.values()) for (const b of t.blks || []) if (s) sat.push(b); else S.addBlock(b);
    try { if (!S.map.getLayer(layer.id)) S.map.addLayer(layer); } catch (e) { /* style still loading; style.load re-adds */ }
    S.repaint();
  }
  // The one-line receipt never covers a caption: it starts just above the attribution strip and steps up above any
  // VISIBLE caption it would touch (#where, #sim-note, the pylon and procedural captions, anything fixed at the foot).
  function captions() {
    const out = [];
    for (const el of document.body.querySelectorAll('body > *, body > * > [id]')) {
      if (el === box || box.contains(el) || el.id === 'sim-menu' || el.tagName === 'SCRIPT' || !el.textContent.trim()) continue;
      const cs = getComputedStyle(el); if (cs.position !== 'fixed' && cs.position !== 'absolute') continue;
      if (el.checkVisibility && !el.checkVisibility({ checkOpacityProperty: true, checkVisibilityCSS: true })) continue;
      const r = el.getBoundingClientRect(); if (r.width > 0 && r.height > 0 && r.top > innerHeight / 2) out.push(r);
    }
    return out;
  }
  function place() {
    if (!box) return;
    let bottom = 0; const cs = captions();
    for (let k = 0; k < 12; k++) {
      box.style.bottom = bottom + 'px';
      const a = line.getBoundingClientRect(), hit = cs.find(c => a.left < c.right && c.left < a.right && a.top < c.bottom && c.top < a.bottom);
      if (!hit) break; bottom = Math.ceil(innerHeight - hit.top + 3);
    }
  }
  async function fetchProduct(key, k) {
    const t = tiles.get(key), src = R5.SOURCES[k], b = R5.clip(t.tile, src.env);
    if (!b) { t[k] = { none: 'outside the service envelope' }; return; }
    if (!pacer.take()) return; // caller checked why() first
    saveDay();
    const url = R5.wcsUrl(src, b), at = new Date().toISOString(); let status = 0;
    t[k] = { pending: 'streaming...' }; show();
    try {
      const res = await (fetchImpl || fetch)(url, { mode: 'cors' }); status = res.status;
      if (!res.ok) throw Error(`HTTP ${res.status}${res.status === 403 || res.status === 429 ? ', refused; pausing' : ''}`);
      const geo = await R5.decodeGeoTiff(await res.arrayBuffer()), m = R5.measuredMask(geo);
      if (!m.valid) { t[k] = { none: 'no survey: sea, not flown, or a border (exact zeros)' }; return; }
      const sha = await R5.cellSha256(geo.data, crypto.subtle);
      t[k] = { src, box: b, url, at, geo, mask: m.mask, valid: m.frac, sha, tile: t.tile };
    } catch (e) {
      // Status 0 = the request never got an HTTP answer (network, abort, or a response the browser refused). One retry,
      // in this arrival only, through the pacer (40 s gap); movement never triggers it. 403/429 go to the pause via done().
      const reason = (e && e.message) || 'network error';
      t.tries = t.tries || {};
      if (status === 0 && !t.tries[k]) { t.tries[k] = 1; t[k] = null; t.retryNote = `${k.toUpperCase()} fetch failed (${reason}); retrying once`; }
      else if (status === 0) t[k] = { none: `${k.toUpperCase()} fetch failed (${reason}); no measured ground shown`, failed: true };
      else t[k] = { none: e.message };
    } finally { pacer.done(status); if (gapOverride != null) pacer.state.next = Date.now() + gapOverride; }
  }

  function step() {
    clearTimeout(timer); timer = null;
    const t = current && tiles.get(current);
    if (!t || !on) return;
    const need = !t.dtm ? 'dtm' : (!t.dsm && t.dtm && !t.dtm.none && !t.dtm.pending) ? 'dsm' : null;
    if (!need) { t.status = t.dtm && t.dtm.failed ? t.dtm.none : t.dtm && t.dtm.none ? 'no measured ground here' : 'complete'; show(); return; }
    const why = pacer.why(), retry = t.tries && t.tries[need] ? `${t.retryNote}: ` : '';
    if (why) {
      t.status = `${retry}${need.toUpperCase()} ${why}`; show();
      if (!pacer.state.stopped && !/daily cap/.test(why)) timer = setTimeout(step, 1000);
      return;
    }
    t.status = `${retry}streaming the ${need.toUpperCase()}`; show();
    const key = current;
    fetchProduct(key, need).then(() => { draw(key); if (current === key) step(); show(); });
  }

  // ARRIVAL: the only place that may start a fetch (R5 rule 6). Stored wireframe first (rule 5).
  function arrive(why) {
    if (!on || !R5) return null;
    const S = window.SIM, P = PF(), c = S.map.getCenter(), g = P.toBng(c.lat, c.lng), tile = R5.tileOf(g.e, g.n);
    current = tile.key;
    if (!tiles.has(tile.key)) tiles.set(tile.key, { tile, dtm: null, dsm: null, status: `arrived (${why})` });
    const t = tiles.get(tile.key);
    if (!R5.clip(tile, R5.SOURCES.dtm.env)) { t.dtm = { none: 'outside the EA LiDAR envelope (England only)' }; t.status = 'no measured ground here'; }
    // The arrival line lives only in this module's own receipt panel; #info (the landing caption) is never touched.
    t.arrived = `Arrived (${why}): measured ground for tile ${tile.e0} E ${tile.n0} N streams here; moving never fetches.`;
    show(); step(); return tile;
  }

  wait(async () => {
    const S = window.SIM;
    R5 = await import(new URL('lidar-stream/r5.mjs', HERE).href);
    pacer = R5.createPacer({ used: dayUsed() });
    btn = S.addButton ? S.addButton('Stream ground', () => arrive('button')) : null;
    // Arrival hooks, no edits to the overlay: a flyTo (find/go) that ends, and the Walk, Drone and Build here buttons.
    const fly = S.map.flyTo.bind(S.map);
    S.map.flyTo = (...a) => { arriving = true; return fly(...a); };
    S.map.on('style.load', sync);
    const inf = document.getElementById('info'); if (inf && window.MutationObserver) new MutationObserver(place).observe(inf, { childList: true, characterData: true, subtree: true });
    addEventListener('resize', place); setInterval(place, 1000); // captions come and go (the 8 s note); cheap
    addEventListener('keydown', e => { if (e.key === 'Escape' && open) setOpen(false); });
    S.map.on('idle', () => { for (const [k, t] of tiles) { const w = walker(), moved = w && (!t.wk || Math.hypot(w.e - t.wk.e, w.n - t.wk.n) > STEP);
      if (t.H && (moved || Math.abs(terrainAt(t.anchor.lon, t.anchor.lat) - t.gz) > 0.01 || Math.abs(elevNow() - (t.E || 0)) > 0.01)) draw(k); } });
    S.map.on('moveend', () => { if (arriving) { arriving = false; arrive('find or go'); } });
    for (const [id, w] of [['walk', 'Walk'], ['drone', 'Drone'], ['here', 'Build here']]) {
      const el = document.getElementById(id); if (el) el.addEventListener('click', () => setTimeout(() => arrive(w), 1200));
    }
    show();
    window.__lidarStream = {
      arrive, tiles, heightAt, probe, pacer: () => pacer.state, R5: () => R5,
      // Tests and local checks only: serve a fixture instead of the EA; the gap may be shortened ONLY with a fixture.
      useFixture(fn, gapMs) { fetchImpl = fn; gapOverride = gapMs == null ? null : gapMs; pacer.state.next = 0; },
      segs: () => [...tiles.values()].flatMap(t => t.blks || []).reduce((s, b) => s + b.lines.length, 0),
      layer: () => ({ satellite: satMode(), own: sat.length, inWire: S.blocks.filter(b => b.lidarStream).length, alpha: SAT_ALPHA, onMap: !!S.map.getLayer(layer.id) }),
      line: () => { panel(); return { text: line.textContent, rect: line.getBoundingClientRect().toJSON(), open }; }, setOpen, place,
      blocks: () => [...tiles.values()].flatMap(t => t.blks || []).map(b => ({ kind: b.kind, prov: b.prov, style: b.style || 'solid', segs: b.segs || b.lines.length, lifted: b.lifted || 0, receipt: b.receipt, lat: b.lat, lon: b.lon, n: b.lines.length })),
      receipt: () => panel().textContent  // the full receipt (shown on click)
    };
  });
})();

R5

A JavaScript module in the LiDAR stream folder of Energy Transition Simulator covering LiDAR terrain, using EPSG:27700 and SHA-256 and uses data from Environment Agency.

ingestenergy-transition-simulator / prototype/mod/lidar-stream/r5.mjs · lines 1–186 of 186 · Not reached from any entry point (candidate for review) · pattern decodeGeoTiff (shared by 2 files)

What it does
Defines 11 functions or classes, including tileOf, clip, wcsUrl, measuredMask, bad.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: LiDAR terrain.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It creates pacer (`createPacer`), reads tags (`readTags`) and decodes geo tiff (`decodeGeoTiff`). R5 site tile, the pure part: lattice maths, the two EA WCS source cards, the GeoTIFF decoder, the coverage test and the receipt hash.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/mod/lidar-stream · JavaScript module
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
TILE_M, GAP_MS, LICENCE, SOURCES, tileOf, clip, wcsUrl, ZERO_RUN, measuredMask, cellSha256, createPacer, decodeGeoTiff
Defines here
tileOf, clip, wcsUrl, measuredMask, bad, cellSha256, createPacer, readTags, inflate, decodeGeoTiff, synthTiff
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/lidar-stream/r5.mjs:1-186 · blob ca130380a436e293e90199e1d4a2387778dd782a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
// R5 site tile, the pure part: lattice maths, the two EA WCS source cards, the GeoTIFF decoder, the coverage test
// and the receipt hash. No DOM, no network. Used by mod/lidar-stream.js in the browser and by tests/lidar-stream.cjs.
//
// decodeGeoTiff is copied from the lidar-wire repo, web/world/wcs-terrain.mjs at commit 4da605f (26 Sept 2026),
// which reads exactly what the EA WCS sends (classic TIFF, one 32-bit float band, uncompressed or deflate).

export const TILE_M = 2048; // R5 rule 1: fixed 2,048 m tiles on a 2,048 m lattice of EPSG:27700
export const GAP_MS = 40000, DAY_CAP = 16, PAUSE_MS = 300000, PAUSE_MAX_MS = 3600000; // R5 rule 3
export const LICENCE = 'Contains Environment Agency information © Environment Agency and database right. Open Government Licence v3.0.';

// Source cards. Envelopes are from the services' own GetCapabilities (EPSG:27700). The DSM URL and coverage id
// were read from the data.gov.uk catalogue and the service's GetCapabilities on 27 Sept 2026 (the earlier guess
// .../lidar-composite-first-return-digital-surface-model-fz-dsm-1m/wcs answered 404).
export const SOURCES = Object.freeze({
  dtm: Object.freeze({
    product: 'LIDAR Composite DTM 1 m', release: 'composite (release not stated by the service)',
    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',
    env: Object.freeze({ e0: 80000, n0: 4000, e1: 656000, n1: 665000 })
  }),
  dsm: Object.freeze({
    product: 'LIDAR Composite First Return DSM 1 m', release: 'composite (release not stated by the service)',
    url: 'https://environment.data.gov.uk/spatialdata/lidar-composite-digital-surface-model-first-return-dsm-1m/wcs',
    coverage: 'df4e3ec3-315e-48aa-aaaf-b5ae74d7b2bb__Lidar_Composite_Elevation_FZ_DSM_1m',
    env: Object.freeze({ e0: 133000, n0: 11000, e1: 656000, n1: 657601 })
  })
});

// The lattice tile holding (e, n): south-west corner on the 2,048 m lattice. Cell k: SW corner e0 + k, centre e0 + k + 0.5.
export function tileOf(e, n) {
  const e0 = Math.floor(e / TILE_M) * TILE_M, n0 = Math.floor(n / TILE_M) * TILE_M;
  return { key: `${e0}_${n0}`, e0, n0, e1: e0 + TILE_M, n1: n0 + TILE_M };
}
// The tile clipped to a service envelope (whole metres), or null when nothing is left.
export function clip(t, env) {
  const e0 = Math.max(t.e0, Math.ceil(env.e0)), n0 = Math.max(t.n0, Math.ceil(env.n0));
  const e1 = Math.min(t.e1, Math.floor(env.e1)), n1 = Math.min(t.n1, Math.floor(env.n1));
  return e1 > e0 && n1 > n0 ? { e0, n0, e1, n1 } : null;
}
export function wcsUrl(src, b) {
  return `${src.url}?service=WCS&version=2.0.1&request=GetCoverage&CoverageId=${src.coverage}` +
    `&subset=E(${b.e0},${b.e1})&subset=N(${b.n0},${b.n1})&format=image/tiff`;
}

// Measured-cell test (R5 rule 10): nodata, non-finite and absurd values are not ground. Without a nodata tag, a run
// of ZERO_RUN or more exact zeros along a row (sea, not flown, a border) is not ground either; a whole box of
// zeros therefore has no measured ground at all. Never 0 m.
export const ZERO_RUN = 16;
export function measuredMask(geo) {
  const { data, width: w, height: h } = geo, m = new Uint8Array(w * h);
  const bad = v => !Number.isFinite(v) || (geo.hasNodata && v === geo.nodata) || v < -1e30 || v > 1e5;
  for (let r = 0; r < h; r++) {
    let run = 0;
    for (let c = 0; c <= w; c++) {
      const v = c < w ? data[r * w + c] : NaN;
      if (c < w && v === 0 && !geo.hasNodata) { run++; continue; }
      if (run) { const keep = run < ZERO_RUN ? 1 : 0; for (let k = c - run; k < c; k++) m[r * w + k] = keep; run = 0; }
      if (c < w) m[r * w + c] = bad(v) ? 0 : 1;
    }
  }
  let valid = 0; for (const x of m) valid += x;
  return { mask: m, valid, frac: valid / (w * h) };
}

// Receipt hash (R5 rule 4): sha256 of the decoded cell values (Float32, little-endian, rows north to south),
// not of the file bytes. subtle: a SubtleCrypto (browser crypto.subtle, or node's webcrypto.subtle).
export async function cellSha256(data, subtle) {
  const u = new Uint8Array(data.length * 4), dv = new DataView(u.buffer);
  for (let i = 0; i < data.length; i++) dv.setFloat32(i * 4, data[i], true);
  const d = await subtle.digest('SHA-256', u);
  return [...new Uint8Array(d)].map(x => x.toString(16).padStart(2, '0')).join('');
}

// Polite pace (R5 rule 3), shared by both products: one at a time, GAP_MS apart, DAY_CAP a day, a doubling
// pause on refusal, and a stop that needs a person after a refusal at the longest pause.
export function createPacer({ clock = () => Date.now(), used = 0 } = {}) {
  const s = { inFlight: false, next: 0, pausedUntil: 0, pause: PAUSE_MS, stopped: false, used };
  return {
    state: s,
    why(now = clock()) {
      if (s.stopped) return 'stopped after repeated refusals; a person must restart it';
      if (s.used >= DAY_CAP) return `daily cap of ${DAY_CAP} requests reached`;
      if (s.inFlight) return 'another request is in flight';
      if (now < s.pausedUntil) return `paused ${Math.ceil((s.pausedUntil - now) / 60000)} min after a refusal`;
      if (now < s.next) return `waiting ${Math.ceil((s.next - now) / 1000)} s (40 s gap)`;
      return '';
    },
    take() { const now = clock(); if (this.why(now)) return false; s.inFlight = true; s.used++; return true; },
    done(status) {
      const now = clock(); s.inFlight = false; s.next = now + GAP_MS;
      if (status === 403 || status === 429) {
        if (s.pause > PAUSE_MAX_MS) s.stopped = true;
        s.pausedUntil = now + Math.min(s.pause, PAUSE_MAX_MS); s.pause *= 2;
      } else if (status >= 200 && status < 300) s.pause = PAUSE_MS;
    }
  };
}

// ---- GeoTIFF (copied, see header) ----------------------------------------------------------------
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, hasNodata, 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 synthetic GeoTIFF in the EA's form (big-endian, one strip, float32, ModelPixelScale + ModelTiepoint, and
// GDAL_NODATA unless nodata is null), for tests only. fn(i, j): height of cell column i, row j (row 0 = north edge).
export function synthTiff(west, north, w, h, fn, nodata = '-3.4028234663852886E38') {
  const nd = nodata == null ? null : nodata + '\0';
  const tags = [[256, 4, [w]], [257, 4, [h]], [258, 3, [32]], [259, 3, [1]], [262, 3, [1]], [273, 4, [0]], [277, 3, [1]],
    [278, 4, [h]], [279, 4, [w * h * 4]], [339, 3, [3]], [33550, 12, [1, 1, 0]], [33922, 12, [0, 0, 0, west, north, 0]]];
  if (nd) tags.push([42113, 2, [...nd].map(c => c.charCodeAt(0))]);
  const sz = { 2: 1, 3: 2, 4: 4, 12: 8 }, ifdAt = 8, ifdLen = 2 + tags.length * 12 + 4;
  let extra = ifdAt + ifdLen;
  const ext = tags.map(([, t, v]) => { const n = sz[t] * v.length; if (n <= 4) return -1; const a = extra; extra += n; return a; });
  const pix = extra, buf = new ArrayBuffer(pix + w * h * 4), dv = new DataView(buf);
  dv.setUint8(0, 0x4d); dv.setUint8(1, 0x4d); dv.setUint16(2, 42); dv.setUint32(4, ifdAt); dv.setUint16(ifdAt, tags.length);
  tags.forEach(([tag, t, v], k) => {
    const p = ifdAt + 2 + k * 12, vals = tag === 273 ? [pix] : v;
    dv.setUint16(p, tag); dv.setUint16(p + 2, t); dv.setUint32(p + 4, vals.length);
    let at = ext[k] < 0 ? p + 8 : ext[k];
    if (ext[k] >= 0) dv.setUint32(p + 8, at);
    for (const x of vals) { if (t === 2) dv.setUint8(at, x); else if (t === 3) dv.setUint16(at, x); else if (t === 4) dv.setUint32(at, x); else dv.setFloat64(at, x); at += sz[t]; }
  });
  for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) dv.setFloat32(pix + (j * w + i) * 4, fn(i, j));
  return new Uint8Array(buf);
}