In this section
- Standalone geodesy · stars / library/standalone.mjs lines 4040–4739
Standalone
A JavaScript module in the library folder of Stars that maps Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256, and uses data from the GridAtlas repository.
Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.
Evidence
- line 2 comment: // Generated by the modular star 2026-12-05T23:26:43.596Z. Each export is one family's earliest-seen copy, unchanged; the comment links its source.
geodesystars / library/standalone.mjs · lines 4040–4739 of 12585 (continued from section 1562) · Entry point · pattern segmentConductors (shared by 2 files)
- What it does
- It maps REPD master, heavy emitters UK, notice and substations. Defines 1111 functions or classes, including f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: substations, 750kV, 400kV, 275kV, 132kV, 66kV.
- Inputs & outputs
- In: data source: gridatlas data; JSON file repd_master.json; JSON file heavy_emitters_uk.json; JSON file notice.json; form fields (user input). Out: canvas drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 1.5kV, 1500V.
- Downstream impact
- Used directly by 4 files: Code (stars, https://ventusltd.github.io/stars/code.html); Proof (stars); Modular Star Workflow (stars); Testcode — Code Record Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-record/). Reached from 383 other entry points, including Code Generator — Index Page (code-generator, https://ventusltd.github.io/code-generator/); Generate (code-generator, https://ventusltd.github.io/code-generator/); 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html).
- What it achieves
- It snaps coordinate (`snapCoordinate`), paints cursor (`paintCursor`) and sets plan (`setPlan`). Compiled library of self-contained JavaScript functions that appear in two or more places across Ventusltd code. Its code works with 33 kV, 132 kV and 275 kV. It responds to abort events.
- Why it matters
- Loaded by the Code page at https://ventusltd.github.io/stars/code.html and 1 other page. Run by Proof and Modular Star Workflow.
- Application
- stars · library · JavaScript module
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- Uses
- GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), Declared Connections (estate URL)
- Used by
- named by URL in Code (estate URL), run by Proof (script call), run by Modular Star Workflow (workflow run), named by URL in Testcode — Code Record Page (estate URL)
- Produces
- f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf, f8775_parametersOf, f5168_escapeHTML, f8321_suppliedArrivalFields, f8850__anonymous_, f8786_crossing, f8788_legality, f8789_startNodes
- Defines here
- f5196_haversine, f5197_createGeoJSONCircle, f175913_createJourneyController, empty, el, listen, isReduced, report, pauseMotion, controlsState, removeMap, installMap, writeCursor, lineFor, frameRoute, showStep, advance, resetPlan, animate, frame, choose, installLayerControls, setOrigin, open, styleLoad, preferenceChange, mapRemoved, destroy, f175917_validCoordinate, f175918_radiusKm
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc library/standalone.mjs:4040-4739 · blob fc3d8c8b93e14d4a56b8a26da47071d60bc5bc4d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
const c = geom.coordinates;
if (c.length > 0) { c[0] = snapCoordinate(c[0]); c[c.length-1] = snapCoordinate(c[c.length-1]); }
} else if (geom.type === 'MultiLineString') {
geom.coordinates.forEach(line => {
if (line.length > 0) { line[0] = snapCoordinate(line[0]); line[line.length-1] = snapCoordinate(line[line.length-1]); }
});
}
});
return features;
};
// Family #5196 · element #5196 · 3 places in 2 repositories · https://github.com/Ventusltd/code-generator/blob/3897d83efcd0259d21dce87704b0c33118fe2c2e/apps/substation-finder/Si/index.html#L610-L615
export const f5196_haversine = function haversine(lon1, lat1, lon2, lat2) {
const R = 6371, r = Math.PI/180;
const dLat = (lat2-lat1)*r, dLon = (lon2-lon1)*r;
const a = Math.sin(dLat/2)**2 + Math.cos(lat1*r)*Math.cos(lat2*r)*Math.sin(dLon/2)**2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
};
// Family #5197 · element #5197 · 3 places in 2 repositories · https://github.com/Ventusltd/code-generator/blob/3897d83efcd0259d21dce87704b0c33118fe2c2e/apps/substation-finder/Si/index.html#L617-L627
export const f5197_createGeoJSONCircle = function createGeoJSONCircle(lon, lat, radiusKm, points = 64) {
const coords = [];
const distX = radiusKm / (111.32 * Math.cos(lat * Math.PI / 180));
const distY = radiusKm / 110.574;
for (let i = 0; i < points; i++) {
const theta = (i / points) * (2 * Math.PI);
coords.push([lon + distX * Math.cos(theta), lat + distY * Math.sin(theta)]);
}
coords.push(coords[0]);
return { type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [coords] } }] };
};
// Family #175913 · element #175913 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611172355-grid-journey-preview.js#L636-L836
export const f175913_createJourneyController = function createJourneyController({map, document: D, window: W, planner, fixture, css, generation}) {
const NS = 'gridatlas-gj03', source = NS + '-route', cursor = NS + '-cursor';
const layerIds = [NS + '-verified', NS + '-schematic', NS + '-cursor'];
const empty = () => ({type: 'FeatureCollection', features: []});
const caveat = 'The travelling light is a learning cursor, not measured current or a power-flow simulation. Dotted links are schematic, not cable routes. Flow direction unavailable.';
const layerGroups = [], layerLaunchers = [];
let layerObserver = null, returnFocus = null, originContext = null;
const on = [], ownedSources = new Map(), ownedLayers = new Map();
let alive = true, opened = false, plan = null, step = 0, raf = null, playing = false, epoch = 0, demo = false, routeData = empty(), cursorData = empty();
if (!map || !['addSource', 'addLayer', 'getSource', 'getLayer', 'removeSource', 'removeLayer', 'on', 'off'].every(k => typeof map[k] === 'function')) throw new Error('Native MapLibre map unavailable');
if (D.getElementById(NS)) throw new Error('Journey already mounted');
const container = D.getElementById('map-container') || map.getContainer?.();
const initialPadding = map.getPadding?.();
if (!container) throw new Error('Native map container unavailable');
function el(tag, text, parent, attrs = {}) { const e = D.createElement(tag); if (text) e.textContent = text; for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v); parent?.appendChild(e); return e; }
function listen(e, type, fn) { e.addEventListener(type, fn); on.push(() => e.removeEventListener(type, fn)); }
const root = el('div', null, container, {id: NS, 'data-generation': generation});
const style = el('style', css, root);
const opener = el('button', 'Grid Journeys', root, {type: 'button', 'aria-expanded': 'false', 'aria-controls': NS + '-panel', class: 'gj-launch'});
const panel = el('section', null, root, {id: NS + '-panel', 'aria-label': 'Grid Journeys', hidden: '', class: 'gj-panel'});
const heading = el('div', null, panel, {class: 'gj-heading'});
el('strong', 'GRID JOURNEYS', heading);
const close = el('button', 'Close', heading, {type: 'button', 'aria-label': 'Close Grid Journey'});
const caption = el('p', caveat, panel, {class: 'gj-caveat'});
const state = el('p', 'Explore the physical grid on the map, or choose a learning demonstration below.', panel, {role: 'status', 'aria-live': 'polite', class: 'gj-status'});
const context = el('p', 'Select an asset on the map to explore its surroundings.', panel, {class: 'gj-origin'});
const realGrid = el('button', 'Explore real grid nearby', panel, {type: 'button'});
const demoButton = el('button', 'Load SYNTHETIC demonstration', panel, {type: 'button'});
const label = el('label', 'Explicit starting node ', panel, {class: 'gj-node'});
const select = el('select', null, label, {'aria-label': 'Explicit starting node', disabled: ''});
el('option', 'Choose a reviewed node…', select, {value: ''});
const controls = el('div', null, panel, {class: 'gj-controls'});
const start = el('button', 'Start', controls, {type: 'button', disabled: ''});
const pause = el('button', 'Pause', controls, {type: 'button', disabled: ''});
const next = el('button', 'Next', controls, {type: 'button', disabled: ''});
const reset = el('button', 'Reset', controls, {type: 'button', disabled: ''});
const evidence = el('details', null, panel, {class: 'gj-evidence'});
el('summary', 'Input evidence and limits', evidence);
evidence.appendChild(caption);
const receipt = el('pre', 'Real routes: 0 accepted. No measured or modelled MW inputs. Synthetic data loads only on explicit request.', evidence);
const media = W.matchMedia?.('(prefers-reduced-motion: reduce)');
function isReduced() { return media?.matches === true; }
function report(s) { if (alive) state.textContent = s; }
function pauseMotion() { playing = false; if (raf !== null) W.cancelAnimationFrame(raf); raf = null; pause.disabled = true; start.disabled = !plan?.steps.length || step >= plan.steps.length; }
function controlsState() { const usable = !!plan?.steps.length; start.disabled = !usable || step >= plan.steps.length || playing; next.disabled = !usable || playing || step >= plan.steps.length; reset.disabled = !plan; pause.disabled = !playing; start.textContent = isReduced() ? 'Start · manual' : 'Start'; }
function removeMap() {
for (const [id, object] of [...ownedLayers].reverse()) { if (map.getLayer(id) === object) map.removeLayer(id); ownedLayers.delete(id); }
for (const [id, object] of ownedSources) { if (map.getSource(id) === object) map.removeSource(id); } ownedSources.clear();
}
function installMap() {
if (!alive || !opened || !plan) return false;
// isStyleLoaded also waits on map resources; a loaded stylesheet can accept sources earlier.
if (typeof map.getStyle === 'function' && !map.getStyle()) return true;
try {
for (const id of [source, cursor]) if (map.getSource(id) && ownedSources.get(id) !== map.getSource(id)) throw new Error('Journey source collision; existing map source preserved');
for (const id of layerIds) if (map.getLayer(id) && ownedLayers.get(id) !== map.getLayer(id)) throw new Error('Journey layer collision; existing map layer preserved');
for (const [id, data] of [[source, routeData], [cursor, cursorData]]) { if (!map.getSource(id)) { map.addSource(id, {type: 'geojson', data}); ownedSources.set(id, map.getSource(id)); } else map.getSource(id).setData(data); }
const layers = [
{id: layerIds[0], type: 'line', source, filter: ['==', ['get', 'schematic'], false], paint: {'line-color': '#00ffff', 'line-width': 3}},
{id: layerIds[1], type: 'line', source, filter: ['==', ['get', 'schematic'], true], paint: {'line-color': '#ffd84d', 'line-width': 3, 'line-dasharray': [1, 3]}},
{id: layerIds[2], type: 'circle', source: cursor, paint: {'circle-color': '#fff', 'circle-radius': 5, 'circle-stroke-color': '#00ffff', 'circle-stroke-width': 3}}
];
for (const l of layers) if (!map.getLayer(l.id)) { map.addLayer(l); ownedLayers.set(l.id, map.getLayer(l.id)); }
return true;
} catch (e) { pauseMotion(); report('WITHHELD: ' + e.message); removeMap(); plan = null; controlsState(); return false; }
}
function writeCursor(coordinates) {
cursorData = {type: 'FeatureCollection', features: coordinates ? [{type: 'Feature', properties: {meaning: 'learning cursor only'}, geometry: {type: 'Point', coordinates}}] : []};
if (ownedSources.has(cursor) && ownedSources.get(cursor) === map.getSource(cursor)) map.getSource(cursor).setData(cursorData);
}
function lineFor(s) { const e = plan.edgeCatalog.find(e => e.edgeUid === s.edgeUid); if (!e?.coordinates) return null; const coords = e.coordinates.map(p => [...p]); if (s.direction === 'reverse') coords.reverse(); return {e, coords}; }
function frameRoute() {
if (!alive || !opened || !plan) return;
const pts = plan.edgeCatalog.flatMap(e => e.coordinates || []);
const r = map.getContainer?.().getBoundingClientRect?.(), q = panel.getBoundingClientRect?.();
let padding = 65;
if (r && q) { const top = Math.max(45, q.bottom - r.top + 12); padding = q.width > r.width * .6 && r.height - top > 130 ? {left: 35, right: 35, top, bottom: 50} : {left: 45, right: Math.min(r.width * .6, q.width + 25), top: 55, bottom: 55}; }
if (pts.length && map.fitBounds) { map.setPadding?.({top: 0, right: 0, bottom: 0, left: 0}); map.fitBounds([[Math.min(...pts.map(p => p[0])), Math.min(...pts.map(p => p[1]))], [Math.max(...pts.map(p => p[0])), Math.max(...pts.map(p => p[1]))]], {padding, maxZoom: 9, duration: 0}); }
}
function showStep(index) {
const s = plan.steps[index], line = lineFor(s);
writeCursor(line?.coords.at(-1) || null);
report(`SYNTHETIC ONLY · ${index + 1}/${plan.steps.length} · ${s.traversal} ${s.nearNode} → ${s.farNode} · ${s.geometryStatus === 'published_node_unlocated' ? 'UNLOCATED: text only' : line?.e.schematic ? 'DOTTED SCHEMATIC: not a cable route' : 'synthetic reviewed polyline'} · journey heading, flow direction unavailable`);
step = index + 1; controlsState();
}
function advance() { pauseMotion(); if (plan && step < plan.steps.length) showStep(step); }
function resetPlan() { pauseMotion(); step = 0; writeCursor(null); if (plan) report(`SYNTHETIC ONLY · ready · ${plan.visitedUniqueEdges} source-row edges; ${plan.steps.length} moves including explicit backtracking; physical units unknown`); controlsState(); }
function animate() {
if (!alive || !opened || !plan || step >= plan.steps.length) { pauseMotion(); controlsState(); return; }
if (isReduced()) { pauseMotion(); controlsState(); return; }
const index = step, s = plan.steps[index], line = lineFor(s); let began;
function frame(now) {
if (!alive || !opened || !playing) return;
if (isReduced()) { pauseMotion(); controlsState(); return; }
began ??= now; const t = Math.min(1, (now - began) / 1000);
// Only a reviewed polyline gets a travelling light. Schematic/unlocated moves are discrete.
if (line && !line.e.schematic) {
const p = t * (line.coords.length - 1), i = Math.min(line.coords.length - 2, Math.floor(p)), f = p - i;
writeCursor(line.coords[i].map((v, k) => v + (line.coords[i + 1][k] - v) * f));
}
if (t < 1) raf = W.requestAnimationFrame(frame);
else { showStep(index); if (playing) animate(); }
}
raf = W.requestAnimationFrame(frame);
}
async function choose() {
const ticket = ++epoch; pauseMotion(); plan = null; routeData = empty(); cursorData = empty(); removeMap(); controlsState();
if (!select.value || !demo) { report('Choose an explicit reviewed synthetic node. No nearest-node or project connection is inferred.'); return; }
report('Checking exact source bytes and review ledger…');
try {
const candidate = await planner({sourceBytes: fixture.networkText, ledger: fixture.ledger, query: {seed: {chosenNode: select.value}, bounds: {maxNodes: 25, maxEdges: 30, maxMoves: 60, maxGeometryBytes: 16000}}});
if (!alive || ticket !== epoch || !opened) return;
if (candidate.status === 'refused' || !candidate.steps.length) { report('WITHHELD: ' + (candidate.refusal || 'no eligible reviewed edges')); return; }
// The engine classifies evidence. Presentation refuses unsupported output as well.
if (candidate.edgeCatalog.some(e => !['verified_circuit_and_polyline', 'published_topology_only', 'published_node_unlocated'].includes(e.geometryStatus))) throw new Error('Unsupported geometry evidence');
plan = candidate;
routeData = {type: 'FeatureCollection', features: plan.edgeCatalog.filter(e => e.coordinates).map(e => ({type: 'Feature', properties: {edgeUid: e.edgeUid, schematic: e.schematic, meaning: e.label}, geometry: {type: 'LineString', coordinates: e.coordinates}}))};
receipt.textContent = `SYNTHETIC TEST ONLY; no real assets or third-party approval\nsource SHA256 ${plan.sourceBundleSha}\nreview SHA256 ${plan.reviewLedgerSha}\nplan SHA256 ${plan.planSha256}\n${plan.edgeCatalog.filter(e => e.geometryStatus === 'verified_circuit_and_polyline').length} synthetic polylines; ${plan.edgeCatalog.filter(e => e.schematic).length} schematic; ${plan.edgeCatalog.filt … [line shortened here: 760 characters; full line on GitHub]
if (!installMap()) return;
resetPlan();
frameRoute();
} catch (e) { if (alive && ticket === epoch) report('WITHHELD: ' + e.message); }
}
function installLayerControls() {
const hosts = ['scada-ui-container', 'fs-curtain-keys'].map(id => [id, D.getElementById(id)]);
hosts.push(['native-grid-menu', D.querySelector?.('#gridatlas-menu-bar-panel-4 .gm-panel-body')]);
for (const [id, host] of hosts) {
if (!host || layerGroups.some(g => g.parentNode === host || g.parent === host)) continue;
// Other native modules use .key-group as the engine-dashboard ready marker.
// Never create that marker before the engine's original controls exist.
if (id !== 'native-grid-menu' && !host.querySelector?.('input[data-layer-id]')) continue;
const group = el('div', null, host, {class: 'key-group', 'data-journey-group': id});
const title = el('div', 'Grid Journeys', group, {class: 'key-title'});
const button = el('button', 'Open Grid Journey', group, {type: 'button', class: 'map-ctrl-btn', 'aria-controls': NS + '-panel', 'aria-expanded': String(opened)});
button.style.cssText = 'min-height:44px;min-width:44px;';
el('p', 'Exploratory only; real routes require reviewed circuit evidence.', group);
listen(button, 'click', e => { e.stopPropagation?.(); returnFocus = button; W.__GRIDATLAS_MODULES__?.menuBar?.closeAll?.(); const curtain = D.getElementById('fs-curtain'); if (id === 'fs-curtain-keys' && curtain?.classList?.contains('curtain-open')) D.getElementById('fs-curtain-tab')?.click(); open(); });
layerGroups.push(group); layerLaunchers.push(button);
}
}
function setOrigin(origin) {
originContext = null;
if (origin && typeof origin === 'object') {
const name = typeof origin.name === 'string' ? origin.name.slice(0, 160) : '';
const id = typeof origin.id === 'string' || typeof origin.id === 'number' ? String(origin.id).slice(0, 80) : '';
if (name || id) { originContext = {name, id}; if (Array.isArray(origin.at) && origin.at.length === 2 && origin.at.every(Number.isFinite) && Math.abs(origin.at[0]) <= 180 && Math.abs(origin.at[1]) <= 90 && (origin.at[0] !== 0 || origin.at[1] !== 0)) originContext.at = [...origin.at]; if (['repd', 'datacentre', 'substation'].includes(origin.type)) originContext.type = origin.type; }
}
context.textContent = originContext ? 'Selected asset: ' + [originContext.name, originContext.id].filter(Boolean).join(' ? ') + '. Nearby assets are map context; connections need source evidence.' : 'Select an asset on the map to explore its surroundings.';
realSelection(false);
}
function shut() { ++epoch; pauseMotion(); opened = false; panel.hidden = true; opener.setAttribute('aria-expanded', 'false'); removeMap(); if (initialPadding) map.setPadding(initialPadding); for (const b of layerLaunchers) b.setAttribute('aria-expanded', 'false'); const target = returnFocus?.isConnected === false || (returnFocus?.getClientRects && !returnFocus.getClientRects().length) ? D.getEle … [line shortened here: 491 characters; full line on GitHub]
function open(options) { if (!alive) return; if (options?.origin) setOrigin(options.origin); opened = true; panel.hidden = false; opener.setAttribute('aria-expanded', 'true'); for (const b of layerLaunchers) b.setAttribute('aria-expanded', 'true'); installMap(); frameRoute(); close.focus(); }
function realSelection(clearContext = true) { if (clearContext) { originContext = null; context.textContent = 'Selected asset has no reviewed circuit identity. Real circuit journeys remain withheld.'; } ++epoch; pauseMotion(); plan = null; demo = false; select.value = ''; select.disabled = true; removeMap(); controlsState(); report('Explore this asset and the surrounding grid. Nearby assets do n … [line shortened here: 431 characters; full line on GitHub]
listen(opener, 'click', () => {returnFocus = opener; opened ? shut() : open();}); listen(close, 'click', shut);
listen(panel, 'keydown', e => { if (e.key === 'Escape') { e.preventDefault(); shut(); } });
listen(demoButton, 'click', () => { ++epoch; pauseMotion(); plan = null; removeMap(); demo = true; select.disabled = false; select.replaceChildren(); el('option', 'Choose a reviewed synthetic node…', select, {value: ''}); for (const n of fixture.ledger.nodes) el('option', 'SYNTHETIC ' + n.nodeId, select, {value: n.nodeId}); report('SYNTHETIC DEMONSTRATION LOADED. These are invented assets; choos … [line shortened here: 453 characters; full line on GitHub]
listen(realGrid, 'click', event => {
event.stopPropagation?.();
const vicinity = W.__GRIDATLAS_MODULES__?.gridVicinity;
if (!vicinity?.open) {
const grid = D.getElementById('gridatlas-menu-bar-title-4');
if (!grid?.click) {
const layers = D.getElementById('scada-ui-container');
if (!layers?.scrollIntoView) { report('Grid layers are loading. Try Explore grid again when the map controls appear.'); return; }
if (originContext?.at) map.flyTo?.({center: [...originContext.at], duration: 0});
shut(); layers.scrollIntoView({block: 'start', behavior: 'instant'});
layers.querySelector?.('input[data-layer-id]')?.focus();
return;
}
if (originContext?.at) map.flyTo?.({center: [...originContext.at], duration: 0});
shut();
if (grid.getAttribute?.('aria-expanded') !== 'true') grid.click();
grid.focus();
return;
}
pauseMotion(); vicinity.open({origin: originContext?.at ? {...originContext, at: [...originContext.at]} : undefined, radiusKm: 10}); shut();
});
listen(select, 'change', choose); listen(next, 'click', advance); listen(reset, 'click', resetPlan);
listen(start, 'click', () => { if (!plan) return; if (isReduced()) { advance(); return; } playing = true; controlsState(); animate(); });
listen(pause, 'click', () => { pauseMotion(); controlsState(); });
listen(W, 'gridatlas:card-open', e => { if (e.detail?.origin) setOrigin(e.detail.origin); else realSelection(); });
listen(W, 'gridatlas:journey-open', e => open(e.detail));
installLayerControls();
if (W.MutationObserver && D.documentElement) { layerObserver = new W.MutationObserver(installLayerControls); layerObserver.observe(D.documentElement, {childList: true, subtree: true}); }
const styleLoad = () => { pauseMotion(); installMap(); controlsState(); }; map.on('style.load', styleLoad);
map.on('resize', frameRoute);
const preferenceChange = () => { if (isReduced()) pauseMotion(); controlsState(); };
if (media?.addEventListener) { media.addEventListener('change', preferenceChange); on.push(() => media.removeEventListener('change', preferenceChange)); }
function mapRemoved() { destroy(true); }
function destroy(mapWasRemoved = false) {
if (!alive) return; alive = false; ++epoch; pauseMotion();
try {
map.off('style.load', styleLoad); map.off('resize', frameRoute); map.off('remove', mapRemoved); for (const off of on.splice(0)) off();
// MapLibre fires remove AFTER destroying its style. Its layers/sources have already gone.
if (mapWasRemoved) { ownedLayers.clear(); ownedSources.clear(); } else { removeMap(); if (initialPadding) map.setPadding(initialPadding); }
} finally { layerObserver?.disconnect(); for (const group of layerGroups) group.remove(); root.remove(); }
}
map.on('remove', mapRemoved);
controlsState();
return Object.freeze({open, setOrigin, close: shut, snapshot: () => ({alive, opened, playing, step, status: plan?.status || 'withheld', synthetic: demo, origin: originContext ? {...originContext} : null, layerControls: layerGroups.length, steps: plan?.steps.length || 0, edgeCount: plan?.edgeCatalog.length || 0}), destroy});
};
// Family #175917 · element #175917 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L14-L18
export const f175917_validCoordinate = function validCoordinate(at) {
return Array.isArray(at) && at.length >= 2 && at.slice(0, 2).every(v => typeof v === 'number' && Number.isFinite(v))
&& Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90
&& !(Math.abs(at[0]) < 1e-9 && Math.abs(at[1]) < 1e-9);
};
// Family #175918 · element #175918 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L20-L26
export const f175918_radiusKm = function radiusKm(value) {
if (typeof value !== 'number' && typeof value !== 'string') throw new Error('Choose a whole-kilometre radius from 1 to 50 km.');
if (typeof value === 'string' && !value.trim()) throw new Error('Choose a radius from 1 to 50 km.');
const n = Number(value);
if (!Number.isInteger(n) || n < 1 || n > 50) throw new Error('Choose a whole-kilometre radius from 1 to 50 km.');
return n;
};
// Family #175921 · element #175921 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L66-L72
export const f175921_validateNewsContextBase = function validateNewsContextBase(value) {
if (typeof value !== 'string' || value.length > 200 || !/^https:\/\/globalgrid2050\.com\//.test(value)) throw new Error('News context must use a dated GlobalGrid2050 edition.');
const url = new URL(value);
if (url.origin !== 'https://globalgrid2050.com' || url.username || url.password || url.port || url.search || url.hash
|| !/^\/uk_renewables_pipeline\/\d{12}\/(?:index\.html)?$/.test(url.pathname)) throw new Error('News context must use a dated GlobalGrid2050 edition without extra URL fields.');
return url.href;
};
// Family #175922 · element #175922 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L74-L81
export const f175922_normaliseNewsTopic = function normaliseNewsTopic(value, origin) {
const allowed = ['datacentre','grid','renewables','storage','solar','wind'];
if (value != null && value !== '') {
if (!allowed.includes(value)) throw new Error('News topic is not supported.');
return value;
}
return origin?.type === 'datacentre' ? 'datacentre' : origin?.type === 'substation' ? 'grid' : 'renewables';
};
// Family #175934 · element #175934 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L207-L210
export const f175934_freezeDocumentContext = function freezeDocumentContext(value) {
if (value && typeof value === 'object') { for (const child of Object.values(value)) freezeDocumentContext(child); Object.freeze(value); }
return value;
};
// Family #175935 · element #175935 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L254-L258
export const f175935_documentOrigin = function documentOrigin(origin) {
if (!origin || !['repd', 'datacentre', 'substation'].includes(origin.type) || typeof origin.id !== 'string'
|| !origin.id || origin.id.length > 256 || /[\s\u0000-\u001f\u007f]/.test(origin.id)) return null;
return {type: origin.type, id: origin.id};
};
// Family #175983 · element #175983 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L811-L824
export const f175983_trainLearningFixture = function trainLearningFixture(kind = 'local') {
const names = kind === 'express' ? ['Harbour', 'Highland', 'Far Reach']
: kind === 'branch' ? ['Junction', 'West Branch', 'Junction', 'East Branch']
: ['Central', 'Interchange', 'Gardens', 'Terminus'];
const spacing = kind === 'express' ? 2 : 0.04;
return {schema: 'gridatlas.train.fixture.v1', synthetic: true,
title: kind === 'express' ? 'Fictional express learning journey'
: kind === 'branch' ? 'Fictional branch and junction journey' : 'Fictional local and interchange journey',
stops: names.map((name, i) => ({stationId: 'synthetic-' + name.toLowerCase().replaceAll(' ', '-'),
id: 'synthetic-' + name.toLowerCase().replaceAll(' ', '-'), stopId: 'visit-' + i, name, kv: 400,
at: [kind === 'branch' && i === 2 ? -1 : -1 + i * spacing, 52 + (i % 2) * spacing / 2],
source: 'SYNTHETIC_TEACHING_FIXTURE'})),
note: 'Original invented example. Lines require the same explicit simulated-journey action; no real electrical or railway connection is asserted.'};
};
// Family #175991 · element #175991 · 3 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L1006-L1008
export const f175991_rowOrigin = function rowOrigin(row) {
return {at: row.at, name: row.name, id: row.originId || row.id, type: row.kind === 'datacentre' ? 'datacentre' : ['generation','storage'].includes(row.kind) ? 'repd' : 'context-asset'};
};
// Family #10999 · element #10999 · 64 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051344/atlas/cartridges/202609051344-sld-sandbox.js#L2-L145
export const f10999__anonymous_ = ()=>{
/**
* Module: geodesy
*
* Extracted verbatim (formula and constant unchanged) from
* gridatlas/atlas/modules/202609011950-geodesy.js.
*
* One Earth radius for the whole estate, and the three operations every
* measurement here is built from. This existed three times tonight - in
* the sandbox, in the substation cartridge and in the data repository -
* which is exactly how two of them end up on different radii without
* anyone noticing.
*
* Radius 6378.137 km, matching Ventusltd/grid-distance-maths. Haversine.
* No projection, no turf, no second radius for geometry.
*
* Pure functions. No DOM, no network, no state.
*
* CHANGED: source wraps this in `(() => { ... NS.geodesy = Object.freeze({...}) })()`
* and registers itself on `window.__GRIDATLAS_MODULES__.geodesy`. That
* closure/global-namespace wiring is removed; every function below is
* otherwise byte-identical to the source, including the atan2 argument
* order that the source's own comment insists on for numerical parity
* with ventus-corev8engine.js haversine() (see distanceKm below).
*/
const EARTH_RADIUS_KM = 6378.137;
const DEG = Math.PI / 180;
function distanceKm(lon1, lat1, lon2, lat2) {
const dLat = (lat2 - lat1) * DEG;
const dLon = (lon2 - lon1) * DEG;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
/* atan2, in this operand order, because that is the form every version
of this estate has shipped - ventus-corev8engine.js haversine() and
every cartridge carried from it.
-------------------------------------------------------------------
The extraction wrote 2 * R * asin(sqrt(a)) instead. Algebraically the
same; numerically one unit in the last place apart, which the
all-versions proof caught on West Burton Solar to Cottam:
7.050150827184836 shipped, 7.050150827184837 from the module. It is
1e-15 km and changes no figure any reader will ever see - and it is
still wrong, because the claim being made is PARITY. A module that is
nearly the incumbent is a module that has to be argued about every
time a digit differs. */
return EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
/* A polygon reduces to the mean of its outer ring, not its first corner.
A substation drawn as a compound outline would otherwise be measured
from whichever vertex the mapper happened to start at.
Point, Polygon and MultiPolygon, and NOTHING ELSE. The first draft of
this module accepted any nested coordinate array and so returned a
mean for a LineString where the incumbent returns null; the parity
proof caught it against the live cartridge. Extraction is not the
moment to change behaviour, so the behaviour is pinned here and any
widening becomes its own version with its own reasoning.
One deliberate difference, on malformed input only: this returns null
where the incumbent would throw on a Point with no coordinates. No
real geometry reaches that path, and a proof asserts it. */
function representativePoint(geometry) {
if (!geometry) return null;
const { type, coordinates } = geometry;
if (type === 'Point') {
return Array.isArray(coordinates) && coordinates.length >= 2
? [coordinates[0], coordinates[1]] : null;
}
const ring = type === 'Polygon' ? coordinates && coordinates[0]
: type === 'MultiPolygon' ? coordinates && coordinates[0] && coordinates[0][0]
: null;
if (!Array.isArray(ring) || !ring.length) return null;
let sumLon = 0;
let sumLat = 0;
for (const point of ring) {
sumLon += point[0];
sumLat += point[1];
}
return [sumLon / ring.length, sumLat / ring.length];
}
/* OpenStreetMap's `voltage` is VOLTS at every magnitude, and a feature
may carry several separated by a semicolon. Magnitude is not the unit:
750 is a DC traction supply at a railway depot, not 750 kV. An audit
of the served payload found 229 features (3.95%) carrying a token
below 1,000, every one of which had been misread. An explicit `kv`
property is already kilovolts and is trusted as such. */
function voltagesKv(properties) {
if (!properties) return [];
const out = [];
const explicit = properties.kv ?? properties.KV;
if (explicit != null && String(explicit).trim() !== '') {
for (const token of String(explicit).match(/\d+(?:\.\d+)?/g) || []) {
const value = Number(token);
if (Number.isFinite(value) && value > 0) out.push(value);
}
}
const volts = properties.voltage ?? properties.VOLTAGE;
if (volts != null) {
for (const token of String(volts).match(/\d+(?:\.\d+)?/g) || []) {
const value = Number(token);
if (Number.isFinite(value) && value > 0) out.push(value / 1000);
}
}
return [...new Set(out)].sort((a, b) => b - a);
}
/* Projection and bearing, carried in from the sandbox verbatim.
----------------------------------------------------------------------
The deep scan found the body carrying a SECOND geodesy section - "the
geodesy the layout needs, all on R_ATLAS" - four hundred lines away
from the first. Two geodesies in one file, on a constant that must
never differ, is the configuration that produced the divergence the
all-versions proof caught. Both belong here, on the one radius, and
the body now delegates rather than defining.
The bodies below are the incumbent's, character for character apart
from the radius identifier, so parity is a property of the move rather
than something to argue about afterwards. */
function destinationPoint(lon, lat, km, bearingDeg) {
const ad = km / EARTH_RADIUS_KM;
const brg = bearingDeg * DEG;
const p1 = lat * DEG;
const p2 = Math.asin(Math.sin(p1) * Math.cos(ad)
+ Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
const l2 = lon * DEG + Math.atan2(
Math.sin(brg) * Math.sin(ad) * Math.cos(p1),
Math.cos(ad) - Math.sin(p1) * Math.sin(p2));
return [l2 / DEG, p2 / DEG];
}
function initialBearingDeg(lon1, lat1, lon2, lat2) {
const p1 = lat1 * DEG; const p2 = lat2 * DEG;
const dl = (lon2 - lon1) * DEG;
const y = Math.sin(dl) * Math.cos(p2);
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
return (Math.atan2(y, x) / DEG + 360) % 360;
}
const schema = 'gridatlas.module.geodesy.v1';
return {distanceKm};};
// Family #148754 · element #148754 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/overlay.html#L185-L189
export const f148754_tower = function tower(h) { const L = [], b = h * 0.12, t = h * 0.03, arm = h * 0.8, w = h * 0.3;
const legs = [[-b, -b], [b, -b], [b, b], [-b, b]], top = [[-t, -t], [t, -t], [t, t], [-t, t]];
for (let i = 0; i < 4; i++) { L.push([legs[i][0], legs[i][1], 0, top[i][0], top[i][1], h]); const j = (i + 1) % 4; L.push([legs[i][0], legs[i][1], 0, legs[j][0], legs[j][1], 0]); }
L.push([-w, 0, arm, w, 0, arm], [-w * 0.8, 0, arm - h * 0.15, w * 0.8, 0, arm - h * 0.15]);
return L; };
// Family #148757 · element #148757 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/overlay.html#L34-L38
export const f148757_withAnchor = function withAnchor(m, o) {
const r = Array.from(m);
for (let k = 0; k < 4; k++) r[12 + k] = m[k] * o.x + m[4 + k] * o.y + m[8 + k] * o.z + m[12 + k];
return new Float32Array(r);
};
// Family #148796 · element #148796 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/find-go.js#L38-L45
export const f148796_marker = function marker(lon, lat, h, rFoot) {
const L = [], ring = (r, z, n) => { for (let i = 0; i < n; i++) { const a = 2 * Math.PI * i / n, b = 2 * Math.PI * (i + 1) / n;
L.push([r * Math.cos(a), r * Math.sin(a), z, r * Math.cos(b), r * Math.sin(b), z]); } };
L.push([0, 0, 0, 0, 0, h]); ring(40, 0.5, 32); ring(12, h, 12);
for (let i = 0; i < 4; i++) { const a = Math.PI * i / 2; L.push([0, 0, h, 12 * Math.cos(a), 12 * Math.sin(a), h]); }
if (rFoot) ring(rFoot, 0.5, 96);
return { lon, lat, lines: L, find: true };
};
// Family #148822 · element #148822 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/pylons-real.js#L94-L111
export const f148822_lattice = function lattice(g) {
const L = [], H = g.H, b = g.base, zw = g.armZ[0] * H - 2, w = b * 0.32, zt = g.armZ[2] * H + 1, wt = w * 0.8;
const half = z => z <= zw ? b + (w - b) * z / zw : w + (wt - w) * (z - zw) / (zt - zw);
const lv = [0, zw * 0.3, zw * 0.58, zw * 0.8, zw, ...g.armZ.map(f => f * H), zt];
const sq = (z) => { const h = half(z); return [[-h, -h, z], [h, -h, z], [h, h, z], [-h, h, z]]; };
for (let k = 0; k < lv.length; k++) {
const A = sq(lv[k]);
for (let i = 0; i < 4; i++) { const j = (i + 1) % 4; if (k > 0) L.push([...A[i], ...A[j]]); }
if (k + 1 < lv.length) { const B = sq(lv[k + 1]);
for (let i = 0; i < 4; i++) { const j = (i + 1) % 4; L.push([...A[i], ...B[i]]);
if (lv[k] < zw) L.push([...A[i], ...B[j]], [...A[j], ...B[i]]); else L.push([...A[i], ...B[j]]); } }
}
const top = sq(zt); for (const p of top) L.push([...p, 0, 0, H]); // earth-wire peak
g.armZ.forEach((f, k) => { const z = f * H, h = half(z), a = g.arm[k]; // crossarms: two chords to the tip, both sides
for (const s of [-1, 1]) { const tip = [0, s * a, z];
L.push([-h, s * h, z, ...tip], [h, s * h, z, ...tip], [-h, s * h, z - 2.2, ...tip], [h, s * h, z - 2.2, ...tip], [...tip, 0, s * a, z - g.ins]); } });
return L;
};
// Family #148834 · element #148834 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/rows-geometry.js#L123-L159
export const f148834_mergeRows = function mergeRows(segs) {
const n = segs.length, par = Int32Array.from({ length: n }, (_, i) => i);
const find = i => { while (par[i] !== i) i = par[i] = par[par[i]]; return i; };
for (const s of segs) { s.ux = Math.cos(s.phi + Math.PI / 2); s.uy = Math.sin(s.phi + Math.PI / 2); s.len = Math.hypot(s.x1 - s.x0, s.y1 - s.y0); }
for (let i = 0; i < n; i++) { const A = segs[i];
for (let j = i + 1; j < n; j++) { const B = segs[j];
if (Math.abs(B.x0 - A.x0) > 120 || Math.abs(B.y0 - A.y0) > 120) continue;
let dphi = Math.abs(A.phi - B.phi) % Math.PI; if (dphi > Math.PI / 2) dphi = Math.PI - dphi; if (dphi > 0.07) continue;
const nx = -A.uy, ny = A.ux, off = ((B.x0 + B.x1) / 2 - A.x0) * nx + ((B.y0 + B.y1) / 2 - A.y0) * ny;
if (Math.abs(off) > 1.6) continue;
const sb0 = (B.x0 - A.x0) * A.ux + (B.y0 - A.y0) * A.uy, sb1 = (B.x1 - A.x0) * A.ux + (B.y1 - A.y0) * A.uy;
const lo = Math.min(sb0, sb1), hi = Math.max(sb0, sb1);
if (lo > A.len + 4 || hi < -4) continue;
par[find(i)] = find(j);
}
}
const groups = new Map(); for (let i = 0; i < n; i++) { const r = find(i); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(segs[i]); }
const rows = [];
for (const g of groups.values()) {
let vx = 0, vy = 0; for (const s of g) { vx += Math.cos(2 * s.phi) * s.len; vy += Math.sin(2 * s.phi) * s.len; }
const phi = 0.5 * Math.atan2(vy, vx), ux = -Math.sin(phi), uy = Math.cos(phi), o = g[0];
const iv = g.map(s => { const a = (s.x0 - o.x0) * ux + (s.y0 - o.y0) * uy, b = (s.x1 - o.x0) * ux + (s.y1 - o.y0) * uy;
const nx = Math.cos(phi), ny = Math.sin(phi), off = ((s.x0 + s.x1) / 2 - o.x0) * nx + ((s.y0 + s.y1) / 2 - o.y0) * ny;
return { a: Math.min(a, b), b: Math.max(a, b), off, depth: s.depthPx }; }).sort((p, q) => p.a - q.a);
// union of intervals, broken where the gap exceeds 4 px (about 3 m)
let cur = null; const nx = Math.cos(phi), ny = Math.sin(phi);
const emit = () => { if (!cur || cur.b - cur.a < 8) return; const off = cur.os / cur.w, dep = cur.ds / cur.w;
rows.push({ phi, depthPx: dep, pts: [[o.x0 + ux * cur.a + nx * off, o.y0 + uy * cur.a + ny * off], [o.x0 + ux * cur.b + nx * off, o.y0 + uy * cur.b + ny * off]] }); };
for (const v of iv) {
const w = v.b - v.a + 1;
if (cur && v.a <= cur.b + 4) { cur.b = Math.max(cur.b, v.b); cur.os += v.off * w; cur.ds += v.depth * w; cur.w += w; }
else { emit(); cur = { a: v.a, b: v.b, os: v.off * w, ds: v.depth * w, w }; }
}
emit();
}
return rows;
};
// Family #148844 · element #148844 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/substations.js#L65-L72
export const f148844_frameOf = function frameOf(ring) { // centroid and the principal (longest-edge) axis
var cx = 0, cy = 0, n = ring.length - 1; for (var i = 0; i < n; i++) { cx += ring[i][0]; cy += ring[i][1]; } cx /= n; cy /= n;
var best = 0, ux = 1, uy = 0;
for (i = 0; i < n; i++) { var dx = ring[i + 1][0] - ring[i][0], dy = ring[i + 1][1] - ring[i][1], l = Math.hypot(dx, dy); if (l > best) { best = l; ux = dx / l; uy = dy / l; } }
var w = 0, d = 0; for (i = 0; i < n; i++) { var x = ring[i][0] - cx, y = ring[i][1] - cy; w = Math.max(w, Math.abs(x * ux + y * uy)); d = Math.max(d, Math.abs(-x * uy + y * ux)); }
var area = 0; for (i = 0; i < n; i++) area += ring[i][0] * ring[i + 1][1] - ring[i + 1][0] * ring[i][1];
return { cx: cx, cy: cy, ux: ux, uy: uy, hw: w, hd: d, area: Math.abs(area) / 2 };
};
// Family #148858 · element #148858 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/walk-fps.js#L35-L37
export const f148858_segDist = (px, py, l) => { const dx = l[3] - l[0], dy = l[4] - l[1], q = dx * dx + dy * dy;
const t = q ? Math.max(0, Math.min(1, ((px - l[0]) * dx + (py - l[1]) * dy) / q)) : 0;
return Math.hypot(px - l[0] - t * dx, py - l[1] - t * dy); };
// Family #149157 · element #149157 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/repd-grammar.mjs#L68-L72
export const f149157_filterText = function filterText({ tech, cls, minMw }) {
const t = tech === 'bess' ? 'battery (BESS)' : tech === 'roof' ? 'rooftop solar' : 'solar';
return [t, cls ? (cls === 'planned' ? 'planned (in planning or consented)' : cls === 'current' ? 'current (operational or being built)' : cls) : 'any status',
minMw ? `at least ${minMw} MW` : ''].filter(Boolean).join(', ');
};
// Family #149253 · element #149253 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/plant.js#L50-L73
export const f149253_plantLines = function plantLines(r) {
const F = r.frame, T = r.table, P = r.params, out = [];
const at = (u, v, z) => { const [e, n] = F.en(u, v); return [e, n, z]; };
const seg = (a, b) => out.push([...a, ...b]);
const path = (pts, z) => { for (let i = 1; i < pts.length; i++) seg(at(...pts[i - 1], z), at(...pts[i], z)); };
for (const f of r.fields || [r.boundary]) path([...f, f[0]], 1.5); // fence
const lo = P.lowEdgeM, hi = lo + T.rise, t = r.tables;
for (let q = 0; q < t.length; q += 6) { // tables (flat ground)
const ua = t[q], va = t[q + 1], ub = ua + (r.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth;
if (T.south) { const A = at(ua, va, lo), B = at(ub, va, lo), C = at(ub, vb, hi), D = at(ua, vb, hi); seg(A, B); seg(B, C); seg(C, D); seg(D, A); }
else if (T.tracker) { const z = 1.5, vm = (va + vb) / 2; seg(at(ua, va, z), at(ub, va, z)); seg(at(ub, va, z), at(ub, vb, z)); seg(at(ub, vb, z), at(ua, vb, z)); seg(at(ua, vb, z), at(ua, va, z)); seg(at(ua, vm, z), at(ub, vm, z)); }
else { const vm = (va + vb) / 2, A = at(ua, va, lo), B = at(ub, va, lo), C = at(ub, vb, lo), D = at(ua, vb, lo), M = at(ua, vm, hi), N = at(ub, vm, hi);
seg(A, B); seg(D, C); seg(M, N); seg(A, M); seg(M, D); seg(B, N); seg(N, C); }
}
const sp = r.spine; // roads
for (const d of [-P.spineWidthM / 2, P.spineWidthM / 2]) path([[sp.u + d, sp.v0], [sp.u + d, sp.v1]], 0.05);
for (const tr of r.trackRoads) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path([[tr.u0, tr.v + d], [tr.u1, tr.v + d]], 0.05);
if (r.access) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path([[r.access.u0, r.access.v + d], [r.access.u1, r.access.v + d]], 0.05);
const cube = (u, v, w, dp, h) => { const c = [[u - w / 2, v - dp / 2], [u + w / 2, v - dp / 2], [u + w / 2, v + dp / 2], [u - w / 2, v + dp / 2]];
for (let i = 0; i < 4; i++) { const a = c[i], b = c[(i + 1) % 4]; seg(at(...a, 0), at(...b, 0)); seg(at(...a, h), at(...b, h)); seg(at(...a, 0), at(...a, h)); } };
for (const s of r.stations) cube(s.u, s.v, 12, 3, 3); // stations (skid boxes)
const cm = r.compound; cube(cm.u, cm.v, cm.w, cm.d, 2.4); // compound fence
return out;
};
// Family #149254 · element #149254 · 13 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/plant.js#L74-L79
export const f149254_groupLines = function groupLines(groups) { // buildBlock groups: base + relative xyz pairs
const out = [];
for (const G of Object.values(groups)) { const b = G.base, v = G.v;
for (let i = 0; i + 5 < v.length; i += 6) out.push([b[0] + v[i], b[1] + v[i + 1], b[2] + v[i + 2], b[0] + v[i + 3], b[1] + v[i + 4], b[2] + v[i + 5]]); }
return out;
};
// Family #149391 · element #149391 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/scanner-rows.js#L20-L24
export const f149391_bbox = function bbox(rows) {
let w = Infinity, s = Infinity, e = -Infinity, n = -Infinity;
for (const seg of rows) for (const [lo, la] of seg) { if (lo < w) w = lo; if (lo > e) e = lo; if (la < s) s = la; if (la > n) n = la; }
return { w, s, e, n };
};
// Family #150682 · element #150682 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/addresses.js#L89-L94
export const f150682_marker = function marker(lon, lat) {
const L = [], ring = (r, n) => { for (let i = 0; i < n; i++) { const a = 2 * Math.PI * i / n, b = 2 * Math.PI * (i + 1) / n;
L.push([r * Math.cos(a), r * Math.sin(a), 0.5, r * Math.cos(b), r * Math.sin(b), 0.5]); } };
L.push([0, 0, 0, 0, 0, 40], [-8, 0, 0.5, 8, 0, 0.5], [0, -8, 0.5, 0, 8, 0.5]); ring(6, 24); ring(30, 48);
return { lon, lat, lines: L, find: true, address: true };
};
// Family #150688 · element #150688 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/farm-assess.js#L68-L81
export const f150688_clipRing = function clipRing(ring, b) {
var out = ring.slice(); if (out.length > 1 && out[0][0] === out[out.length - 1][0] && out[0][1] === out[out.length - 1][1]) out.pop();
var edges = [[0, b.e0, 1], [0, b.e1, -1], [1, b.n0, 1], [1, b.n1, -1]];
for (var k = 0; k < 4 && out.length; k++) {
var ax = edges[k][0], v = edges[k][1], s = edges[k][2], inp = out; out = [];
var inside = function (p) { return s * (p[ax] - v) >= 0; };
for (var i = 0; i < inp.length; i++) {
var P = inp[i], Q = inp[(i + 1) % inp.length], pi = inside(P), qi = inside(Q);
if (pi) out.push(P);
if (pi !== qi) { var t = (v - P[ax]) / (Q[ax] - P[ax]); out.push([P[0] + t * (Q[0] - P[0]), P[1] + t * (Q[1] - P[1])]); }
}
}
return out;
};
// Family #150691 · element #150691 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/farm-assess.js#L98-L100
export const f150691_centroid = function centroid(r) { var a = 0, x = 0, y = 0; // area centroid (vertex averages drift toward shared boundaries)
for (var i = 0; i < r.length; i++) { var p = r[i], q = r[(i + 1) % r.length], k = p[0] * q[1] - q[0] * p[1]; a += k; x += (p[0] + q[0]) * k; y += (p[1] + q[1]) * k; }
return a ? [x / (3 * a), y / (3 * a)] : r[0]; };
// Family #150695 · element #150695 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/farm-assess.js#L120-L125
export const f150695_grade3Text = function grade3Text(res, phone) {
var p = (100 * res.grade3Share).toFixed(1) + '%';
if (!(res.grade3Share > 0)) return phone ? ' Grade 3: 0%.' : ' Grades 1+2 (best and most versatile): ' + (100 * res.bmv12Share).toFixed(1) + '%. Grade 3: 0%.';
return phone ? ' Grade 3 not split 3a/3b; may include BMV 3a; field survey needed.'
: ' Grades 1+2 (best and most versatile): ' + (100 * res.bmv12Share).toFixed(1) + '%. Grade 3 not split into 3a/3b here: ' + p + ' may include BMV 3a. Field survey needed.';
};
// Family #150699 · element #150699 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/farm-assess.js#L136-L143
export const f150699_parseFlood = function parseFlood(j) {
if (!j || j.error || !Array.isArray(j.layers)) throw new Error((j && j.error && j.error.message) || 'no layers in answer');
var out = { fz3: [], fz2: [], exceeded: false };
j.layers.forEach(function (l) { var k = l.id === 1 ? 'fz3' : l.id === 2 ? 'fz2' : null; if (!k) return;
if (l.exceededTransferLimit) out.exceeded = true;
(l.features || []).forEach(function (f) { if (f.geometry && f.geometry.rings) out[k].push(f.geometry.rings); }); });
return out;
};
// Family #150706 · element #150706 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/farm-assess.js#L185-L193
export const f150706_gridRef = function gridRef(e, n, digits) {
var d = digits === undefined ? 8 : digits; if (d % 2 || d < 2 || d > 10) return null;
if (typeof e !== 'number' || typeof n !== 'number' || !isFinite(e) || !isFinite(n) || e < 0 || n < 0 || e >= 700000 || n >= 1300000) return null;
var e1 = Math.floor(e / 100000), n1 = Math.floor(n / 100000);
var l1 = (19 - n1) - (19 - n1) % 5 + Math.floor((e1 + 10) / 5), l2 = (19 - n1) * 5 % 25 + e1 % 5;
if (l1 > 7) l1++; if (l2 > 7) l2++;
var h = d / 2, f = function (v) { return String(Math.floor((v % 100000) / Math.pow(10, 5 - h)) + Math.pow(10, h)).slice(1); };
return String.fromCharCode(65 + l1, 65 + l2) + ' ' + f(e) + ' ' + f(n);
};
// Family #150731 · element #150731 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/pylons-real.js#L43-L45
export const f150731__anonymous_ = r => { const ring = r[2]; let w = 180, s = 90, e = -180, n = -90;
for (const [x, y] of ring) { if (x < w) w = x; if (x > e) e = x; if (y < s) s = y; if (y > n) n = y; }
return { bbox: [w, s, e, n], ring }; };
// Family #150736 · element #150736 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/pylons-real.js#L62-L64
export const f150736_inRing = function inRing(x, y, R) { // even-odd point in polygon, [lon, lat]
let c = false; for (let i = 0, j = R.length - 1; i < R.length; j = i++) { const [xi, yi] = R[i], [xj, yj] = R[j];
if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c; } return c; };
// Family #150752 · element #150752 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/scanner-rows.js#L65-L74
export const f150752_surveyGate = function surveyGate(buildYear, dsmYears, dtmYears) {
const yrs = [...(dsmYears || []), ...(dtmYears || [])], ok = y => Number.isInteger(y) && y > 1900;
if (!ok(buildYear)) return { lidarRows: false, ground: 'pre-construction', reason: 'build year unknown' };
if (!(dsmYears || []).length || !(dtmYears || []).length || !yrs.every(ok))
return { lidarRows: false, ground: 'pre-construction', reason: 'a DSM or DTM survey year is unknown' };
const early = yrs.filter(y => y <= buildYear);
if (early.length) return { lidarRows: false, ground: 'pre-construction',
reason: `LiDAR survey ${Math.min(...early)} is not later than the build year ${buildYear}` };
return { lidarRows: true, ground: 'post-construction', reason: `every LiDAR survey (${yrs.join(', ')}) is later than the build year ${buildYear}` };
};
// Family #150762 · element #150762 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/trench-measure.js#L77-L81
export const f150762_validate = function validate(s) { // the section must fit: cables below cover and above the trench floor, circuits inside the walls
const h = s.od + s.od * Math.sqrt(3) / 2, half = (s.circuits - 1) * s.cs / 2 + s.od;
if (s.cover + h > s.d + 1e-9) throw Error(`section ${s.id}: cover ${s.cover} m + trefoil ${h.toFixed(3)} m is deeper than the trench ${s.d} m`);
if (half > s.w / 2 + 1e-9) throw Error(`section ${s.id}: the cables (half width ${half.toFixed(3)} m) do not fit a ${s.w} m trench`);
};
// Family #150763 · element #150763 · 12 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/trench-measure.js#L83-L90
export const f150763_formation = function formation(s) {
const r = s.od / 2, top = -s.cover - r, low = top - s.od * Math.sqrt(3) / 2, out = [];
for (let c = 0; c < s.circuits; c++) {
const oc = (c - (s.circuits - 1) / 2) * s.cs;
out.push({ c, p: 'top', o: oc, z: top }, { c, p: 'left', o: oc + r, z: low }, { c, p: 'right', o: oc - r, z: low });
}
return out;
};
// Family #150782 · element #150782 · 11 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/lidar-stream.js#L72-L77
export const f150782_hAt = function hAt(r, i, j) {
if (!r || r.none || r.pending) return NaN;
const c = r.tile.e0 + i - r.geo.west, rr = r.geo.north - (r.tile.n0 + j) - 1;
if (c < 0 || rr < 0 || c >= r.geo.width || rr >= r.geo.height) return NaN;
const k = rr * r.geo.width + c; return r.mask[k] ? r.geo.data[k] : NaN;
};