In this section
- Land ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/land.mjs lines 1–140
- Shade ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/shade.mjs lines 1–199
- Slope ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/slope.mjs lines 1–144
- Visibility ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/visibility.mjs lines 1–141
Land
A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), using SHA-256.
ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/land.mjs · lines 1–140 of 140 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern colorFor (shared by 3 files)
- What it does
- It lists and searches its content. Defines 12 functions or classes, including setIndexSha, finite, colorFor, onBox, same.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file land.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- What it achieves
- It sets index sha (`setIndexSha`) and is built from the finite step (`finite`) and the color for helper (`colorFor`). Agricultural Land Classification grade boundaries from `land.json` (cut per site by `tools/features/cut_land.py` from Natural England's open data), draped 4 cm above the ground in quiet, low-alpha earth tones: boundaries only, no fills, so the ground stays the picture.
- 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
- none found
- Produces
- setIndexSha, LIFT_M, STEP_M, BOX_EPS, GRADE_COLOR, OTHER_COLOR, ALPHA, colorFor, onBox, boundaryRuns, allRuns, LIB_VERSION
- Defines here
- setIndexSha, finite, colorFor, onBox, same, boundaryRuns, key, allRuns, createLand, origin, load, localRuns
- 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/land.mjs:1-140 · blob 04e1b12cddc8f98160a0ca52ee5541742f6a2149 · 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: land. Agricultural Land Classification grade boundaries from land.json (cut per site by
// tools/features/cut_land.py from Natural England's open data), draped 4 cm above the ground in quiet,
// low-alpha earth tones: boundaries only, no fills, so the ground stays the picture.
//
// Post-1988 survey boundaries are drawn a little stronger than the provisional map's, which is mapped at
// about 1:250,000 and is only a guide. Edges that lie on the cut box are not drawn (they are not grade
// boundaries), and a boundary shared by two polygons is drawn once.
//
// land.json: { alc: { provisional: [{ grade, rings }], post1988: [{ grade, rings }] }, box: { e0, n0, e1, n1 },
// not_a_grade: [..], attribution }. Rings are British National Grid metres; they become local metres from the
// live site origin here. Loaded through the substrate's hash check (api.fetchJSON with api.config.sha256).
// No imports: the file runs from a blob URL.
const INDEX_PATH = 'land/land.json';
let INDEX_SHA256 = '__LAND_JSON_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }
export const LIFT_M = 0.04; // just above the ground, below the water lines (5 cm)
export const STEP_M = 2; // no draped segment longer than 2 m
export const BOX_EPS = 0.05; // an edge within 5 cm of the box side lies on it
// Muted tones on the dark background: better land a little greener, poorer land browner and greyer.
export const GRADE_COLOR = Object.freeze({
'Grade 1': [0.46, 0.66, 0.42], 'Grade 2': [0.56, 0.68, 0.42], 'Grade 3': [0.66, 0.66, 0.44],
'Grade 3a': [0.66, 0.68, 0.44], 'Grade 3b': [0.66, 0.62, 0.44], 'Grade 4': [0.64, 0.56, 0.44],
'Grade 5': [0.58, 0.52, 0.46],
});
export const OTHER_COLOR = [0.55, 0.55, 0.55];
export const ALPHA = { post1988: 0.5, provisional: 0.3 };
const finite = h => (Number.isFinite(h) ? h : 0);
export function colorFor(grade, kind) {
return [...(GRADE_COLOR[grade] || OTHER_COLOR), ALPHA[kind] ?? 0.3];
}
// Pure: is the segment a-b on a side of box?
export function onBox(a, b, box, eps = BOX_EPS) {
if (!box) return false;
const same = (u, v, s) => Math.abs(u - s) <= eps && Math.abs(v - s) <= eps;
return same(a[0], b[0], box.e0) || same(a[0], b[0], box.e1) || same(a[1], b[1], box.n0) || same(a[1], b[1], box.n1);
}
// Pure: boundary polylines of one kind. Each ring is walked, box edges dropped, segments already drawn
// (by an earlier polygon, in either direction) skipped; runs of kept segments become polylines.
// Returns [{ grade, points: [[e, n], ...] }].
export function boundaryRuns(items, box, seen = new Set()) {
const key = (a, b) => { const p = `${a[0]},${a[1]}`, q = `${b[0]},${b[1]}`; return p < q ? p + '|' + q : q + '|' + p; };
const out = [];
for (const it of items || []) {
for (const ring of it.rings || []) {
let run = null;
for (let i = 0; i < ring.length; i++) {
const a = ring[i], b = ring[(i + 1) % ring.length], k = key(a, b);
if (onBox(a, b, box) || seen.has(k) || (a[0] === b[0] && a[1] === b[1])) { if (run) out.push(run); run = null; continue; }
seen.add(k);
if (!run) run = { grade: it.grade, points: [[a[0], a[1]]] };
run.points.push([b[0], b[1]]);
}
if (run) out.push(run);
}
}
return out;
}
// Pure: all runs to draw, post-1988 first (so a shared edge takes the survey's colour), then provisional.
export function allRuns(land) {
const notGrade = new Set(land.not_a_grade || ['', ' ', 'Not Surveyed']), seen = new Set();
const survey = (land.alc?.post1988 || []).filter(p => !notGrade.has(p.grade));
return [
...boundaryRuns(survey, land.box, seen).map(r => ({ ...r, kind: 'post1988' })),
...boundaryRuns(land.alc?.provisional || [], land.box, seen).map(r => ({ ...r, kind: 'provisional' })),
];
}
// The layer: runs are densified and draped by the shared library (api.lib.drape), which the substrate hash-checks.
export const LIB_VERSION = 1;
export function createLand() {
let api = null, D = null, enabled = false, data = null, state = 'idle'; // idle | loading | ready | failed
let runs = null, runsOrigin = null, cache = { 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 sha = api.config?.sha256 || INDEX_SHA256, path = api.config?.index || INDEX_PATH;
if (!sha || sha.startsWith('__')) { state = 'failed'; layer.status = 'no land.json hash configured'; return; }
state = 'loading';
Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
if (!j || !j.alc) throw Error('land.json has no alc section');
data = j; state = 'ready';
const n = (j.alc.provisional || []).length + (j.alc.post1988 || []).length;
layer.status = `${n} land grade areas; provisional grades are mapped at about 1:250,000 and a survey decides`;
api.invalidate({ ground: false });
}).catch(e => { state = 'failed'; layer.status = 'land.json failed: ' + e.message; });
}
function localRuns() {
const o = origin(), id = `${o.e},${o.n},${o.id}`;
if (runs && runsOrigin === id) return runs;
runs = allRuns(data).map((r, i) => ({ i, grade: r.grade, kind: r.kind,
pts: D.densify(r.points.map(([e, n]) => [e - o.e, n - o.n]), STEP_M) }));
runsOrigin = id;
cache = { version: null, batches: [] };
return runs;
}
const layer = {
id: 'land',
status: 'waiting for init',
init(a) {
if (!a.lib?.drape) { layer.status = 'refused: api.lib.drape not provided'; return; }
api = a; D = a.lib.drape;
if (a.config?.enabled) enabled = true;
layer.status = 'ready to load'; load();
},
setEnabled(on) { enabled = !!on; api?.invalidate({ ground: false }); return enabled; },
get enabled() { return enabled; },
// ctx: { pos, heightAt, groundVersion }
lines(ctx) {
if (!api) return [];
if (state === 'idle') load();
if (state !== 'ready') return [];
const rs = localRuns(), version = `land@${ctx.groundVersion || 0}@${runsOrigin}`;
if (cache.version !== version || cache.heightAt !== ctx.heightAt) {
cache = { version, heightAt: ctx.heightAt, batches: rs.map(r => {
const o = [r.pts[0][0], r.pts[0][1], finite(ctx.heightAt(r.pts[0][0], r.pts[0][1]))];
return { key: `land/${r.kind}/${r.i}`, version, origin: o, color: colorFor(r.grade, r.kind),
positions: D.drapeSegments(r.pts, ctx.heightAt, LIFT_M, o, typeof ctx.known === 'function' ? ctx.known : undefined) };
}) };
}
return cache.batches.slice();
},
// The loaded land.json, for the land cartridge (web/world/land.mjs) and the console.
data: () => data,
debug: () => ({ state, enabled, runs: runs ? runs.length : 0 }),
};
return layer;
}
export default createLand();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.
Set aside from the main view: 99% of its lines are the same as solar-design-studio/202609270439-site-world/world/layers/shade.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Shade; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9873 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/layers/shade.mjs:1-199 e08f2a918ffd0eb7634105186f2d7cff5d092027
- sha256 7575610e9f1d328216f25b7ab3d1adc5b3a51f17fa1076ea48e4755fdc00712c
- target sha256 90a5f6830d8649968a2af8061678020f163b8490f2d74082c650e04e146b76d9
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/shade.mjs · lines 1–199 of 199 · version 2026-09-27 03:30 · 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/202609270330-site-world-v3/world/layers · JavaScript module
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- 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/202609270330-site-world-v3/world/layers/shade.mjs:1-199 · blob 4a91114e12cb77af11aa4e34fc14fab3e04a2008 · 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: 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 (tester 3): 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();Slope
A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), covering slope tiles and LiDAR terrain, using SHA-256.
ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/slope.mjs · lines 1–144 of 144 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern setIndexSha (shared by 14 files)
- What it does
- Defines 8 functions or classes, including setIndexSha, decodeSlopeTile, classForLimit, downslope, ticks.
- 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 slope-tiles.json.
- What it achieves
- It sets index sha (`setIndexSha`) and decodes slope tile (`decodeSlopeTile`). Short downslope tick marks (hachures) draped on the ground, drawn only where the slope exceeds a chosen limit (default 10 %).
- 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, LOWER, DEFAULT_LIMIT, LOAD_RADIUS, STRIDE, COLORS, decodeSlopeTile, classForLimit, downslope, ticks, LIB_VERSION
- Defines here
- setIndexSha, decodeSlopeTile, classForLimit, downslope, ticks, finite, createSlope, ready
- 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/slope.mjs:1-144 · blob 2bbede58ea80a7d83d9c4e26391aadeb89edf75b · 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: slope. Short downslope tick marks (hachures) draped on the ground, drawn only where the slope
// exceeds a chosen limit (default 10 %). Off by default: until setEnabled(true) (or api.config.enabled)
// it fetches nothing and draws nothing. Slope classes come from .gst tiles written by the lidar pipeline
// (lidar/src/slope_tiles.py, Horn's method, paired on the GPU against Zevenbergen-Thorne); every file is
// fetched through the substrate's hash check (api.fetchVerified). Heights come from ctx.heightAt, the ground.
//
// Tile format (.gst, little-endian). 32-byte header:
// 0 magic "GGS1" | 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 u8 classes=6 | 21 u8 method=1 (Horn)
// 22 u16 reserved | 24 u32 nodata_count | 28 u32 steep_count (class >= 3)
// Body: samples*samples u8 slope class, then samples*samples u8 aspect; rows south to north, west to east.
// Class 0: 0-2 %, 1: 2-5, 2: 5-10, 3: 10-15, 4: 15-25, 5: >25; 255 no data.
// Aspect: 0..7 = downslope N NE E SE S SW W NW; 8 flat; 255 no data.
const INDEX_PATH = 'slope/slope-tiles.json';
// Filled by the build tool with the SHA-256 of slope-tiles.json. Until then the layer loads nothing.
let INDEX_SHA256 = '__SLOPE_TILES_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }
export const HEADER_BYTES = 32, NODATA = 255, FLAT = 8;
export const LOWER = [0, 2, 5, 10, 15, 25]; // lower edge of each class, percent
export const DEFAULT_LIMIT = 10;
export const LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 16;
export const STRIDE = 3, TICK_M = 1.4, LIFT_M = 0.08; // one tick every 3 m, 1.4 m long, 8 cm above ground
// Quiet colours for a dark background: sage, olive, ochre, clay, muted red; alpha rises with the slope.
export const COLORS = [null,
[0.56, 0.66, 0.58, 0.22], [0.66, 0.68, 0.48, 0.28], [0.78, 0.67, 0.42, 0.34],
[0.84, 0.56, 0.38, 0.42], [0.84, 0.44, 0.40, 0.52]];
// Pure: bytes -> { samples, spacing, e0, n0, classes, method, nodata, steep, cls, asp }.
export function decodeSlopeTile(buffer) {
const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
if (bytes.byteLength < HEADER_BYTES) throw Error('slope 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 !== 'GGS1') throw Error(`slope tile magic "${magic}" is not GGS1`);
const version = dv.getUint16(4, true);
if (version !== 1) throw Error(`slope tile version ${version} is not 1`);
const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true);
if (samples < 2 || spacingMm === 0) throw Error('slope tile has no usable grid');
const n = samples * samples;
if (bytes.byteLength !== HEADER_BYTES + 2 * n) throw Error(`slope 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),
classes: dv.getUint8(20), method: dv.getUint8(21), nodata: dv.getUint32(24, true), steep: dv.getUint32(28, true),
cls: new Uint8Array(bytes, HEADER_BYTES, n), asp: new Uint8Array(bytes, HEADER_BYTES + n, n)
};
}
// Pure: the first class that lies wholly at or above the limit (a limit between edges snaps up).
export function classForLimit(pct) {
if (!(pct > 0)) return 1;
for (let k = 1; k < LOWER.length; k++) if (LOWER[k] >= pct - 1e-9) return k;
return LOWER.length; // above 25 %: nothing the classes can promise
}
// Unit vector (east, north) pointing downslope for an aspect octant.
export function downslope(o) {
const a = o * Math.PI / 4;
return [Math.round(Math.sin(a) * 1e12) / 1e12, Math.round(Math.cos(a) * 1e12) / 1e12];
}
// Pure: tick segments for one tile, grouped by class. x0, y0: the tile's south-west corner in local metres.
// Positions are relative to origin. Returns { [class]: Float32Array } for classes with ticks.
export function ticks(t, x0, y0, minClass, heightAt, { stride = STRIDE, tick = TICK_M, lift = LIFT_M, origin = [0, 0, 0] } = {}) {
const out = {}, half = tick / 2, s = t.samples;
for (let j = 0; j < s; j += stride) {
for (let i = 0; i < s; i += stride) {
const k = j * s + i, c = t.cls[k], o = t.asp[k];
if (c === NODATA || c < minClass || o >= FLAT) continue;
const [dx, dy] = downslope(o), x = x0 + i * t.spacing, y = y0 + j * t.spacing;
const ax = x - dx * half, ay = y - dy * half, bx = x + dx * half, by = y + dy * half;
(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;
}
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 createSlope() {
let api = null, tl = null, enabled = false, limit = DEFAULT_LIMIT;
const ready = () => `index: ${tl.index.length} slope tiles`;
const layer = {
id: 'slope',
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: 'slope-tiles.json', path: INDEX_PATH, sha: () => INDEX_SHA256, tileNoun: 'slope tile', decode: decodeSlopeTile,
radius: LOAD_RADIUS, maxInFlight: MAX_IN_FLIGHT, maxTiles: MAX_TILES, active: () => enabled, keep: t => t.steep !== 0,
say: t => { layer.status = t; }, onReady: () => { layer.status = ready(); }
});
if (Number.isFinite(a.config?.limit)) limit = a.config.limit;
if (a.config?.enabled) layer.setEnabled(true);
},
setEnabled(on) {
enabled = !!on;
layer.status = enabled ? (tl?.state === 'ready' ? ready() : 'on') : 'off';
if (enabled) tl?.load();
api?.invalidate({ ground: false });
return enabled;
},
setLimit(pct) {
if (!Number.isFinite(pct)) throw Error('slope limit must be a number of percent');
limit = pct;
api?.invalidate({ ground: false });
return classForLimit(limit);
},
get enabled() { return enabled; },
get limit() { return limit; },
// ctx: { pos, heightAt, groundVersion }
lines(ctx) {
if (!api || !enabled) return [];
tl.frame(ctx.pos);
const minClass = classForLimit(limit), gv = ctx.groundVersion || 0, out = [];
if (minClass >= LOWER.length) return out;
for (const [key, t] of tl.near(ctx.pos)) {
const version = `${minClass}@${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 byClass = ticks(t.tile, t.x0, t.y0, minClass, ctx.heightAt, { origin: o });
t.cache = { version, heightAt: ctx.heightAt, batches: Object.keys(byClass).map(c => ({
key: `slope/${key}/${c}`, version, origin: o, color: COLORS[c], positions: byClass[c] })) };
}
tl.touch(t);
out.push(...t.cache.batches);
}
return out;
},
// For tests and the console.
debug: () => ({ ...tl?.debug(), enabled, limit, ...tl?.stats })
};
return layer;
}
export default createSlope();Visibility
A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`), covering visibility tiles and LiDAR terrain, using SHA-256.
ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/visibility.mjs · lines 1–141 of 141 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern hatch (shared by 9 files)
- What it does
- It lists and searches visibility tiles and LiDAR terrain. Defines 11 functions or classes, including setIndexSha, decodeVisibilityTile, caveatFor, seen, hatch.
- 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 visibility-tiles.json.
- What it achieves
- It sets index sha (`setIndexSha`) and decodes visibility tile (`decodeVisibilityTile`). Faint diagonal hatching draped on the ground wherever a target of the stated height (default 3 m, a panel top) could be seen by at least one observer standing on a road or footpath (eye height 1.7 m).
- 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
- none found
- Produces
- setIndexSha, LABEL, CAVEAT, CAVEAT_CANOPY, HEADER_BYTES, LOAD_RADIUS, STRIDE, COLOR, decodeVisibilityTile, caveatFor, hatch, LIB_VERSION
- Defines here
- setIndexSha, decodeVisibilityTile, caveatFor, seen, hatch, off, z, finite, createVisibility, describe, ready
- 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/visibility.mjs:1-141 · blob ff45d1ee0bc31ffe60189b4f1aab5524c55aa409 · 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: visibility. Faint diagonal hatching draped on the ground wherever a target of the stated height
// (default 3 m, a panel top) could be seen by at least one observer standing on a road or footpath (eye
// height 1.7 m). Off by default: until setEnabled(true) (or api.config.enabled) it fetches nothing and draws
// nothing. Visibility comes from .gvs tiles written by the lidar pipeline (lidar/src/viewshed.py: an exact
// sight line per cell, paired on the GPU against a radial sweep, with Earth curvature and refraction);
// every file is fetched through the substrate's hash check (api.fetchVerified). Heights come from
// ctx.heightAt, the ground.
//
// Unless the index says canopy heights were used, the layer carries the caveat CAVEAT: the answer is from
// bare-earth terrain only, so hedges, trees and buildings that would hide a target are not included.
//
// Tile format (.gvs, little-endian). 32-byte header:
// 0 magic "GGV1" | 4 u16 version=1 | 6 u16 samples | 8 u16 spacing_mm | 10 u16 flags (bit 0 curvature,
// bit 1 canopy) | 12 i32 origin_e_m | 16 i32 origin_n_m (south-west corner) | 20 u16 eye_mm | 22 u16 target_mm
// 24 u32 visible_count | 28 u32 nodata_count
// Body: samples*samples u8; rows south to north, west to east. 0 hidden from every observer; 1..254 the
// number of observers who see it (254 = 254 or more); 255 no data.
const INDEX_PATH = 'visibility/visibility-tiles.json';
// Filled by the build tool with the SHA-256 of visibility-tiles.json. Until then the layer loads nothing.
let INDEX_SHA256 = '__VISIBILITY_TILES_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }
export const LABEL = 'Visibility from roads and paths';
export const CAVEAT = 'computed from the EA LIDAR terrain only (thinned to 2 m); hedges, trees and buildings not included';
export const CAVEAT_CANOPY = 'computed from terrain and canopy heights';
export const HEADER_BYTES = 32, NODATA = 255;
export const LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 16;
export const STRIDE = 3, LIFT_M = 0.12; // a hatch lattice every 3 samples, 12 cm above ground
export const COLOR = [0.82, 0.88, 0.94, 0.16]; // faint: pale grey-blue, low alpha
// Pure: bytes -> { samples, spacing, flags, curvature, canopy, e0, n0, eye, target, visible, nodata, v }.
export function decodeVisibilityTile(buffer) {
const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
if (bytes.byteLength < HEADER_BYTES) throw Error('visibility 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 !== 'GGV1') throw Error(`visibility tile magic "${magic}" is not GGV1`);
const version = dv.getUint16(4, true);
if (version !== 1) throw Error(`visibility tile version ${version} is not 1`);
const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true), flags = dv.getUint16(10, true);
if (samples < 2 || spacingMm === 0) throw Error('visibility tile has no usable grid');
const n = samples * samples;
if (bytes.byteLength !== HEADER_BYTES + n) throw Error(`visibility tile is ${bytes.byteLength} bytes, expected ${HEADER_BYTES + n}`);
return {
samples, spacing: spacingMm / 1000, flags, curvature: !!(flags & 1), canopy: !!(flags & 2),
e0: dv.getInt32(12, true), n0: dv.getInt32(16, true), eye: dv.getUint16(20, true) / 1000,
target: dv.getUint16(22, true) / 1000, visible: dv.getUint32(24, true), nodata: dv.getUint32(28, true),
v: new Uint8Array(bytes, HEADER_BYTES, n)
};
}
// Pure: the caveat for an index (or null before one has loaded).
export function caveatFor(index) { return index && index.canopy === true ? CAVEAT_CANOPY : CAVEAT; }
const seen = c => c >= 1 && c !== NODATA;
// Pure: hatch strokes for one tile. A lattice every `stride` samples, aligned to the national grid so
// neighbouring tiles line up; from each visible lattice node whose north-east lattice neighbour is also
// visible, a stroke runs to that neighbour, bent once at its middle to follow the ground. Strokes on the
// tile's last row or column are left to the neighbouring tile (they share that edge).
// x0, y0: the tile's south-west corner in local metres. Returns a Float32Array of segments (6 floats each).
export function hatch(t, x0, y0, heightAt, { stride = STRIDE, lift = LIFT_M, origin = [0, 0, 0] } = {}) {
const out = [], s = t.samples, sp = t.spacing;
const gi0 = Math.round(t.e0 / sp), gj0 = Math.round(t.n0 / sp);
const off = g => ((stride - (g % stride)) % stride + stride) % stride; // first lattice index in the tile
const z = (x, y) => finite(heightAt(x, y)) + lift - origin[2];
for (let j = off(gj0); j + stride < s; j += stride) {
for (let i = off(gi0); i + stride < s; i += stride) {
if (!seen(t.v[j * s + i]) || !seen(t.v[(j + stride) * s + i + stride])) continue;
const ax = x0 + i * sp, ay = y0 + j * sp, d = stride * sp, mx = ax + d / 2, my = ay + d / 2;
const bx = ax + d, by = ay + d, mz = z(mx, my);
out.push(ax - origin[0], ay - origin[1], z(ax, ay), mx - origin[0], my - origin[1], mz,
mx - origin[0], my - origin[1], mz, bx - origin[0], by - origin[1], z(bx, by));
}
}
return new Float32Array(out);
}
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 createVisibility() {
let api = null, tl = null, enabled = false, indexMeta = null;
const describe = () => {
const what = indexMeta ? `target ${indexMeta.target_m} m, eye ${indexMeta.eye_m} m, ${(indexMeta.observers || []).length} observers` : '';
return [what, `${caveatFor(indexMeta)}`].filter(Boolean).join('; ');
};
const ready = () => `index: ${tl.index.length} visibility tiles; ${describe()}`;
const layer = {
id: 'visibility',
label: LABEL,
status: 'off',
get caveat() { return caveatFor(indexMeta); },
init(a) {
if (!a.lib?.tiles) { layer.status = 'refused: api.lib.tiles not provided'; return; }
api = a;
tl = a.lib.tiles.createTileLoader(a, {
file: 'visibility-tiles.json', path: INDEX_PATH, sha: () => INDEX_SHA256, tileNoun: 'visibility tile',
decode: decodeVisibilityTile, radius: LOAD_RADIUS, maxInFlight: MAX_IN_FLIGHT, maxTiles: MAX_TILES,
active: () => enabled, keep: t => t.visible !== 0,
say: t => { layer.status = t; }, onIndex: j => { indexMeta = j; }, onReady: () => { layer.status = ready(); }
});
if (a.config?.enabled) layer.setEnabled(true);
},
setEnabled(on) {
enabled = !!on;
layer.status = enabled ? (tl?.state === 'ready' ? ready() : `on; ${caveatFor(indexMeta)}`) : '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 = `v@${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 = hatch(t.tile, t.x0, t.y0, ctx.heightAt, { origin: o });
t.cache = { version, heightAt: ctx.heightAt,
batch: positions.length ? { key: `visibility/${key}`, version, origin: o, color: COLOR, positions } : null };
}
tl.touch(t);
if (t.cache.batch) out.push(t.cache.batch);
}
return out;
},
// For tests and the console.
debug: () => ({ ...tl?.debug(), enabled, ...tl?.stats })
};
return layer;
}
export default createVisibility();