GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / graphics-engines-open-source / tests

GridAtlas and 6 more files

A JavaScript module in Graphics Engines Open Source that fetches projects and grid substations, using SHA-256 from the data-GridAtlas and GridAtlas repositories. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/.

385 lines of JavaScript from graphics-engines-open-source, in 7 files. Topic: Maps, GIS and field navigation. Section 514 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. GridAtlas Test test · graphics-engines-open-source / tests/gridatlas.test.mjs lines 1–38
  2. Route File Test test · graphics-engines-open-source / tests/route-file.test.mjs lines 1–31
  3. Atlas Picker interaction · graphics-engines-open-source / web/atlas-picker.mjs lines 1–66
  4. GridAtlas ingest · graphics-engines-open-source / web/gridatlas.mjs lines 1–109
  5. Route File ingest · graphics-engines-open-source / web/route-file.mjs lines 1–29
  6. Route Files UI interaction · graphics-engines-open-source / web/route-files-ui.mjs lines 1–19
  7. Route Tool transform · graphics-engines-open-source / web/versions/202609262227-site-world/world/route-tool.mjs lines 1–93

GridAtlas Test

A test in the tests folder of Graphics Engines Open Source that checks GridAtlas.

testgraphics-engines-open-source / tests/gridatlas.test.mjs · lines 1–38 of 38 · Entry point · pattern payload (shared by 6 files)

What it does
It tests solar. Defines payload. Uses libraries node:test, node:assert/strict.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 2 files: Geometry Check Workflow (graphics-engines-open-source); Pages Workflow (graphics-engines-open-source).
What it achieves
Defines `payload`.
Why it matters
Run by Geometry Check Workflow and Pages Workflow.
Application
graphics-engines-open-source · tests · test
Uses
GridAtlas (import), node:test, node:assert/strict
Used by
run by Geometry Check Workflow (workflow run), run by Pages Workflow (workflow run)
Produces
payload
Defines here
payload
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tests/gridatlas.test.mjs:1-38 · blob 3d9cd481e69887c4b5bfdb2d4cbd679b399fad90 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import { decodeGridAtlasProjects, GRIDATLAS_SOURCE, projectToLocalMetres, searchProjects, gridAtlasProjectUrl } from '../web/gridatlas.mjs';

const fields = ['repd_ref', 'name', 'technology', 'status', 'capacity_mw', 'geometry_status', 'latitude', 'longitude'];
const row = ['123', 'Public solar example', 0, 0, 10, 0, 52, -1];
const payload = rows => ({ schema: GRIDATLAS_SOURCE.schema, fields, rows,
  dictionaries: { technology: ['solar'], status: ['Operational'], geometry_status: ['valid'] } });

test('decodes dictionary fields without coercing JSON null coordinates', () => {
  const invalid = [null, '', '52', Infinity, NaN, 91].map(latitude => [...row.slice(0, 6), latitude, -1]);
  const rows = [row, ...invalid, [...row.slice(0, 6), 0, 0], [...row.slice(0, 6), 49.766807, -7.55716]];
  const { projects } = decodeGridAtlasProjects(payload(rows));
  assert.equal(projects.length, 1);
  assert.equal(projects[0].technology, 'solar');
  assert.equal(searchProjects(projects, '123')[0].name, row[1]);
  assert.equal(new URL(gridAtlasProjectUrl(projects[0])).searchParams.get('repd_ref'), '123');
});

test('rejects ambiguous schema, missing identities and invalid dictionary indexes', () => {
  assert.throws(() => decodeGridAtlasProjects({ ...payload([row]), fields: [...fields, 'latitude'] }));
  assert.throws(() => decodeGridAtlasProjects({ ...payload([row]), schema: 'unknown' }));
  const badIdentity = [...row]; badIdentity[0] = null;
  const badTechnology = [...row]; badTechnology[2] = 99;
  assert.equal(decodeGridAtlasProjects(payload([badIdentity, badTechnology])).projects.length, 0);
});

test('local WGS84 axes, dateline wrapping and invalid coordinate rejection', () => {
  const origin = { latitude: 0, longitude: 0 };
  assert.deepEqual(projectToLocalMetres(origin, origin), [0, 0]);
  const east = projectToLocalMetres({ latitude: 0, longitude: 0.001 }, origin);
  const north = projectToLocalMetres({ latitude: 0.001, longitude: 0 }, origin);
  assert.ok(Math.abs(east[0] - 111.319490793) < 0.0001);
  assert.ok(Math.abs(north[1] - 110.574275822) < 0.0001);
  const wrapped = projectToLocalMetres({ latitude: 0, longitude: -179.999 }, { latitude: 0, longitude: 179.999 });
  assert.ok(wrapped[0] > 222 && wrapped[0] < 223);
  assert.throws(() => projectToLocalMetres({ latitude: null, longitude: 0 }, origin));
});

Route File Test

A test in the tests folder of Graphics Engines Open Source that checks Route File and Explore.

testgraphics-engines-open-source / tests/route-file.test.mjs · lines 1–31 of 31 · Entry point · pattern envelope (shared by 2 files)

What it does
It tests its inputs. Defines envelope. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 2 files: Geometry Check Workflow (graphics-engines-open-source); Pages Workflow (graphics-engines-open-source).
What it achieves
Defines `envelope`.
Why it matters
Run by Geometry Check Workflow and Pages Workflow.
Application
graphics-engines-open-source · tests · test
Uses
Route File (import), Explore (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
Used by
run by Geometry Check Workflow (workflow run), run by Pages Workflow (workflow run)
Produces
envelope
Defines here
envelope
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tests/route-file.test.mjs:1-31 · blob 8ab9461af0b1670f9a15c1cdc884e4914161cd5c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {parseRouteFile,serializeRouteFile,MAX_ROUTE_FILE_BYTES} from '../web/route-file.mjs';
const routes=[{id:'DC-1',label:'Circuit A · DC unspecified',points:[[0,0,.4],[1,2,.4],[3,2,.4]]}];
const envelope=()=>({schema:'electrical-routes/1',units:'metres',axes:'ENU',routes});
test('round-trip retains labels, metres and XYZ coordinates',()=>{assert.deepEqual(parseRouteFile(serializeRouteFile(routes)),routes);});
test('requires version and metric ENU; rejects malformed and oversized files',()=>{
 for(const replacement of [{schema:'v2'},{units:'feet'},{axes:'NED'},{routes:[]}])assert.throws(()=>parseRouteFile(JSON.stringify({...envelope(),...replacement})));
 assert.throws(()=>parseRouteFile('{'));
 assert.throws(()=>parseRouteFile(' '.repeat(MAX_ROUTE_FILE_BYTES+1)),/16 MB/);
});
test('rejects invalid route geometry and metadata',()=>{
 for(const r of [{...routes[0],points:[[0,0,0],[0,0,0]]},{...routes[0],points:[[0,0,0],['1',2,3]]},{...routes[0],id:''},{...routes[0],label:{}},{...routes[0],points:[[0,0,0],[1e7,0,0]]}])assert.throws(()=>parseRouteFile(JSON.stringify({...envelope(),routes:[r]})));
 assert.throws(()=>parseRouteFile(JSON.stringify({...envelope(),routes:[routes[0],routes[0]]})),/unique/);
 const many=Array.from({length:11},(_,n)=>({id:String(n),points:Array.from({length:10000},(_,i)=>[i,0,0])}));
 assert.throws(()=>parseRouteFile(JSON.stringify({...envelope(),routes:many})),/100000/);
});
test('import through real viewer API is atomic and export survives roundtrip',()=>{
 const nodes=new Map();const node=id=>{if(!nodes.has(id))nodes.set(id,{value:'2',checked:id==='props',clientWidth:1200,clientHeight:800,getContext:()=>null,addEventListener(){},focus(){},replaceChildren(){},setPointerCapture(){}});return nodes.get(id);};
 const context=vm.createContext({document:{getElementById:node,querySelector:()=>node('aside')},window:{addEventListener(){}},console,Float32Array,Option:class{},requestAnimationFrame(){},devicePixelRatio:1});
 vm.runInContext(fs.readFileSync(new URL('../web/explore.mjs',import.meta.url),'utf8'),context);
 const api=context.window.electricalExplorer;
 api.setRoutes(parseRouteFile(serializeRouteFile(routes)));
 assert.equal(api.state.routes[0].label,routes[0].label);
 const before=serializeRouteFile(api.state.routes);
 assert.throws(()=>api.setRoutes([{id:'bad',points:[[0,0,0],[0,0,0]]}]));
 assert.equal(serializeRouteFile(api.state.routes),before);
 assert.deepEqual(parseRouteFile(before),routes);
});

Atlas Picker

A JavaScript module in Graphics Engines Open Source covering solar and the Renewable Energy Planning Database (REPD) register. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/.

interactiongraphics-engines-open-source / web/atlas-picker.mjs · lines 1–66 of 66 · Entry point

What it does
It draws solar and the REPD register. Defines element, refresh. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, the REPD register.
Downstream impact
Used directly by 2 files: Graphics Engines Open Source — Index Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/); Pages Workflow (graphics-engines-open-source). Reached from 1 other entry point, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/). It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/.
What it achieves
Defines `element` and `refresh`. It responds to input and click events.
Why it matters
Loaded by the Graphics Engines Open Source page at https://ventusltd.github.io/graphics-engines-open-source/web/. Run by Pages Workflow.
Application
graphics-engines-open-source · web · JavaScript module
Uses
GridAtlas (import)
Used by
loaded by Graphics Engines Open Source — Index Page (script src), run by Pages Workflow (workflow run)
Produces
element, refresh
Defines here
element, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/atlas-picker.mjs:1-66 · blob a32445715a3f43bfafb05e69aeb5917b51744f59 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
import { loadGridAtlasProjects, searchProjects, gridAtlasProjectUrl, GRIDATLAS_SOURCE } from './gridatlas.mjs';

const mount = document.getElementById('atlas-picker');
if (mount) {
  const element = (tag, text, attributes = {}) => {
    const node = document.createElement(tag);
    if (text) node.textContent = text;
    for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
    return node;
  };
  const title = element('h2', 'Anchor at a public solar project');
  const note = element('p', 'A published project point anchors this illustrative layout. It does not reconstruct the site or its cable routes.', { class: 'muted' });
  const load = element('button', 'Load GridAtlas projects', { type: 'button' });
  const label = element('label', 'REPD ID');
  const query = element('input', '', { type: 'search', placeholder: 'Search REPD ID', 'aria-label': 'Search public solar projects by REPD ID', disabled: '' });
  label.append(query);
  const resultsLabel = element('label', 'Project');
  const results = element('select', '', { 'aria-label': 'Public solar project matches', disabled: '' });
  resultsLabel.append(results);
  const apply = element('button', 'Anchor illustrative layout', { type: 'button', disabled: '' });
  const status = element('p', 'Public snapshot loads on request.', { role: 'status', 'aria-live': 'polite', class: 'muted' });
  const details = element('p', '', { class: 'muted' });
  const source = element('a', 'GridAtlas source snapshot', { href: GRIDATLAS_SOURCE.url, target: '_blank', rel: 'noopener noreferrer' });
  source.style.color = '#a5cfff';
  const atlas = element('a', 'Open selected project in GridAtlas', { target: '_blank', rel: 'noopener noreferrer', hidden: '' });
  atlas.style.color = '#a5cfff';
  mount.append(title, note, load, label, resultsLabel, apply, status, details, source, element('br'), atlas);
  let projects = [], matches = [], generation = '';
  function refresh() {
    const term = query.value.trim();
    matches = searchProjects(projects.filter(project => !term || project.repd_ref.includes(term)), '', { limit: 40 });
    results.replaceChildren();
    for (const project of matches) results.append(element('option', `Solar project ${project.repd_ref}`, { value: project.repd_ref }));
    results.disabled = apply.disabled = matches.length === 0;
    status.textContent = matches.length ? `${matches.length} matches shown (maximum 40). Select a project to anchor.` : 'No matching solar projects with valid coordinates.';
  }
  query.addEventListener('input', refresh);
  load.addEventListener('click', async () => {
    load.disabled = true;
    status.textContent = 'Loading public GridAtlas snapshot…';
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 20000);
    try {
      const data = await loadGridAtlasProjects({ signal: controller.signal });
      projects = data.projects; generation = data.generation;
      query.disabled = false;
      refresh();
      load.textContent = 'Public snapshot loaded';
    } catch (error) {
      status.textContent = `Public data unavailable: ${error.name === 'AbortError' ? 'request timed out' : error.message}. Retry loading.`;
      load.disabled = false;
    } finally { clearTimeout(timeout); }
  });
  apply.addEventListener('click', () => {
    const project = matches.find(item => item.repd_ref === results.value);
    if (!project) return;
    if (typeof window.electricalExplorer?.setOrigin !== 'function' || !window.electricalExplorer.state?.gpu) {
      status.textContent = 'The GPU scene is unavailable.'; return;
    }
    try { window.electricalExplorer.setOrigin({ latitude: project.latitude, longitude: project.longitude, label: `Solar project ${project.repd_ref}` }); }
    catch (error) { status.textContent = `Could not anchor the scene: ${error.message}`; return; }
    details.textContent = `Anchored solar project ${project.repd_ref} · ${project.status} · ${Number.isFinite(project.capacity_mw) && project.capacity_mw >= 0 ? `${project.capacity_mw} MW published capacity` : 'capacity unavailable'} · snapshot ${generation}. Published point: ${project.latitude.toFixed(6)}, ${project.longitude.toFixed(6)}.`;
    atlas.href = gridAtlasProjectUrl(project); atlas.hidden = false;
    status.textContent = 'Published point selected. Array dimensions and routes remain illustrative.';
  });
}

GridAtlas

A JavaScript module in Graphics Engines Open Source that fetches projects and grid substations, using SHA-256 from the data-GridAtlas and GridAtlas repositories. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/.

ingestgraphics-engines-open-source / web/gridatlas.mjs · lines 1–109 of 109 · pattern coordinate (shared by 8 files)

What it does
It fetches projects, grid substations and the REPD register. Defines 9 functions or classes, including coordinate, publishedCoordinate, decodeGridAtlasProjects, loadGridAtlasProjects, searchProjects. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: data source: data-gridatlas data; data source: gridatlas data; JSON file projects.json; GeoJSON file grid_substations.geojson. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 3 files: Substation Picker (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/); GridAtlas Test (graphics-engines-open-source); Atlas Picker (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/). Reached from 4 other entry points, including Graphics Engines Open Source — Index Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/); Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Geometry Check Workflow (graphics-engines-open-source).
What it achieves
It decodes grid atlas projects (`decodeGridAtlasProjects`), loads grid atlas projects (`loadGridAtlasProjects`) and searches projects (`searchProjects`). GridAtlas's public Renewable Energy Planning Database (REPD) routing index supplies points, not surveyed boundaries.
Why it matters
Imported by Substation Picker and Atlas Picker. Checked by GridAtlas Test.
Application
graphics-engines-open-source · web · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL)
Used by
imported by Substation Picker (import), imported by GridAtlas Test (import), imported by Atlas Picker (import)
Produces
GRIDATLAS_SOURCE, decodeGridAtlasProjects, loadGridAtlasProjects, searchProjects, projectToLocalMetres, gridAtlasProjectUrl, GRIDATLAS_SUBSTATION_SOURCE, decodeGridAtlasSubstations, loadGridAtlasSubstations
Defines here
coordinate, publishedCoordinate, decodeGridAtlasProjects, loadGridAtlasProjects, searchProjects, projectToLocalMetres, gridAtlasProjectUrl, decodeGridAtlasSubstations, loadGridAtlasSubstations
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/gridatlas.mjs:1-109 · blob 475256982dfeb06b536a77fc2ca06f698868583e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
// GridAtlas's public REPD routing index supplies points, not surveyed boundaries.
export const GRIDATLAS_SOURCE = Object.freeze({
  url: 'https://ventusltd.github.io/data-gridatlas/202608291410-repd-routing/projects.json',
  atlas: 'https://ventusltd.github.io/gridatlas/atlas/',
  schema: 'pipelinenews.v8.fast-project-index.v1',
  label: 'GridAtlas public REPD routing snapshot',
  geometry: 'Published project point; generated array geometry is illustrative.'
});

const coordinate = (latitude, longitude) => Number.isFinite(latitude) && Number.isFinite(longitude)
  && Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180;
// Match the Atlas receiver's rejection of empty coordinates and the BNG false origin.
const publishedCoordinate = (latitude, longitude) => coordinate(latitude, longitude)
  && !(Math.abs(latitude) < 1e-12 && Math.abs(longitude) < 1e-12)
  && !(Math.abs(latitude - 49.766807) < 1e-9 && Math.abs(longitude + 7.55716) < 1e-9);

export function decodeGridAtlasProjects(data) {
  if (data?.schema !== GRIDATLAS_SOURCE.schema || !Array.isArray(data.fields)
      || !Array.isArray(data.rows) || data.rows.length > 100000) throw Error('Unsupported GridAtlas project index');
  const required = ['repd_ref', 'name', 'technology', 'status', 'capacity_mw', 'geometry_status', 'latitude', 'longitude'];
  if (required.some(field => !data.fields.includes(field)) || new Set(data.fields).size !== data.fields.length)
    throw Error('Incomplete or ambiguous GridAtlas field schema');
  const columns = Object.fromEntries(required.map(field => [field, data.fields.indexOf(field)]));
  const projects = [];
  for (const row of data.rows) {
    if (!Array.isArray(row)) continue;
    const project = {};
    for (const field of required) {
      const value = row[columns[field]], dictionary = data.dictionaries?.[field];
      project[field] = Array.isArray(dictionary) ? (Number.isInteger(value) && value >= 0 ? dictionary[value] : undefined) : value;
    }
    if (project.geometry_status !== 'valid' || !publishedCoordinate(project.latitude, project.longitude)) continue;
    if (typeof project.name !== 'string' || typeof project.technology !== 'string'
        || typeof project.status !== 'string' || !/^\d+$/.test(String(project.repd_ref))) continue;
    project.repd_ref = String(project.repd_ref);
    projects.push(project);
  }
  return { projects, generation: String(data.generation ?? ''), source: GRIDATLAS_SOURCE };
}

export async function loadGridAtlasProjects({ signal } = {}) {
  const response = await fetch(GRIDATLAS_SOURCE.url, { signal });
  if (!response.ok) throw Error(`GridAtlas data request failed (${response.status})`);
  return decodeGridAtlasProjects(await response.json());
}

export function searchProjects(projects, query = '', { limit = 30, technology = 'solar' } = {}) {
  const term = String(query).trim().toLocaleLowerCase();
  const count = Math.max(0, Math.min(100, Math.floor(limit) || 0));
  return projects.filter(project => (!technology || project.technology === technology)
    && (!term || project.name.toLocaleLowerCase().includes(term) || project.repd_ref === term))
    .slice(0, count);
}

// Local WGS84 tangent-plane approximation: [east metres, north metres].
// Intended for neighbourhood drawings; it does not calculate cable routes.
export function projectToLocalMetres(point, origin) {
  if (!coordinate(point?.latitude, point?.longitude) || !coordinate(origin?.latitude, origin?.longitude))
    throw Error('Invalid geographic point');
  const radians = Math.PI / 180, latitude = origin.latitude * radians;
  const a = 6378137, eccentricitySquared = 6.69437999014e-3;
  const denominator = 1 - eccentricitySquared * Math.sin(latitude) ** 2;
  const northRadius = a * (1 - eccentricitySquared) / denominator ** 1.5;
  const eastRadius = a / Math.sqrt(denominator);
  const deltaLongitude = ((point.longitude - origin.longitude + 540) % 360) - 180;
  return [deltaLongitude * radians * eastRadius * Math.cos(latitude),
    (point.latitude - origin.latitude) * radians * northRadius];
}

export function gridAtlasProjectUrl(project) {
  if (!coordinate(project?.latitude, project?.longitude)) throw Error('Invalid geographic point');
  const url = new URL(GRIDATLAS_SOURCE.atlas);
  url.search = new URLSearchParams({ repd_ref: project.repd_ref, technology: project.technology,
    lat: String(project.latitude), lon: String(project.longitude) }).toString();
  return url.href;
}

export const GRIDATLAS_SUBSTATION_SOURCE = Object.freeze({
  url: 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson',
  sha256: '87976435766a58ddf19c99540b58cd7f18a224148af42ba55075d8851f9e6251',
  generation: '202608300453-atlas-v9',
  label: 'GridAtlas public substation point snapshot'
});

export function decodeGridAtlasSubstations(data) {
  if (data?.type !== 'FeatureCollection' || !Array.isArray(data.features) || data.features.length > 100000)
    throw Error('Unsupported GridAtlas substation snapshot');
  const substations = [];
  for (const [index, feature] of data.features.entries()) {
    const coordinates = feature?.geometry?.coordinates;
    if (feature?.geometry?.type !== 'Point' || !Array.isArray(coordinates)
        || !publishedCoordinate(coordinates[1], coordinates[0])) continue;
    substations.push({ id: `substation-${index}`, source_index: index,
      snapshot_sha256: GRIDATLAS_SUBSTATION_SOURCE.sha256,
      latitude: coordinates[1], longitude: coordinates[0],
      voltage: typeof feature.properties?.voltage === 'string' ? feature.properties.voltage : null });
  }
  return { substations, source: GRIDATLAS_SUBSTATION_SOURCE };
}

export async function loadGridAtlasSubstations({ signal } = {}) {
  const response = await fetch(GRIDATLAS_SUBSTATION_SOURCE.url, { signal });
  if (!response.ok) throw Error(`GridAtlas substation request failed (${response.status})`);
  const bytes = await response.arrayBuffer();
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  const hash = [...new Uint8Array(digest)].map(value => value.toString(16).padStart(2, '0')).join('');
  if (hash !== GRIDATLAS_SUBSTATION_SOURCE.sha256) throw Error('GridAtlas substation snapshot hash mismatch');
  return decodeGridAtlasSubstations(JSON.parse(new TextDecoder().decode(bytes)));
}

Route File

A JavaScript module in Graphics Engines Open Source that calculates planar distances, covering cables. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/. It is built from the serialize route file helper (`serializeRouteFile`).

ingestgraphics-engines-open-source / web/route-file.mjs · lines 1–29 of 29

What it does
Defines parseRouteFile, serializeRouteFile.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables.
Downstream impact
Used directly by 2 files: Route File Test (graphics-engines-open-source); Route Files UI (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/). Reached from 4 other entry points, including Graphics Engines Open Source — Index Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/); Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Geometry Check Workflow (graphics-engines-open-source).
What it achieves
Portable local metric routes. No network requests or inferred site geometry.
Why it matters
Imported by Route Files UI. Checked by Route File Test.
Application
graphics-engines-open-source · web · JavaScript module
Uses
none found
Used by
imported by Route File Test (import), imported by Route Files UI (import)
Produces
MAX_ROUTE_FILE_BYTES, parseRouteFile, serializeRouteFile
Defines here
parseRouteFile, serializeRouteFile
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/route-file.mjs:1-29 · blob 83b632c1696316061867ab4924bb13afa7689710 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
// Portable local metric routes. No network requests or inferred site geometry.
export const MAX_ROUTE_FILE_BYTES=16*1024*1024;
export function parseRouteFile(text){
 if(typeof text!=='string'||text.length>MAX_ROUTE_FILE_BYTES)throw Error('Route file must be JSON, at most 16 MB.');
 const data=JSON.parse(text);
 if(!data||data.schema!=='electrical-routes/1'||data.units!=='metres'||data.axes!=='ENU')throw Error('Expected electrical-routes/1 with units metres and axes ENU.');
 if(!Array.isArray(data.routes)||!data.routes.length||data.routes.length>1000)throw Error('Provide 1–1000 cable routes.');
 let count=0;const ids=new Set();
 return data.routes.map(r=>{
  if(!r||typeof r.id!=='string'||!r.id.trim()||r.id.length>200||ids.has(r.id))throw Error('Each route requires a unique ID of 1–200 characters.');
  ids.add(r.id);
  if(r.label!==undefined&&(typeof r.label!=='string'||r.label.length>1000))throw Error('Route labels must be text, at most 1000 characters.');
  if(!Array.isArray(r.points)||r.points.length<2||r.points.length>10000)throw Error('Each route requires 2–10000 points.');
  count+=r.points.length;if(count>100000)throw Error('Maximum 100000 cable points per file.');
  const points=r.points.map((p,i)=>{
   if(!Array.isArray(p)||p.length!==3||!p.every(n=>typeof n==='number'&&Number.isFinite(n)&&Math.abs(n)<1e7))throw Error('Points must contain finite east, north, up coordinates in metres.');
   if(i&&Math.hypot(...p.map((v,j)=>v-r.points[i-1][j]))<1e-6)throw Error('Repeated consecutive points are not allowed.');
   return [...p];
  });
  return {id:r.id,label:r.label??r.id,points};
 });
}
export function serializeRouteFile(routes){
 const envelope={schema:'electrical-routes/1',units:'metres',axes:'ENU',routes:routes.map(r=>({id:r.id,label:r.label??r.id,points:r.points}))};
 const text=JSON.stringify(envelope,null,2);
 parseRouteFile(text);
 if(new TextEncoder().encode(text).length>MAX_ROUTE_FILE_BYTES)throw Error('Export exceeds the 16 MB file limit.');
 return text;
}

Route Files UI

A JavaScript module in Graphics Engines Open Source that draws electrical routes and cables. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/.

interactiongraphics-engines-open-source / web/route-files-ui.mjs · lines 1–19 of 19 · Entry point

What it does
It draws electrical routes and cables. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables.
Inputs & outputs
Out: JSON file electrical-routes.json; downloaded file electrical-routes.json.
Downstream impact
Used directly by 2 files: Graphics Engines Open Source — Index Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/); Geometry Check Workflow (graphics-engines-open-source). Reached from 1 other entry point, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/). It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/.
What it achieves
It responds to change and click events.
Why it matters
Loaded by the Graphics Engines Open Source page at https://ventusltd.github.io/graphics-engines-open-source/web/. Run by Geometry Check Workflow.
Application
graphics-engines-open-source · web · JavaScript module
Uses
Route File (import)
Used by
loaded by Graphics Engines Open Source — Index Page (script src), run by Geometry Check Workflow (workflow run)
Produces
none declared
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
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/route-files-ui.mjs:1-19 · blob 996fa35c605625c7377ee109f3ccaf28c6199a9a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
import {MAX_ROUTE_FILE_BYTES,parseRouteFile,serializeRouteFile} from './route-file.mjs';
const input=document.getElementById('route-file'),status=document.getElementById('route-file-status');
input.addEventListener('change',async()=>{
 const file=input.files?.[0];if(!file)return;
 try{
  if(file.size>MAX_ROUTE_FILE_BYTES)throw Error('Choose a JSON file smaller than 16 MB.');
  const routes=parseRouteFile(await file.text());
  window.electricalExplorer.setRoutes(routes);
  status.textContent=`Loaded ${routes.length} cable routes. Select a cable to walk it, or use Full-site blueprint.`;
 }catch(error){status.textContent='Import failed: '+error.message;}
 finally{input.value='';}
});
document.getElementById('export-routes').addEventListener('click',()=>{
 try{
  const text=serializeRouteFile(window.electricalExplorer.state.routes),url=URL.createObjectURL(new Blob([text],{type:'application/json'})),a=document.createElement('a');
  a.href=url;a.download='electrical-routes.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
  status.textContent='Exported all modelled cable routes as metric ENU JSON.';
 }catch(error){status.textContent='Export failed: '+error.message;}
});

Route Tool

A JavaScript module in the world folder of Graphics Engines Open Source that describes controls (`describeControls`) and calculates planar distances.

transformgraphics-engines-open-source / web/versions/202609262227-site-world/world/route-tool.mjs · lines 1–93 of 93 · version 2026-09-26 22:27 · pattern describeControls (shared by 2 files)

What it does
It calculates its inputs. Defines createRouteTool, snapshot, changed, point, describeControls.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: Design UI (graphics-engines-open-source). Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
What it achieves
It describes controls (`describeControls`) and is built from the snapshot step (`snapshot`) and the changed step (`changed`). A small state machine for drawing a route on the ground, in Walk or Drone view.
Why it matters
Imported by Design UI.
Application
graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
Uses
none found
Used by
imported by Design UI (import)
Produces
createRouteTool, describeControls
Defines here
createRouteTool, snapshot, changed, point, describeControls
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/route-tool.mjs:1-93 · blob f02616000d156992dbdf4444dd5f814ae85d462b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
// Route tool: a small state machine for drawing a route on the ground, in Walk or Drone view.
// It knows nothing about the DOM, trenches or cables; it only holds an ordered list of points in local
// metres [x, y, z] (east, north, up from the site origin). The page turns clicks into ground points and
// keys into calls; a layer draws state.points. Every change calls onChange(state) once.
//
// Rules:
//   addPoint   appends a point; ignored once the route is finished, or if it repeats the last point.
//   movePoint  moves an existing point (allowed before and after finishing) and selects it.
//   removeLast undoes the last point; ignored once the route is finished (clear starts again).
//   finish     closes the route; needs at least two points.
//   clear      empties the route and reopens it.
// Each method returns true if it changed the route, false if it was ignored.

const MAX_POINTS = 10000;   // one route; route-file.mjs caps a whole file at 100 000 points
const MAX_ABS_M = 1e6;      // local metres; anything further is a bad ground pick, not a route
const SAME_M = 0.01;        // a second click within 1 cm of the last point is a double click, not a point

export function createRouteTool({ onChange = () => {} } = {}) {
  let points = [], finished = false, selected = null;

  const snapshot = () => Object.freeze({
    points: Object.freeze(points.map(p => Object.freeze([...p]))),
    finished, selected
  });
  const changed = () => { onChange(snapshot()); return true; };

  return {
    get state() { return snapshot(); },

    addPoint(p) {
      if (finished || points.length >= MAX_POINTS) return false;
      const q = point(p);
      const last = points[points.length - 1];
      if (last && Math.hypot(q[0] - last[0], q[1] - last[1], q[2] - last[2]) < SAME_M) return false;
      points.push(q);
      selected = points.length - 1;
      return changed();
    },

    movePoint(i, p) {
      if (!Number.isInteger(i) || i < 0 || i >= points.length) return false;
      points[i] = point(p);
      selected = i;
      return changed();
    },

    removeLast() {
      if (finished || !points.length) return false;
      points.pop();
      selected = points.length ? points.length - 1 : null;
      return changed();
    },

    finish() {
      if (finished || points.length < 2) return false;
      finished = true;
      selected = null;
      return changed();
    },

    clear() {
      if (!points.length && !finished) return false;
      points = []; finished = false; selected = null;
      return changed();
    }
  };
}

// Copies and checks one point; throws on anything that is not three finite local-metre numbers.
function point(p) {
  if (!Array.isArray(p) || p.length !== 3) throw Error('a route point is [x, y, z] in metres');
  const q = p.map(Number);
  if (!q.every(v => Number.isFinite(v) && Math.abs(v) <= MAX_ABS_M)) throw Error('a route point needs finite metres within 1000 km of the origin');
  return q;
}

// Lines for the '?' panel while the route tool is active: [keys, meaning] pairs, so the page can render
// them as <dt>/<dd> like the rest of the panel. Plain British English.
export function describeControls({ touch = false } = {}) {
  return touch
    ? [
        ['Tap', 'the ground to add a point'],
        ['Undo', 'removes the last point'],
        ['Done', 'completes the route (two points or more)'],
        ['Clear', 'removes the route and starts again']
      ]
    : [
        ['Click', 'the ground to add a point'],
        ['Backspace', 'removes the last point'],
        ['Enter', 'completes the route (two points or more)'],
        ['Esc', 'removes the route and starts again']
      ];
}