In this section
- Procedural render · energy-transition-simulator / prototype/mod/procedural.js lines 1–265
- Pylons Real render · energy-transition-simulator / prototype/mod/pylons-real.js lines 1–185
- Rows Geometry geodesy · energy-transition-simulator / prototype/mod/rows-geometry.js lines 1–222
Procedural
A JavaScript file in the prototype folder of Energy Transition Simulator that maps cables, find go, battery storage (BESS) and overhead lines (OHL).
renderenergy-transition-simulator / prototype/mod/procedural.js · lines 1–265 of 265 · Not reached from any entry point (candidate for review) · pattern halfSide (shared by 2 files)
- What it does
- It maps cables, find go, battery storage (BESS) and overhead lines (OHL). Defines 29 functions or classes, including keptSay, E, start, mount, addLayer. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, battery storage (BESS), overhead lines (OHL).
- Inputs & outputs
- In: JSON file cables.json; JSON file find-go.data.json.
- What it achieves
- It adds layer (`addLayer`), loads rows (`loadRows`) and fits rows (`fitRows`). Procedural fill ANYWHERE. Each public register asset (Renewable Energy Planning Database (REPD): ground solar and battery storage) in view gets a wireframe anchored at its published register point and sized from its published capacity. Its code works with 3.7 MWh.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- keptSay, E, start, mount, addLayer, drop, say, place, box, segD, ohlNear, bad
- Defines here
- keptSay, E, start, mount, addLayer, drop, say, place, box, segD, ohlNear, bad, kvList, ohlOk, ohlSay, crosses, rowDocs, loadRows, sig, wrap90, halfSide, fitRows, solar, turn, lay, bess, near, refresh, inView
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/procedural.js:1-265 · blob 255646ec4cd8da7ff71d1eec362563e6b28db140 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// procedural.js: procedural fill ANYWHERE. Each public register asset (REPD: ground solar and battery storage) in view
// gets a wireframe anchored at its published register point and sized from its published capacity.
// Solar: the morning engine's own generator, the same one plant.js runs (engine/cmd-model.mjs derive + layoutInput,
// engine/plant-layout.mjs layoutPlantAsync), on a square of open land sized by plant.js's open-land rule. No new generator.
// Battery storage: a container yard sized by a stated, ASSUMED rule (below), since the engine has no battery generator.
// EV forecourts: not drawn, because no public register of forecourts with capacity is loaded here (said on screen).
// Calibration, said as it is: see CALIB below. No layout dimension is calibrated on a measured sample yet (N = 0).
// Every dimension is an engine default or an assumption, and says so.
// Arrival and view only: the register index is the overlay's own local file; nothing is fetched on movement.
(function () {
'use strict';
// keptSay:begin (pure; tests/procedural.cjs lifts this block out and runs it in Node)
// kept = tables drawn without the line minus tables drawn with it. It can be 0 or negative when the positions
// inside the line zones were made up from free ground in the box; the caption then never shows a minus or 'fewer'.
function keptSay(kept, inZones) {
const z = Number(inZones || 0).toLocaleString('en-GB');
if (!(kept > 0)) return `no tables lost to the line (the ${z} positions inside the line zones were placed on free ground in the box; illustrative)`;
return `${kept.toLocaleString('en-GB')} fewer tables drawn than without the line (${z} positions inside the line zones left empty, the rest placed on free ground in the box; illustrative)`;
}
// keptSay:end
// kV line file status (round r5), recorded HERE without touching pylons-real: its catch leaves lines[kv] = [] when a
// fetch fails, which looks like a loaded empty file. So procedural watches the page's own resource timings for the
// grid_<kv>kv.geojson requests (nothing fetched here) and treats a kV as UNKNOWN when its file produced no lines at all.
// That empty-list rule does the work: pylons-real's catch leaves [] for any failed fetch, so every failure lands there.
// The HTTP status below is only a second witness for the readout; status 0 (cross-origin, network) or a full timing
// buffer tells us nothing: it is ignored, and the empty-list rule alone decides.
const kvHttp = {}; // kv -> HTTP status of its line file (0 = unknown)
try { new PerformanceObserver(l => { for (const e of l.getEntries()) { const m = /grid_(\d+)kv\.geojson/.exec(e.name); if (m) kvHttp[m[1]] = e.responseStatus || 0; } })
.observe({ type: 'resource', buffered: true }); } catch (e) { /* no observer: fall back on the empty-file rule alone */ }
const here = document.currentScript && document.currentScript.src ? document.currentScript.src : location.href;
const E = n => new URL('engine/' + n, here).href;
// Calibration state, said as it is: the six measured samples hold ground heights only (no row pitch, no fenced area), so
// N = 0 measured samples calibrate the south formula. Where the page has loaded imagery row runs (Scanner rows, derived
// from imagery, estimated) INSIDE a site's own box, the rows are fitted to them (azimuth, and pitch when the engine rule
// accepts it); a site with none inside its box keeps the south formula, tagged not calibrated. MW per hectare stays engine-derived.
const CALIB = { N: 0, pitchTag: 'engine default (gcr formula), not calibrated', mwPerHaTag: 'derived from the engine site box, not calibrated' };
const LABEL = `procedural estimate (formula calibrated on ${CALIB.N} measured samples: the 6 samples hold ground only; imagery row runs, estimated, set row azimuth and pitch only for a site with runs inside its own box)`;
const MAX_ASSETS = 4, MIN_ZOOM = 12, REACH_DEG = 0.015; // a site whose register point is within ~1.5 km of the view counts
// GHOST style (the night's line-style rule: solid = measured, dashed = documented, ghost = estimated). Procedural wire is
// estimated, so it is drawn by this module's OWN layer, faint and see-through, never in the solid cyan of measured wire,
// and the satellite stays visible under it.
const GHOST_RGBA = [0.82, 0.95, 1.0, 0.32];
// Battery yard, ASSUMED (not measured, not cited): 2 h duration, 3.7 MWh per 20 ft container (6.06 x 2.44 x 2.9 m),
// containers in rows of 10 at 3 m gaps, rows 6 m apart, fence 10 m outside.
const BESS = { hours: 2, mwhPerUnit: 3.7, w: 6.06, d: 2.44, h: 2.9, perRow: 10, gap: 3, aisle: 6, fence: 10 };
// Overhead line zones. Line geometry: READ from what pylons-real already loaded (its towersOf runs along the GridAtlas
// lines), never copied or fetched here. reachM, ASSUMED: the conductor outreach pylons-real estimates for the voltage
// (its largest arm half-length) plus 6 m horizontal, the barrier distance of HSE GS6, which the engine's plant-layout
// cites for its overhead line zone ("GS6 planning zone, illustrative"). The engine adds its own ohlMarginM on top.
const GS6_M = 6, SQUARE = 'square site box at register point, not the real field';
function start(SIM, PF) {
Promise.all([import(E('cmd-model.mjs')), import(E('plant-layout.mjs')), fetch(E('data/cables.json')).then(r => r.json()),
fetch(new URL('find-go.data.json', here).href).then(r => r.json())])
.then(([CM, PL, catalogue, reg]) => mount(SIM, PF, CM, PL, catalogue, reg))
.catch(e => SIM.info('Procedural: did not load (' + e.message + ')'));
}
function mount(SIM, PF, CM, PL, catalogue, reg) {
const f = reg.fields, ix = k => f.indexOf(k);
const rows = reg.records.map(x => ({ ref: x[ix('ref')], tech: reg.tech[x[ix('tech')]], mw: x[ix('mw10')] / 10,
lat: x[ix('lat5')] / 1e5, lon: x[ix('lon5')] / 1e5 })).filter(r => (r.tech === 'solar' || r.tech === 'bess') && r.mw > 0);
const map = SIM.map, cache = new Map(), ghost = [];
let on = false, busy = false, pending = false, shown = [];
const layer = { id: 'procedural-ghost', type: 'custom', renderingMode: '3d',
onAdd(m, gl) { const sh = (t, s) => { const o = gl.createShader(t); gl.shaderSource(o, s); gl.compileShader(o); return o; };
this.pr = gl.createProgram();
gl.attachShader(this.pr, sh(gl.VERTEX_SHADER, 'uniform mat4 u; attribute vec3 p; void main(){ gl_Position = u * vec4(p, 1.0); }'));
gl.attachShader(this.pr, sh(gl.FRAGMENT_SHADER, 'precision mediump float; uniform vec4 c; void main(){ gl_FragColor = c; }'));
gl.linkProgram(this.pr); this.gl = gl; },
render(gl, args) {
if (!ghost.length) return;
const m = args.defaultProjectionData?.mainMatrix || args, loc = gl.getAttribLocation(this.pr, 'p');
gl.useProgram(this.pr); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
gl.uniform4fv(gl.getUniformLocation(this.pr, 'c'), GHOST_RGBA);
for (const b of ghost) {
if (!b.vbo) { b.vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b.vbo); gl.bufferData(gl.ARRAY_BUFFER, b.buf, gl.STATIC_DRAW); }
const a = b.anchor, gz = (map.queryTerrainElevation && map.queryTerrainElevation([a.lon, a.lat])) || 0, o = PF.toMercator(a.lat, a.lon, gz), 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];
gl.bindBuffer(gl.ARRAY_BUFFER, b.vbo); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
gl.uniformMatrix4fv(gl.getUniformLocation(this.pr, 'u'), false, new Float32Array(r)); gl.drawArrays(gl.LINES, 0, b.buf.length / 3);
}
gl.depthMask(true);
} };
const addLayer = () => { try { if (!map.getLayer(layer.id)) map.addLayer(layer); } catch (e) { map.once('idle', addLayer); } };
addLayer(); map.on('style.load', addLayer); // the Satellite / Dark / Wire buttons replace the style
const drop = fn => { for (let i = ghost.length - 1; i >= 0; i--) if (fn(ghost[i])) { const b = ghost.splice(i, 1)[0];
if (b.vbo && layer.gl) layer.gl.deleteBuffer(b.vbo); } map.triggerRepaint(); };
const cap = document.createElement('div'); cap.id = 'procedural-caption'; // its own caption, never #info
cap.style.cssText = 'position:absolute;right:8px;top:150px;z-index:2;max-width:440px;font:12px sans-serif;color:rgba(225,245,255,.9);'
+ 'background:rgba(0,0,0,.55);padding:6px 8px;border-radius:6px;border:1px dashed rgba(210,242,255,.45);display:none';
document.body.appendChild(cap);
const say = t => { cap.textContent = t; cap.style.display = t ? 'block' : 'none'; };
function place(r, lines) { // local metres at the register point -> anchored block
const a = PF.placeKey(r.lat, r.lon), off = PF.toLocal(a, r.lat, r.lon, 0), out = [];
for (let i = 0; i < lines.length; i += 20000) {
const L = lines.slice(i, i + 20000).map(([x0, y0, z0, x1, y1, z1]) => [x0 + off.x, y0 + off.y, z0, x1 + off.x, y1 + off.y, z1]);
out.push({ lon: r.lon, lat: r.lat, anchor: a, lines: L, buf: PF.wireBuffer(a, L), procedural: r.ref });
}
return out;
}
const box = (out, x, y, w, d, z0, h) => { const c = [[x, y], [x + w, y], [x + w, y + d], [x, y + d]];
for (let i = 0; i < 4; i++) { const p = c[i], q = c[(i + 1) % 4]; out.push([p[0], p[1], z0, q[0], q[1], z0], [p[0], p[1], z0 + h, q[0], q[1], z0 + h], [p[0], p[1], z0, p[0], p[1], z0 + h]); } };
const segD = (px, py, ax, ay, bx, by) => { const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy,
t = L ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / L)) : 0; return Math.hypot(px - ax - t * dx, py - ay - t * dy); };
// Overhead lines (round r4): every GridAtlas line the page has ALREADY loaded (pylons-real holds the whole national files),
// never only the tiles in view, so a site's clearance does not change with pan or zoom. Only spans within the site's own
// reach (sqrt2*h + reachM + 50 m of the register point) count. Nothing fetched here. null = no line data loaded yet.
function ohlNear(r, R) { // real line spans within reach of the site box, in its local metres
const P = window.__pylonsReal; if (!P || !P.lines || !P.towersOf || !P.KV) return null;
const kvs = Object.keys(P.KV); if (!kvs.every(kv => Array.isArray(P.lines[kv]))) return null; // still loading
const bad = kv => !P.lines[kv].length || (kv in kvHttp && kvHttp[kv] !== 0 && (kvHttp[kv] < 200 || kvHttp[kv] > 299));
const missing = kvs.filter(bad); // failed or missing kV files: unknown, never "no line
const a = PF.placeKey(r.lat, r.lon), off = PF.toLocal(a, r.lat, r.lon, 0), out = [], k = Math.cos(r.lat * Math.PI / 180);
for (const kv of kvs) { if (missing.includes(kv)) continue; const reachM = Math.max(...P.KV[kv].arm) + GS6_M, lim = Math.SQRT2 * R + reachM + 50, dLa = (lim + 200) / 111320, dLo = dLa / k;
P.lines[kv].forEach((ln, li) => { const [w, s, e, n] = ln.bbox;
if (e < r.lon - dLo || w > r.lon + dLo || n < r.lat - dLa || s > r.lat + dLa) return; // bbox far from the site: skip
const pts = P.towersOf(kv, li).map(t => { const q = PF.toLocal(a, t.lat, t.lon, 0); return [q.x - off.x, q.y - off.y]; });
for (let i = 1; i < pts.length; i++) if (segD(0, 0, ...pts[i - 1], ...pts[i]) < lim) out.push({ pts: [pts[i - 1], pts[i]], closed: false, reachM, kv }); }); }
out.missing = missing; out.kvs = kvs; // one zone per span near the site, so far-away spans cost nothing
return out;
}
const kvList = a => a.length < 2 ? a.join('') : a.slice(0, -1).join(', ') + ' and ' + a[a.length - 1];
const ohlOk = o => o !== null && !o.missing.length; // every kV line file loaded: the only case a "no line" is a negative
const ohlSay = (ohl, what) => ohl === null ? 'no overhead line data loaded for this site box: clearance not applied'
: ohl.missing.length === ohl.kvs.length ? `overhead line data for ${kvList(ohl.missing)} kV not loaded: clearance not applied`
: ohl.missing.length ? `overhead line data for ${kvList(ohl.missing)} kV not loaded: clearance partial (`
+ (ohl.length ? what : `no mapped ${kvList(ohl.kvs.filter(k => !ohl.missing.includes(k)))} kV line within reach`) + ')'
: ohl.length ? what : 'no mapped overhead line within reach of this site box: nothing kept out';
const crosses = (c, a, b) => { const ccw = (p, q, r) => (r[1] - p[1]) * (q[0] - p[0]) > (q[1] - p[1]) * (r[0] - p[0]);
return c.some((p, i) => { const q = c[(i + 1) % 4]; return ccw(p, a, b) !== ccw(q, a, b) && ccw(p, q, a) !== ccw(p, q, b); }); };
const rowDocs = () => { const R = window.SIM && window.SIM.scannerRows; return R && R.state && R.state.docs ? Object.values(R.state.docs) : []; };
// Round r6: the row files are loaded HERE on arrival, through Scanner rows' own loader (check(): reads the farm list and
// its row files into the same cache, draws nothing), so the fit depends only on the site and the row file, never on
// whether someone pressed Scanner rows first, nor on the kV line files or the order of tests. A failed load is said.
let rowsAsked = false, rowsErr = null;
const loadRows = () => { const R = window.SIM && window.SIM.scannerRows; if (rowsAsked || !R || typeof R.check !== 'function') return; rowsAsked = true;
R.check().then(() => { rowsErr = null; refresh(); }, e => { rowsErr = String(e && e.message || e); refresh(); }); };
const sig = () => { const P = window.__pylonsReal; // redo when the national line files or row files arrive, never on camera moves
return 'lines' + (P && P.lines ? Object.keys(P.lines).filter(kv => Array.isArray(P.lines[kv])).sort().join(',') : '') + '|rows' + rowDocs().length; };
// Row fit (round r3): the measured rows in Scanner rows' cache (the lab's row files, lon/lat runs from imagery), loaded
// by its own loader on arrival (loadRows, r6). Only runs whose midpoint lies inside THIS site's own square box (within h of the register
// point, in PF.toLocal metres) count, so a site is never credited with a neighbour's rows and the fit does not depend on
// the camera. The box used for the test is the south default box (the engine's layout before any fit), so it does not
// depend on the fit it feeds. Azimuth: axial median, compass degrees 0-180; pitch: the row file's own reading.
// No runs inside the box: null, and the south formula stays, tagged not calibrated.
const wrap90 = d => ((d % 180) + 270) % 180 - 90; // to (-90, 90]
function halfSide(st, latDeg) { // plant.js's open-land rule: half the square site box side, metres
const tpl = CM.derive(st, { catalogue }).tpl, ld = { ...PL.LAYOUT_DEFAULTS, ...(CM.layoutInput(st, { latDeg, catalogue }).options || {}) }, T0 = PL.tableGeometry(st.layout, ld, tpl);
return (Math.sqrt(Math.ceil(tpl.counts.strings / 2) * T0.pitch * (T0.lenU + PL.LAYOUT_DEFAULTS.tableGapM) * 1.5) + 2 * st.fence) / 2;
}
function fitRows(r) {
const a = PF.placeKey(r.lat, r.lon), off = PF.toLocal(a, r.lat, r.lon, 0), hBox = halfSide({ ...CM.DEFAULTS, mw: r.mw }, r.lat), az = [], pitches = [];
for (const doc of rowDocs()) { let n0 = 0;
for (const [[lo0, la0], [lo1, la1]] of doc.rows || []) {
const M = PF.toLocal(a, (la0 + la1) / 2, (lo0 + lo1) / 2, 0);
if (Math.abs(M.x - off.x) > hBox || Math.abs(M.y - off.y) > hBox) continue;
const A = PF.toLocal(a, la0, lo0, 0), B = PF.toLocal(a, la1, lo1, 0); az.push(Math.atan2(B.x - A.x, B.y - A.y) * 180 / Math.PI); n0++; }
if (n0 && doc.row_pitch_m > 0) pitches.push(doc.row_pitch_m); }
if (!az.length) return { n: 0, boxHalfM: hBox };
let sx = 0, sy = 0; for (const d of az) { sx += Math.cos(d * Math.PI / 90); sy += Math.sin(d * Math.PI / 90); }
const c = Math.atan2(sy, sx) * 90 / Math.PI, dev = az.map(d => wrap90(d - c)).sort((p, q) => p - q);
pitches.sort((p, q) => p - q);
return { azDeg: ((c + dev[dev.length >> 1]) % 180 + 180) % 180, pitchM: pitches.length ? pitches[pitches.length >> 1] : null, n: az.length, boxHalfM: hBox };
}
async function solar(r) { // the engine's generator, as plant.js runs it
// Rows fitted to the measured rows inside the site's own box when there are any: rows within 45 deg of north-south use the engine's
// east-west (tent) layout, others its south layout; the residual angle turns the whole layout about the register point.
const fr = fitRows(r), fit = fr.n ? fr : null, st = { ...CM.DEFAULTS, mw: r.mw };
let rot = 0, pitchUsed = false;
if (fit) { st.layout = Math.abs(wrap90(fit.azDeg)) <= 45 ? 'east-west' : 'south'; rot = wrap90(fit.azDeg - (st.layout === 'south' ? 90 : 0));
if (fit.pitchM) { const d = CM.derive({ ...st, pitch: fit.pitchM }, { catalogue }); // the engine's own pitch rule, kept only if it fits
pitchUsed = st.layout === 'south' ? d.gcr > 0 && d.gcr <= 0.9 : d.ewGapM >= 0.5; if (pitchUsed) st.pitch = fit.pitchM; } }
const env = { latDeg: r.lat, catalogue }, inp = CM.layoutInput(st, env);
const h = halfSide(st, r.lat), side = 2 * h;
const ohlR = ohlNear(r, h), ohl = ohlR || [], th = rot * Math.PI / 180, cs = Math.cos(th), sn = Math.sin(th);
const turn = ([e, n], s = 1) => [e * cs + s * n * sn, -s * e * sn + n * cs]; // clockwise by rot (s = -1: back)
const ohlL = ohl.map(z => ({ ...z, pts: z.pts.map(q => turn(q, -1)) })); // the real spans, in the layout's own frame
const lay = z => PL.layoutPlantAsync({ boundary: [[-h, -h], [h, -h], [h, h], [-h, h]], targetMW: r.mw, layout: st.layout, template: inp.template,
piles: false, groundAt: () => 0, grid: null, water: [], ohl: z, options: { ...inp.options, slopeLimitPct: st.slope, fenceSetbackM: st.fence } });
const res = await lay(ohlL.length ? ohlL : null);
// The engine's skipped.ohl counts CANDIDATE positions inside the zones over the whole box; the plant then takes only the
// tables its MW needs from the free ones, so most of those positions are simply replaced elsewhere in the box. The readout
// is therefore the drawn difference: the same layout without the lines, minus the tables drawn with them.
const free = ohlL.length ? await lay(null) : res, lessT = free.tables.length / 6 - res.tables.length / 6;
const Fr0 = res.frame, Fr = { en: (u, v) => turn(Fr0.en(u, v)) }, T = res.table, P = res.params, out = [], at = (u, v, z) => [...Fr.en(u, v), z], seg = (a, b) => out.push([...a, ...b]);
const rowAz = ((st.layout === 'south' ? 90 : 0) + rot + 180) % 180;
const rowTag = fit ? `row azimuth ${rowAz.toFixed(1)} deg, pitch ${T.pitch.toFixed(2)} m, fitted to ${fit.n.toLocaleString('en-GB')} measured rows inside a ${Math.round(2 * fit.boxHalfM).toLocaleString('en-GB')} m square around the register point`
+ (pitchUsed ? ' (pitch: the row file reading, estimated from imagery)' : ` (pitch: engine default, the row file's ${fit.pitchM ? fit.pitchM + ' m' : 'none'} did not fit the engine rule)`)
: `south formula, not calibrated: row azimuth 90 deg, pitch ${T.pitch.toFixed(2)} m` + (rowsErr ? ` (row file not loaded: ${rowsErr})` : '');
for (const fl of res.fields || [res.boundary]) for (let i = 0; i < fl.length; i++) seg(at(...fl[i], 1.5), at(...fl[(i + 1) % fl.length], 1.5));
const lo = P.lowEdgeM, hi = lo + T.rise, t = res.tables;
for (let q = 0; q < t.length; q += 6) { const ua = t[q], va = t[q + 1], ub = ua + (res.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth;
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); }
const tb = [];
for (let q = 0; q < t.length; q += 6) { const ua = t[q], va = t[q + 1], ub = ua + (res.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth;
tb.push([Fr.en(ua, va), Fr.en(ub, va), Fr.en(ub, vb), Fr.en(ua, vb)]); }
for (const s of res.stations) { const [e, n] = Fr.en(s.u, s.v); box(out, e - 6, n - 1.5, 12, 3, 0, 3); }
const kept = lessT, inZones = (res.skipped && res.skipped.ohl) || 0, areaHa = side * side / 1e4, mwPerHa = r.mw / areaHa;
const rowsV = [...new Set(Array.from({ length: t.length / 6 }, (_, i) => Math.round(t[6 * i + 1] * 1000) / 1000))].sort((a, b) => a - b);
return { lines: out, geom: { ohl, ohlLoaded: ohlOk(ohlR), ohlMissing: ohlR ? ohlR.missing : null, ohlRadiusM: h, marginM: P.ohlMarginM, tables: tb, containers: [], skipped: kept, positionsInZones: inZones, tablesWithoutLine: free.tables.length / 6,
formula: { pitchM: T.pitch, pitchTag: fit && pitchUsed ? 'row file reading, estimated from imagery' : CALIB.pitchTag, rowAzDeg: rowAz, layout: st.layout, fitN: fit ? fit.n : 0, fitBoxHalfM: fr.boxHalfM, fitAzDeg: fit ? fit.azDeg : null, rowTag, areaHa, mwPerHa, mwPerHaTag: CALIB.mwPerHaTag, N: CALIB.N,
boundary: [[-h, -h], [h, -h], [h, h], [-h, h]], rowsV } },
text: `${r.mw} MW solar: ${res.built.tables.toLocaleString('en-GB')} tables, ${rowTag}, `
+ `site box ${areaHa.toFixed(1)} ha = ${mwPerHa.toFixed(2)} MW/ha (${CALIB.mwPerHaTag}), ${res.built.stations} stations; `
+ ohlSay(ohlR, keptSay(kept, inZones))
+ `; ${SQUARE}` };
}
function bess(r) { // ASSUMED yard rule (see BESS above)
const n = Math.max(1, Math.ceil(r.mw * BESS.hours / BESS.mwhPerUnit)), cols = Math.min(n, BESS.perRow), nr = Math.ceil(n / BESS.perRow);
const W = cols * BESS.w + (cols - 1) * BESS.gap, D = nr * BESS.d + (nr - 1) * BESS.aisle, out = [], ohlR = ohlNear(r, Math.max(W, D) / 2 + BESS.fence), ohl = ohlR || [];
const margin = PL.LAYOUT_DEFAULTS.ohlMarginM, cont = []; // the engine's own margin, so tables and containers keep the same clearance
const near = c => ohl.some(z => { const [a, b] = z.pts, lim = z.reachM + margin; // box within reach + margin of the span
return c.some(p => segD(...p, ...a, ...b) < lim) || [a, b].some(p => Math.hypot(Math.max(c[0][0] - p[0], 0, p[0] - c[2][0]),
Math.max(c[0][1] - p[1], 0, p[1] - c[2][1])) < lim) || crosses(c, a, b); });
let dropped = 0;
for (let k = 0; k < n; k++) { const x = -W / 2 + (k % BESS.perRow) * (BESS.w + BESS.gap), y = -D / 2 + Math.floor(k / BESS.perRow) * (BESS.d + BESS.aisle);
const c = [[x, y], [x + BESS.w, y], [x + BESS.w, y + BESS.d], [x, y + BESS.d]];
if (near(c)) { dropped++; continue; } cont.push(c); box(out, x, y, BESS.w, BESS.d, 0, BESS.h); }
box(out, -W / 2 - BESS.fence, -D / 2 - BESS.fence, W + 2 * BESS.fence, D + 2 * BESS.fence, 0, 2.4);
return { lines: out, geom: { ohl, ohlLoaded: ohlOk(ohlR), ohlMissing: ohlR ? ohlR.missing : null, ohlRadiusM: Math.max(W, D) / 2 + BESS.fence, marginM: margin, tables: [], containers: cont, skipped: dropped },
text: `${r.mw} MW storage: ${n - dropped} of ${n} containers (assumed 2 h, 3.7 MWh each); `
+ ohlSay(ohlR, `${dropped} container positions kept out of overhead line zones (illustrative)`) + `; ${SQUARE}` };
}
async function refresh() {
if (!on) return; loadRows(); if (busy) { pending = true; return; } busy = true;
try {
const c = map.getCenter(), b = map.getBounds(), k = Math.cos(c.lat * Math.PI / 180);
const inView = r => r.lat > b.getSouth() - REACH_DEG && r.lat < b.getNorth() + REACH_DEG && r.lon > b.getWest() - REACH_DEG / k && r.lon < b.getEast() + REACH_DEG / k;
const near = map.getZoom() < MIN_ZOOM ? [] : rows.filter(inView)
.map(r => ({ r, d: Math.hypot(r.lat - c.lat, (r.lon - c.lng) * k) })).sort((a, z) => a.d - z.d).slice(0, MAX_ASSETS).map(x => x.r);
const texts = [];
for (const r of near) {
const sg = sig(), old = cache.get(r.ref); // redo once the real lines arrive (pylons-real loads them async)
if (!old || old.sig !== sg) { const g = r.tech === 'bess' ? bess(r) : await solar(r);
if (old) { drop(x => x.procedural === r.ref); shown = shown.filter(z => z !== r.ref); }
cache.set(r.ref, { blocks: place(r, g.lines), text: g.text, n: g.lines.length, geom: g.geom, sig: sg }); }
texts.push(cache.get(r.ref).text);
}
const keep = new Set(near.map(r => r.ref));
drop(x => !keep.has(x.procedural));
for (const r of near) if (!shown.includes(r.ref)) for (const bl of cache.get(r.ref).blocks) { delete bl.vbo; ghost.push(bl); }
map.triggerRepaint();
shown = near.map(r => r.ref);
btn.textContent = `Procedural (${shown.length})`;
say(shown.length ? `${LABEL}. Ghost lines = estimated (solid = measured, dashed = documented). At register points, sized from register capacity: ${texts.join('; ')}. EV forecourts: no register loaded, not drawn.`
: `Procedural: no register solar or storage in view${map.getZoom() < MIN_ZOOM ? ' (zoom in to ' + MIN_ZOOM + ')' : ''}. ${LABEL}.`);
window.__procedural = { label: LABEL, style: 'ghost', ghostBlocks: ghost.length, layer: !!map.getLayer(layer.id), calibN: CALIB.N, shown: near.map(r => ({ ref: r.ref, tech: r.tech, mw: r.mw, lat: r.lat, lon: r.lon, segments: cache.get(r.ref).n, text: cache.get(r.ref).text, geom: cache.get(r.ref).geom })) };
} catch (e) { say('Procedural: ' + e.message); }
busy = false; if (pending) { pending = false; refresh(); }
}
const btn = SIM.addButton('Procedural', () => { on = !on; btn.classList.toggle('on', on); if (on) refresh(); else { drop(() => true); shown = []; say(''); btn.textContent = 'Procedural'; } });
btn.id = 'procedural';
map.on('moveend', refresh);
window.__proceduralRefresh = refresh; window.__proceduralFit = ref => { const r = rows.find(x => x.ref === ref); return r ? fitRows(r) : null; }; window.__proceduralGhost = () => ghost.length;
window.__proceduralOhl = ref => { const r = rows.find(x => x.ref === ref), c = cache.get(ref); if (!r || !c) return null; // fresh, not the cache
const o = ohlNear(r, c.geom.ohlRadiusM); return { loaded: ohlOk(o), missing: o ? o.missing : null, http: { ...kvHttp }, spans: o ? o.length : 0, key: o ? o.map(z => z.kv + ':' + z.pts.flat().map(v => v.toFixed(2)).join(',')).join('|') : '' }; };
}
(function wait() { if (window.SIM && window.__pf && window.__pf.PF) start(window.SIM, window.__pf.PF); else setTimeout(wait, 100); })();
})();Pylons Real
A JavaScript file in the prototype folder of Energy Transition Simulator that fetches substations footprints odbl, using point in polygon from the GridAtlas repository.
renderenergy-transition-simulator / prototype/mod/pylons-real.js · lines 1–185 of 185 · Not reached from any entry point (candidate for review) · pattern makeBlock (shared by 2 files)
- What it does
- It fetches substations footprints odbl. Defines 18 functions or classes, including ready, start, kx, dist, inRing. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: data source: gridatlas data; JSON file substations-footprints.odbl.json. Coordinate systems named: WGS84 / EPSG:4326.
- What it achieves
- It makes block (`makeBlock`) and is built from the ready step (`ready`) and the start step (`start`). Lattice pylons and sagging conductors on the real GridAtlas lines.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- ready, start, kx, dist, inRing, inSubstation, towersOf, lattice, half, sq, attach, elev
- Defines here
- ready, start, kx, dist, inRing, inSubstation, towersOf, lattice, half, sq, attach, elev, makeBlock, X, refresh, label, regrade, check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/pylons-real.js:1-185 · blob ea5048fba38897c283dbf2ab9aca424e3c382f72 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// mod/pylons-real.js - lattice pylons and sagging conductors on the real GridAtlas lines.
// Plain script. Attaches to window.SIM ({ map, addBlock, removeWhere, ... }) and uses the overlay's place frame
// (window.__pf.PF), so every tower is authored in metres around a 100 m place key and lands on its exact WGS84 position.
// ASSUMED AT A MAPPED LINE VERTEX: a tower is assumed at each GridAtlas line vertex (lines from OpenStreetMap, ODbL).
// The file drops node tags, so a vertex may be a bend, not a surveyed tower. A vertex closer than MERGE_M to the
// previous kept one is dropped, never moved. A tower that falls inside a mapped substation footprint (OpenStreetMap,
// ODbL, mod/substations-footprints.odbl.json) is dropped: the line ends at a gantry inside the fence, not a lattice
// tower. ESTIMATED: infill towers on long straight runs (typical
// span), tower shape and height, arm lengths, insulator length and conductor sag, all by voltage class (not surveyed).
// Drawn through the overlay's ONE wire layer (SIM.addBlock): one block per tower, no layer or GL program of its own.
// Hidden below zoom MIN_Z. window.__pylonsReal.check() tests every mapped tower against its GridAtlas vertex with ===.
(function () {
'use strict';
const MIN_Z = 14, MAX_TOWERS = 260, MERGE_M = 60, SEG = 12;
const GA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data';
// Estimated geometry by voltage class (GB double-circuit lattice types, typical values, not surveyed):
// H tower height, base half-width, arm heights (fractions of H, bottom to top), arm half-lengths (m),
// suspension insulator length (m), typical span (m), catenary parameter a = T/w (m), conductor colour.
const KV = {
'400': { H: 50, base: 6.0, armZ: [0.62, 0.77, 0.92], arm: [10.5, 12.0, 9.0], ins: 4.5, span: 360, a: 1500, col: [0.25, 0.5, 1.0] },
'275': { H: 46, base: 5.5, armZ: [0.62, 0.77, 0.92], arm: [9.5, 11.0, 8.2], ins: 3.4, span: 340, a: 1400, col: [1.0, 0.3, 0.3] },
'132': { H: 27, base: 3.2, armZ: [0.60, 0.76, 0.92], arm: [4.6, 5.3, 4.1], ins: 1.8, span: 280, a: 1100, col: [0.2, 0.9, 0.4] }
};
const TOWER_COL = [0.82, 0.86, 0.9];
const here = (document.currentScript && document.currentScript.src) || location.href;
const FP_URL = new URL('substations-footprints.odbl.json', here).href;
let fps = []; // [{ bbox, ring }] substation footprints, [lon, lat] rings
let dropped = 0; // towers dropped because they fall inside a footprint
let SIM, map, PF, on = true, btn = null;
const lines = { }; // kv -> [{ bbox, coords }]
const runs = new Map(); // `${kv}:${lineIndex}` -> tower list (built lazily, cached)
const live = new Map(); // tower id -> block { anchor, lon, lat, gz, buf, nTower, nWire, col }
let pending = 0, regrades = 0;
const ready = () => { SIM = window.SIM; PF = window.__pf && window.__pf.PF; return SIM && SIM.map && PF; };
(function wait(n) { if (ready()) start(); else if (n < 200) setTimeout(() => wait(n + 1), 100); })(0);
function start() {
map = SIM.map;
if (SIM.addButton) { btn = SIM.addButton('Pylons (mapped)', () => { on = !on; btn.classList.toggle('on', on); refresh(); }); btn.classList.add('on'); }
const fpLoad = fetch(FP_URL).then(r => r.ok ? r.json() : null).then(j => {
fps = ((j && j.f) || []).map(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 }; });
}).catch(() => { fps = []; });
Promise.all([fpLoad].concat(Object.keys(KV).map(kv => fetch(`${GA}/grid_${kv}kv.geojson`).then(r => r.json()).then(j => {
const L = [];
for (const f of j.features || []) { const g = f.geometry; if (!g) continue;
for (const c of g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : []) {
let w = 180, s = 90, e = -180, n = -90; for (const [x, y] of c) { if (x < w) w = x; if (x > e) e = x; if (y < s) s = y; if (y > n) n = y; }
L.push({ bbox: [w, s, e, n], coords: c }); } } // properties (names) are never read or shown
lines[kv] = L;
}).catch(() => { lines[kv] = []; })))).then(refresh);
map.on('moveend', refresh);
map.on('idle', () => { if (pending && regrades < 6) { pending = 0; regrades++; regrade(); } });
}
// ---- towers along one GridAtlas line: exact vertices, close ones merged, long runs filled at the typical span ----
const kx = lat => 111320 * Math.cos(lat * Math.PI / 180);
const dist = (a, b) => Math.hypot((b[0] - a[0]) * kx((a[1] + b[1]) / 2), (b[1] - a[1]) * 111320);
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; }
function inSubstation(lon, lat) {
for (const f of fps) { const [w, s, e, n] = f.bbox; if (lon < w || lon > e || lat < s || lat > n) continue; if (inRing(lon, lat, f.ring)) return true; }
return false; }
function towersOf(kv, li) {
const id = kv + ':' + li; if (runs.has(id)) return runs.get(id);
const c = lines[kv][li].coords, P = [];
for (const p of c) { if (!P.length || dist(P[P.length - 1].p, p) >= MERGE_M) P.push({ p, est: false }); }
if (P.length > 1 && dist(P[P.length - 1].p, c[c.length - 1]) > 1) P[P.length - 1] = { p: c[c.length - 1], est: false };
const T = [];
for (let i = 0; i < P.length; i++) {
T.push(P[i]);
if (i + 1 < P.length) { const d = dist(P[i].p, P[i + 1].p), n = Math.round(d / KV[kv].span) - 1;
for (let k = 1; k <= n; k++) { const t = k / (n + 1), a = P[i].p, b = P[i + 1].p; T.push({ p: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], est: true, seg: [a, b] }); } }
}
// Drop towers inside a substation footprint; a span never jumps across a dropped tower (break = no conductor).
const all = T.map((t, i) => ({ id: `${id}:${i}`, kv, lon: t.p[0], lat: t.p[1], est: t.est, seg: t.seg || null,
inSub: inSubstation(t.p[0], t.p[1]) }));
const out = []; let brk = false;
for (const t of all) { if (t.inSub) { dropped++; brk = true; continue; } t.brk = brk; brk = false; out.push(t); }
for (let i = 0; i < out.length; i++) { // along-line direction in local metres (bisector at angle towers)
const t = out[i], dir = [0, 0];
for (const j of [i - 1, i + 1]) { const o = out[j]; if (!o) continue; const s = j < i ? 1 : -1;
const dx = (t.lon - o.lon) * kx(t.lat) * s, dy = (t.lat - o.lat) * 111320 * s, l = Math.hypot(dx, dy) || 1; dir[0] += dx / l; dir[1] += dy / l; }
const l = Math.hypot(dir[0], dir[1]) || 1; t.u = [dir[0] / l, dir[1] / l]; t.next = out[i + 1] && !out[i + 1].brk ? out[i + 1] : null;
}
runs.set(id, out); return out;
}
// ---- geometry in tower-frame metres: (along, left, up) ----
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;
}
const attach = g => { const P = []; g.armZ.forEach((f, k) => { for (const s of [-1, 1]) P.push([s * g.arm[k], f * g.H - g.ins]); }); P.push([0, g.H]); return P; };
function elev(lon, lat) { const e = map.queryTerrainElevation ? map.queryTerrainElevation([lon, lat]) : 0; if (e == null) pending = 1; return e || 0; }
// One block per tower for the ONE wire layer (SIM.addBlock). The wire layer lifts each block by the ground height
// at its place-key anchor, so the tower's own ground offset (tower minus anchor) is baked into z here.
function makeBlock(t) {
const g = KV[t.kv], an = PF.placeKey(t.lat, t.lon), o = PF.toLocal(an, t.lat, t.lon, 0);
const u = t.u, v = [-u[1], u[0]], ga = elev(an.lon, an.lat), gz = elev(t.lon, t.lat) - ga;
const X = (a, l, z, base = o, uu = u, vv = v, dz = gz) => [base.x + uu[0] * a + vv[0] * l, base.y + uu[1] * a + vv[1] * l, z + dz];
const T = lattice(g).map(s => [...X(s[0], s[1], s[2]), ...X(s[3], s[4], s[5])]);
const W = [];
if (t.next) { // conductors to the next tower: 3 phases per side + earth wire
const n = t.next, q = PF.toLocal(an, n.lat, n.lon, 0), nv = [-n.u[1], n.u[0]], dz = elev(n.lon, n.lat) - ga;
const span = Math.hypot(q.x - o.x, q.y - o.y), sag = span * span / (8 * g.a);
for (const [l, z] of attach(g)) {
const A = X(0, l, z), B = X(0, l, z, q, n.u, nv, dz); let prev = A;
for (let k = 1; k <= SEG; k++) { const s = k / SEG, p = [A[0] + (B[0] - A[0]) * s, A[1] + (B[1] - A[1]) * s, A[2] + (B[2] - A[2]) * s - 4 * sag * s * (1 - s) * (l ? 1 : 0.7)];
W.push([...prev, ...p]); prev = p; }
}
}
const lines = T.concat(W);
return { pylonsReal: true, id: t.id, lon: t.lon, lat: t.lat, anchor: an, lines, buf: PF.wireBuffer(an, lines),
nTower: T.length * 2, nWire: W.length * 2, col: g.col, est: t.est, kv: t.kv, t,
prov: t.est ? 'estimated: infill tower at the typical span between two mapped vertices'
: 'assumed: tower at a mapped line vertex (GridAtlas, OpenStreetMap, ODbL); the vertex may be a bend, not a tower' };
}
function refresh() {
if (!map || !SIM.addBlock) return;
const want = new Set();
if (on && map.getZoom() >= MIN_Z) {
const b = map.getBounds(), c = map.getCenter(), mx = (b.getEast() - b.getWest()) * 0.25, my = (b.getNorth() - b.getSouth()) * 0.25;
const W = b.getWest() - mx, E = b.getEast() + mx, S = b.getSouth() - my, N = b.getNorth() + my, cand = [];
for (const kv of Object.keys(lines)) lines[kv].forEach((ln, li) => {
const [w, s, e, n] = ln.bbox; if (e < W || w > E || n < S || s > N) return;
for (const t of towersOf(kv, li)) if (t.lon >= W && t.lon <= E && t.lat >= S && t.lat <= N) cand.push([dist([c.lng, c.lat], [t.lon, t.lat]), t]);
});
cand.sort((a, b) => a[0] - b[0]);
for (const [, t] of cand.slice(0, MAX_TOWERS)) { want.add(t.id); if (!live.has(t.id)) live.set(t.id, SIM.addBlock(makeBlock(t))); }
}
let gone = 0; for (const id of live.keys()) if (!want.has(id)) { live.delete(id); gone++; }
if (gone) SIM.removeWhere(b => b.pylonsReal && !want.has(b.id));
if (SIM.info && on && live.size) SIM.info(label());
SIM.repaint();
}
// The on-screen label: what is a mapped position and what is estimated, with the count of each.
function label() {
let m = 0, e = 0; for (const bk of live.values()) bk.est ? e++ : m++;
return `Pylons: ${m} towers assumed at mapped line vertices (GridAtlas, © OpenStreetMap contributors, ODbL) and ${e} estimated infill towers; ` +
'none drawn inside a mapped substation footprint. Tower shape, height, arms and conductor sag are estimates by voltage class.';
}
// Terrain arrives after the first build: re-grade the blocks built on missing heights (their spans too).
function regrade() { SIM.removeWhere(b => b.pylonsReal); live.clear(); refresh(); }
// Exact check: every tower not flagged estimated must equal a vertex of its GridAtlas line (===, no tolerance),
// and every estimated tower must lie on the straight segment between two vertices of its line (ends === vertices,
// off-line distance < 1 mm, strictly between the ends); no drawn tower may fall inside a substation footprint.
function check() {
let exact = 0, bad = [], est = 0, estBad = [], inSub = [];
for (const bk of live.values()) {
const [kv, li] = bk.id.split(':'), c = lines[kv][+li].coords, isV = q => c.some(p => p[0] === q[0] && p[1] === q[1]);
if (inSubstation(bk.lon, bk.lat)) inSub.push(bk.id);
if (!bk.est) { if (isV([bk.lon, bk.lat])) exact++; else bad.push(bk.id); continue; }
est++; const sg = bk.t.seg; if (!sg || !isV(sg[0]) || !isV(sg[1])) { estBad.push(bk.id); continue; }
const [a, b] = sg, k = kx(bk.lat), ax = (b[0] - a[0]) * k, ay = (b[1] - a[1]) * 111320, px = (bk.lon - a[0]) * k, py = (bk.lat - a[1]) * 111320;
const L2 = ax * ax + ay * ay, u = (px * ax + py * ay) / L2, off = Math.abs(px * ay - py * ax) / Math.sqrt(L2);
if (!(off < 0.001 && u > 0 && u < 1)) estBad.push(bk.id);
}
return { live: live.size, exact, est, bad, estBad, inSub, dropped, label: label() };
}
window.__pylonsReal = { live, refresh, count: () => live.size, towersOf, KV, check, label, lines, inSubstation, fps: () => fps.length };
})();Rows Geometry
A JavaScript file in the prototype folder of Energy Transition Simulator that tiles to lon lat (`tileToLonLat`), loads img (`loadImg`), builds mask (`buildMask`) and calculates planar distances and angles.
geodesyenergy-transition-simulator / prototype/mod/rows-geometry.js · lines 1–222 of 222 · Not reached from any entry point (candidate for review) · pattern lonLatToTile (shared by 3 files)
- What it does
- It draws its content. Defines 15 functions or classes, including lonLatToTile, tileToLonLat, loadImg, buildMask, directions. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- Out: canvas drawing.
- What it achieves
- It loads img (`loadImg`), builds mask (`buildMask`) and merges rows (`mergeRows`). Better "Rows from satellite". Reads Esri z17 imagery around the map centre, builds a panel mask (darkness test OR a colour test for the bright/grey glare gaps next to dark panels).
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- lonLatToTile, tileToLonLat, loadImg, buildMask, directions, cellSegments, flush, mergeRows, find, emit, tables, f
- Defines here
- lonLatToTile, tileToLonLat, loadImg, buildMask, directions, cellSegments, flush, mergeRows, find, emit, tables, f, run, toM, attach
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/rows-geometry.js:1-222 · blob 50e9d64d13730dfb2bf3e2be024751a78187ee2e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// rows-geometry: better "Rows from satellite". Reads Esri z17 imagery around the map centre, builds a panel mask
// (darkness test OR a colour test for the bright/grey glare gaps next to dark panels), finds the row DIRECTION locally
// (structure tensor of the mask per 64 px cell, smoothed), finds row centre lines and the real row pitch from the
// profile across the rows, merges pieces into continuous row polylines, and stands them up as tilted tables:
// front edge 0.8 m, back edge 2.4 m, legs every 5 m. Everything is an ESTIMATE from imagery, not a survey.
// Plain script: attaches to window.SIM (map, blocks, addBlock, removeWhere, repaint, info). One block, one buffer.
(function () {
'use strict';
const Z = 17, NT = 4, W = NT * 256; // 4 x 4 tiles = 1024 px, about 760 m square in southern England
const CELL = 64; // direction cells, about 48 m
const FRONT = 0.8, BACK = 2.4, LEG = 5; // table heights (assumed) and leg spacing, metres
const TILE = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
const CREDIT = 'Imagery: Esri, Maxar, Earthstar Geographics';
const lonLatToTile = (lon, lat, z) => { const n = 2 ** z, r = lat * Math.PI / 180;
return [(lon + 180) / 360 * n, (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n]; };
const tileToLonLat = (x, y, z) => { const n = 2 ** z; return [x / n * 360 - 180, Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n))) * 180 / Math.PI]; };
const loadImg = u => new Promise((ok, no) => { const im = new Image(); im.crossOrigin = 'anonymous'; im.onload = () => ok(im); im.onerror = no; im.src = u; });
// ---- 1. mask: darkness test, plus colour test (neutral/blue-grey, not vegetation, not soil) near dark panels ----
function buildMask(d) {
const N = W * W, strong = new Uint8Array(N), weak = new Uint8Array(N);
for (let i = 0, k = 0; i < N; i++, k += 4) {
const r = d[k], g = d[k + 1], b = d[k + 2], lum = 0.3 * r + 0.59 * g + 0.11 * b;
const mx = Math.max(r, g, b), mn = Math.min(r, g, b);
if (lum < 62 && b >= r - 6) strong[i] = 1;
else if (lum < 165 && mx - mn < 48 && b >= r - 4 && !(g > r + 8 && g > b + 6) && !(r > b + 16)) weak[i] = 1;
}
// integral image of strong pixels -> local density in a 9 x 9 window
const I = new Uint32Array((W + 1) * (W + 1));
for (let y = 0; y < W; y++) { let s = 0; for (let x = 0; x < W; x++) { s += strong[y * W + x]; I[(y + 1) * (W + 1) + x + 1] = I[y * (W + 1) + x + 1] + s; } }
const R = 4, mask = new Uint8Array(N); let nWeak = 0;
for (let y = 0; y < W; y++) for (let x = 0; x < W; x++) {
const i = y * W + x; if (strong[i]) { mask[i] = 1; continue; } if (!weak[i]) continue;
const x0 = Math.max(0, x - R), y0 = Math.max(0, y - R), x1 = Math.min(W, x + R + 1), y1 = Math.min(W, y + R + 1);
const s = I[y1 * (W + 1) + x1] - I[y0 * (W + 1) + x1] - I[y1 * (W + 1) + x0] + I[y0 * (W + 1) + x0];
if (s > 0.22 * (x1 - x0) * (y1 - y0)) { mask[i] = 1; nWeak++; }
}
return { mask, nWeak };
}
// ---- 2. local row direction: structure tensor of the mask per cell, doubled-angle smoothing over neighbours ----
function directions(mask) {
const nc = W / CELL, cells = [];
for (let cy = 0; cy < nc; cy++) for (let cx = 0; cx < nc; cx++) {
let jxx = 0, jyy = 0, jxy = 0, cnt = 0;
for (let y = cy * CELL + 1; y < (cy + 1) * CELL - 1; y++) for (let x = cx * CELL + 1; x < (cx + 1) * CELL - 1; x++) {
const i = y * W + x; cnt += mask[i];
const gx = mask[i + 1] - mask[i - 1], gy = mask[i + W] - mask[i - W];
jxx += gx * gx; jyy += gy * gy; jxy += gx * gy;
}
const fill = cnt / (CELL * CELL), tr = jxx + jyy;
const coh = tr ? Math.hypot(jxx - jyy, 2 * jxy) / tr : 0;
const ok = fill > 0.12 && fill < 0.985 && coh > 0.25;
cells.push({ cx, cy, fill, coh, ok, vx: ok ? (jxx - jyy) * coh : 0, vy: ok ? 2 * jxy * coh : 0 });
}
for (const c of cells) { // smooth the doubled angle with the 3 x 3 neighbours
if (!c.ok) continue; let sx = 0, sy = 0;
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
const x = c.cx + dx, y = c.cy + dy; if (x < 0 || y < 0 || x >= nc || y >= nc) continue;
const o = cells[y * nc + x], w = dx || dy ? 0.5 : 1; sx += o.vx * w; sy += o.vy * w;
}
c.phi = 0.5 * Math.atan2(sy, sx); // gradient (across-row) angle, pixel frame (y down)
}
for (const c of cells) { // solid panel cells with no texture: borrow the neighbours' direction
if (c.ok || c.fill < 0.35) continue; let sx = 0, sy = 0;
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) {
const x = c.cx + dx, y = c.cy + dy; if (x < 0 || y < 0 || x >= nc || y >= nc) continue;
const o = cells[y * nc + x]; if (o.ok) { sx += o.vx; sy += o.vy; } }
if (sx || sy) { c.phi = 0.5 * Math.atan2(sy, sx); c.ok = true; c.borrowed = true; }
}
return cells;
}
// ---- 3. per cell: profile across the rows -> pitch, centre lines, depth; walk each line -> runs ----
function cellSegments(mask, c, mpp, gPitch) {
const nx = Math.cos(c.phi), ny = Math.sin(c.phi), ux = -ny, uy = nx;
const ox = (c.cx + 0.5) * CELL, oy = (c.cy + 0.5) * CELL, H = 50, B = 2 * H * 2 + 1; // bins of 0.5 px over +-50 px
const prof = new Float32Array(B);
for (let y = c.cy * CELL; y < (c.cy + 1) * CELL; y++) for (let x = c.cx * CELL; x < (c.cx + 1) * CELL; x++) {
if (!mask[y * W + x]) continue; const t = (x - ox) * nx + (y - oy) * ny; const b = Math.round((t + H) * 2); if (b >= 0 && b < B) prof[b]++;
}
const sm = new Float32Array(B); for (let i = 0; i < B; i++) { let s = 0, w = 0; for (let k = -3; k <= 3; k++) { const j = i + k; if (j < 0 || j >= B) continue; const g = Math.exp(-k * k / 4.5); s += prof[j] * g; w += g; } sm[i] = s / w; }
// pitch: autocorrelation peak for lags 4.5 .. 16 m
let mean = 0; for (const v of sm) mean += v; mean /= B;
let best = 0, bestLag = 0; const l0 = Math.round(4.5 / mpp * 2), l1 = Math.round(16 / mpp * 2);
for (let L = l0; L <= l1; L++) { let s = 0; for (let i = 0; i + L < B; i++) s += (sm[i] - mean) * (sm[i + L] - mean); s /= (B - L); if (s > best) { best = s; bestLag = L; } }
const pitchPx = bestLag ? bestLag / 2 : 0;
let mx = 0, lo = 1e9; for (let i = 20; i < B - 20; i++) { mx = Math.max(mx, sm[i]); if (sm[i] > 0) lo = Math.min(lo, sm[i]); }
const contrast = mx ? 1 - lo / mx : 0;
if (!gPitch) return { pitchPx: contrast > 0.5 && best > 0 ? pitchPx : 0 };
const peaks = [], sep = gPitch * 2 * 0.7;
if (contrast > 0.45) {
for (let i = 1; i < B - 1; i++) if (sm[i] >= sm[i - 1] && sm[i] > sm[i + 1] && sm[i] > 0.3 * mx) {
if (peaks.length && i - peaks[peaks.length - 1].i < sep) { if (sm[i] > peaks[peaks.length - 1].v) peaks[peaks.length - 1] = { i, v: sm[i] }; continue; }
peaks.push({ i, v: sm[i] });
}
} else { // solid panel area: rows not resolved, laid at the measured pitch (estimate)
const ph = (((Math.round(nx * 1e3) + ox * nx + oy * ny) % gPitch) + gPitch) % gPitch; // phase tied to the image, so cells line up
for (let t = -H + ((gPitch - ph) % gPitch); t <= H; t += gPitch) { const i = Math.round((t + H) * 2); if (sm[i] > 0) peaks.push({ i, v: mx, flat: true }); }
}
const segs = [];
for (const p of peaks) {
let a = p.i, b = p.i; while (a > 0 && sm[a] > p.v / 2) a--; while (b < B - 1 && sm[b] > p.v / 2) b++;
const depthPx = p.flat ? gPitch * 0.75 : (b - a) / 2, t = p.i / 2 - H;
const cxp = ox + nx * t, cyp = oy + ny * t;
let run = null, gap = 0;
const flush = () => { if (run && run.s1 - run.s0 >= 4) segs.push({ phi: c.phi, depthPx, x0: cxp + ux * run.s0, y0: cyp + uy * run.s0, x1: cxp + ux * run.s1, y1: cyp + uy * run.s1 }); run = null; gap = 0; };
for (let s = -H; s <= H; s++) {
const px = cxp + ux * s, py = cyp + uy * s;
const inCell = px >= c.cx * CELL && px < (c.cx + 1) * CELL && py >= c.cy * CELL && py < (c.cy + 1) * CELL;
if (!inCell) { if (run) flush(); continue; }
let on = 0; for (const o of [-1, 0, 1]) { const qx = Math.round(px + nx * o), qy = Math.round(py + ny * o); if (qx >= 0 && qy >= 0 && qx < W && qy < W) on += mask[qy * W + qx]; }
if (on >= 2) { if (!run) run = { s0: s, s1: s }; else run.s1 = s; gap = 0; }
else if (run && ++gap > 3) flush();
}
flush();
}
return { segs, pitchPx, spacings: peaks.slice(1).map((p, k) => (p.i - peaks[k].i) / 2) };
}
// ---- 4. merge pieces into continuous rows (same direction, same line, small along-row gap) ----
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;
}
// ---- 5. tables in local metres around the anchor ----
function tables(rows, toM, pitchM) {
const L = []; let km = 0;
for (const r of rows) {
const P = r.pts.map(([x, y]) => toM(x, y));
const dx = P[1][0] - P[0][0], dy = P[1][1] - P[0][1], len = Math.hypot(dx, dy); if (len < 6) continue; km += len / 1000;
const ux = dx / len, uy = dy / len; let nx = -uy, ny = ux;
if (ny < -0.2 || (Math.abs(ny) <= 0.2 && nx < 0)) { nx = -nx; ny = -ny; } // back edge to the north (south-facing, assumed)
const d = Math.min(6, Math.max(2.5, Math.min(r.depthM, pitchM ? pitchM * 0.75 : 6))) / 2;
const f = s => [P[0][0] + ux * s - nx * d, P[0][1] + uy * s - ny * d], b = s => [P[0][0] + ux * s + nx * d, P[0][1] + uy * s + ny * d];
const F0 = f(0), F1 = f(len), B0 = b(0), B1 = b(len);
L.push([F0[0], F0[1], FRONT, F1[0], F1[1], FRONT], [B0[0], B0[1], BACK, B1[0], B1[1], BACK]);
const k = Math.max(1, Math.round(len / LEG));
for (let i = 0; i <= k; i++) { const s = len * i / k, A = f(s), C = b(s);
L.push([A[0], A[1], 0, A[0], A[1], FRONT], [C[0], C[1], 0, C[0], C[1], BACK], [A[0], A[1], FRONT, C[0], C[1], BACK]); }
}
return { L, km };
}
async function run() {
const S = window.SIM, PF = window.__pf && window.__pf.PF; if (!S || !PF) return null;
const bt = document.getElementById('detect'); if (bt) bt.textContent = 'Reading satellite...';
const t0 = performance.now(), map = S.map, c = map.getCenter(), [tx, ty] = lonLatToTile(c.lng, c.lat, Z);
const x0 = Math.floor(tx) - NT / 2 + (tx % 1 >= 0.5 ? 1 : 0), y0 = Math.floor(ty) - NT / 2 + (ty % 1 >= 0.5 ? 1 : 0);
const cv = document.createElement('canvas'); cv.width = cv.height = W; const g = cv.getContext('2d', { willReadFrequently: true });
try { const jobs = []; for (let j = 0; j < NT; j++) for (let i = 0; i < NT; i++)
jobs.push(loadImg(TILE.replace('{z}', Z).replace('{x}', x0 + i).replace('{y}', y0 + j)).then(im => g.drawImage(im, i * 256, j * 256)));
await Promise.all(jobs); } catch (e) { if (bt) bt.textContent = 'Satellite read failed'; return null; }
const d = g.getImageData(0, 0, W, W).data;
const an = PF.placeKey(c.lat, c.lng);
const toM = (px, py) => { const [lon, lat] = tileToLonLat(x0 + px / 256, y0 + py / 256, Z); const q = PF.toLocal(an, lat, lon, 0); return [q.x, q.y]; };
const a = toM(0, 0), b = toM(W, 0), mpp = Math.hypot(b[0] - a[0], b[1] - a[1]) / W;
const { mask, nWeak } = buildMask(d);
const cells = directions(mask);
const use = cells.filter(cl => cl.ok && cl.phi != null);
const sp = use.map(cl => cellSegments(mask, cl, mpp, 0).pitchPx).filter(Boolean).sort((p, q) => p - q);
const gPitch = sp.length ? sp[sp.length >> 1] : 7 / mpp, pitchM = gPitch * mpp; // median row pitch over resolved cells
let segs = []; for (const cl of use) segs = segs.concat(cellSegments(mask, cl, mpp, gPitch).segs);
const rows = mergeRows(segs); for (const r of rows) r.depthM = r.depthPx * mpp;
const { L, km } = tables(rows, toM, pitchM);
S.removeWhere(x => x.sat);
S.addBlock({ lon: an.lon, lat: an.lat, anchor: an, lines: L, buf: PF.wireBuffer(an, L), sat: true, rowsGeometry: true });
S.repaint();
// dominant direction, as a compass bearing of the rows
let vx = 0, vy = 0; for (const r of rows) { const l = Math.hypot(r.pts[1][0] - r.pts[0][0], r.pts[1][1] - r.pts[0][1]); vx += Math.cos(2 * r.phi) * l; vy += Math.sin(2 * r.phi) * l; }
const pd = 0.5 * Math.atan2(vy, vx), brg = ((Math.atan2(-Math.sin(pd), -Math.cos(pd)) * 180 / Math.PI) % 180 + 180) % 180;
const stats = { rows: rows.length, km: +km.toFixed(2), pitchM: +pitchM.toFixed(1), bearingDeg: Math.round(brg),
cellsWithRows: cells.filter(x => x.ok).length, cellsBorrowed: cells.filter(x => x.borrowed).length, pitchCells: sp.length, cells: cells.length, gapPixelsFilled: nWeak, lines: L.length, ms: Math.round(performance.now() - t0), mpp: +mpp.toFixed(3) };
if (bt) bt.textContent = `Rows from satellite (${stats.rows})`;
S.info(`Estimated from satellite imagery, not measured: ${stats.rows} continuous rows, ${stats.km} km of tables over about ${Math.round(W * mpp)} m square. ` +
`Row pitch about ${stats.pitchM} m (estimate); tables drawn 0.8 m front, 2.4 m back, legs every 5 m (assumed). ${CREDIT}.`);
window.__rowsGeometry = stats; return stats;
}
function attach() {
if (!window.SIM || !window.__pf) return setTimeout(attach, 200);
const bt = document.getElementById('detect');
if (bt) bt.onclick = run; else window.SIM.addButton && window.SIM.addButton('Rows from satellite', run);
window.SIM.rowsGeometry = run;
}
attach();
})();