GLOBALGRID2050 / EXPLORE CODE

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

Flow and 2 more files

A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), decodes hollow tile (`decodeHollowTile`), loads index (`loadIndex`) and calculates planar distances, using SHA-256.

635 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 155 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. Flow ingest · globalgrid2050 / solar-design-studio/202609270439-site-world/world/layers/flow.mjs lines 1–352
  2. Shade ingest · globalgrid2050 / solar-design-studio/202609270439-site-world/world/layers/shade.mjs lines 1–199
  3. Phases Design transform · globalgrid2050 / solar-design-studio/202609270439-site-world/world/phases-design.mjs lines 1–84

Flow

A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), decodes hollow tile (`decodeHollowTile`), loads index (`loadIndex`) and calculates planar distances, using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609270439-site-world/world/layers/flow.mjs · lines 1–352 of 352 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern decodeHollowTile (shared by 2 files)

What it does
It lists and searches flow tiles and LiDAR terrain. Defines 24 functions or classes, including setIndexSha, decodeFlowTile, fits, looksEsri, colorFor.
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: LiDAR terrain.
Inputs & outputs
In: JSON file flow-tiles.json.
What it achieves
It sets index sha (`setIndexSha`), decodes flow tile (`decodeFlowTile`) and decodes hollow tile (`decodeHollowTile`). The natural drainage lines: every cell whose log-accumulation class is at or above a chosen class, drawn as a short downhill segment to the cell it drains into (D8), draped just above the ground, brighter as the flow grows.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world/layers · JavaScript module
Uses
none found
Used by
none found
Produces
LABEL, HOLLOW_LABEL, GPH_MAGIC, setIndexSha, HEADER_BYTES, DEFAULT_MIN_CLASS, LOAD_RADIUS, LIFT_M, HOLLOW_COLOR, decodeFlowTile, STEP, colorFor
Defines here
setIndexSha, decodeFlowTile, fits, looksEsri, colorFor, segments, decodeHollowTile, hollowMask, hollowOutline, inside, seg, finite, rectDist, createFlow, now, say, loadIndex, loadHollows, ready, empty, 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/202609270439-site-world/world/layers/flow.mjs:1-352 · blob 3c6c0c8bb282281bcddc892cfb3013bf9f8c5cd5 · 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
// Layer: flow. The natural drainage lines: every cell whose log-accumulation class is at or above a chosen
// class, drawn as a short downhill segment to the cell it drains into (D8), draped just above the ground,
// brighter as the flow grows. Ponding hollows are outlined: the pipeline's kept hollows (flow-hollows.json and its
// hollows/<key>.gph depth masks, lidar lane-gpu/src/flow_hollows.py) when configured, else the tile's own mask body.
// COMPUTED FROM LIDAR, NOT AN OFFICIAL FLOOD MAP: every status, batch and label says so.
// Off by default: until setEnabled(true) (or api.config.enabled) it fetches nothing and draws nothing.
// Tiles come from the lidar pipeline (lidar/src/flow_tiles.py) and every file is fetched through the
// substrate's hash check (api.fetchVerified). Heights come from ctx.heightAt, the ground.
//
// Tile format (expected .gfl, little-endian), laid out like the .gst slope tile. 32-byte header:
//   0 magic "GGF?" | 4 u16 version=1 | 6 u16 samples (257 node grid or 256 cell grid) | 8 u16 spacing_mm
//   10 u16 flags | 12 i32 origin_e_m | 16 i32 origin_n_m (south-west corner) | 20 u8 log_scale (10: k = floor(10 log10 m2))
//   21 u8 method (1 = D8) | 22 u16 channel_m2 | 24 u32 nodata_count | 28 u32 channel_count
//   Body: n u8 accumulation class, then n u8 D8 direction, optionally n u8 hollow mask; rows south to
//   north, west to east. Class 255 = no data.
//   Direction, compass code: 0..7 = N NE E SE S SW W NW, 8 = no downhill step (the pipeline: outlet at the site
//   edge), 255 no data. Code 8 is never drawn as a hollow: hollows come only from the mask body.
//   Direction, ESRI code: 1 E, 2 SE, 4 S, 8 SW, 16 W, 32 NW, 64 N, 128 NE, 0 = pit, 255 no data.
// The decoder is tolerant: any magic starting "GGF", a header of another length when the body fixes the
// grid, and the direction code from the index (dir_encoding) or the values themselves, never from the header
// (byte 21 is the method, 1 = D8, which an ESRI flag would misread).

export const LABEL = 'computed from LiDAR (D8 on a filled surface), not an official flood map';
export const HOLLOW_LABEL = 'ponding hollows: computed from LiDAR, not an official flood map';
export const GPH_MAGIC = 'GGP1', GPH_NODATA = 255;
const INDEX_PATH = 'flow/flow-tiles.json';
// Filled by the build tool with the SHA-256 of flow-tiles.json. Until then the layer loads nothing.
let INDEX_SHA256 = '__FLOW_TILES_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }

export const HEADER_BYTES = 32, NODATA = 255, PIT = 8;
export const DEFAULT_MIN_CLASS = 8, MIN_HOLLOW_CELLS = 4;
export const LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 32; // flow and hollow tiles together
export const LIFT_M = 0.12, HOLLOW_LIFT_M = 0.1;       // above the slope hachures (8 cm)
export const HOLLOW_COLOR = [0.62, 0.74, 0.86, 0.45];
const ESRI = { 64: 0, 128: 1, 1: 2, 2: 3, 4: 4, 8: 5, 16: 6, 32: 7 };  // ESRI power of two -> compass octant

// Pure: bytes -> { samples, nodeGrid, spacing, size, e0, n0, classes, nodata, channels, acc, dir, hollow }.
// dir is always returned in the compass code (0..7, PIT, NODATA).
export function decodeFlowTile(buffer, { encoding } = {}) {
  const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  if (bytes.byteLength < 16) throw Error('flow 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.startsWith('GGF')) throw Error(`flow tile magic "${magic}" is not GGF*`);
  const version = dv.getUint16(4, true);
  if (version !== 1) throw Error(`flow tile version ${version} is not 1`);
  let samples = dv.getUint16(6, true), header = HEADER_BYTES, bodies = 0;
  const spacingMm = dv.getUint16(8, true);
  if (spacingMm === 0) throw Error('flow tile has no usable grid');
  const fits = (s, h) => { for (const b of [2, 3]) if (bytes.byteLength === h + b * s * s) return b; return 0; };
  bodies = samples >= 2 ? fits(samples, header) : 0;
  if (!bodies) { // the header may be another length: let the body fix the grid
    for (const s of [samples, 257, 256]) {
      for (const b of [2, 3]) {
        const h = bytes.byteLength - b * s * s;
        if (s >= 2 && h >= 16 && h <= 256) { samples = s; header = h; bodies = b; break; }
      }
      if (bodies) break;
    }
  }
  if (!bodies) throw Error(`flow tile is ${bytes.byteLength} bytes, which fits no ${samples}-sample grid`);
  const n = samples * samples, spacing = spacingMm / 1000, nodeGrid = samples % 2 === 1;
  const acc = new Uint8Array(bytes, header, n), raw = new Uint8Array(bytes, header + n, n);
  const hollow = bodies === 3 ? new Uint8Array(bytes, header + 2 * n, n) : null;
  const esri = encoding ? encoding === 'esri' : looksEsri(raw);
  const dir = new Uint8Array(n);
  for (let k = 0; k < n; k++) {
    const d = raw[k];
    dir[k] = d === NODATA ? NODATA : esri ? (d === 0 ? PIT : ESRI[d] ?? NODATA) : (d <= PIT ? d : NODATA);
  }
  return {
    samples, nodeGrid, spacing, size: (nodeGrid ? samples - 1 : samples) * spacing,
    e0: dv.getInt32(12, true), n0: dv.getInt32(16, true), logScale: header >= 21 ? dv.getUint8(20) : 0,
    nodata: header >= 28 ? dv.getUint32(24, true) : 0, channels: header >= 32 ? dv.getUint32(28, true) : 0,
    esri, acc, dir, hollow
  };
}

// ESRI codes 16..128 cannot be compass octants; 1/2/4 alone can, so they decide nothing.
function looksEsri(raw) {
  for (let k = 0; k < raw.length; k++) { const d = raw[k]; if (d !== NODATA && d > PIT) return true; }
  return false;
}

// Unit step (east, north) in cells for a compass octant.
export const STEP = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]];

// Colour for an accumulation class: a quiet grey-blue that brightens and firms up as the flow grows.
export function colorFor(c, minClass, maxClass) {
  const f = maxClass > minClass ? Math.min(1, Math.max(0, (c - minClass) / (maxClass - minClass))) : 1;
  return [0.30 + 0.30 * f, 0.50 + 0.30 * f, 0.72 + 0.20 * f, 0.30 + 0.55 * f];
}

// Pure: downhill segments for one tile, grouped by class. x0, y0: the tile's south-west corner in local
// metres; positions relative to origin. Each segment runs from a cell centre to the centre of the cell it
// drains into (so a channel reads as a continuous line). Returns { [class]: Float32Array }.
export function segments(t, x0, y0, minClass, heightAt, { lift = LIFT_M, origin = [0, 0, 0] } = {}) {
  const out = {}, s = t.samples, h = t.spacing, off = t.nodeGrid ? 0 : h / 2;
  for (let j = 0; j < s; j++) {
    for (let i = 0; i < s; i++) {
      const k = j * s + i, c = t.acc[k], d = t.dir[k];
      if (c === NODATA || c < minClass || d >= PIT) continue;
      const ax = x0 + off + i * h, ay = y0 + off + j * h, bx = ax + STEP[d][0] * h, by = ay + STEP[d][1] * h;
      (out[c] ||= []).push(
        ax - origin[0], ay - origin[1], finite(heightAt(ax, ay)) + lift - origin[2],
        bx - origin[0], by - origin[1], finite(heightAt(bx, by)) + lift - origin[2]);
    }
  }
  for (const c in out) out[c] = new Float32Array(out[c]);
  return out;
}

// Pure: a .gph ponding-hollow tile (flow_hollows.py): 32-byte header "GGP1" | u16 version=1 | u16 samples |
// u16 spacing_mm | u16 unit_mm | i32 origin_e_m | i32 origin_n_m (SW) | u32 wet_count | u32 hollows | u32 0, then
// samples^2 u8 depth in unit_mm steps (1..254 inside a kept hollow, 0 dry, 255 no data), rows south to north.
// Returned shaped like a flow tile (samples, spacing, nodeGrid, hollow) so hollowOutline draws it.
export function decodeHollowTile(buffer) {
  const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  if (bytes.byteLength < HEADER_BYTES) throw Error('hollow 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));
  const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true);
  if (magic !== GPH_MAGIC || dv.getUint16(4, true) !== 1) throw Error(`hollow tile "${magic}" is not GGP1 version 1`);
  if (!spacingMm || bytes.byteLength !== HEADER_BYTES + samples * samples) throw Error(`hollow tile is ${bytes.byteLength} bytes, not a ${samples}-sample grid`);
  const spacing = spacingMm / 1000, nodeGrid = samples % 2 === 1;
  return { samples, nodeGrid, spacing, size: (nodeGrid ? samples - 1 : samples) * spacing, unitM: dv.getUint16(10, true) / 1000,
    e0: dv.getInt32(12, true), n0: dv.getInt32(16, true), wet: dv.getUint32(20, true), hollows: dv.getUint32(24, true),
    hollow: new Uint8Array(bytes, HEADER_BYTES, samples * samples) };
}

// Pure: which cells are hollows (flagged in the optional mask body), kept only in
// 4-connected groups of at least minCells. Returns a Uint8Array mask.
export function hollowMask(t, minCells = MIN_HOLLOW_CELLS) {
  const s = t.samples, n = s * s, raw = new Uint8Array(n), keep = new Uint8Array(n), seen = new Uint8Array(n);
  if (!t.hollow) return keep; // no mask written: no hollows are claimed
  for (let k = 0; k < n; k++) raw[k] = t.hollow[k] !== 0 && t.hollow[k] !== NODATA ? 1 : 0;
  const stack = [];
  for (let k0 = 0; k0 < n; k0++) {
    if (!raw[k0] || seen[k0]) continue;
    const group = [];
    stack.push(k0); seen[k0] = 1;
    while (stack.length) {
      const k = stack.pop(), i = k % s, j = (k - i) / s;
      group.push(k);
      for (const [di, dj] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
        const a = i + di, b = j + dj, q = b * s + a;
        if (a < 0 || b < 0 || a >= s || b >= s || !raw[q] || seen[q]) continue;
        seen[q] = 1; stack.push(q);
      }
    }
    if (group.length >= minCells) for (const k of group) keep[k] = 1;
  }
  return keep;
}

// Pure: the outline of the hollows as cell-edge segments (each cell a square of side spacing about its
// centre), draped. Returns a Float32Array of segments.
// openEdges: a neighbour beyond the tile counts as inside (a .gph hollow runs on into the next tile; no seam line).
export function hollowOutline(t, x0, y0, heightAt, { minCells = MIN_HOLLOW_CELLS, lift = HOLLOW_LIFT_M, origin = [0, 0, 0], openEdges = false } = {}) {
  const m = hollowMask(t, minCells), s = t.samples, h = t.spacing, off = t.nodeGrid ? 0 : h / 2, out = [];
  const inside = (i, j) => (i < 0 || j < 0 || i >= s || j >= s) ? openEdges : m[j * s + i] === 1;
  const seg = (ax, ay, bx, by) => out.push(
    ax - origin[0], ay - origin[1], finite(heightAt(ax, ay)) + lift - origin[2],
    bx - origin[0], by - origin[1], finite(heightAt(bx, by)) + lift - origin[2]);
  for (let j = 0; j < s; j++) {
    for (let i = 0; i < s; i++) {
      if (!m[j * s + i]) continue;
      const cx = x0 + off + i * h, cy = y0 + off + j * h, w = cx - h / 2, e = cx + h / 2, so = cy - h / 2, no = cy + h / 2;
      if (!inside(i, j - 1)) seg(w, so, e, so);
      if (!inside(i, j + 1)) seg(w, no, e, no);
      if (!inside(i - 1, j)) seg(w, so, w, no);
      if (!inside(i + 1, j)) seg(e, so, e, no);
    }
  }
  return new Float32Array(out);
}

const finite = h => (Number.isFinite(h) ? h : 0);
const rectDist = (x, y, x0, y0, x1, y1) => Math.hypot(Math.max(x0 - x, 0, x - x1), Math.max(y0 - y, 0, y - y1));

export function createFlow() {
  let api = null, enabled = false, minClass = DEFAULT_MIN_CLASS, userClass = false, encoding;
  let index = null, indexState = 'idle', maxClass = 0; // idle | loading | ready | failed
  let pond = null; // the pipeline's hollows: { count, tiles } once flow-hollows.json is verified
  const loaded = new Map();   // key -> { tile, e0, n0, size, used, cache }
  const inFlight = new Set(), failed = new Set();
  let clock = 0, lastPos = null;
  const stats = { requested: [], evicted: [] };
  const now = () => (api && typeof api.origin === 'function' ? api.origin() || { e: 0, n: 0 } : { e: 0, n: 0 });
  const say = s => { layer.status = `${s} (${LABEL})`; };

  function loadIndex() {
    if (indexState !== 'idle' || !api || !enabled) return;
    const sha = api.config?.sha256 || INDEX_SHA256;
    const path = api.config?.index || INDEX_PATH;
    if (!sha || sha.startsWith('__')) { indexState = 'failed'; say('no flow-tiles.json hash configured'); return; }
    indexState = 'loading';
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      if (!j || !Array.isArray(j.tiles)) throw Error('flow-tiles.json has no tiles list');
      const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '';
      encoding = j.dir_encoding || j.direction_encoding || undefined;
      // Drainage lines start at the index's default class, else its channel area (k = floor(10 log10 m2)): class 8
      // (about 6 m2) would draw 44 % of the site.
      if (!userClass && Number.isFinite(j.default_class)) minClass = j.default_class;
      else if (!userClass && j.channel_m2 > 0) minClass = Math.floor(10 * Math.log10(j.channel_m2));
      if (Number.isFinite(j.classes)) maxClass = j.classes - 1;
      for (const t of j.tiles) if (Number.isFinite(t.max_log_class)) maxClass = Math.max(maxClass, t.max_log_class);
      index = j.tiles.map(t => ({ ...t, path: dir + t.file, size: j.tile_m || 256 }));
      return loadHollows();
    }).then(() => {
      indexState = 'ready';
      say(ready());
      pump();
      api.invalidate({ ground: false });
    }).catch(e => { indexState = 'failed'; say('flow-tiles.json failed: ' + e.message); });
  }

  // flow-hollows.json (config.hollows = { path, sha256 }): its tiles join the flow tiles, keyed h:<key>. A bad or
  // missing index leaves the drainage lines drawn and says so; the tile mask body is then not used either.
  function loadHollows() {
    const h = api.config?.hollows;
    if (!h?.path || !h?.sha256) return null;
    return Promise.resolve().then(() => api.fetchJSON(h.path, h.sha256)).then(j => {
      if (!j || !Array.isArray(j.tiles) || !Array.isArray(j.hollows)) throw Error('no tiles or hollows list');
      const dir = h.path.includes('/') ? h.path.slice(0, h.path.lastIndexOf('/') + 1) : '';
      pond = { count: j.hollows.length, tiles: j.tiles.map(t => ({ ...t, key: 'h:' + t.key, hollowTile: true, path: dir + t.file, size: j.tile_m || 256 })) };
    }).catch(e => { pond = { count: 0, tiles: [], error: 'flow-hollows.json failed: ' + e.message }; });
  }
  const ready = () => `index: ${index.length} flow tiles` + (!pond ? '' : pond.error ? `; ${pond.error}`
    : `; ${pond.count} ponding hollows (${HOLLOW_LABEL})`);

  // A tile the index says has no channel cells at all is never fetched.
  const empty = t => [t.channels, t.channel_count, t.drain].some(v => v === 0);

  function wanted(x, y) {
    if (!index) return [];
    const o = now();
    return [...index, ...(pond ? pond.tiles : [])]
      .map(t => ({ t, d: rectDist(x, y, t.e0 - o.e, t.n0 - o.n, t.e0 - o.e + t.size, t.n0 - o.n + t.size) }))
      .filter(v => v.d <= LOAD_RADIUS && !empty(v.t))
      .sort((a, b) => a.d - b.d)
      .map(v => v.t);
  }

  function request(entry) {
    inFlight.add(entry.key);
    stats.requested.push(entry.key);
    Promise.resolve().then(() => api.fetchVerified(entry.path, entry.sha256)).then(buf => {
      const tile = entry.hollowTile ? decodeHollowTile(buf) : decodeFlowTile(buf, { encoding });
      loaded.set(entry.key, { tile, e0: tile.e0, n0: tile.n0, size: tile.size, used: ++clock, cache: null });
      evict();
      api.invalidate({ ground: false });
    }).catch(e => { failed.add(entry.key); say(`flow tile ${entry.key} failed: ${e.message}`); })
      .finally(() => { inFlight.delete(entry.key); pump(); });
  }

  function pump() {
    if (!lastPos || indexState !== 'ready' || !enabled) return;
    for (const t of wanted(lastPos[0], lastPos[1])) {
      if (inFlight.size >= MAX_IN_FLIGHT) 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 > MAX_TILES) {
      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);
    }
  }

  const layer = {
    id: 'flow',
    label: `Drainage lines and ponding hollows: ${LABEL}`,
    status: `off (${LABEL})`,
    init(a) {
      api = a;
      if (Number.isFinite(a.config?.minClass)) { minClass = a.config.minClass; userClass = true; }
      if (a.config?.encoding) encoding = a.config.encoding;
      if (a.config?.enabled) layer.setEnabled(true);
    },
    setEnabled(on) {
      enabled = !!on;
      say(enabled ? (indexState === 'ready' ? ready() : 'on') : 'off');
      if (enabled) loadIndex();
      api?.invalidate({ ground: false });
      return enabled;
    },
    // The smallest accumulation class drawn as a drainage line.
    setMinClass(c) {
      if (!Number.isInteger(c) || c < 0 || c > 254) throw Error('flow class must be an integer 0..254');
      minClass = c; userClass = true;
      api?.invalidate({ ground: false });
      return minClass;
    },
    get enabled() { return enabled; },
    get minClass() { return minClass; },
    // ctx: { pos, heightAt, groundVersion }
    lines(ctx) {
      if (!api || !enabled) return [];
      lastPos = ctx.pos;
      if (indexState === 'idle') loadIndex();
      pump();
      // One tile is rebuilt per frame: when new ground arrives while walking, the others keep their last lines a
      // frame or two longer instead of every tile in reach rebuilding at once (a phone then drops below 30 fps).
      const gv = ctx.groundVersion || 0, o = now(), out = [];
      let rebuilt = 0, deferred = false;
      for (const [key, t] of loaded) {
        const x0 = t.e0 - o.e, y0 = t.n0 - o.n;
        if (rectDist(ctx.pos[0], ctx.pos[1], x0, y0, x0 + t.size, y0 + t.size) > LOAD_RADIUS) continue;
        const version = key.startsWith('h:') ? `h@${gv}@${x0},${y0}` : `${minClass}@${gv}@${x0},${y0}`;
        if ((!t.cache || t.cache.version !== version || t.cache.heightAt !== ctx.heightAt) && rebuilt++ > 0) {
          deferred = true;
          if (t.cache) { t.used = ++clock; out.push(...t.cache.batches); }
          continue;
        }
        if (!t.cache || t.cache.version !== version || t.cache.heightAt !== ctx.heightAt) {
          const cx = x0 + t.size / 2, cy = y0 + t.size / 2, org = [cx, cy, finite(ctx.heightAt(cx, cy))];
          if (key.startsWith('h:')) { // a pipeline hollow tile: every kept hollow, whole, outlined
            const rim = hollowOutline(t.tile, x0, y0, ctx.heightAt, { origin: org, minCells: 1, openEdges: true });
            t.cache = { version, heightAt: ctx.heightAt, batches: rim.length ? [{ key: `flow/hollows/${key.slice(2)}`, version,
              origin: org, color: HOLLOW_COLOR, positions: rim, label: HOLLOW_LABEL }] : [] };
            t.used = ++clock; out.push(...t.cache.batches); continue;
          }
          const top = Math.max(maxClass, minClass + 1);
          const byClass = segments(t.tile, x0, y0, minClass, ctx.heightAt, { origin: org });
          const batches = Object.keys(byClass).map(c => ({
            key: `flow/${key}/${c}`, version, origin: org, color: colorFor(+c, minClass, top),
            positions: byClass[c], label: LABEL }));
          const rim = pond ? new Float32Array(0) : hollowOutline(t.tile, x0, y0, ctx.heightAt, { origin: org });
          if (rim.length) batches.push({ key: `flow/${key}/hollows`, version, origin: org, color: HOLLOW_COLOR, positions: rim, label: LABEL });
          t.cache = { version, heightAt: ctx.heightAt, batches };
        }
        t.used = ++clock;
        out.push(...t.cache.batches);
      }
      if (deferred) api.invalidate({ ground: false }); // another frame finishes the rest
      return out;
    },
    // For tests and the console.
    debug: () => ({ loaded: [...loaded.keys()], inFlight: [...inFlight], failed: [...failed], indexState, enabled, minClass, maxClass, encoding, label: LABEL,
      hollows: pond ? pond.count : null, ...stats })
  };
  return layer;
}

export default createFlow();

Shade

A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), decodes horizon tile (`decodeHorizonTile`) and reads sun (`readSun`), covering horizon tiles and LiDAR terrain, using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609270439-site-world/world/layers/shade.mjs · lines 1–199 of 199 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern decodeHorizonTile (shared by 2 files)

What it does
Defines 11 functions or classes, including setIndexSha, decodeHorizonTile, horizonAt, inShadow, shadowMask.
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: LiDAR terrain.
Inputs & outputs
In: JSON file horizon-tiles.json.
What it achieves
It sets index sha (`setIndexSha`), decodes horizon tile (`decodeHorizonTile`) and reads sun (`readSun`). Short hatching on ground that lies in terrain shadow for the chosen sun position.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world/layers · JavaScript module
Uses
none found
Used by
none found
Produces
setIndexSha, CAVEAT, HEADER_BYTES, LOAD_RADIUS, HATCH_M, COLOR, decodeHorizonTile, horizonAt, inShadow, shadowMask, hatches, readSun
Defines here
setIndexSha, decodeHorizonTile, horizonAt, inShadow, shadowMask, hatches, readSun, finite, createShade, cellAt, describe
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/202609270439-site-world/world/layers/shade.mjs:1-199 · blob e08f2a918ffd0eb7634105186f2d7cff5d092027 · 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
// Layer: shade. Short hatching on ground that lies in terrain shadow for the chosen sun position.
// Off by default: until setEnabled(true) (or api.config.enabled) it fetches nothing and draws nothing.
// The sun comes from setSun({ azimuth, elevation }) in degrees (azimuth clockwise from GRID north; the page
// computes it with web/world/sun.mjs and subtracts the grid convergence), or from ctx.sun when the
// substrate passes one. Horizon angles come from .ghz tiles written by the lidar pipeline
// (lidar/src/horizon_tiles.py: 32 azimuths per 4 m cell, a GPU ray march paired against a max-pyramid
// sampling, CPU witness), fetched through the substrate's hash check (api.fetchVerified). Ground is shaded
// where the sun's elevation is below the horizon angle in the sun's azimuth (Dozier and Frew, IEEE TGRS
// 28(5), 1990). The source is a bare-earth model: hedges, trees and buildings cast no shadow here.
//
// Tile format (.ghz, little-endian). 32-byte header:
//   0 magic "GHZ1" | 4 u16 version=1 | 6 u16 samples=65 | 8 u16 spacing_mm=4000 | 10 u16 azimuths=32
//   12 i32 origin_e_m | 16 i32 origin_n_m (south-west corner) | 20 u16 unit=100 (value / unit = degrees)
//   22 u16 min_reach_m | 24 u32 nodata_count | 28 i16 max_value | 30 u16 reserved
//   Body: samples*samples*azimuths i16; rows south to north, west to east, azimuth k at k*360/azimuths
//   degrees clockwise from grid north. -32768 is no data (the ray left the site too soon): never shaded.

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

// Said in the status: the horizons come from the bare-earth EA LIDAR DTM 1 m only.
export const CAVEAT = 'computed from the EA LIDAR terrain only; hedges, trees and buildings cast no shadow';
export const HEADER_BYTES = 32, NODATA = -32768;
export const LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 16;
export const HATCH_M = 1.6, LIFT_M = 0.1;             // one stroke per 4 m cell, 1.6 m long, 10 cm above ground
export const COLOR = [0.46, 0.54, 0.74, 0.5];          // quiet blue-grey on a dark background

// Pure: bytes -> { samples, spacing, azimuths, unit, e0, n0, minReach, nodata, maxValue, h }.
export function decodeHorizonTile(buffer) {
  const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  if (bytes.byteLength < HEADER_BYTES) throw Error('horizon 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 !== 'GHZ1') throw Error(`horizon tile magic "${magic}" is not GHZ1`);
  const version = dv.getUint16(4, true);
  if (version !== 1) throw Error(`horizon tile version ${version} is not 1`);
  const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true), azimuths = dv.getUint16(10, true);
  const unit = dv.getUint16(20, true);
  if (samples < 2 || spacingMm === 0 || azimuths < 4 || unit === 0) throw Error('horizon tile has no usable grid');
  const n = samples * samples * azimuths;
  if (bytes.byteLength !== HEADER_BYTES + 2 * n) throw Error(`horizon tile is ${bytes.byteLength} bytes, expected ${HEADER_BYTES + 2 * n}`);
  const h = new Int16Array(n);
  for (let k = 0; k < n; k++) h[k] = dv.getInt16(HEADER_BYTES + 2 * k, true);   // little-endian on any machine
  return {
    samples, spacing: spacingMm / 1000, azimuths, unit, e0: dv.getInt32(12, true), n0: dv.getInt32(16, true),
    minReach: dv.getUint16(22, true), nodata: dv.getUint32(24, true), maxValue: dv.getInt16(28, true), h
  };
}

// Pure: horizon angle in degrees at cell (i, j) towards azimuth az (degrees), linear between the two
// neighbouring azimuths. NaN when either neighbour is no data.
export function horizonAt(t, i, j, az) {
  const f = ((az % 360) + 360) % 360 / (360 / t.azimuths), k0 = Math.floor(f) % t.azimuths, k1 = (k0 + 1) % t.azimuths;
  const w = f - Math.floor(f), base = (j * t.samples + i) * t.azimuths;
  const a = t.h[base + k0], b = t.h[base + k1];
  if (a === NODATA || b === NODATA) return NaN;
  return (a * (1 - w) + b * w) / t.unit;
}

// Pure: is cell (i, j) in terrain shadow for this sun? No data is never shaded; a sun at or below the
// horizon line (elevation <= 0) is night, handled by the caller, not here.
export function inShadow(t, i, j, sun) {
  const h = horizonAt(t, i, j, sun.azimuth);
  return Number.isFinite(h) && sun.elevation < h;
}

// Pure: the cells of one tile in shadow, as a Uint8Array mask (row-major, south row first) and a count.
export function shadowMask(t, sun) {
  const s = t.samples, mask = new Uint8Array(s * s);
  let count = 0;
  for (let j = 0; j < s; j++) for (let i = 0; i < s; i++) if (inShadow(t, i, j, sun)) { mask[j * s + i] = 1; count++; }
  return { mask, count };
}

// Pure: hatch strokes for one tile, one per shaded cell, pointing away from the sun (the way the shadow
// falls). x0, y0: the tile's south-west corner in local metres; positions relative to origin.
export function hatches(t, x0, y0, sun, heightAt, { length = HATCH_M, lift = LIFT_M, origin = [0, 0, 0] } = {}) {
  const { mask, count } = shadowMask(t, sun), s = t.samples, out = new Float32Array(count * 6);
  const a = sun.azimuth * Math.PI / 180, dx = -Math.sin(a) * length / 2, dy = -Math.cos(a) * length / 2;
  let p = 0;
  for (let j = 0; j < s; j++) {
    for (let i = 0; i < s; i++) {
      if (!mask[j * s + i]) continue;
      const x = x0 + i * t.spacing, y = y0 + j * t.spacing;
      const ax = x - dx, ay = y - dy, bx = x + dx, by = y + dy;
      out[p++] = ax - origin[0]; out[p++] = ay - origin[1]; out[p++] = finite(heightAt(ax, ay)) + lift - origin[2];
      out[p++] = bx - origin[0]; out[p++] = by - origin[1]; out[p++] = finite(heightAt(bx, by)) + lift - origin[2];
    }
  }
  return out;
}

// Pure: a sun position from anything offering azimuth and elevation in degrees, or null.
export function readSun(s) {
  if (!s || !Number.isFinite(s.azimuth) || !Number.isFinite(s.elevation)) return null;
  return { azimuth: ((s.azimuth % 360) + 360) % 360, elevation: s.elevation };
}

const finite = h => (Number.isFinite(h) ? h : 0);
// The layer: tiles come through the shared loader (api.lib.tiles), which the substrate hash-checks.
export const LIB_VERSION = 1;

export function createShade() {
  let api = null, tl = null, enabled = false, sun = null, problem = '';
  // The loaded tile holding local point (x, y), as a cell: the Sun readout asks for horizons here.
  function cellAt(x, y) {
    tl?.follow();
    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;
      const s = t.tile.samples - 1;
      return { t: t.tile, i: Math.min(s, Math.round((x - t.x0) / t.tile.spacing)), j: Math.min(s, Math.round((y - t.y0) / t.tile.spacing)) };
    }
    return null;
  }

  function describe() {
    if (!enabled) return 'off';
    if (tl?.state === 'failed') return problem;
    if (!sun) return 'on: no sun position set';
    if (sun.elevation <= 0) return 'sun below the horizon: no terrain shadow drawn';
    const where = tl?.state === 'ready' ? `${tl.index.length} horizon tiles` : 'loading';
    return `sun ${sun.elevation.toFixed(1)} deg up, bearing ${sun.azimuth.toFixed(1)} deg; ${where}; ${CAVEAT}${problem ? '; ' + problem : ''}`;
  }

  const layer = {
    id: 'shade',
    status: 'off',
    init(a) {
      if (!a.lib?.tiles) { layer.status = 'refused: api.lib.tiles not provided'; return; }
      api = a;
      tl = a.lib.tiles.createTileLoader(a, {
        file: 'horizon-tiles.json', path: INDEX_PATH, sha: () => INDEX_SHA256, tileNoun: 'horizon tile', decode: decodeHorizonTile,
        radius: LOAD_RADIUS, maxInFlight: MAX_IN_FLIGHT, maxTiles: MAX_TILES, active: () => enabled,
        say: t => { layer.status = problem = t; }, onReady: () => { layer.status = describe(); }
      });
      if (a.config?.sun) sun = readSun(a.config.sun);
      if (a.config?.enabled) layer.setEnabled(true);
    },
    setEnabled(on) {
      enabled = !!on;
      layer.status = describe();
      if (enabled) tl?.load();
      api?.invalidate({ ground: false });
      return enabled;
    },
    // sun: { azimuth (grid, degrees clockwise from north), elevation (degrees, refraction included) }
    setSun(s) {
      const next = readSun(s);
      if (!next) throw Error('sun needs a finite azimuth and elevation in degrees');
      sun = next;
      layer.status = describe();
      api?.invalidate({ ground: false });
      return sun;
    },
    get enabled() { return enabled; },
    get sun() { return sun; },
    // ctx: { pos, heightAt, groundVersion, sun? }
    lines(ctx) {
      if (!api || !enabled) return [];
      if (ctx.sun) { const s = readSun(ctx.sun); if (s) sun = s; }
      tl.frame(ctx.pos);
      layer.status = describe();
      if (!sun || sun.elevation <= 0) return [];
      const version = `${sun.azimuth.toFixed(2)}/${sun.elevation.toFixed(2)}@${ctx.groundVersion || 0}o${api.origin?.().id || 0}`, out = [];
      for (const [key, t] of tl.near(ctx.pos)) {
        if (!t.cache || t.cache.version !== version || t.cache.heightAt !== ctx.heightAt) {
          const cx = t.x0 + t.size / 2, cy = t.y0 + t.size / 2, o = [cx, cy, finite(ctx.heightAt(cx, cy))];
          const positions = hatches(t.tile, t.x0, t.y0, sun, ctx.heightAt, { origin: o });
          t.cache = { version, heightAt: ctx.heightAt,
            batches: positions.length ? [{ key: `shade/${key}`, version, origin: o, color: COLOR, positions }] : [] };
        }
        tl.touch(t);
        out.push(...t.cache.batches);
      }
      return out;
    },
    // The horizon at the nearest 4 m cell to local point (x, y): an array of angles (degrees, NaN = no data)
    // at k * 360 / n clockwise from grid north, or null where no tile is loaded. Used by the Sun readout.
    horizonProfile(x, y) {
      const c = cellAt(x, y);
      if (!c) return null;
      const n = c.t.azimuths, base = (c.j * c.t.samples + c.i) * n, out = new Array(n);
      for (let k = 0; k < n; k++) { const v = c.t.h[base + k]; out[k] = v === NODATA ? NaN : v / c.t.unit; }
      return out;
    },
    // Horizon angle (degrees) at (x, y) towards grid azimuth az; NaN where unknown.
    horizonAngle(x, y, az) {
      const c = cellAt(x, y);
      return c ? horizonAt(c.t, c.i, c.j, az) : NaN;
    },
    // For tests and the console.
    debug: () => ({ ...tl?.debug(), enabled, sun, ...tl?.stats })
  };
  return layer;
}

export default createShade();

Phases Design

A JavaScript module in the world folder of GlobalGrid2050 that works with cables and solar.

transformglobalgrid2050 / solar-design-studio/202609270439-site-world/world/phases-design.mjs · lines 1–84 of 84 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern itemsFromDesign (shared by 2 files)

What it does
It calculates cables and solar. Defines itemsFromStore, itemsFromDesign.
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.
Downstream impact
Used directly by 1 file: Project UI (globalgrid2050).
What it achieves
It is built from the items from store helper (`itemsFromStore`) and the items from design helper (`itemsFromDesign`). Derive construction items from a design.
Why it matters
Imported by Project UI.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
Uses
none found
Used by
imported by Project UI (import)
Produces
itemsFromStore, itemsFromDesign
Defines here
itemsFromStore, itemsFromDesign
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/202609270439-site-world/world/phases-design.mjs:1-84 · blob 6a35fe793a364e7535fbd2e74c8e9a2d532b1091 · 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
// phases-design.mjs: derive construction items from a design. Pure: no imports, no DOM.
// itemsFromStore reads the viewer's own saved design (world.design.v1, design-store.mjs);
// itemsFromDesign reads an imported layout (the output of importDesign in design-import.mjs).
//
// What the design carries becomes items directly:
//   each cable run        -> a trench and the cable laid in it
//   each equipment solid  -> a pad and the equipment set on it
//   solar tables          -> one pile item per table
//   array boundary rings  -> a fence per outer ring
// What the design does not carry (roads, HDD bores, deliveries) is passed in
// by the caller as `roads`, `hdd` and `extra`; nothing is invented.

const EQUIPMENT_TYPES = new Set(['skid', 'inverter', 'transformer_compound', 'bess_container']);
const PHASE_KINDS = new Set(['road', 'pad', 'fence', 'pile', 'delivery', 'equipment', 'trench', 'hdd', 'cable']);
const LINKS = ['trench', 'hdd', 'pad', 'via', 'after'];

// A world.design.v1 document -> phases items. Links live in each item's params (trench, hdd, pad, via, after)
// and are lifted to the top level, so the ordering rules run on real designs. A cable with neither a trench nor
// a bore is laid in a trench of its own route ("<id>-trench"), as the viewer draws it. Kinds the phases do not
// sequence (a measurement, a note) are left out; opts.extra items are appended as given.
export function itemsFromStore(doc, opts = {}) {
  if (!doc || doc.schema !== 'world.design.v1' || !Array.isArray(doc.items)) {
    throw new Error('itemsFromStore: expected a world.design.v1 document');
  }
  const items = [];
  for (const it of doc.items) {
    if (!it || typeof it !== 'object') continue; // a damaged entry is left out, never a TypeError
    const kind = it.kind === 'piles' ? 'pile' : it.kind; // the Design panel stores pile rows as 'piles'
    if (!PHASE_KINDS.has(kind)) continue;
    const p = it.params || {}, item = { id: it.id, kind, geometry: it.points_bng };
    for (const k of LINKS) if (p[k] != null) item[k] = p[k];
    if (it.kind === 'cable' && item.trench == null && item.hdd == null) {
      items.push({ id: `${it.id}-trench`, kind: 'trench', geometry: it.points_bng });
      item.trench = `${it.id}-trench`;
    }
    items.push(item);
  }
  items.push(...(opts.extra || []));
  return items;
}

// opts.roads: [{ id?, points }]; opts.hdd: [{ id?, points, cables?: [cable index] }]
// (cables that pass through a bore are drawn in the bore instead of a trench);
// opts.extra: items in the phases.mjs shape, appended as given.
export function itemsFromDesign(design, opts = {}) {
  if (!design || typeof design !== 'object') throw new Error('itemsFromDesign: expected the importDesign result');
  const items = [];
  const roads = (opts.roads || []).map((r, i) => ({ id: r.id || `road-${i + 1}`, kind: 'road', geometry: r.points || null }));
  items.push(...roads);

  const boreOf = new Map();
  (opts.hdd || []).forEach((h, i) => {
    const id = h.id || `hdd-${i + 1}`;
    items.push({ id, kind: 'hdd', geometry: h.points || null });
    for (const c of h.cables || []) boreOf.set(c, id);
  });

  (design.outlines || []).filter(o => o.type === 'array_boundary' && !o.hole)
    .forEach((o, i) => items.push({ id: `fence-${i + 1}`, kind: 'fence', geometry: o.points }));

  (design.cables || []).forEach((c, i) => {
    const n = i + 1, bore = boreOf.get(i);
    const cable = { id: `cable-${n}`, kind: 'cable', role: c.role, geometry: c.points, lengthM: c.lengthM };
    if (bore) cable.hdd = bore;
    else {
      items.push({ id: `trench-${n}`, kind: 'trench', geometry: c.points, lengthM: c.lengthM });
      cable.trench = `trench-${n}`;
    }
    items.push(cable);
  });

  let e = 0;
  for (const s of design.solids || []) {
    if (!EQUIPMENT_TYPES.has(s.type)) continue;
    e++;
    items.push({ id: `pad-${e}`, kind: 'pad', geometry: s.quad || null, forType: s.type });
    items.push({ id: `equipment-${e}`, kind: 'equipment', pad: `pad-${e}`, type: s.type, geometry: s.quad || null });
  }

  (design.tables?.solids || []).forEach((t, i) => items.push({ id: `piles-${i + 1}`, kind: 'pile', geometry: t.quad || null }));

  items.push(...(opts.extra || []));
  return items;
}