GLOBALGRID2050 / EXPLORE CODE

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

Earthworks and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that strips volume (`stripVolume`) and calculates planar distances.

617 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 147 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. Water ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/water.mjs lines 1–119
  2. Ways ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/ways.mjs lines 1–160
  3. Drape transform · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/lib/drape.mjs lines 1–99
  4. Earthworks transform · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/lib/earthworks.mjs lines 1–226
  5. Site World V3 — World other · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/lib/index.mjs lines 1–13

Water

A JavaScript module in the layers folder of GlobalGrid2050 that sets index sha (`setIndexSha`) and calculates planar distances, covering rivers, using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/layers/water.mjs · lines 1–119 of 119 · 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 rivers. Defines 6 functions or classes, including setIndexSha, finite, createWater, origin, load.
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 rivers.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 origin step (`origin`). Watercourse centrelines from OS Open Rivers (`rivers.json`, cut per site by `tools/features/cut_rivers.py`), draped 5 cm above the ground, in a quiet blue.
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, LIFT_M, STEP_M, NEAR_M, SPACING_M, MAX_DT, MOVE_EPS, LINE_COLOR, TICK_COLOR, TICKS, LIB_VERSION, createWater
Defines here
setIndexSha, finite, createWater, origin, load, localLines
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/water.mjs:1-119 · blob 1f9af9c404c402a7d12769a0c264435f06d9aaa4 · 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: water. Watercourse centrelines from OS Open Rivers (rivers.json, cut per site by
// tools/features/cut_rivers.py), draped 5 cm above the ground, in a quiet blue. Each line's points run
// downstream: OS digitise links in the direction of water flow, and the cutter reverses the few marked
// otherwise. Lines with "flow": "unknown" are drawn but carry no flow ticks.
//
// Flow ticks: short marks that creep downstream along a line. They are shown only while the Water layer is
// switched on (setEnabled(true) or api.config.enabled), or while the viewer is moving within 300 m of the
// line. The layer never asks for a frame to animate: the ticks advance only on frames the world draws
// anyway, and their clock runs only while the viewer moves, so standing still costs 0 fps and nothing jumps.
//
// rivers.json: { licence, attribution, source: { sha256 }, lines: [{ name?, form, flow?, points: [[e, n], ...] }] }
// Points 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.

const INDEX_PATH = 'water/rivers.json';
let INDEX_SHA256 = '__WATER_RIVERS_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }

export const LIFT_M = 0.05, TICK_LIFT_M = 0.07;  // line 5 cm above ground; ticks just above the line
export const STEP_M = 2;                          // no draped segment longer than 2 m
export const NEAR_M = 300;                        // ticks within 300 m of the viewer
export const SPACING_M = 12, TICK_M = 1.5, SPEED_MS = 0.6; // one tick per 12 m, 1.5 m long, 0.6 m/s
export const MAX_DT = 0.1;                        // a long pause between frames never jumps the ticks
export const MOVE_EPS = 1e-3;                     // the viewer moved if the position changed by 1 mm or more
// Quiet blue on the dark background; ticks a little lighter.
export const LINE_COLOR = [0.34, 0.56, 0.80, 0.55];
export const TICK_COLOR = [0.62, 0.80, 0.96, 0.70];
// Flow ticks as the shared library draws them (lib.drape.ticksAlong).
export const TICKS = Object.freeze({ near: NEAR_M, spacing: SPACING_M, tick: TICK_M, speed: SPEED_MS, lift: TICK_LIFT_M });

const finite = h => (Number.isFinite(h) ? h : 0);

// The layer: lines are densified, measured and draped by the shared library (api.lib.drape), which the substrate
// hash-checks.
export const LIB_VERSION = 1;

export function createWater({ now = () => (globalThis.performance ? performance.now() : Date.now()) } = {}) {
  let api = null, D = null, enabled = false, data = null, state = 'idle'; // idle | loading | ready | failed
  let lines = null, linesOrigin = null;   // local lines, built for one origin id
  let cache = { version: null, batches: [] };
  let lastPos = null, lastWall = null, flowClock = 0, moving = false;
  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 rivers.json hash configured'; return; }
    state = 'loading';
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      if (!j || !Array.isArray(j.lines)) throw Error('rivers.json has no lines list');
      data = j.lines.filter(l => Array.isArray(l.points) && l.points.length >= 2);
      state = 'ready';
      layer.status = `${data.length} watercourses`;
      api.invalidate({ ground: false });
    }).catch(e => { state = 'failed'; layer.status = 'rivers.json failed: ' + e.message; });
  }

  // Local, densified lines for the current origin; rebuilt only when the origin moves.
  function localLines() {
    const o = origin(), id = `${o.e},${o.n},${o.id}`;
    if (lines && linesOrigin === id) return lines;
    lines = data.map((l, i) => {
      const pts = D.densify(l.points.map(([e, n]) => [e - o.e, n - o.n]), STEP_M);
      return { i, name: l.name || null, form: l.form, flows: l.flow !== 'unknown', pts, cum: D.cumulative(pts) };
    });
    linesOrigin = id;
    cache = { version: null, batches: [] };
    return lines;
  }

  const layer = {
    id: 'water',
    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, known? }
    lines(ctx) {
      if (!api) return [];
      const known = typeof ctx.known === 'function' ? ctx.known : () => true;
      if (state === 'idle') load();
      // moving: the viewer's position changed since the last frame; only then does the flow clock run
      const wall = now();
      moving = !!lastPos && Math.hypot(ctx.pos[0] - lastPos[0], ctx.pos[1] - lastPos[1], (ctx.pos[2] || 0) - (lastPos[2] || 0)) >= MOVE_EPS;
      if (moving && lastWall !== null) flowClock += Math.min(MAX_DT, Math.max(0, (wall - lastWall) / 1000));
      lastPos = [ctx.pos[0], ctx.pos[1], ctx.pos[2] || 0]; lastWall = wall;
      if (state !== 'ready') return [];
      const ls = localLines(), gv = ctx.groundVersion || 0, version = `water@${gv}@${linesOrigin}`;
      if (cache.version !== version || cache.heightAt !== ctx.heightAt) {
        cache = { version, heightAt: ctx.heightAt, batches: ls.map(l => {
          const o = [l.pts[0][0], l.pts[0][1], finite(ctx.heightAt(l.pts[0][0], l.pts[0][1]))];
          return { key: `water/line/${l.i}`, version, origin: o, color: LINE_COLOR, positions: D.drapeSegments(l.pts, ctx.heightAt, LIFT_M, o, known) };
        }) };
      }
      const out = cache.batches.slice();
      for (const l of ls) {
        if (!l.flows) continue;
        const near = D.distToLine(l.pts, ctx.pos[0], ctx.pos[1]) <= NEAR_M;
        if (!(enabled || (moving && near))) continue;
        if (!near) continue; // ticks are a near-field cue; the far line alone says where the water is
        const o = [ctx.pos[0], ctx.pos[1], finite(ctx.heightAt(ctx.pos[0], ctx.pos[1]))];
        const positions = D.ticksAlong(l.pts, l.cum, flowClock, ctx.heightAt, { ...TICKS, pos: ctx.pos, origin: o, known });
        if (positions.length) out.push({ key: `water/ticks/${l.i}`, version: `${version}@${flowClock.toFixed(3)}@${o[0].toFixed(2)},${o[1].toFixed(2)}`, origin: o, color: TICK_COLOR, positions });
      }
      return out;
    },
    // For tests and the console.
    debug: () => ({ state, enabled, moving, flowClock, lines: data ? data.length : 0 })
  };
  return layer;
}

export default createWater();

Ways

A JavaScript module in the layers folder of GlobalGrid2050 that sets file sha (`setFileSha`) and status (`setStatus`) and calculates planar distances, covering roads, rail and motorways, using SHA-256.

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

What it does
It lists and searches roads, rail and motorways. Defines 9 functions or classes, including setFileSha, offsetLine, edgeOffsets, buildWays, finite.
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: motorways.
Inputs & outputs
In: JSON file roads.json; JSON file rail.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It sets file sha (`setFileSha`) and sets status (`setStatus`). Roads and railways draped on the ground.
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
FILES, setFileSha, CLASSES, DEFAULT_WIDTH, GAUGE_M, STEP_M, LIB_VERSION, COLORS, offsetLine, edgeOffsets, buildWays, createWays
Defines here
setFileSha, offsetLine, edgeOffsets, buildWays, finite, createWays, now, load, setStatus
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/ways.mjs:1-160 · blob ef092bb372c9157cad9a6f904f7fbb94d7c711c2 · 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: ways. Roads and railways draped on the ground. Each road is drawn as its two kerb lines at the
// width its file gives (typical, assumed by class; nothing is measured); each railway track as its two
// rails at the gauge. No animation: the batches change only when new ground or a new origin arrives.
// Data comes from tools/features/cut_roads.py: roads.json (OS Open Roads) and rail.json (OS OpenMap -
// Local), both OGL v3.0, fetched through the substrate's hash check (api.fetchJSON). The two files are
// kept apart (an OpenStreetMap rail file, if ever used, is ODbL and stays in its own file too).
// File coordinates are British National Grid metres; the layer turns them into local metres from the
// live site origin. Heights come from ctx.heightAt, the ground. Quiet greys for a dark background.
//
// File (ggw-ways/1): { kind: 'roads'|'rail', licence, attribution, lines: [
//   roads: { class, width_m, pts: [[e, n], ...] }   rail: { tracks, gauge_m, track_spacing_m, pts } ] }

export const FILES = {
  roads: { path: 'ways/roads.json', sha256: '__WAYS_ROADS_SHA256__' },
  rail: { path: 'ways/rail.json', sha256: '__WAYS_RAIL_SHA256__' }
};
export function setFileSha(kind, sha) { FILES[kind].sha256 = sha; }

export const CLASSES = ['motorway', 'A', 'B', 'minor', 'local', 'track'];
export const DEFAULT_WIDTH = { motorway: 11, A: 7.3, B: 6.5, minor: 5.5, local: 4.8, track: 3 };
export const GAUGE_M = 1.435, TRACK_SPACING_M = 3.4;
export const STEP_M = 4, LIFT_M = 0.06, MITRE_LIMIT = 3;

// The layer: side lines are draped by the shared library (api.lib.drape), which the substrate hash-checks.
export const LIB_VERSION = 1;
// Greys, brighter and firmer for the bigger roads; rails a touch warmer.
export const COLORS = {
  motorway: [0.80, 0.80, 0.80, 0.60], A: [0.74, 0.74, 0.74, 0.52], B: [0.68, 0.68, 0.68, 0.46],
  minor: [0.62, 0.62, 0.62, 0.40], local: [0.56, 0.56, 0.56, 0.34], track: [0.50, 0.50, 0.50, 0.28],
  rail: [0.66, 0.64, 0.61, 0.50]
};

// Pure: a polyline offset sideways by d metres (positive = left of travel), mitred at the joints.
// A mitre longer than MITRE_LIMIT * |d| is cut to that length, so a hairpin cannot throw a spike.
export function offsetLine(pts, d) {
  const n = pts.length, out = [];
  if (n < 2) return out;
  const nrm = [];
  for (let i = 0; i < n - 1; i++) {
    const dx = pts[i + 1][0] - pts[i][0], dy = pts[i + 1][1] - pts[i][1], L = Math.hypot(dx, dy);
    nrm.push(L > 0 ? [-dy / L, dx / L] : null);
  }
  // Zero-length segments borrow the neighbouring normal.
  for (let i = 0; i < nrm.length; i++) if (!nrm[i]) nrm[i] = nrm[i - 1] || nrm.slice(i).find(Boolean) || [0, 1];
  for (let i = 0; i < n; i++) {
    let m;
    if (i === 0) m = nrm[0];
    else if (i === n - 1) m = nrm[n - 2];
    else {
      const a = nrm[i - 1], b = nrm[i], sx = a[0] + b[0], sy = a[1] + b[1], sl = Math.hypot(sx, sy);
      if (sl < 1e-9) m = a; // a full reversal: no mitre exists
      else {
        const ux = sx / sl, uy = sy / sl, cos = ux * a[0] + uy * a[1];
        const k = Math.min(1 / Math.max(cos, 1e-9), MITRE_LIMIT);
        m = [ux * k, uy * k];
      }
    }
    out.push([pts[i][0] + m[0] * d, pts[i][1] + m[1] * d]);
  }
  return out;
}

// Pure: the side lines of one way. Roads: two kerbs at +-width/2. Rail: two rails per track, tracks
// spread about the centreline at the track spacing.
export function edgeOffsets(line, kind) {
  if (kind === 'rail') {
    const tracks = Math.max(1, line.tracks | 0), g = line.gauge_m || GAUGE_M, s = line.track_spacing_m || TRACK_SPACING_M;
    const out = [];
    for (let t = 0; t < tracks; t++) {
      const c = (t - (tracks - 1) / 2) * s;
      out.push(c - g / 2, c + g / 2);
    }
    return out;
  }
  const w = line.width_m > 0 ? line.width_m : DEFAULT_WIDTH[line.class] || DEFAULT_WIDTH.local;
  return [-w / 2, w / 2];
}

// Pure: file lines -> { group: Float32Array } in local metres. group is the road class, or 'rail'. drape is the
// shared library's lib.drape.drape (a layer cannot import it): each side line is draped in pieces of at most step.
export function buildWays(doc, originEN, heightAt, { drape, origin = [0, 0, 0], step = STEP_M, lift = LIFT_M, known } = {}) {
  const kind = doc && doc.kind === 'rail' ? 'rail' : 'roads', groups = {};
  for (const line of (doc && doc.lines) || []) {
    if (!Array.isArray(line.pts) || line.pts.length < 2) continue;
    const local = line.pts.map(([e, n]) => [e - originEN.e, n - originEN.n]);
    const g = kind === 'rail' ? 'rail' : (CLASSES.includes(line.class) ? line.class : 'local');
    const out = (groups[g] ||= []);
    for (const d of edgeOffsets(line, kind)) drape(out, offsetLine(local, d), heightAt, { origin, step, lift, known });
  }
  for (const g in groups) groups[g] = new Float32Array(groups[g]);
  return groups;
}

const finite = h => (Number.isFinite(h) ? h : 0);

export function createWays() {
  let api = null;
  const docs = { roads: null, rail: null }, state = { roads: 'idle', rail: 'idle' };
  let cache = { version: null, heightAt: null, batches: [] }, dataVersion = 0;
  const now = () => (api && typeof api.origin === 'function' ? api.origin() : { e: 0, n: 0, id: 0 });

  function load(kind) {
    if (state[kind] !== 'idle' || !api) return;
    const cfg = api.config?.[kind] || {}, path = cfg.path || FILES[kind].path, sha = cfg.sha256 || FILES[kind].sha256;
    if (!sha || sha.startsWith('__')) { state[kind] = 'failed'; setStatus(`no ${kind}.json hash configured`); return; }
    state[kind] = 'loading';
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      if (!j || !Array.isArray(j.lines)) throw Error(`${kind}.json has no lines list`);
      docs[kind] = j; state[kind] = 'ready'; dataVersion++;
      setStatus();
      api.invalidate({ ground: false });
    }).catch(e => { state[kind] = 'failed'; setStatus(`${kind}.json failed: ${e.message}`); });
  }

  function setStatus(msg) {
    const parts = ['roads', 'rail'].filter(k => docs[k]).map(k => `${docs[k].lines.length} ${k}`);
    layer.status = msg || (parts.length ? parts.join(', ') : 'loading');
  }

  const layer = {
    id: 'ways',
    status: 'waiting for init',
    init(a) {
      if (!a.lib?.drape) { layer.status = 'refused: api.lib.drape not provided'; return; }
      api = a; layer.status = 'ready to load'; load('roads'); load('rail');
    },
    // Tests and tools may hand a file straight in (it skips the hash check, so the page never does this).
    setData(kind, doc) { docs[kind] = doc; state[kind] = 'ready'; dataVersion++; setStatus(); api?.invalidate({ ground: false }); },
    // What the attribution panel should show for the files actually loaded.
    get attribution() { return [...new Set(['roads', 'rail'].map(k => docs[k]?.attribution).filter(Boolean))]; },
    // ctx: { pos, heightAt, groundVersion }
    lines(ctx) {
      if (!api) return [];
      load('roads'); load('rail');
      const o = now(), version = `${dataVersion}@${ctx.groundVersion || 0}@${o.e},${o.n}`;
      if (cache.version === version && cache.heightAt === ctx.heightAt) return cache.batches;
      const batches = [];
      for (const kind of ['roads', 'rail']) {
        const doc = docs[kind];
        if (!doc || !doc.lines.length) continue;
        // Batch origin: the middle of the file's lines, so positions stay small on the GPU.
        let sx = 0, sy = 0, c = 0;
        for (const l of doc.lines) for (const p of l.pts || []) { sx += p[0]; sy += p[1]; c++; }
        const cx = c ? sx / c - o.e : 0, cy = c ? sy / c - o.n : 0;
        const origin = [cx, cy, finite(ctx.heightAt(cx, cy))];
        const groups = buildWays(doc, o, ctx.heightAt, { drape: api.lib.drape.drape, origin, known: typeof ctx.known === 'function' ? ctx.known : undefined });
        for (const g of [...CLASSES, 'rail']) {
          if (groups[g] && groups[g].length) batches.push({ key: `ways/${g}`, version, origin, color: COLORS[g], positions: groups[g] });
        }
      }
      cache = { version, heightAt: ctx.heightAt, batches };
      return batches;
    },
    // For tests and the console.
    debug: () => ({ state: { ...state }, lines: { roads: docs.roads?.lines.length || 0, rail: docs.rail?.lines.length || 0 } })
  };
  return layer;
}

export default createWays();

Drape

A JavaScript module in the world folder of GlobalGrid2050 that works with dist to line (`distToLine`) and ticks along (`ticksAlong`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/lib/drape.mjs · lines 1–99 of 99 · version 2026-09-27 03:30 · Entry point · pattern distToLine (shared by 2 files)

What it does
It calculates its inputs. Defines 9 functions or classes, including finite, yes, densify, cumulative, pointAt.
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.
Downstream impact
Used directly by 3 files: Site World V3 — World (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/). Reached from 4 other entry points, including Layers (globalgrid2050); Layers (globalgrid2050); Substrate (globalgrid2050).
What it achieves
It is built from the finite step (`finite`), the yes step (`yes`) and the densify step (`densify`). Lines laid on the ground, shared by the water, ways and land layers (through api.lib.drape) and by the cartridges (by import).
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 Site World V3 — World.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world/lib · JavaScript module
Uses
none found
Used by
imported by Site World V3 — World (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), preloaded by Solar Design Studio — Site World Page (modulepreload), mentioned in Standalone (comment link)
Produces
finite, densify, cumulative, pointAt, distToLine, drapeSegments, drape, ticksAlong
Defines here
finite, yes, densify, cumulative, pointAt, distToLine, drapeSegments, drape, ticksAlong
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/lib/drape.mjs:1-99 · blob 59cd4aa0b07c7e0beacda13edb88d9860967d679 · 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: production_core
// lib/drape.mjs: lines laid on the ground, shared by the water, ways and land layers (through api.lib.drape) and
// by the cartridges (by import). No imports, no DOM. Plan points are [x, y] in local metres; heights come from
// heightAt(x, y), and a height that is not a number drapes at 0. known(x, y) says whether there is surveyed
// ground there: a piece with an end off it is left out rather than drawn at a guessed height.

export const finite = h => (Number.isFinite(h) ? h : 0);
const yes = () => true;

// Split a polyline so no segment is longer than step. Keeps order and every original vertex.
export function densify(pts, step) {
  if (pts.length < 2) return pts.map(p => [p[0], p[1]]);
  const out = [[pts[0][0], pts[0][1]]];
  for (let i = 1; i < pts.length; i++) {
    const [ax, ay] = pts[i - 1], [bx, by] = pts[i], n = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / step));
    for (let k = 1; k <= n; k++) out.push([ax + (bx - ax) * k / n, ay + (by - ay) * k / n]);
  }
  return out;
}

// Cumulative distance along a polyline; cum[0] = 0, cum[last] = length.
export function cumulative(pts) {
  const cum = [0];
  for (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
  return cum;
}

// The point at distance s along the polyline (clamped to its ends).
export function pointAt(pts, cum, s) {
  const L = cum[cum.length - 1];
  if (s <= 0) return [pts[0][0], pts[0][1]];
  if (s >= L) return [pts[pts.length - 1][0], pts[pts.length - 1][1]];
  let lo = 0, hi = cum.length - 1;
  while (hi - lo > 1) { const m = (lo + hi) >> 1; if (cum[m] <= s) lo = m; else hi = m; }
  const f = (s - cum[lo]) / (cum[hi] - cum[lo] || 1);
  return [pts[lo][0] + (pts[hi][0] - pts[lo][0]) * f, pts[lo][1] + (pts[hi][1] - pts[lo][1]) * f];
}

// Shortest plan distance from (x, y) to a polyline.
export function distToLine(pts, x, y) {
  let best = Infinity;
  for (let i = 1; i < pts.length; i++) {
    const [ax, ay] = pts[i - 1], [bx, by] = pts[i], dx = bx - ax, dy = by - ay, d2 = dx * dx + dy * dy;
    const t = d2 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / d2)) : 0;
    best = Math.min(best, Math.hypot(x - ax - t * dx, y - ay - t * dy));
  }
  return pts.length === 1 ? Math.hypot(x - pts[0][0], y - pts[0][1]) : best;
}

// Draped segments (pairs of xyz) through every point of an already densified line, relative to origin o,
// lift metres above the ground. Returns a Float32Array.
export function drapeSegments(pts, heightAt, lift, o = [0, 0, 0], known = yes) {
  const out = [];
  let prev = null;
  for (let i = 0; i < pts.length; i++) {
    const p = known(pts[i][0], pts[i][1]) ? [pts[i][0] - o[0], pts[i][1] - o[1], finite(heightAt(pts[i][0], pts[i][1])) + lift - o[2]] : null;
    if (prev && p) out.push(...prev, ...p);
    prev = p;
  }
  return new Float32Array(out);
}

// Pushes a polyline onto out as draped segments relative to origin, each input segment split into pieces no
// longer than step (at fractions j / k of it). Returns out.
export function drape(out, pts, heightAt, { step, lift, origin = [0, 0, 0], known = yes }) {
  for (let i = 0; i < pts.length - 1; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[i + 1];
    const k = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / step));
    let px = ax, py = ay, pz = finite(heightAt(ax, ay)), pk = known(ax, ay);
    for (let j = 1; j <= k; j++) {
      const t = j / k, x = ax + (bx - ax) * t, y = ay + (by - ay) * t, z = finite(heightAt(x, y)), qk = known(x, y);
      if (pk && qk) out.push(px - origin[0], py - origin[1], pz + lift - origin[2], x - origin[0], y - origin[1], z + lift - origin[2]);
      px = x; py = y; pz = z; pk = qk;
    }
  }
  return out;
}

// Short marks that creep along a line at clock t (seconds): tick k starts at s = phase + k * spacing, phase =
// (t * speed) mod spacing, so the ticks move towards the last point as t grows. Only ticks starting within near
// metres of pos are made; a tick bends with the line. Returns a Float32Array of xyz pairs.
export function ticksAlong(pts, cum, t, heightAt, { pos = null, near, spacing, tick, speed, lift, origin = [0, 0, 0], known = yes }) {
  const L = cum[cum.length - 1], out = [];
  if (!(L > 0)) return new Float32Array(0);
  const phase = ((t * speed) % spacing + spacing) % spacing;
  for (let s = phase; s < L; s += spacing) {
    const a = pointAt(pts, cum, s), b = pointAt(pts, cum, Math.min(L, s + tick));
    if (pos && Math.hypot(a[0] - pos[0], a[1] - pos[1]) > near) continue;
    const seq = [a];
    for (let i = 1; i < cum.length - 1; i++) if (cum[i] > s && cum[i] < s + tick) seq.push(pts[i]);
    seq.push(b);
    for (let i = 1; i < seq.length; i++) {
      const p = seq[i - 1], q = seq[i];
      if (!known(p[0], p[1]) || !known(q[0], q[1])) continue;
      out.push(p[0] - origin[0], p[1] - origin[1], finite(heightAt(p[0], p[1])) + lift - origin[2],
        q[0] - origin[0], q[1] - origin[1], finite(heightAt(q[0], q[1])) + lift - origin[2]);
    }
  }
  return new Float32Array(out);
}

Earthworks

A JavaScript module in the world folder of GlobalGrid2050 that strips volume (`stripVolume`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/lib/earthworks.mjs · lines 1–226 of 226 · version 2026-09-27 03:30 · Entry point · pattern batterZ (shared by 2 files)

What it does
It calculates its inputs. Defines 19 functions or classes, including inv, batterZ, daylight, polyArea, insidePoly.
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.
Downstream impact
Used directly by 6 files: Trench (globalgrid2050); Site World V3 — World (globalgrid2050); Pad (globalgrid2050); Road (globalgrid2050); and 2 more. Reached from 4 other entry points, including Layers (globalgrid2050); Layers (globalgrid2050); Substrate (globalgrid2050).
What it achieves
It is built from the inv step (`inv`), the batter z helper (`batterZ`) and the daylight step (`daylight`). The one cut and fill engine for trenches, roads and pads, and the one composer that puts every dig into the ground.
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 4 files, including Trench, Site World V3 — World and Pad.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world/lib · JavaScript module
Uses
none found
Used by
imported by Trench (import), imported by Site World V3 — World (import), imported by Pad (import), imported by Road (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), preloaded by Solar Design Studio — Site World Page (modulepreload), mentioned in Standalone (comment link)
Produces
inv, batterZ, daylight, polyArea, insidePoly, edgeDistance, sampleCells, volumesAt, balance, gridIntegrate, stripVolume, padHeight
Defines here
inv, batterZ, daylight, polyArea, insidePoly, edgeDistance, sampleCells, volumesAt, balance, gridIntegrate, stripVolume, bis, padHeight, nearPad, inBox, composeGround, withRoads, withPads, withTrenches
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/lib/earthworks.mjs:1-226 · blob b5c7d917df32a8433f0901b652333ae78595bfad · 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: production_core
// lib/earthworks.mjs: the one cut and fill engine for trenches, roads and pads, and the one composer that puts
// every dig into the ground. Cartridges import it; layers reach it through api.lib.earthworks. No imports, no DOM.
//
// Local metres: x east, y north, z up. The ground is any function groundAt(x, y). Batters are horizontal metres
// per metre of height; the engine works with their inverses (vertical per horizontal), so a zero batter is a
// vertical face (inverse Infinity). Volumes are bank (in place) measure: no bulking or shrinkage.

const EPS = 1e-9;

// ---------------------------------------------------------------- batters

export const inv = h => (h > 0 ? 1 / h : Infinity);

// Surface d metres out from an edge at `level`: the ground, clamped between the fill batter falling from the
// edge and the cut batter rising from it. So a batter meets the ground at the daylight line and runs no further.
export const batterZ = (g, level, d, invCut, invFill) => Math.min(Math.max(g, level - d * invFill), level + d * invCut);

// Distance along a ray to where a batter meets the ground (the daylight point). met(t) says the batter has met
// the ground by t; the ray is walked in steps and the crossing bisected 30 times. With strict, a batter still
// working past `limit` is not met (null); otherwise the walk stops at limit and bisects what it has.
export function daylight(met, step, limit, { strict = false } = {}) {
  let a = 0, b = step;
  if (strict) { while (!met(b)) { a = b; b += step; if (b > limit) return null; } }
  else while (b < limit && !met(b)) { a = b; b += step; }
  for (let k = 0; k < 30; k++) { const m = (a + b) / 2; if (met(m)) b = m; else a = m; }
  return b;
}

// ---------------------------------------------------------------- footprints

export const polyArea = pts => {
  let a = 0;
  for (let i = 0; i < pts.length; i++) { const p = pts[i], q = pts[(i + 1) % pts.length]; a += p[0] * q[1] - q[0] * p[1]; }
  return Math.abs(a) / 2;
};

// The same even-odd crossing test as measure.mjs insidePoly and lidar/src/earthworks_pair.py inside_poly.
export function insidePoly(x, y, vx, vy) {
  let ins = false;
  for (let i = 0, n = vx.length; i < n; i++) {
    const j = (i - 1 + n) % n, x1 = vx[i], y1 = vy[i], x2 = vx[j], y2 = vy[j];
    if (y1 === y2) continue;
    if ((y1 > y) !== (y2 > y) && x < x1 + (y - y1) * (x2 - x1) / (y2 - y1)) ins = !ins;
  }
  return ins;
}

// Plan distance from a point to a closed polygon's boundary.
export function edgeDistance(x, y, pts) {
  let best = Infinity;
  for (let i = 0, n = pts.length; i < n; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[(i + 1) % n], dx = bx - ax, dy = by - ay;
    const t = Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / (dx * dx + dy * dy)));
    best = Math.min(best, Math.hypot(x - ax - t * dx, y - ay - t * dy));
  }
  return best;
}

// ---------------------------------------------------------------- sampling and volumes

// Samples the ground once over a polygon grown by `reach`, on cell centres anchored as measure.mjs
// cutFillForPlatform (floor of min x and y, centres at (i + 0.5) cell). Per cell: ground z, distance d outside
// the polygon (0 inside) and the formation offset o from off(x, y).
export function sampleCells(pts, groundAt, cell, reach, off = () => 0) {
  const vx = pts.map(p => p[0]), vy = pts.map(p => p[1]);
  const pad = Math.ceil(reach / cell) * cell;                     // whole cells, so centres stay on measure's grid
  const x0 = Math.floor(Math.min(...vx)) - pad, y0 = Math.floor(Math.min(...vy)) - pad;
  const nx = Math.ceil((Math.max(...vx) + pad - x0) / cell), ny = Math.ceil((Math.max(...vy) + pad - y0) / cell);
  const z = [], d = [], o = [];
  for (let j = 0; j < ny; j++) {
    const y = y0 + (j + 0.5) * cell;
    for (let i = 0; i < nx; i++) {
      const x = x0 + (i + 0.5) * cell;
      const inside = insidePoly(x, y, vx, vy), dist = inside ? 0 : Math.max(edgeDistance(x, y, pts), EPS);
      if (!inside && dist > reach) continue;
      const g = groundAt(x, y);
      if (!Number.isFinite(g)) throw Error(`pad: no ground at ${x.toFixed(2)}, ${y.toFixed(2)}`);
      z.push(g); d.push(dist); o.push(off(x, y));
    }
  }
  return { z: Float64Array.from(z), d: Float64Array.from(d), o: Float64Array.from(o), cell, reach };
}

// Cut and fill (m³) for a formation level over sampled cells, split into platform (inside) and batters.
export function volumesAt(cells, level0, invCut, invFill) {
  let pc = 0, pf = 0, bc = 0, bf = 0, n = 0, edge = 0, worked = 0, gMax = -Infinity;
  const { z, d, o, cell, reach } = cells;
  for (let k = 0; k < z.length; k++) {
    const g = z[k], level = level0 + o[k];
    if (d[k] === 0) { n++; gMax = Math.max(gMax, g); if (g > level) pc += g - level; else pf += level - g; continue; }
    const dz = g - batterZ(g, level, d[k], invCut, invFill);
    if (dz !== 0) worked++;
    if (dz > 0) bc += dz; else bf -= dz;
    if (dz !== 0 && d[k] > reach - 2 * cell) edge++;             // batter still working at the edge of the sample
  }
  const a = cell * cell;
  return { platformCut: pc * a, platformFill: pf * a, batterCut: bc * a, batterFill: bf * a, cells: n, area: n * a, edge,
    footprint: (n + worked) * a, gMax };
}

// Formation level where cut equals fill (bisection: cut - fill falls as the level rises).
export function balance(cells, invCut, invFill) {
  let lo = Infinity, hi = -Infinity;
  cells.z.forEach((g, k) => { lo = Math.min(lo, g - cells.o[k]); hi = Math.max(hi, g - cells.o[k]); });
  for (let it = 0; it < 80 && hi - lo > 1e-7; it++) {
    const mid = (lo + hi) / 2, v = volumesAt(cells, mid, invCut, invFill);
    if (v.platformCut + v.batterCut > v.platformFill + v.batterFill) lo = mid; else hi = mid;
  }
  return (lo + hi) / 2;
}

// Adaptive midpoint integration over nx x ny cells from (x0, y0): visit(x, y, w) at each cell centre (w = 1), or,
// where split(x, y, i, j) says a face or an end crosses the cell, at sub x sub points (w = 1 / sub²).
export function gridIntegrate({ x0, y0, nx, ny, cell, sub = 8, split, visit }) {
  const h = cell / sub, w = 1 / (sub * sub);
  for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
    const x = x0 + (i + 0.5) * cell, y = y0 + (j + 0.5) * cell;
    if (!split(x, y, i, j)) { visit(x, y, 1); continue; }
    for (let b = 0; b < sub; b++) for (let a = 0; a < sub; a++) visit(x - cell / 2 + (a + 0.5) * h, y - cell / 2 + (b + 0.5) * h, w);
  }
}

// Volume dug by a vertical-walled cut of the given width and depth below the ground along a path: integrated along
// strips that follow each segment from mitre line to mitre line, so the walls fall on strip edges and nothing
// aliases with a lattice (checked 26 Sept: worst 0.021 %, 73 x faster than a 0.25 m grid, which was up to 4 %
// out on trenches running along a grid axis).
export function stripVolume(path, width, depth, g, { nt = 6, du = 0.25 } = {}) {
  const p = [];
  for (const q of path) { const l = p[p.length - 1]; if (!l || Math.hypot(q[0] - l[0], q[1] - l[1]) > 1e-6) p.push([+q[0], +q[1]]); }
  const segs = [];
  for (let i = 0; i < p.length - 1; i++) {
    const len = Math.hypot(p[i + 1][0] - p[i][0], p[i + 1][1] - p[i][1]);
    segs.push({ a: p[i], dx: (p[i + 1][0] - p[i][0]) / len, dy: (p[i + 1][1] - p[i][1]) / len, len });
  }
  const bis = (s, t) => { const x = s.dx + t.dx, y = s.dy + t.dy, l = Math.hypot(x, y); return l < 1e-6 ? [s.dx, s.dy] : [x / l, y / l]; };
  let vol = 0;
  segs.forEach((s, i) => {
    const nx = -s.dy, ny = s.dx;
    const mS = i === 0 ? null : bis(segs[i - 1], s), mE = i === segs.length - 1 ? null : bis(s, segs[i + 1]);
    for (let k = 0; k < nt; k++) {
      const t = ((k + 0.5) / nt - 0.5) * width;
      const u0 = mS ? -t * (nx * mS[0] + ny * mS[1]) / (s.dx * mS[0] + s.dy * mS[1]) : 0;
      const u1 = mE ? s.len - t * (nx * mE[0] + ny * mE[1]) / (s.dx * mE[0] + s.dy * mE[1]) : s.len;
      const m = Math.max(1, Math.ceil((u1 - u0) / du)), h = (u1 - u0) / m;
      for (let j = 0; j < m; j++) {
        const u = u0 + (j + 0.5) * h, uc = Math.min(Math.max(u, 0), s.len);
        const x = s.a[0] + s.dx * u + nx * t, y = s.a[1] + s.dy * u + ny * t;
        const floor = g(s.a[0] + s.dx * uc, s.a[1] + s.dy * uc) - depth;
        vol += Math.max(0, g(x, y) - floor) * h;
      }
    }
  });
  return vol * width / nt;
}

// ---------------------------------------------------------------- the ground with the digs in it

/** Finished height of a pad (from createPad) at (x, y): top of stone on it, the batter beside it, the ground beyond. */
export function padHeight(pad, x, y, groundAt) {
  const vx = pad.polygon.map(p => p[0]), vy = pad.polygon.map(p => p[1]);
  const o = pad.off ? pad.off(x, y) : 0;
  if (insidePoly(x, y, vx, vy)) return pad.top + o;
  const g = groundAt(x, y);
  if (!Number.isFinite(g)) return g;
  return batterZ(g, pad.level + o, Math.max(edgeDistance(x, y, pad.polygon), EPS), inv(pad.cutBatter), inv(pad.fillBatter));
}

// Inside the pad's grown box (a cheap reject before the exact test).
export function nearPad(p, x, y) {
  if (!p.box) {
    const xs = p.polygon.map(q => q[0]), ys = p.polygon.map(q => q[1]), r = p.reach + p.cell;
    p.box = [Math.min(...xs) - r, Math.min(...ys) - r, Math.max(...xs) + r, Math.max(...ys) + r];
  }
  return x >= p.box[0] && y >= p.box[1] && x <= p.box[2] && y <= p.box[3];
}

const inBox = (b, x, y) => !(x < b.minX || x > b.maxX || y < b.minY || y > b.maxY);

/**
 * composeGround(groundAt, { roads, pads, trenches }) -> heightAt with every dig in the ground, in that order:
 *   roads     built on the ground; on a carriageway that road wins, between batters the first road listed wins
 *   pads      pressed into the ground with the roads; the first pad whose box holds the point wins
 *   trenches  cut last, each against the ground under it; where they overlap the lowest surface wins
 * With nothing to put in, the ground itself comes back.
 */
export function composeGround(groundAt, { roads = [], pads = [], trenches = [] } = {}) {
  let ground = groundAt;
  if (roads.length) ground = withRoads(ground, [...roads]);
  if (pads.length) ground = withPads(ground, [...pads]);
  if (trenches.length) ground = withTrenches(ground, [...trenches]);
  return ground;
}

function withRoads(groundAt, list) {
  return function heightAt(x, y) {
    let side = null, ground = null;
    for (const r of list) {
      if (!inBox(r.bbox, x, y)) continue;
      if (r.onRoad(x, y)) return r.roadHeight(x, y, groundAt);
      if (side !== null) continue;
      if (ground === null) ground = groundAt(x, y);
      const h = r.roadHeight(x, y, groundAt);
      if (h !== ground) side = h;
    }
    return side ?? ground ?? groundAt(x, y);
  };
}

function withPads(groundAt, list) {
  return (x, y) => {
    for (const p of list) if (nearPad(p, x, y)) return padHeight(p, x, y, groundAt);
    return groundAt(x, y);
  };
}

function withTrenches(groundAt, list) {
  return function heightAt(x, y) {
    let z = groundAt(x, y);
    for (const t of list) {
      if (!inBox(t.bbox, x, y)) continue;
      const c = t.cutHeight(x, y, groundAt);
      if (c < z) z = c;
    }
    return z;
  };
}

Site World V3 — World

A JavaScript module in the solar design studio folder of GlobalGrid2050 that uses SHA-256.

otherglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/lib/index.mjs · lines 1–13 of 13 · version 2026-09-27 03:30 · Entry point

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.
Downstream impact
Used directly by 4 files: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Layers (globalgrid2050); Layers (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/). Reached from 2 other entry points, including Substrate (globalgrid2050); Substrate (globalgrid2050).
What it achieves
The shared world library as one object, and its version.
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 Layers.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world/lib · JavaScript module
Uses
Tiles (import), Drape (import), Earthworks (import)
Used by
preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Layers (import), imported by Layers (import), preloaded by Solar Design Studio — Site World Page (modulepreload)
Produces
LIB_VERSION, LIB_FILES
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270330-site-world-v3/world/lib/index.mjs:1-13 · blob e4646d32867c097d5f0b581abaafbe7321d5d656 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// lib/index.mjs: the shared world library as one object, and its version.
// LIB_VERSION goes up whenever a lib file changes what it returns or takes. tools/world-manifest.mjs writes it and
// each lib file's SHA-256 into the manifest; a layer declares the version it was written for (export const
// LIB_VERSION) and the substrate refuses a layer whose version is not the one it serves. The substrate serves the
// lib files it has hash-checked (layers.mjs); this static copy is for cartridges' tests and for makeApi's default.
import * as tiles from './tiles.mjs';
import * as drape from './drape.mjs';
import * as earthworks from './earthworks.mjs';

export const LIB_VERSION = 1;
export const LIB_FILES = Object.freeze(['tiles', 'drape', 'earthworks']);   // web/world/lib/<id>.mjs, hashed in the manifest

export default Object.freeze({ version: LIB_VERSION, tiles, drape, earthworks });