In this section
- Contours ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/contours.mjs lines 1–182
- Ground Grid render · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/ground-grid.mjs lines 1–163
- Imagery render · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/imagery.mjs lines 1–248
Contours
A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha, decodes contour tile and calculates planar distances, covering contour tiles and LiDAR terrain, using Douglas-Peucker and SHA-256.
Set aside from the main view: 99% of its lines are the same as solar-design-studio/202609270439-site-world/world/layers/contours.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Contours; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9861 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/layers/contours.mjs:1-182 132dfa1989b4a1ca65e6f089c3305284bbb8d170
- sha256 cf733120a8c99f22e79119c77eebf7052d1026141366c4c0a4ef8286f462dcd4
- target sha256 7d8a7a3d5384cb1de00f101ac1064a3dc33daeceb1ea7eaf75764c868c758d56
- 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/contours.mjs · lines 1–182 of 182 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern decodeContourTile (shared by 2 files)
- What it does
- It lists and searches contour tiles and LiDAR terrain. Defines 14 functions or classes, including statusLine, setIndexSha, multiple, isIndex, onInterval.
- 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 contour-tiles.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- What it achieves
- It sets index sha (`setIndexSha`) and decodes contour tile (`decodeContourTile`). Contour lines draped 5 cm above the ground at a chosen interval (0.5, 1 or 5 m; default 1 m), with every 5 m line (an index contour) drawn slightly brighter.
- 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
- CAVEAT, EA_CREDIT, statusLine, setIndexSha, INTERVALS, LIFT_M, LOAD_RADIUS, LABEL_MIN_M, COLORS, isIndex, onInterval, decodeContourTile
- Defines here
- statusLine, setIndexSha, multiple, isIndex, onInterval, decodeContourTile, segments, labelsFor, fmt, drape, ivKey, createContours, ready, d
- 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/contours.mjs:1-182 · blob dc658868164f02f95aa63559ba8ebd047f3d963e · 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: contours. Contour lines draped 5 cm above the ground at a chosen interval (0.5, 1 or 5 m; default
// 1 m), with every 5 m line (an index contour) drawn slightly brighter. Optional height labels on index
// contours. Off by default: until setEnabled(true) (or api.config.enabled) it fetches nothing and draws
// nothing. Lines come from ggc1 tiles written by the lidar pipeline (lidar/src/contour_tiles.py: every
// 0.5 m level traced twice on the GPU, marching squares against row and column crossings, with a CPU
// witness; Douglas-Peucker simplified at 0.25 m). Every file is fetched through the substrate's hash check
// (api.fetchJSON with the sha256 from the index). Heights for draping come from ctx.heightAt, the ground.
//
// Tile (ggc1 JSON): { format: 'ggc1', e0, n0, tile_m: 256, unit_m: 0.01, dp_tol_m,
// levels: [{ z: metres, lines: [[x0, y0, x1, y1, ...], ...] }] } x, y whole centimetres from the tile's
// south-west corner (British National Grid metres = e0 + x * unit_m). Heights: metres above ODN.
const INDEX_PATH = 'contours/contour-tiles.json';
// Filled by the build tool with the SHA-256 of contour-tiles.json. Until then the layer loads nothing.
let INDEX_SHA256 = '__CONTOUR_TILES_SHA256__';
// Said wherever the layer's status is shown (tester 3): what the lines are drawn from, and how far they may sit
// from the true level in plan (the index's dp_tol_basis: traced chords plus simplification, 0.553 m measured), then
// the Environment Agency's credit (the index's attribution when it carries one).
export const CAVEAT = 'computed from the EA LIDAR terrain; up to about 0.55 m from the true contour between vertices; ' +
'heights in metres above Ordnance Datum Newlyn';
export const EA_CREDIT = '© Environment Agency copyright and/or database right 2022. All rights reserved.';
export const statusLine = (tiles, credit = EA_CREDIT) => `index: ${tiles} contour tiles; ${CAVEAT}. ${credit || EA_CREDIT}`;
export function setIndexSha(sha) { INDEX_SHA256 = sha; }
export const INTERVALS = [0.5, 1, 5], DEFAULT_INTERVAL = 1, INDEX_EVERY = 5;
export const LIFT_M = 0.05, STEP_M = 2; // 5 cm above ground; re-drape at least every 2 m
export const LOAD_RADIUS = 300, MAX_IN_FLIGHT = 2, MAX_TILES = 16;
export const LABEL_MIN_M = 40, MAX_LABELS = 48;
// Quiet on a dark background: minor lines a pale sage, index lines a little brighter and firmer.
export const COLORS = { minor: [0.62, 0.68, 0.60, 0.30], index: [0.80, 0.84, 0.74, 0.52] };
const multiple = (z, step) => Math.abs(z / step - Math.round(z / step)) < 1e-9;
export const isIndex = z => multiple(z, INDEX_EVERY);
export const onInterval = (z, iv) => multiple(z, iv);
// Pure: checks a parsed ggc1 tile and returns it with numbers in metres ready to use.
export function decodeContourTile(doc) {
if (!doc || doc.format !== 'ggc1') throw Error(`contour tile format "${doc && doc.format}" is not ggc1`);
if (!Number.isFinite(doc.e0) || !Number.isFinite(doc.n0)) throw Error('contour tile has no south-west corner');
const unit = doc.unit_m ?? 0.01;
if (!(unit > 0)) throw Error('contour tile has no unit');
if (!Array.isArray(doc.levels)) throw Error('contour tile has no levels list');
for (const lv of doc.levels) {
if (!Number.isFinite(lv.z) || !Array.isArray(lv.lines)) throw Error('contour level without z or lines');
for (const l of lv.lines) if (!Array.isArray(l) || l.length % 2 || l.length < 4) throw Error(`contour line at ${lv.z} m is not a list of x, y pairs`);
}
return { e0: doc.e0, n0: doc.n0, unit, size: doc.tile_m || 256, tol: doc.dp_tol_m, levels: doc.levels };
}
// Pure: line segments for one tile at one interval, as { minor, index } Float32Arrays of segment pairs.
// x0, y0: the tile's south-west corner in local metres. Each stored segment is split so no drawn piece is
// longer than `step`, and every vertex is draped at heightAt + lift. Positions are relative to origin.
export function segments(t, x0, y0, interval, heightAt, { lift = LIFT_M, step = STEP_M, origin = [0, 0, 0] } = {}) {
const out = { minor: [], index: [] }, u = t.unit;
for (const lv of t.levels) {
if (!onInterval(lv.z, interval)) continue;
const dst = isIndex(lv.z) ? out.index : out.minor;
for (const l of lv.lines) {
let px = x0 + l[0] * u, py = y0 + l[1] * u, pz = drape(heightAt, px, py, lift);
for (let k = 2; k < l.length; k += 2) {
const qx = x0 + l[k] * u, qy = y0 + l[k + 1] * u, n = Math.max(1, Math.ceil(Math.hypot(qx - px, qy - py) / step));
let ax = px, ay = py, az = pz;
for (let s = 1; s <= n; s++) {
const x = s === n ? qx : px + (qx - px) * s / n, y = s === n ? qy : py + (qy - py) * s / n, z = drape(heightAt, x, y, lift);
dst.push(ax - origin[0], ay - origin[1], az - origin[2], x - origin[0], y - origin[1], z - origin[2]);
ax = x; ay = y; az = z;
}
px = qx; py = qy; pz = az;
}
}
}
return { minor: new Float32Array(out.minor), index: new Float32Array(out.index) };
}
// Pure: one label per index contour line at least LABEL_MIN_M long, at the vertex nearest its middle,
// turned along the line. Local metres (not origin-relative); the host's text overlay draws them.
export function labelsFor(t, x0, y0, heightAt, { lift = LIFT_M, minLen = LABEL_MIN_M } = {}) {
const out = [], u = t.unit;
for (const lv of t.levels) {
if (!isIndex(lv.z)) continue;
for (const l of lv.lines) {
const cum = [0];
for (let k = 2; k < l.length; k += 2) cum.push(cum[cum.length - 1] + Math.hypot(l[k] - l[k - 2], l[k + 1] - l[k - 1]) * u);
const len = cum[cum.length - 1];
if (len < minLen) continue;
let m = 0;
for (let i = 1; i < cum.length; i++) if (Math.abs(cum[i] - len / 2) < Math.abs(cum[m] - len / 2)) m = i;
const j = Math.min(m + 1, cum.length - 1), i = j - 1;
const x = x0 + l[2 * m] * u, y = y0 + l[2 * m + 1] * u;
out.push({ pos: [x, y, drape(heightAt, x, y, lift)], text: `${fmt(lv.z)} m`, z: lv.z,
angle: Math.atan2(l[2 * j + 1] - l[2 * i + 1], l[2 * j] - l[2 * i]) });
}
}
return out;
}
const fmt = z => (Number.isInteger(z) ? String(z) : z.toFixed(1));
const drape = (h, x, y, lift) => { const v = h(x, y); return (Number.isFinite(v) ? v : 0) + lift; };
const ivKey = iv => iv.toFixed(1); // the index writes by_interval keys as "0.5", "1.0", "5.0"
// The layer: tiles come through the shared loader (api.lib.tiles), which the substrate hash-checks.
export const LIB_VERSION = 1;
export function createContours() {
let api = null, tl = null, enabled = false, interval = DEFAULT_INTERVAL, labelsOn = false, credit = EA_CREDIT;
const ready = () => statusLine(tl.index.length, credit);
const layer = {
id: 'contours',
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: 'contour-tiles.json', path: INDEX_PATH, sha: () => INDEX_SHA256, tileNoun: 'contour tile', json: true,
decode: decodeContourTile, size: t => t.size, radius: LOAD_RADIUS, maxInFlight: MAX_IN_FLIGHT, maxTiles: MAX_TILES,
active: () => enabled, keep: t => (t.by_interval?.[ivKey(interval)]?.lines ?? 1) > 0,
say: t => { layer.status = t; }, onReady: () => { layer.status = ready(); },
onIndex: j => { if (typeof j?.attribution === 'string' && /Environment Agency/.test(j.attribution)) credit = j.attribution; },
onMove: () => { for (const t of tl.loaded.values()) t.labels = null; }
});
if (INTERVALS.includes(a.config?.interval)) interval = a.config.interval;
if (a.config?.labels) labelsOn = true;
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;
},
setInterval(m) {
if (!INTERVALS.includes(m)) throw Error(`contour interval must be one of ${INTERVALS.join(', ')} m`);
interval = m;
tl?.pump();
api?.invalidate({ ground: false });
return interval;
},
setLabels(on) { labelsOn = !!on; api?.invalidate({ ground: false }); return labelsOn; },
get enabled() { return enabled; },
get interval() { return interval; },
get labelsOn() { return labelsOn; },
// ctx: { pos, heightAt, groundVersion }
lines(ctx) {
if (!api || !enabled) return [];
tl.frame(ctx.pos);
const gv = ctx.groundVersion || 0, out = [], version = `${interval}@${gv}`;
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, drape(ctx.heightAt, cx, cy, 0)];
const s = segments(t.tile, t.x0, t.y0, interval, ctx.heightAt, { origin: o });
t.cache = { version, heightAt: ctx.heightAt, batches: ['minor', 'index'].filter(k => s[k].length).map(k => ({
key: `contours/${key}/${k}`, version, origin: o, color: COLORS[k], positions: s[k] })) };
}
tl.touch(t);
out.push(...t.cache.batches);
}
return out;
},
// Optional height labels on index contours, nearest tiles first: [{ pos, text, z, angle }]. Empty
// unless setLabels(true); the renderer needs a text overlay to show them.
labels(ctx) {
if (!api || !enabled || !labelsOn) return [];
const out = [], gv = ctx.groundVersion || 0;
for (const [, t] of tl.near(ctx.pos)) {
if (!t.labels || t.labels.gv !== gv || t.labels.heightAt !== ctx.heightAt) {
t.labels = { gv, heightAt: ctx.heightAt, list: labelsFor(t.tile, t.x0, t.y0, ctx.heightAt) };
}
out.push(...t.labels.list);
}
const d = l => Math.hypot(l.pos[0] - ctx.pos[0], l.pos[1] - ctx.pos[1]);
return out.sort((a, b) => d(a) - d(b)).slice(0, MAX_LABELS);
},
// For tests and the console.
debug: () => ({ ...tl?.debug(), enabled, interval, labelsOn, ...tl?.stats })
};
return layer;
}
export default createContours();Ground Grid
A JavaScript module in the layers folder of GlobalGrid2050 that works with height store (`heightStore`) and origin mark (`originMark`).
Set aside from the main view: 93% of its lines are the same as solar-design-studio/202609271740-site-world/world/layers/ground-grid.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Ground Grid; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9328 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/layers/ground-grid.mjs:1-158 ccb2f775cb9dcf7a424e23e6370d8242611c2f16
- sha256 df6e9333bbb2cd46660afd016d312371e8f907f65c05bdf172b2ac7576683c84
- target sha256 0556afb378177d8a8647776f2c70406a658f0ca1013b382d969dbf9712eb8d46
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
renderglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/ground-grid.mjs · lines 1–163 of 163 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern originMark (shared by 2 files)
- What it does
- Defines 7 functions or classes, including later, grid, wrap, slotOf, heightStore.
- 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 later step (`later`), the grid step (`grid`) and the wrap step (`wrap`). A 1 m grid near the viewer and a 10 m grid to the horizon, draped on whatever ground the world has (flat until a terrain layer supplies `heightAt`).
- 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
- DETAIL, REACH, grid
- Defines here
- later, grid, wrap, slotOf, heightStore, originMark, finite
- 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/ground-grid.mjs:1-163 · blob 1f5513fafe7d7c915300779643d5d855d6823e68 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Layer: ground grid. A 1 m grid near the viewer and a 10 m grid to the horizon, draped on whatever
// ground the world has (flat until a terrain layer supplies heightAt). The grid follows the viewer in
// 10 m steps, so it looks endless but only ever holds a few thousand lines.
// Within 100 m of the viewer every segment is split to 2 m or less, so the grid follows real banks and
// ditches rather than bridging them. Batches carry an origin at the centre of the viewer's 10 m cell and
// positions relative to it, so they stay sharp on the GPU. The grid is rebuilt on a new cell or new ground.
//
// Cost: every grid point is a heightAt call, and real terrain makes those dear (about 45,000 per rebuild
// before, when each segment asked for both ends). Now each point is asked for once: heights are kept in
// a store for one ground (one heightAt and groundVersion), so stepping into a new 10 m cell only asks for
// the strip of points that came into view. New ground starts a new store and nothing old is trusted: the
// first frame asks again for everything within 50 m (the 1 m grid and the nearest banks and ditches), and
// the next few frames widen that to 150 m, 300 m and the horizon. Until a far point is asked again it is
// drawn at its height on the previous ground, so a new tile never stalls a walk for a whole rebuild.
//
// Measured ground only (v05, phantom plateau): past the loaded terrain tiles the world's heightAt keeps the
// last height it knew, and a grid drawn there is a flat plateau that is not on the ground (up to 59 px of false
// horizon over a valley, GPU ray-cast check). When the page says which ground is measured (ctx.known) and the
// viewer stands on measured ground, a segment is drawn only if both its ends are measured: the grid ends at the
// loaded edge. With no measured ground under the viewer (the empty world) the flat grid is the only ground.
const MINOR = { spacing: 1, radius: 30, color: [156 / 255, 219 / 255, 1, 0.16] }; // #9cdbff
const MAJOR = { spacing: 10, radius: 400, color: [156 / 255, 219 / 255, 1, 0.42] };
const ORIGIN = { color: [1, 1, 1, 0.9], arm: 5 };
const FOLLOW = 10;
export const DETAIL = { radius: 100, step: 2 }; // near the viewer, no segment is longer than 2 m
export const REACH = [50, 150, 300, Infinity]; // metres asked again on the frames after new ground
let cached = { version: null, batches: [] };
let store = null, api = null;
export default {
id: 'ground-grid',
init(a) { api = a; },
// ctx: { pos, heightAt, known?(x, y) -> measured ground there, groundVersion?, origin? }
lines({ pos, heightAt, known = null, groundVersion = 0 }) {
const cx = Math.floor(pos[0] / FOLLOW) * FOLLOW, cy = Math.floor(pos[1] / FOLLOW) * FOLLOW;
const clip = typeof known === 'function' && !!known(cx + FOLLOW / 2, cy + FOLLOW / 2) ? known : null;
const version = cx + ',' + cy + '@' + groundVersion + (clip ? '/m' : ''), same = cached.version === version && cached.heightAt === heightAt;
if (same && cached.pass === store.pass) return cached.batches; // new cell, new ground or a wider reach only
if (!store || !store.fits(heightAt, groundVersion, clip)) store = heightStore(heightAt, groundVersion, cx, cy, api ? store : null, clip);
const mx = cx + FOLLOW / 2, my = cy + FOLLOW / 2, sample = store.begin(mx, my), mz = sample(mx, my);
const origin = [mx, my, mz], opts = { origin, near: [mx, my], sample, known: clip && store.knownAt };
const step = store.pass ? '#' + store.pass : '', tag = version + step;
const minor = same && cached.minorWhole ? cached.batches[0]
: { key: 'ground-grid/minor', version: tag, origin, color: MINOR.color, positions: grid(cx, cy, MINOR, heightAt, opts) };
const minorWhole = !store.partial;
const major = { key: 'ground-grid/major', version: tag, origin, color: MAJOR.color, positions: grid(cx, cy, MAJOR, heightAt, opts) };
const mark = { key: 'ground-grid/origin', version: 'origin@' + groundVersion + step, color: ORIGIN.color, positions: originMark(sample, mz) };
cached = { version, heightAt, pass: store.pass, minorWhole, batches: [minor, major, mark] };
if (store.partial) later(store); // after this frame: widen the reach and ask for another frame
return cached.batches;
}
};
// Only with a live page (init gave an api to ask for frames) does new ground arrive in steps; without
// one, every rebuild asks for every point it lacks.
function later(s) {
setTimeout(() => { if (s === store && s.partial) { s.widen(); api.invalidate({ ground: false }); } }, 0);
}
// Lines of the grid centred on (cx, cy). Positions are relative to opts.origin ([0, 0, 0] by default).
// Segments whose midpoint lies within DETAIL.radius of opts.near are split to DETAIL.step or less.
// opts.sample(x, y, guess), if given, is used in place of heightAt and must return a finite height; guess is
// the height of the point before it on the line (the origin's for the first), for a sampler that may guess.
// opts.known(x, y), if given, says where ground is measured: a segment is left out unless both its ends are.
export function grid(cx, cy, { spacing, radius }, heightAt, { origin = [0, 0, 0], near = null, sample = null, known = null } = {}) {
const h = sample || ((x, y) => finite(heightAt(x, y)));
const n = Math.round(radius / spacing), pieces = spacing > DETAIL.step ? Math.ceil(spacing / DETAIL.step) : 1;
const [ox, oy, oz] = origin, r2 = DETAIL.radius * DETAIL.radius;
// How many pieces the segment from b0 to b0 + spacing along a line at offset a is cut into.
const split = pieces > 1 && near
? (ax, ay, bx, by) => { const dx = (ax + bx) / 2 - near[0], dy = (ay + by) / 2 - near[1]; return dx * dx + dy * dy <= r2 ? pieces : 1; }
: () => 1;
let count = 0;
for (let i = -n; i <= n; i++) {
const a = i * spacing;
for (let j = -n; j < n; j++) {
const b0 = j * spacing, b1 = b0 + spacing;
count += split(cx + a, cy + b0, cx + a, cy + b1) + split(cx + b0, cy + a, cx + b1, cy + a);
}
}
const out = new Float32Array(count * 6);
let w = 0;
for (let i = -n; i <= n; i++) {
const a = i * spacing;
for (let dir = 0; dir < 2; dir++) { // 0: north-south line at x = cx + a; 1: east-west line at y = cy + a
let px = dir ? cx - n * spacing : cx + a, py = dir ? cy + a : cy - n * spacing, pz = h(px, py, oz);
let pk = !known || !!known(px, py);
for (let j = -n; j < n; j++) {
const b0 = j * spacing, b1 = b0 + spacing;
const x0 = dir ? cx + b0 : cx + a, y0 = dir ? cy + a : cy + b0, x1 = dir ? cx + b1 : cx + a, y1 = dir ? cy + a : cy + b1;
const k = split(x0, y0, x1, y1);
for (let p = 0; p < k; p++) {
const qx = x0 + (x1 - x0) * (p + 1) / k, qy = y0 + (y1 - y0) * (p + 1) / k, qz = h(qx, qy, pz); // whole metres stay whole
const qk = !known || !!known(qx, qy);
if (pk && qk) {
out[w++] = px - ox; out[w++] = py - oy; out[w++] = pz - oz;
out[w++] = qx - ox; out[w++] = qy - oy; out[w++] = qz - oz;
}
px = qx; py = qy; pz = qz; pk = qk;
}
}
}
}
return w < out.length ? out.slice(0, w) : out;
}
// Heights asked for once per ground, kept in fixed typed arrays that wrap around as the viewer walks
// (no Map, nothing to trim). A whole-metre point on a 10 m line has a slot in one of two line planes;
// any other whole-metre point near the viewer has one in the inner plane; each slot remembers which point
// and which ground it holds. Other points go straight to heightAt. A store serves one heightAt and one
// groundVersion (and one known, whose answers it keeps beside the heights). When the store before it had the same heightAt, a new store asks only within its reach
// of the centre and answers further points from older ground (or the guess), marking itself partial.
const LINES = 2 * Math.ceil(MAJOR.radius / MAJOR.spacing) + 4, ALONG = 2 * MAJOR.radius + 4 * FOLLOW, INNER = 2 * MINOR.radius + 12;
let slots = null, generation = 0;
const wrap = (v, m) => ((v % m) + m) % m;
function slotOf(x, y) {
if ((x | 0) !== x || (y | 0) !== y) return -1;
if (x % MAJOR.spacing === 0) return wrap(x / MAJOR.spacing, LINES) * ALONG + wrap(y, ALONG);
if (y % MAJOR.spacing === 0) return (LINES + wrap(y / MAJOR.spacing, LINES)) * ALONG + wrap(x, ALONG);
return 2 * LINES * ALONG + wrap(x, INNER) * INNER + wrap(y, INNER);
}
function heightStore(heightAt, groundVersion, cx, cy, before, known = null) {
if (!slots) {
const n = 2 * LINES * ALONG + INNER * INNER;
slots = { z: new Float64Array(n), x: new Int32Array(n).fill(-0x80000000), y: new Int32Array(n), gen: new Uint32Array(n), k: new Uint8Array(n) };
}
const { z, x: sx, y: sy, gen, k: kn } = slots, g = ++generation;
const guessing = !!before && before.heightAt === heightAt;
let pass = guessing ? 0 : REACH.length - 1, reach2 = REACH[pass] ** 2, mx = 0, my = 0;
const self = {
heightAt, partial: false,
get pass() { return pass; },
sample(x, y, guess = 0) {
const k = slotOf(x, y);
if (k < 0) return finite(heightAt(x, y));
const held = sx[k] === x && sy[k] === y;
if (held && gen[k] === g) return z[k];
if ((x - mx) ** 2 + (y - my) ** 2 > reach2) { self.partial = true; return held ? z[k] : guess; } // older ground
const h = finite(heightAt(x, y));
z[k] = h; sx[k] = x; sy[k] = y; gen[k] = g; kn[k] = known && known(x, y) ? 1 : 0;
return h;
},
// Whether (x, y) is measured, for a point sample has just answered: a slot keeps the answer with its height;
// a far point answered from older ground is taken as unmeasured until it is asked again.
knownAt(x, y) {
const k = slotOf(x, y);
if (k < 0) return !!known(x, y);
return sx[k] === x && sy[k] === y && gen[k] === g ? kn[k] === 1 : false;
},
begin(x, y) { mx = x; my = y; self.partial = false; return self.sample; },
widen() { pass = Math.min(pass + 1, REACH.length - 1); reach2 = REACH[pass] ** 2; },
fits: (f, gv, kf = null) => f === heightAt && gv === groundVersion && kf === known && g === generation
};
return self;
}
function originMark(sample, guess) {
const a = ORIGIN.arm, h = sample(0, 0, guess);
return new Float32Array([-a, 0, h, a, 0, h, 0, -a, h, 0, a, h, 0, 0, h, 0, 0, h + 2 * a]);
}
const finite = h => (Number.isFinite(h) ? h : 0);Imagery
A JavaScript module in the layers folder of GlobalGrid2050 that loads index (`loadIndex`) and draws on a canvas, using k-means and SHA-256. It indexes pixels (`indexPixels`) and loads index (`loadIndex`).
renderglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/imagery.mjs · lines 1–248 of 248 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern browserDecode (shared by 2 files)
- What it does
- It draws its content. Defines 18 functions or classes, including framesOf, creditFor, sliderModel, paletteOf, lum. 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.
- Inputs & outputs
- Out: canvas drawing.
- What it achieves
- A satellite picture of the site laid on the ground, under every other line, in the Map and Drone views only (never Walk). It responds to input events.
- 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
- LIFT_M, SHOWN_IN, CREDIT, framesOf, creditFor, sliderModel, paletteOf, nearest, indexPixels, heightGrid, drapeImage, createImagery
- Defines here
- framesOf, creditFor, sliderModel, paletteOf, lum, nearest, indexPixels, finite, heightGrid, drapeImage, ok, browserDecode, createImagery, origin, box, loadIndex, request, sync
- 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/imagery.mjs:1-248 · blob 4c0a8fe495c4098bb4f237e6072994a85130deb8 · 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: unreached_review
// Layer: imagery. A satellite picture of the site laid on the ground, under every other line, in the Map
// and Drone views only (never Walk). Off by default: until setEnabled(true) it fetches and draws nothing.
//
// Frames, in date order, chosen with a slider:
// season cloud-free composite of one meteorological season (median of the clear looks, GPU-checked)
// date one clear Sentinel-2 date (measured box cloud <= 1 %), the best one a month, for a time lapse
// Frames come from the site's imagery/index.json, written by the lidar pipeline and staged by
// tools/stage-imagery.mjs. Each image is fetched through the substrate's hash check. Open data only
// (Copernicus Sentinel); no keyed or licensed basemap is used (docs/imagery-licences.md).
//
// The world draws lines only, so the picture is drawn as lines too: every pixel row becomes east-west runs
// of one colour, a short lift above the ground, so the design and the grid lines are drawn over it. The
// colours are reduced to a palette of PALETTE colours fitted to each picture (k-means, seeded by luminance rank,
// no randomness), so the whole picture is at most PALETTE batches and keeps its true colours.
// Self-contained: no imports (the loader runs it from a blob URL).
export const LIFT_M = 0.03, ALPHA = 0.8, PALETTE = 48, RUN_MAX_PX = 4, ROWS_PER_PX = 4, FADE_M = 6000;
export const SHOWN_IN = Object.freeze(['aerial', 'map']); // Drone and Map, never Walk ('standing')
export const CREDIT = 'Contains modified Copernicus Sentinel data';
const SEASON_WORD = { winter: 'Winter', spring: 'Spring', summer: 'Summer', autumn: 'Autumn' };
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// Pure: the frames of an imagery index, oldest first.
export function framesOf(index) {
const out = [];
for (const c of index?.composites || []) {
if (!c.file || !/^[0-9a-f]{64}$/i.test(c.sha256 || '')) continue;
const [s, y] = String(c.season).split('-');
out.push({ id: 'season:' + c.season, kind: 'season', key: c.start, file: c.file, sha256: c.sha256,
label: `${SEASON_WORD[s] || s} ${y} composite · ${c.looks} clear looks` });
}
for (const d of index?.dates || []) {
if (!d.file || !/^[0-9a-f]{64}$/i.test(d.sha256 || '')) continue;
const [y, m, dd] = d.date.split('-');
out.push({ id: 'date:' + d.date, kind: 'date', key: d.date, file: d.file, sha256: d.sha256,
label: `${Number(dd)} ${MONTHS[Number(m) - 1]} ${y} · cloud ${(100 * (d.box_cloud || 0)).toFixed(1)} %` });
}
out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : a.kind === 'season' ? -1 : 1));
return out;
}
// Pure: the credit line a frame needs on screen.
export function creditFor(frame, index) {
if (!frame) return '';
const c = index?.licence?.credit;
return typeof c === 'string' && c.startsWith(CREDIT) ? c : CREDIT;
}
// Pure: the slider's state for frame i.
export function sliderModel(frames, i, index) {
const n = frames.length, v = n ? Math.max(0, Math.min(n - 1, i | 0)) : 0;
return { min: 0, max: Math.max(0, n - 1), value: v, label: n ? frames[v].label : 'No imagery for this site', credit: creditFor(frames[v], index) };
}
// Pure: palette index of an sRGB colour (0..255 each).
// Pure: a palette of up to k colours fitted to the opaque pixels (Lloyd's k-means, 8 rounds, on at most
// about 8000 evenly spaced pixels; seeds at evenly spaced luminance ranks). Returns [[r, g, b], ...] 0..255.
export function paletteOf(img, k = PALETTE) {
const d = img.data, n = img.width * img.height, opaque = [];
for (let p = 0; p < n; p++) if (d[4 * p + 3] >= 128) opaque.push(p);
if (!opaque.length) return [];
const step = Math.max(1, Math.floor(opaque.length / 8000)), S = opaque.filter((_, i) => i % step === 0);
const lum = p => 0.299 * d[4 * p] + 0.587 * d[4 * p + 1] + 0.114 * d[4 * p + 2];
S.sort((a, b) => lum(a) - lum(b) || a - b);
const m = Math.min(k, S.length);
let C = Array.from({ length: m }, (_, i) => { const p = S[Math.floor((i + 0.5) * S.length / m)]; return [d[4 * p], d[4 * p + 1], d[4 * p + 2]]; });
for (let round = 0; round < 8; round++) {
const sum = C.map(() => [0, 0, 0, 0]);
for (const p of S) { const c = nearest(C, d[4 * p], d[4 * p + 1], d[4 * p + 2]), t = sum[c]; t[0] += d[4 * p]; t[1] += d[4 * p + 1]; t[2] += d[4 * p + 2]; t[3]++; }
C = C.map((c, i) => (sum[i][3] ? [sum[i][0] / sum[i][3], sum[i][1] / sum[i][3], sum[i][2] / sum[i][3]] : c));
}
return C;
}
export function nearest(C, r, g, b) {
let best = 0, bd = Infinity;
for (let i = 0; i < C.length; i++) { const q = C[i], e = (q[0] - r) ** 2 + (q[1] - g) ** 2 + (q[2] - b) ** 2; if (e < bd) { bd = e; best = i; } }
return best;
}
// Pure: palette index per pixel, -1 where the pixel is clear (alpha < 128).
export function indexPixels(img, C) {
const d = img.data, n = img.width * img.height, out = new Int16Array(n);
for (let p = 0; p < n; p++) out[p] = d[4 * p + 3] < 128 || !C.length ? -1 : nearest(C, d[4 * p], d[4 * p + 1], d[4 * p + 2]);
return out;
}
// Pure: heights at the pixel corners of a w x h picture over the square box ((w + 1) x (h + 1), row 0 north).
// box: { x0, y0, size } local metres, south-west corner; row 0 of the picture is the north edge.
// known(x, y), if given, says where ground is measured; elsewhere the corner is NaN and nothing is drawn on it
// (v05: no picture laid on the flat last-known height past the loaded terrain).
const finite = v => (Number.isFinite(v) ? v : 0);
export function heightGrid(w, h, box, heightAt, known = null) {
const px = box.size / w, py = box.size / h, H = new Float32Array((w + 1) * (h + 1));
for (let j = 0; j <= h; j++) {
const y = box.y0 + box.size - j * py;
for (let i = 0; i <= w; i++) {
const x = box.x0 + i * px, z = known && !known(x, y) ? NaN : heightAt(x, y);
H[j * (w + 1) + i] = Number.isFinite(z) ? z : known ? NaN : 0;
}
}
return H;
}
// Pure: the drape. px: { width, height, idx } (indexPixels). Returns { [palette index]: Float32Array of x,y,z pairs }
// relative to origin. Runs of one colour are merged up to RUN_MAX_PX pixels so the lines follow the ground;
// each pixel row is drawn as `rows` lines (heights interpolated between its corners) so the picture reads solid.
// A pixel with an unmeasured (NaN) corner is left out, and no run crosses one.
export function drapeImage(img, box, H, { lift = LIFT_M, origin = [0, 0, 0], rows = ROWS_PER_PX } = {}) {
const w = img.width, h = img.height, px = box.size / w, py = box.size / h, out = {}, q = img.idx, W = w + 1;
for (let j = 0; j < h; j++) {
const ok = k => Number.isFinite(H[j * W + k]) && Number.isFinite(H[(j + 1) * W + k]);
let i = 0;
while (i < w) {
const pal = q[j * w + i];
if (pal < 0 || !ok(i)) { i++; continue; }
let e = i + 1;
while (e < w && e - i < RUN_MAX_PX && q[j * w + e] === pal && ok(e)) e++;
if (!ok(e)) { if (e - 1 > i) e--; else { i = e; continue; } }
const o = (out[pal] ||= []), xa = box.x0 + i * px - origin[0], xb = box.x0 + e * px - origin[0];
for (let r = 0; r < rows; r++) {
const t = (r + 0.5) / rows, y = box.y0 + box.size - (j + t) * py - origin[1];
const za = H[j * W + i] * (1 - t) + H[(j + 1) * W + i] * t, zb = H[j * W + e] * (1 - t) + H[(j + 1) * W + e] * t;
o.push(xa, y, za + lift - origin[2], xb, y, zb + lift - origin[2]);
}
i = e;
}
}
for (const k in out) out[k] = new Float32Array(out[k]);
return out;
}
async function browserDecode(bytes) {
const bmp = await createImageBitmap(new Blob([bytes]));
const c = new OffscreenCanvas(bmp.width, bmp.height), g = c.getContext('2d');
g.drawImage(bmp, 0, 0);
const im = g.getImageData(0, 0, bmp.width, bmp.height);
bmp.close?.();
return { width: im.width, height: im.height, data: im.data };
}
export function createImagery({ decode = browserDecode, doc = globalThis.document } = {}) {
let api = null, enabled = false, index = null, indexState = 'idle', frames = [], pick = 0, view = null;
const images = new Map(); // frame id -> { width, height, data }
const pending = new Set();
let heights = null, cache = null, ui = null;
const origin = () => (api?.origin ? api.origin() : { e: 0, n: 0, id: 0 });
const box = () => { const o = origin(), b = index.box; return { x0: b.origin_e - o.e, y0: b.origin_n - o.n, size: b.size_m }; };
function loadIndex() {
if (indexState !== 'idle' || !api || !enabled) return;
const path = api.config?.index, sha = api.config?.sha256;
if (!path || !/^[0-9a-f]{64}$/i.test(sha || '')) { indexState = 'failed'; layer.status = 'no imagery staged for this site'; sync(); return; }
indexState = 'loading';
Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
if (!j?.box || !Number.isFinite(j.box.size_m)) throw Error('imagery index has no box');
index = { ...j, dir: path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '' };
frames = framesOf(index);
pick = Math.max(0, frames.findLastIndex(f => f.kind === 'season'));
indexState = 'ready';
layer.status = `${frames.length} frames`;
sync(); request();
}).catch(e => { indexState = 'failed'; layer.status = 'imagery index failed: ' + e.message; sync(); });
}
function request() {
const f = frames[pick];
if (!f || images.has(f.id) || pending.has(f.id) || !enabled) return;
pending.add(f.id);
Promise.resolve().then(() => api.fetchVerified(index.dir + f.file, f.sha256)).then(b => decode(b)).then(img => { images.set(f.id, img); api.invalidate({ ground: false }); })
.catch(e => { layer.status = `${f.label}: ${e.message}`; sync(); })
.finally(() => pending.delete(f.id));
}
function sync() {
if (!ui) return;
const m = sliderModel(frames, pick, index), show = enabled && SHOWN_IN.includes(view);
ui.root.hidden = !show;
ui.range.min = m.min; ui.range.max = m.max; ui.range.value = m.value; ui.range.disabled = frames.length < 2;
ui.label.textContent = indexState === 'ready' ? m.label : layer.status;
ui.credit.textContent = m.credit;
}
const layer = {
id: 'imagery',
status: 'off',
init(a) { api = a; if (a.config?.enabled) layer.setEnabled(true); },
setEnabled(on) {
enabled = !!on;
layer.status = enabled ? (indexState === 'ready' ? `${frames.length} frames` : 'on') : 'off';
if (enabled) { loadIndex(); request(); }
sync();
api?.invalidate({ ground: false });
return enabled;
},
get enabled() { return enabled; },
frames: () => frames.map(f => ({ id: f.id, kind: f.kind, label: f.label })),
get selected() { return pick; },
select(i) {
if (!frames.length) return pick;
pick = Math.max(0, Math.min(frames.length - 1, i | 0));
request(); sync(); api?.invalidate({ ground: false });
return pick;
},
// attribution.json layer keys for what is on screen now: none, or 'imagery' (Copernicus).
creditKeys: () => (!enabled || !SHOWN_IN.includes(view) || !frames[pick] || !images.has(frames[pick].id) ? [] : ['imagery']),
credit: () => creditFor(frames[pick], index),
// A slider, its label and the credit, shown only while the layer is on in Map or Drone.
mountControls(container) {
if (!doc || !container || ui) return ui?.root || null;
const root = doc.createElement('div'), range = doc.createElement('input'), label = doc.createElement('p'), credit = doc.createElement('p');
root.id = 'imagery-controls'; root.hidden = true;
root.style.cssText = 'position:fixed;left:8px;bottom:64px;width:min(300px,calc(100vw - 16px));box-sizing:border-box;padding:6px 10px;' +
'background:var(--panel,rgba(10,10,10,0.86));border:1px solid var(--edge,#1c2c3a);border-radius:6px;color:var(--text,#cfe9ff);font-size:12px';
range.type = 'range'; range.step = 1; range.style.width = '100%'; range.setAttribute('aria-label', 'Imagery date');
label.style.margin = '2px 0 0'; credit.style.cssText = 'margin:2px 0 0;font-size:10px;color:var(--dim,#6f8ea6)';
range.addEventListener('input', () => layer.select(Number(range.value)));
root.append(range, label, credit); container.appendChild(root);
ui = { root, range, label, credit }; sync();
return root;
},
// ctx: { pos, heightAt, groundVersion, view }
lines(ctx) {
if (view !== ctx.view) { view = ctx.view; sync(); }
if (!api || !enabled || !SHOWN_IN.includes(ctx.view)) return [];
if (indexState === 'idle') loadIndex();
const f = frames[pick], img = f && images.get(f.id);
if (!img) { request(); return []; }
const o = origin(), gv = ctx.groundVersion || 0, b = box();
const hk = `${img.width}x${img.height}@${gv}/${o.id}`;
if (!heights || heights.key !== hk || heights.heightAt !== ctx.heightAt) heights = { key: hk, heightAt: ctx.heightAt, H: heightGrid(img.width, img.height, b, ctx.heightAt,
typeof ctx.known === 'function' ? ctx.known : null) };
const version = `${f.id}/${hk}`;
if (!cache || cache.version !== version) {
const hc = heights.H[(img.height >> 1) * (img.width + 1) + (img.width >> 1)];
const c = [b.x0 + b.size / 2, b.y0 + b.size / 2, Number.isFinite(hc) ? hc : finite(ctx.heightAt(b.x0 + b.size / 2, b.y0 + b.size / 2))];
img.C ||= paletteOf(img); img.idx ||= indexPixels(img, img.C);
const byPal = drapeImage(img, b, heights.H, { origin: c });
cache = { version, batches: Object.keys(byPal).map(k => ({ key: `imagery/${k}`, version, origin: c, fade: FADE_M,
color: [...img.C[k].map(v => v / 255), ALPHA], positions: byPal[k] })) };
}
return cache.batches;
},
debug: () => ({ indexState, enabled, view, pick, frames: frames.length, images: [...images.keys()], pending: [...pending] })
};
return layer;
}
export default createImagery();