GLOBALGRID2050 / EXPLORE CODE

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

Layers Panel and 2 more files (part 2)

A JavaScript module in the world folder of GlobalGrid2050 that works with panel model (`panelModel`) and status line (`statusLine`), covering overhead lines (OHL).

571 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 144 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. Layers Panel render · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers-panel.mjs lines 1–256
  2. Canopy ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/canopy.mjs lines 1–206
  3. Construction ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/construction.mjs lines 1–109

Layers Panel

A JavaScript module in the world folder of GlobalGrid2050 that works with panel model (`panelModel`) and status line (`statusLine`), covering overhead lines (OHL).

renderglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers-panel.mjs · lines 1–256 of 256 · version 2026-09-27 03:30 · Entry point · pattern shownIds (shared by 2 files)

What it does
It draws overhead lines (OHL). Defines 14 functions or classes, including isOptional, isLoaded, panelModel, statusLine, sourceKeysFor. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: overhead lines (OHL).
Downstream impact
Used directly by 7 files: Layers UI (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Layers UI (globalgrid2050); and 3 more.
What it achieves
It is built from the is optional helper (`isOptional`), the is loaded helper (`isLoaded`) and the panel model helper (`panelModel`). A small panel titled "Layers" with one labelled switch per optional layer, grouped by the groups Grid, Access, Water and ground, Planning (`docs/world-lenses.md`; desktop studies under Planning). It responds to click and keydown events.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by 5 files, including Layers UI, Substrate and Legend UI.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Layers UI (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), imported by Layers UI (import), imported by Legend UI (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import), mentioned in Standalone (comment link)
Produces
OPTIONAL_LAYERS, START_OFF, isOptional, LENSES, panelModel, statusLine, sourceKeysFor, attributionLines, shownIds, attributionText, toggle, createLayersPanel
Defines here
isOptional, isLoaded, panelModel, statusLine, sourceKeysFor, attributionLines, shownIds, attributionText, toggle, createLayersPanel, el, render, set, onKey
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/202609270330-site-world-v3/world/layers-panel.mjs:1-256 · blob d3eca9b3262f691d31ad4a298d363e4accd2bdc0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Layers panel. A small panel titled "Layers" with one labelled switch per optional layer, grouped by the
// groups Grid, Access, Water and ground, Planning (docs/world-lenses.md; desktop studies under Planning). For each layer switched on it shows the layer's
// status line (from loadLayers) and the attribution its data requires (web/world/data/attribution.json,
// keyed by layer id). attributionText() gives the combined small print for the bottom footer.
//
// The logic is in pure functions (panelModel, attributionLines, attributionText) so node tests can check
// it without a DOM; createLayersPanel only draws the model and wires events.

// Optional layers in display order. `sources` are the keys under attribution.json "layers" whose sources
// this layer draws on (flow is computed from the DTM, so it carries the terrain credit).
export const OPTIONAL_LAYERS = Object.freeze([
  { id: 'grid', label: 'Grid network', lens: 'grid', sources: ['grid-lines', 'substations'] },
  { id: 'ohl-safety', label: 'Overhead line safety zones', lens: 'grid', sources: ['grid-lines'] }, // HSE GS6, from the grid's conductors
  // Tower and crane pads, conductors at an assumed sag, compound platform, access, stringing: GPU study, illustrative
  { id: 'construction', label: 'Construction, illustrative', lens: 'grid', sources: ['construction'] },
  { id: 'ways', label: 'Roads and rail', lens: 'access', sources: ['ways'] },
  // Roads (A roads OpenStreetMap, B and minor OS Open Roads) and mainline rail within 2, 5 or 10 miles (range-ui.mjs).
  { id: 'national', label: 'Roads and rail, wider area', lens: 'access', sources: ['national', 'national-os'] },
  { id: 'imagery', label: 'Imagery', lens: 'ground', sources: ['imagery'] }, // Sentinel-2, Drone and Map only
  { id: 'contours', label: 'Contours', lens: 'ground', sources: ['contours'] }, // from the DTM
  { id: 'slope', label: 'Slope', lens: 'ground', sources: ['slope'] },
  { id: 'canopy', label: 'Hedges and trees', lens: 'ground', sources: ['canopy'] }, // DTM and both DSMs
  { id: 'water', label: 'Water', lens: 'ground', sources: ['rivers'] }, // rivers only: no flood zones are drawn
  { id: 'flow', label: 'Drainage', lens: 'ground', sources: ['terrain'] },
  { id: 'ground', label: 'Ground', lens: 'planning', sources: ['ground'] }, // desktop study: geology, boreholes, mining, SPZ
  { id: 'land', label: 'Land grades', lens: 'planning', sources: ['land'] },
  { id: 'buffers', label: 'Buffers', lens: 'planning', sources: ['buffers'] }, // zones round the grid, water, roads, hedges
  { id: 'visibility', label: 'Visibility', lens: 'planning', sources: ['visibility'] }, // DTM seen from OS Open Roads
  { id: 'shade', label: 'Terrain shadow', lens: 'planning', sources: ['shade'] }, // from the DTM: the terrain credit
]);

// Optional layers that never start on, whatever the page's start list (layers-ui.mjs DEFAULT_ON) says.
export const START_OFF = Object.freeze(['ground', 'imagery']);
export const isOptional = id => OPTIONAL_LAYERS.some(l => l.id === id);

export const LENSES = Object.freeze([
  { id: 'grid', label: 'Grid' },
  { id: 'access', label: 'Access' },
  { id: 'ground', label: 'Water and ground' },
  { id: 'planning', label: 'Planning' },
]);

const OPTIONAL_IDS = new Set(OPTIONAL_LAYERS.map(l => l.id));
// A layer is available once loaded, or when it is ready to load on first switch-on (deferred, layers.mjs).
const isLoaded = entry => !!entry && typeof entry.status === 'string' && /^(loaded|ready)/.test(entry.status);

// layers: loadLayers(...).layers, i.e. [{ id, status }]. on: Set or array of switched-on ids.
// Returns [{ id, label, layers: [{ id, label, available, on, status }] }]; a layer is available only when
// the manifest loaded it, and a layer that is not available is never on.
export function panelModel(layers = [], on = []) {
  const byId = new Map((layers || []).map(l => [l.id, l]));
  const onSet = new Set(on);
  return LENSES.map(lens => ({
    id: lens.id,
    label: lens.label,
    layers: OPTIONAL_LAYERS.filter(l => l.lens === lens.id).map(l => {
      const entry = byId.get(l.id);
      const available = isLoaded(entry);
      const isOn = available && onSet.has(l.id);
      // status: the full words (tests, the Layer details); short: what the panel shows, plain and brief.
      return { id: l.id, label: l.label, available, on: isOn, status: isOn ? statusLine(entry) : '', short: isOn ? (entry.short || '') : '' };
    }),
  }));
}

// A plain sentence from the loader's status.
export function statusLine(entry) {
  if (!entry) return 'Not in this site\'s data yet.';
  const s = String(entry.status || '').trim();
  if (!s) return 'No status given.';
  return s.charAt(0).toUpperCase() + s.slice(1) + (/[.!?]$/.test(s) ? '' : '.');
}

// Source keys (attribution.json "layers" keys) for the ids given: optional layers map through
// OPTIONAL_LAYERS, any other id (terrain, ground-grid) is used as its own key.
export function sourceKeysFor(ids) {
  const keys = [];
  for (const id of ids) {
    const def = OPTIONAL_LAYERS.find(l => l.id === id);
    for (const k of def ? def.sources : [id]) if (!keys.includes(k)) keys.push(k);
  }
  return keys;
}

// [{ source, name, text, link }] for the ids given, de-duplicated by source id and by text, in first-seen order.
// Sources with on_screen === false are credited in ATTRIBUTION.md only and are left out. {year} is filled.
export function attributionLines(ids, attribution, year = new Date().getFullYear()) {
  const map = attribution?.layers || {};
  const sources = attribution?.sources || {};
  const seen = new Set(), out = [];
  for (const key of sourceKeysFor(ids)) {
    for (const sid of map[key] || []) {
      if (seen.has(sid)) continue;
      seen.add(sid);
      const src = sources[sid];
      if (!src || src.on_screen === false || !src.line) continue;
      const text = String(src.line).replaceAll('{year}', String(year));
      if (out.some(l => l.text === text)) continue; // e.g. OS Open Roads and OS OpenMap - Local share one OS line
      out.push({ source: sid, name: src.name || sid, text, link: src.link || '' });
    }
  }
  return out;
}

// The ids whose data is on screen: every loaded base (non-optional) layer, plus optional layers switched on.
export function shownIds(layers = [], on = []) {
  const onSet = new Set(on);
  return (layers || []).filter(l => isLoaded(l) && (!OPTIONAL_IDS.has(l.id) || onSet.has(l.id))).map(l => l.id);
}

// Combined small print for the footer: one string, lines joined with " · ".
export function attributionText(layers, on, attribution, year) {
  return attributionLines(shownIds(layers, on), attribution, year).map(l => l.text).join(' · ');
}

// Next on-set after a toggle; unknown or unavailable ids leave it unchanged.
export function toggle(on, id, layers, want) {
  const next = new Set(on);
  const entry = (layers || []).find(l => l.id === id);
  if (!OPTIONAL_IDS.has(id) || !isLoaded(entry)) return next;
  const value = typeof want === 'boolean' ? want : !next.has(id);
  if (value) next.add(id); else next.delete(id);
  return next;
}

const STYLE = `
.lp { position: fixed; top: 46px; right: 8px; width: min(300px, calc(100vw - 16px)); box-sizing: border-box;
  max-height: calc(100vh - 110px); overflow-y: auto; background: var(--panel, rgba(10,10,10,0.86));
  border: 1px solid var(--edge, #1c2c3a); border-radius: 6px; padding: 8px 12px 10px; color: var(--text, #cfe9ff); }
.lp[hidden] { display: none; }
.lp h2 { font-size: 13px; font-weight: 600; margin: 0 0 4px; }
.lp fieldset { border: 0; margin: 6px 0 0; padding: 0; }
.lp legend { color: var(--dim, #6f8ea6); font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; padding: 0; }
.lp .row { border-top: 1px solid var(--edge, #1c2c3a); padding: 2px 0; }
.lp .row:first-of-type { border-top: 0; }
.lp button[role="switch"] { display: flex; align-items: center; justify-content: space-between; width: 100%;
  min-height: 40px; padding: 0; background: none; border: 0; color: inherit; font: inherit; cursor: pointer; text-align: left; }
.lp button[role="switch"]:focus-visible { outline: 2px solid var(--line, #9cdbff); outline-offset: 2px; border-radius: 3px; }
.lp button[role="switch"][aria-disabled="true"] { color: var(--dim, #6f8ea6); cursor: default; }
.lp .track { flex: none; width: 34px; height: 18px; border-radius: 9px; border: 1px solid var(--edge, #1c2c3a);
  background: rgba(255,255,255,0.04); position: relative; margin-left: 10px; }
.lp .track::after { content: ""; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%;
  background: var(--dim, #6f8ea6); transition: left 120ms; }
.lp button[aria-checked="true"] .track { border-color: var(--line, #9cdbff); }
.lp button[aria-checked="true"] .track::after { left: 18px; background: var(--line, #9cdbff); }
.lp .note, .lp .status, .lp .credit { font-size: 11px; color: var(--dim, #6f8ea6); margin: 0 0 4px; overflow-wrap: anywhere; }
.lp .credit a { color: inherit; }
@media (prefers-reduced-motion: reduce) { .lp .track::after { transition: none; } }
`;

// container: element to hold the panel. options:
//   layers       loadLayers(...).layers ([{ id, status }]); can be replaced later with update(layers)
//   onToggle     (id, on, onIds[]) called after a switch changes
//   attribution  parsed web/world/data/attribution.json
//   on           ids switched on at start (default none)
//   year         fills {year} in attribution lines (default this year)
// Returns { element, set(id, on), isOn(id), onIds(), update(layers), attributionText(), show(v), hidden(), destroy() }.
export function createLayersPanel(container, { layers = [], onToggle = () => {}, attribution = null, on = [], year } = {}) {
  if (!container || typeof container.appendChild !== 'function') throw Error('createLayersPanel needs a container element');
  const doc = container.ownerDocument || document;
  let current = layers || [];
  let onSet = new Set([...on].filter(id => OPTIONAL_IDS.has(id) && isLoaded(current.find(l => l.id === id))));

  if (!doc.getElementById('layers-panel-style')) {
    const st = doc.createElement('style');
    st.id = 'layers-panel-style';
    st.textContent = STYLE;
    doc.head.appendChild(st);
  }
  const root = doc.createElement('section');
  root.className = 'lp';
  root.id = 'layers-panel';
  root.setAttribute('aria-labelledby', 'layers-panel-title');
  container.appendChild(root);

  const el = (tag, cls, text) => {
    const e = doc.createElement(tag);
    if (cls) e.className = cls;
    if (text != null) e.textContent = text;
    return e;
  };

  function render() {
    const focusId = doc.activeElement?.dataset?.layer;
    root.replaceChildren();
    const h = el('h2', null, 'Layers');
    h.id = 'layers-panel-title';
    root.appendChild(h);
    for (const lens of panelModel(current, onSet)) {
      const fs = el('fieldset');
      fs.appendChild(el('legend', null, lens.label));
      for (const l of lens.layers) {
        const row = el('div', 'row');
        const b = el('button');
        b.type = 'button';
        b.setAttribute('role', 'switch');
        b.dataset.layer = l.id;
        b.setAttribute('aria-checked', String(l.on));
        if (!l.available) b.setAttribute('aria-disabled', 'true');
        b.appendChild(el('span', null, l.label));
        b.appendChild(el('span', 'track'));
        b.addEventListener('click', () => set(l.id));
        row.appendChild(b);
        if (!l.available) {
          const n = el('p', 'note', 'Not available for this site yet.');
          n.id = `lp-note-${l.id}`;
          b.setAttribute('aria-describedby', n.id);
          row.appendChild(n);
        }
        if (l.on) {
          const st = el('p', 'status', l.short || l.status); st.title = l.status; row.appendChild(st);
          for (const c of attributionLines([l.id], attribution, year)) {
            const p = el('p', 'credit');
            if (c.link && /^https?:/i.test(c.link)) {
              const a = el('a', null, c.text);
              a.href = c.link; a.target = '_blank'; a.rel = 'noopener';
              p.appendChild(a);
            } else p.textContent = c.text;
            row.appendChild(p);
          }
        }
        fs.appendChild(row);
      }
      root.appendChild(fs);
    }
    if (focusId) root.querySelector(`[data-layer="${focusId}"]`)?.focus();
  }

  function set(id, want) {
    const next = toggle(onSet, id, current, want);
    const changed = next.has(id) !== onSet.has(id);
    onSet = next;
    if (changed) { render(); onToggle(id, onSet.has(id), [...onSet]); }
    return onSet.has(id);
  }

  const onKey = e => { if (e.key === 'Escape' && !root.hidden) { root.hidden = true; root.dispatchEvent(new Event('close')); } };
  root.addEventListener('keydown', onKey);
  render();

  return {
    element: root,
    set,
    isOn: id => onSet.has(id),
    onIds: () => [...onSet],
    update(layers) {
      current = layers || [];
      onSet = new Set([...onSet].filter(id => isLoaded(current.find(l => l.id === id))));
      render();
    },
    attributionText: () => attributionText(current, onSet, attribution, year),
    show(v = true) { root.hidden = !v; if (v) root.querySelector('button[role="switch"]:not([aria-disabled])')?.focus(); },
    hidden: () => root.hidden,
    destroy() { root.removeEventListener('keydown', onKey); root.remove(); },
  };
}

Canopy

A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), loads hedges (`loadHedges`) and calculates planar distances, covering canopy tiles, hedges and LiDAR terrain, using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/canopy.mjs · lines 1–206 of 206 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern decodeCanopyTile (shared by 2 files)

What it does
It lists and searches canopy tiles, hedges and LiDAR terrain. Defines 11 functions or classes, including setIndexSha, decodeCanopyTile, blockOffset, treeTicks, along.
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 canopy-tiles.json; JSON file hedges.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It sets index sha (`setIndexSha`), decodes canopy tile (`decodeCanopyTile`) and loads hedges (`loadHedges`). Hedges and tree canopies as sparse vertical ticks, each from the ground up to the real canopy height measured by the Environment Agency LiDAR (first-return surface minus bare earth).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world/layers · JavaScript module
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
setIndexSha, HEADER_BYTES, LOAD_RADIUS, STRIDE, HEDGE_STEP, SOLID_STEP, COLORS, decodeCanopyTile, blockOffset, treeTicks, along, hedgeGeometry
Defines here
setIndexSha, decodeCanopyTile, blockOffset, treeTicks, along, hedgeGeometry, finite, createCanopy, statusLine, loadHedges, hedges
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/202609270330-site-world-v3/world/layers/canopy.mjs:1-206 · blob 632ef3964e5dea4a1b53c627bdf7ee2f97414fb3 · 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: duplicate_candidate
// Layer: canopy. Hedges and tree canopies as sparse vertical ticks, each from the ground up to the real canopy
// height measured by the Environment Agency LiDAR (first-return surface minus bare earth). Hedges are also solids:
// a walker cannot pass through one, the drone can fly over it. Off by default: until setEnabled(true) (or
// api.config.enabled) it fetches nothing and draws nothing. Tiles and hedge lines come from the lidar pipeline
// (lidar/src/canopy_tiles.py: two classification methods paired on the GPU, a CPU witness); every file is
// fetched through the substrate's hash check (api.fetchVerified). Heights of the ground come from ctx.heightAt.
//
// RULE: no buildings are shown. Only classes 1 (hedge) and 2 (tree) are ever drawn; class 3 (structure) and
// class 4 (uncertain: the two methods disagree, or vegetation on the rim of a structure) are skipped here even
// if a tile were to carry a height for them.
//
// Tile format (.gcn, little-endian). 32-byte header:
//   0 magic "GGC1" | 4 u16 version=1 | 6 u16 samples=257 | 8 u16 spacing_mm | 10 u16 flags
//   12 i32 origin_e_m | 16 i32 origin_n_m (south-west corner) | 20 u16 height_step_mm (200) | 22 u16 reserved
//   24 u32 nodata_count | 28 u32 shown_count (classes 1 and 2)
//   Body: samples*samples u8 class, then samples*samples u8 canopy height in steps; rows south to north, west to east.
// Index (canopy-tiles.json): { tiles: [{ key, file, sha256, e0, n0, hedge, tree }], hedges: { file, sha256 } }.
// hedges.json: { lines: [{ id, pts: [[e, n, height_m], ...], width_m }] } in British National Grid metres.

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

export const HEADER_BYTES = 32, NODATA = 255, HEDGE = 1, TREE = 2, SHOWN = Object.freeze([HEDGE, TREE]);
export const LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 16;
export const STRIDE = 4;            // one tree tick per 4 m square, at a fixed pseudo-random cell inside it
export const HEDGE_STEP = 1.5;      // metres between hedge ticks along a line
export const SOLID_STEP = 1, SOLID_RADIUS = 60, SOLID_MIN_HALF = 0.5, SOLID_MAX_HALF = 1.5, SOLID_SINK = 0.5;
export const COLORS = { tree: [0.50, 0.72, 0.52, 0.44], hedge: [0.78, 0.84, 0.52, 0.62], hedgeTop: [0.74, 0.80, 0.50, 0.30] };

// Pure: bytes -> { samples, spacing, e0, n0, step, nodata, shown, cls, h }.
export function decodeCanopyTile(buffer) {
  const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  if (bytes.byteLength < HEADER_BYTES) throw Error('canopy 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 !== 'GGC1') throw Error(`canopy tile magic "${magic}" is not GGC1`);
  const version = dv.getUint16(4, true);
  if (version !== 1) throw Error(`canopy tile version ${version} is not 1`);
  const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true), stepMm = dv.getUint16(20, true);
  if (samples < 2 || spacingMm === 0 || stepMm === 0) throw Error('canopy tile has no usable grid');
  const n = samples * samples;
  if (bytes.byteLength !== HEADER_BYTES + 2 * n) throw Error(`canopy tile is ${bytes.byteLength} bytes, expected ${HEADER_BYTES + 2 * n}`);
  return {
    samples, spacing: spacingMm / 1000, e0: dv.getInt32(12, true), n0: dv.getInt32(16, true), step: stepMm / 1000,
    nodata: dv.getUint32(24, true), shown: dv.getUint32(28, true),
    cls: new Uint8Array(bytes, HEADER_BYTES, n), h: new Uint8Array(bytes, HEADER_BYTES + n, n)
  };
}

// A fixed pseudo-random offset per block, so ticks do not stand in rows but are the same every frame.
export function blockOffset(bi, bj, stride) {
  let x = (Math.imul(bi, 73856093) ^ Math.imul(bj, 19349663)) >>> 0;
  x = Math.imul(x ^ (x >>> 15), 2246822519) >>> 0; x = (x ^ (x >>> 13)) >>> 0;
  return [x % stride, (x >>> 8) % stride];
}

// Pure: vertical tree ticks for one tile. x0, y0: the tile's south-west corner in local metres. Only class 2.
// Returns Float32Array of segments (6 floats each) relative to origin.
export function treeTicks(t, x0, y0, heightAt, { stride = STRIDE, origin = [0, 0, 0] } = {}) {
  const out = [], s = t.samples, last = s - 1; // the last row and column belong to the next tile
  for (let bj = 0; bj * stride < last; bj++) {
    for (let bi = 0; bi * stride < last; bi++) {
      const [oi, oj] = blockOffset(bi + Math.round(t.e0 / stride), bj + Math.round(t.n0 / stride), stride);
      const i = bi * stride + oi, j = bj * stride + oj;
      if (i >= last || j >= last) continue;
      const k = j * s + i;
      if (t.cls[k] !== TREE || t.h[k] === 0) continue;
      const x = x0 + i * t.spacing, y = y0 + j * t.spacing, g = finite(heightAt(x, y));
      out.push(x - origin[0], y - origin[1], g - origin[2], x - origin[0], y - origin[1], g + t.h[k] * t.step - origin[2]);
    }
  }
  return new Float32Array(out);
}

// Points every `step` metres along a polyline [[x, y, h], ...] (local metres), height interpolated. Pure.
export function along(pts, step) {
  const out = [];
  for (let k = 0; k + 1 < pts.length; k++) {
    const [ax, ay, ah] = pts[k], [bx, by, bh] = pts[k + 1], L = Math.hypot(bx - ax, by - ay);
    const n = Math.max(1, Math.ceil(L / step));
    for (let m = k === 0 ? 0 : 1; m <= n; m++) { const f = m / n; out.push([ax + (bx - ax) * f, ay + (by - ay) * f, ah + (bh - ah) * f]); }
  }
  return out;
}

// Pure: hedge ticks, a faint top line and solid boxes. lines: hedges.json lines; en: site origin { e, n }.
// Returns { ticks: Float32Array, tops: Float32Array, solids: [{ min, max, line }] } (ticks/tops relative to origin).
export function hedgeGeometry(lines, en, heightAt, { step = HEDGE_STEP, solidStep = SOLID_STEP, origin = [0, 0, 0] } = {}) {
  const ticks = [], tops = [], solids = [];
  for (const l of lines || []) {
    if (!Array.isArray(l.pts) || l.pts.length < 2) continue;
    const pts = l.pts.map(([e, n, h]) => [e - en.e, n - en.n, Math.max(0, +h || 0)]);
    let prev = null;
    for (const [x, y, h] of along(pts, step)) {
      const g = finite(heightAt(x, y)), top = [x - origin[0], y - origin[1], g + h - origin[2]];
      ticks.push(x - origin[0], y - origin[1], g - origin[2], ...top);
      if (prev) tops.push(...prev, ...top);
      prev = top;
    }
    const half = Math.min(SOLID_MAX_HALF, Math.max(SOLID_MIN_HALF, (+l.width_m || 1) / 2));
    for (const [x, y, h] of along(pts, solidStep)) {
      if (!(h > 0)) continue;
      const g = finite(heightAt(x, y));
      solids.push({ min: [x - half, y - half, g - SOLID_SINK], max: [x + half, y + half, g + h], line: l.id });
    }
  }
  return { ticks: new Float32Array(ticks), tops: new Float32Array(tops), solids };
}

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 createCanopy() {
  let api = null, tl = null, enabled = false;
  let hedgeLines = null, hedgeBuilt = null;  // hedgeBuilt: { version, heightAt, batches, solids }

  function statusLine() {
    const n = tl?.index ? tl.index.length : 0, h = hedgeLines ? hedgeLines.length : 0;
    return `${n} canopy tiles, ${h} hedge lines; structures and uncertain cells hidden`;
  }

  // The hedge lines come with the index: fetched once it has arrived, through the same hash check.
  function loadHedges(j, dir) {
    if (!j.hedges?.file || !j.hedges?.sha256) return;
    return api.fetchJSON(dir + j.hedges.file, j.hedges.sha256).then(hj => {
      if (!hj || !Array.isArray(hj.lines)) throw Error('hedges.json has no lines list');
      hedgeLines = hj.lines;
      layer.status = statusLine();
      api.invalidate({ ground: false });
    });
  }

  function hedges(ctx) {
    if (!hedgeLines) return null;
    const origin = tl.origin, version = `${ctx.groundVersion || 0}@${origin.e},${origin.n}`;
    if (!hedgeBuilt || hedgeBuilt.version !== version || hedgeBuilt.heightAt !== ctx.heightAt) {
      const o = [0, 0, finite(ctx.heightAt(0, 0))];
      const g = hedgeGeometry(hedgeLines, origin, ctx.heightAt, { origin: o });
      hedgeBuilt = { version, heightAt: ctx.heightAt, solids: g.solids, batches: [
        { key: 'canopy/hedge-ticks', version, origin: o, color: COLORS.hedge, positions: g.ticks },
        { key: 'canopy/hedge-tops', version, origin: o, color: COLORS.hedgeTop, positions: g.tops }] };
    }
    return hedgeBuilt;
  }

  const layer = {
    id: 'canopy',
    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: 'canopy-tiles.json', path: INDEX_PATH, sha: () => INDEX_SHA256, tileNoun: 'canopy tile', decode: decodeCanopyTile,
        radius: LOAD_RADIUS, maxInFlight: MAX_IN_FLIGHT, maxTiles: MAX_TILES, active: () => enabled, keep: t => t.tree !== 0,
        say: t => { layer.status = t; }, onReady: () => { layer.status = statusLine(); }, afterReady: loadHedges,
        onIndexError: (e, whileLoading) => { layer.status = (whileLoading ? 'canopy-tiles.json' : 'hedges.json') + ' failed: ' + e.message; },
        onMove: () => { hedgeBuilt = null; }
      });
      if (a.config?.enabled) layer.setEnabled(true);
    },
    setEnabled(on) {
      enabled = !!on;
      layer.status = enabled ? (tl?.state === 'ready' ? statusLine() : 'on') : 'off';
      if (enabled) tl?.load();
      api?.invalidate({ ground: false });
      return enabled;
    },
    get enabled() { return enabled; },
    // ctx: { pos, heightAt, groundVersion }
    lines(ctx) {
      if (!api || !enabled) return [];
      tl.frame(ctx.pos);
      const gv = ctx.groundVersion || 0, out = [];
      for (const [key, t] of tl.near(ctx.pos)) {
        const version = `${gv}`;
        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 = treeTicks(t.tile, t.x0, t.y0, ctx.heightAt, { origin: o });
          t.cache = { version, heightAt: ctx.heightAt, batch: { key: `canopy/tree/${key}`, version, origin: o, color: COLORS.tree, positions } };
        }
        tl.touch(t);
        if (t.cache.batch.positions.length) out.push(t.cache.batch);
      }
      const h = hedges(ctx);
      if (h) out.push(...h.batches.filter(b => b.positions.length));
      return out;
    },
    // Hedge boxes near the viewer (built with the ground the last lines() call saw). Walkers are blocked;
    // each box stops at the hedge top, so the drone passes over.
    solids(ctx) {
      if (!enabled || !hedgeBuilt || !ctx?.pos) return [];
      const [x, y] = ctx.pos;
      const d = api.lib.tiles.rectDist;
      return hedgeBuilt.solids.filter(b => d(x, y, b.min[0], b.min[1], b.max[0], b.max[1]) <= SOLID_RADIUS);
    },
    // For tests and the console.
    debug: () => ({ ...tl?.debug(), enabled,
      hedgeLines: hedgeLines ? hedgeLines.length : 0, solids: hedgeBuilt ? hedgeBuilt.solids.length : 0, ...tl?.stats })
  };
  return layer;
}

export default createCanopy();

Construction

A JavaScript module in the layers folder of GlobalGrid2050 that works with clearance words (`clearanceWords`), using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/construction.mjs · lines 1–109 of 109 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern origin (shared by 6 files)

What it does
It lists and searches its content. Defines 8 functions or classes, including parseConstruction, clearanceWords, buildConstruction, L, constructionStatus.
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.
What it achieves
It is built from the clearance words helper (`clearanceWords`), the construction status helper (`constructionStatus`) and the origin step (`origin`). How an overhead line and its connection might be built on this ground, from the GPU construction study (gpu-night agent A, `export/` /construction.odbl.json).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world/layers · JavaScript module
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
ILLUSTRATIVE, SCHEMA, KINDS, parseConstruction, clearanceWords, buildConstruction, constructionStatus, createConstruction
Defines here
parseConstruction, clearanceWords, buildConstruction, L, constructionStatus, createConstruction, origin, load
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/202609270330-site-world-v3/world/layers/construction.mjs:1-109 · blob bdcb22bae13fa1194afccda40e72c51c12f379fb · 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: construction. How an overhead line and its connection might be built on this ground, from the GPU
// construction study (gpu-night agent A, export/<site>/construction.odbl.json): tower pads, crane pads, conductors
// at an ASSUMED sag, a HYPOTHETICAL connection compound platform, access routes at their finished levels, stringing
// sites and ranked siting candidates. ILLUSTRATIVE ONLY: towers are inferred from OpenStreetMap vertices, sizes,
// heights and sag are assumed. Nothing here is a design, a survey, or a pass or fail on any real asset, and the
// clearance figures are illustrative distances at an assumed sag, never a statement about a place.
//
// The file is ODbL (OpenStreetMap positions): it is staged as its own file and credited on its own line, never
// merged with OGL or MIT data. Heights are metres above Ordnance Datum Newlyn from the EA DTM, carried in the file,
// so every feature stands at its own level (nothing is draped on a guessed height).
// Off by default: it fetches nothing until switched on (Layers > Grid > Construction, illustrative).

export const ILLUSTRATIVE = 'illustrative only: towers inferred from OpenStreetMap, sizes, heights and sag assumed';
export const SCHEMA = 'gpu-night-a.construction/1';
// Kind in the file -> how it is drawn and named. Words only; no verdicts.
export const KINDS = Object.freeze({
  'tower-pad': { name: 'tower pads', color: [1, 0.62, 0.2, 0.9] },
  'crane-pad': { name: 'crane pads', color: [1, 0.85, 0.3, 0.8] },
  'conductor-ILLUSTRATIVE': { name: 'conductors at an assumed sag', color: [0.95, 0.55, 0.55, 0.75] },
  'compound-platform': { name: 'hypothetical compound platforms', color: [0.8, 0.6, 1, 0.9] },
  'access-route-ILLUSTRATIVE': { name: 'access routes', color: [0.92, 0.92, 0.92, 0.8] },
  'stringing-site-ILLUSTRATIVE': { name: 'stringing sites', color: [0.4, 0.9, 0.7, 0.8] },
  'siting-candidate-HYPOTHETICAL': { name: 'hypothetical siting candidates', color: [0.7, 0.72, 1, 0.7] }
});
const POST_M = 1, MARK = { arm: 4, post: 8 };

// Pure: the checked file -> { features: [{ kind, id, pts: [[e, n, z]...], closed, props }], sources, receipts }.
export function parseConstruction(j) {
  if (!j || j.schema !== SCHEMA || !Array.isArray(j.features)) throw Error(`not a ${SCHEMA} file`);
  if (!/OpenStreetMap/.test(j.attribution || '')) throw Error('the file carries no OpenStreetMap credit');
  const features = [];
  for (const f of j.features) {
    const kind = f?.properties?.kind, g = f?.geometry;
    if (!KINDS[kind] || !g) continue;
    const pts = g.type === 'Point' ? [g.coordinates] : g.type === 'LineString' ? g.coordinates : g.type === 'Polygon' ? g.coordinates[0] : null;
    if (!pts || !pts.every(p => p.length >= 3 && p.every(Number.isFinite))) continue;
    features.push({ kind, id: f.properties.id || f.properties.span || f.properties.tower || '', pts, closed: g.type === 'Polygon', props: f.properties });
  }
  return { features, attribution: j.attribution, other: j.other_sources || [], receipts: (j.receipts || []).length, site: j.site };
}

// Pure: a clearance in words. Illustrative distance at an assumed sag; never a verdict on a place.
export function clearanceWords(m) {
  return Number.isFinite(m) ? `illustrative ground clearance ${m.toFixed(1)} m at an assumed sag` : 'no illustrative clearance worked out';
}

// Pure: features -> line batches in local metres (origin { e, n }). Each batch carries its own origin (the first
// point of its first feature) so it stays sharp far from the site origin.
export function buildConstruction(model, origin) {
  const byKind = new Map();
  for (const f of model.features) {
    if (!byKind.has(f.kind)) byKind.set(f.kind, { o: [f.pts[0][0] - origin.e, f.pts[0][1] - origin.n, f.pts[0][2]], v: [] });
    const b = byKind.get(f.kind), [ox, oy, oz] = b.o, v = b.v;
    const L = p => [p[0] - origin.e - ox, p[1] - origin.n - oy, p[2] - oz];
    if (f.pts.length === 1) { // a point: a cross on the ground and a post
      const [x, y, z] = L(f.pts[0]), a = MARK.arm;
      v.push(x - a, y, z, x + a, y, z, x, y - a, z, x, y + a, z, x, y, z, x, y, z + MARK.post);
      continue;
    }
    for (let i = 1; i < f.pts.length; i++) v.push(...L(f.pts[i - 1]), ...L(f.pts[i]));
    if (f.closed) for (const p of f.pts.slice(0, -1)) { const [x, y, z] = L(p); v.push(x, y, z, x, y, z - POST_M); } // edge posts
  }
  return [...byKind].map(([kind, b]) => ({ key: `construction/${kind}`, origin: b.o, color: KINDS[kind].color,
    positions: new Float32Array(b.v), label: `${KINDS[kind].name}: ${ILLUSTRATIVE}` }));
}

// Pure: the status line: counts by kind, the lowest illustrative clearance, the credit reminder.
export function constructionStatus(model) {
  const n = {};
  for (const f of model.features) n[f.kind] = (n[f.kind] || 0) + 1;
  const parts = Object.keys(KINDS).filter(k => n[k]).map(k => `${n[k]} ${KINDS[k].name}`);
  const c = model.features.filter(f => f.kind === 'conductor-ILLUSTRATIVE').map(f => f.props.min_clearance_m_ILLUSTRATIVE).filter(Number.isFinite);
  const low = c.length ? `; lowest ${clearanceWords(Math.min(...c))}` : '';
  return `${parts.join(', ')}${low}; ${ILLUSTRATIVE}; ${model.receipts} GPU receipts`;
}

export function createConstruction() {
  let api = null, model = null, state = 'idle'; // idle | loading | ready | failed
  let built = { version: null, batches: [] };
  const origin = () => (api && typeof api.origin === 'function' ? api.origin() : { e: 0, n: 0, id: 0 });
  function load() {
    if (state !== 'idle' || !api) return;
    const path = api.config?.path, sha = api.config?.sha256;
    if (!path || !sha) { state = 'failed'; layer.status = 'no construction file configured (config.path and config.sha256)'; return; }
    state = 'loading'; layer.status = 'loading ' + path;
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      model = parseConstruction(j); state = 'ready'; layer.status = constructionStatus(model);
      api.invalidate({ ground: false });
    }).catch(e => { state = 'failed'; layer.status = 'construction file failed: ' + e.message; });
  }
  const layer = {
    id: 'construction',
    status: 'off until switched on',
    init(a) { api = a; },
    lines() {
      if (!api) return [];
      if (state === 'idle') load();
      if (state !== 'ready') return [];
      const o = origin(), version = `${o.e},${o.n},${o.id}`;
      if (built.version !== version) built = { version, batches: buildConstruction(model, o).map(b => ({ ...b, version })) };
      return built.batches;
    },
    ready: () => state === 'ready',
    debug: () => ({ state, features: model?.features.length ?? 0, version: built.version })
  };
  return layer;
}

export default createConstruction();