In this section
- Block UI interaction · globalgrid2050 / solar-design-studio/202609271740-site-world/world/block-ui.mjs lines 1–363
Block UI
A JavaScript module in the world folder of GlobalGrid2050 that draws GPU compounds, cables, 33kV and overhead lines (OHL). It creates block (`createBlock`), places gpu (`placeGpu`) and shows export (`showExport`).
interactionglobalgrid2050 / solar-design-studio/202609271740-site-world/world/block-ui.mjs · lines 1–363 of 363 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern refreshItems (shared by 2 files)
- What it does
- It draws GPU compounds, cables, 33kV and overhead lines (OHL). Defines 45 functions or classes, including n0, createBlock, $, say, local. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV, overhead lines (OHL), 132kV.
- Inputs & outputs
- In: JSON file modules.json; JSON file gpu-compounds.json. Voltage levels named: 132kV, 33kV.
- Downstream impact
- Used directly by 1 file: Design Sections (globalgrid2050).
- What it achieves
- Design > Solar block. Places the owner's 10MVA station block (`block-build.mjs`) on the measured ground in front of the viewer, chains the stations on 33kV rings to the grid, and plays the build sequence (`block-sequence.mjs`). Its code works with 33 kV, 10 MVA and 132 kV. It reads `./world/data/modules.json`. It responds to change and click events.
- Why it matters
- Imported by Design Sections.
- Application
- globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
- Uses
- Origin (import), Block Build (import), Block MV (import), Single-Line Diagram (SLD) Connect (import), Block Sequence (import), Plant Ground (import), Measure Format (import), String Design (import), and 5 more
- Used by
- imported by Design Sections (dynamic import)
- Produces
- BLOCK_LABEL, createBlock
- Defines here
- n0, createBlock, $, say, local, catalogue, formMps, formTmin, design, gpuPads, offerStaged, has, place, measured, fallback, placeGpu, showExport, exportBatches, gpuCounts, gpuHour, gpuBatches, showGpu, cableGroup, o3, prefix, upto, pulling, batches, blockBatches, whole
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/block-ui.mjs:1-363 · blob fe43f5cb2b79d3e99c20ee06056f7979c0fbbd7f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// block-ui.mjs: Design > Solar block. Places the owner's 10 MVA station block (block-build.mjs) on the measured ground
// in front of the viewer, chains the stations on 33 kV rings to the grid, and plays the build sequence
// (block-sequence.mjs): Play runs the clock and asks the page for frames at 30 fps; Pause and Step stop the clock,
// so no frame is drawn until something else changes (0 fps). Everything is held in national-grid metres; each line
// group keeps its positions relative to its own base, so a move of the site origin only moves the base.
// Trenches are handed to the design (trenchItems), which cuts them into the ground and draws their cross-sections.
import { toBng } from './origin.mjs';
import { buildBlock, blockCounts, overheadClearance } from './block-build.mjs';
import { mvChain } from './block-mv.mjs';
import { kvForMW } from './sld-connect.mjs';
import { createClock, progress, reveal, partial, stageAt, STAGES, TOTAL } from './block-sequence.mjs';
import { createSiteGround } from './plant-ground.mjs';
import { formatNumber, formatLength } from './measure-format.mjs';
import { stringDesign, stringWords, STRING_ADVICE, ILLUSTRATIVE } from './string-design.mjs';
import { rgba } from './elec-style.mjs';
let G = null, X = null; // block-gpu.mjs and block-export.mjs, imported on first use so the section opens as fast as before
export const BLOCK_LABEL = 'Illustrative, not a design for any site.';
const C = { outline: [0.75, 0.75, 0.75, 0.45], tables: [0.62, 0.72, 0.86, 0.8], strings: rgba('dc', 0.75), inverters: [0.95, 0.97, 1, 1],
station: [0.95, 0.97, 1, 1], others: [0.6, 0.67, 0.78, 0.45], rmu: [1, 0.72, 0.35, 1], open: rgba('open'), grid: [0.95, 0.97, 1, 1],
dc: [0.55, 0.62, 0.7, 1], dcLive: rgba('dc'), ac: [0.6, 0.6, 0.62, 1], acLive: rgba('lv'), mv: [0.7, 0.6, 0.55, 1],
mvLive: rgba('mv') }; // energised: colour by voltage level (elec-style.mjs); grey until then
const FPS = 30, CLEAR_M = 40; // CLEAR_M: tables kept this far from an overhead line (assumed; the line owner sets the easement)
const n0 = x => formatNumber(x, 0), n1 = x => formatNumber(x, 1), n2 = x => formatNumber(x, 2);
// deps: { doc, origin(), viewer(), measuredAt(x, y) local, heightAt(x, y) local, towers() -> [{ e, n, kv }], redraw(), animate() }
export function createBlock({ doc, origin, viewer, measuredAt, heightAt, towers = () => [], redraw, animate = () => {} }) {
const $ = id => doc.getElementById(id);
const ground = createSiteGround(), clock = createClock();
const state = { built: null, version: 0, anchor: null, busy: false, stageShown: -1, full: {}, gpuPads: null, playing: false, gpu: null, exp: null };
const say = (msg, warn = false) => { const el = $('block-status'); el.textContent = msg; el.className = warn ? 'warn' : ''; };
const local = (e, n) => [e - origin().e, n - origin().n];
// Modules in series and the coldest cell: the owner's to change (the form, or typed "string 28", "temp min -10").
let cat = null;
const catalogue = () => (cat ||= fetch('./world/data/modules.json', { cache: 'no-cache' }).then(r => (r.ok ? r.json() : null)).catch(() => null));
const formMps = () => Math.round(Number($('block-mps')?.value)) || state.params?.modulesPerString || 30;
const formTmin = () => { const t = $('block-tmin')?.value, v = Number(t); return t != null && t !== '' && Number.isFinite(v) ? v : -10; };
async function design(params = state.params) {
const c = await catalogue(), cls = c?.classes?.find(k => k.id === (globalThis.world?.module?.debug?.()?.class || 'A')) || c?.classes?.[0];
return params && cls ? stringDesign({ cls, cat: c, mps: params.modulesPerString, tempMinC: params.tempMinC }) : null;
}
async function gpuPads() { // optional, read-only: station and compound pads from the GPU run
if (state.gpuPads) return state.gpuPads;
state.gpuPads = [];
try {
const m = (await ground.start()).site, site = m?.name;
if (!m?.staged?.includes('gpu-compounds')) return state.gpuPads; // not staged here: never asked for (no 404)
const r = await fetch(`./world/sites/${site}/gpu-compounds.json`, { cache: 'no-cache' });
const j = r.ok ? await r.json() : null;
if (j?.schema === 'gpu-night-a.compounds/1') state.gpuPads = (j.compounds || []).filter(c => Array.isArray(c.poly) && Number.isFinite(c.level_e))
.map(c => ({ poly: c.poly, level: c.level_e, cut: c.cut_e, fill: c.fill_e }));
} catch { /* none staged: the world's own pad earthworks */ }
return state.gpuPads;
}
// The study's placement and export route show only where their files are staged for this site (user test H9: a
// button that answers 404 is never offered).
async function offerStaged() {
const staged = (await ground.start().catch(() => null))?.site?.staged || []; // the manifest lists what is staged: nothing else is asked for
const has = async dir => staged.includes(dir);
const [gpu, exp] = await Promise.all([has('gpu-prototype'), has('gpu-export')]); // GPU_DIR, EXPORT_DIR
if ($('block-gpu')) $('block-gpu').hidden = !gpu;
if ($('block-export')) $('block-export').hidden = !exp;
return { gpu, exp };
}
const offered = offerStaged();
// params (optional; the form and the viewer fill the rest): { stations, pocKv, at: { e, n } where the block starts }
async function place(params = {}) {
if (state.busy) return null;
state.busy = true; $('block-place').disabled = true;
try {
const v = viewer(), c = params.at ? { e: params.at.e + 16, n: params.at.n - 12 } : toBng(origin(), v.pos[0], v.pos[1]);
const stations = Math.min(10, Math.max(1, Math.round(Number(params.stations ?? $('block-stations').value) || 4)));
// The connection voltage: as asked (typed or chosen), else by the plant's size (sld-connect.mjs, 132 kV at least).
const asked = Number(params.pocKv ?? $('block-poc').value), lines = towers();
const pocKv = [132, 275, 400].includes(asked) ? asked : kvForMW(mvChain({ stations, pocKv: 132 }).exportMW, { minKv: 132 });
if (params.stations) $('block-stations').value = String(stations);
if (params.pocKv) $('block-poc').value = String(pocKv);
const modulesPerString = Math.min(40, Math.max(10, Math.round(Number(params.modulesPerString ?? formMps())) || 30));
const tempMinC = Math.min(15, Math.max(-40, Number(params.tempMinC ?? formTmin())));
if ($('block-mps')) $('block-mps').value = String(modulesPerString);
if ($('block-tmin')) $('block-tmin').value = String(tempMinC);
// The viewer stands in the first aisle, facing north; where an overhead line would cross the tables the block
// steps east (60 m at a time, up to 1.2 km) until every table is at least CLEAR_M from it.
let anchor = [c.e - 16, c.n + 12], moved = 0;
for (let k = 0; k <= 20; k++) {
const o = overheadClearance([anchor[0] + 60 * k, anchor[1]], stations, lines);
if (!o || o.distanceM >= CLEAR_M) { moved = 60 * k; break; }
}
anchor = [anchor[0] + moved, anchor[1]];
const mv = mvChain({ stations, pocKv }), e1 = anchor[0] + mv.compound.x + mv.compound.w, n1 = anchor[1] + mv.rows * 800;
say('Reading the measured ground under the block…');
await ground.loadFor({ e0: anchor[0] - 40, n0: anchor[1] - 80, e1, n1 }).catch(() => null);
const sample = ground.sampler();
const measured = (e, n) => { const h = sample(e, n); if (Number.isFinite(h)) return h; const [x, y] = local(e, n); return measuredAt(x, y); };
const fallback = (e, n) => { const [x, y] = local(e, n); return heightAt(x, y); };
state.gpu = null;
if (params.trench) state.trench = { ...params.trench }; // sizing inputs typed on the command line (soil, load, split)
const b = buildBlock({ anchor, ground: measured, fallback, stations, pocKv, towers: lines, gpuPads: await gpuPads(), modulesPerString, trench: state.trench || {} });
for (const k of ['dc', 'ac', 'mv']) state.full[k] = cableGroup(b.cables[k], k === 'mv' ? null : 'inverter');
// The string check first, then the block goes live and its readout is written in the same step (no half-placed block).
const params1 = { stations, pocKv, modulesPerString, tempMinC }, string1 = await design(params1);
state.built = b; state.anchor = anchor; state.params = params1; state.string = string1; state.version++; state.stageShown = -1;
clock.finish(); refreshItems(); showReadout(b); redraw();
if (params.frame) { // from the button: the drone frames the whole block (user test: it was hard to find)
const e0 = anchor[0] - 40, n0 = anchor[1] - 80, span = Math.max(e1 - e0, n1 - n0);
globalThis.world?.flyTo?.((e0 + e1) / 2, (n0 + n1) / 2 - span * 0.35, { height: Math.min(1500, Math.max(150, span * 0.6)), seconds: 1.2 });
}
say(`${BLOCK_LABEL} Placed${moved ? `, ${moved} m east of you to keep ${CLEAR_M} m from the overhead line` : ''}. Play builds it in sequence.`);
return counts();
} catch (e) { say(e.message, true); return null; }
finally { state.busy = false; $('block-place').disabled = false; }
}
// GPU-checked placement (block-gpu.mjs): the study's prototype station where the GPU placed it, its build as the feed.
async function placeGpu() {
if (state.busy) return null;
state.busy = true;
try {
const site = (await ground.start()).site?.name;
say('Reading the GPU-checked placement…');
G ||= await import('./block-gpu.mjs');
const f = await G.loadPrototype(site), p = G.parsePrototype(f.layout, f.sequence, f.receipt);
await ground.loadFor(p.bbox).catch(() => null);
const sample = ground.sampler(), measured = (e, n) => { const h = sample(e, n); if (Number.isFinite(h)) return h; const [x, y] = local(e, n); return measuredAt(x, y); };
state.built = null; state.gpu = { p, feed: G.buildFeed(p, measured) }; state.version++; state.stageShown = -1;
clock.finish(); refreshItems(); showGpu(state.gpu); redraw();
say(G.GPU_LABEL);
return gpuCounts();
} catch (e) { say(e.message, true); return null; }
finally { state.busy = false; }
}
// Export route (block-export.mjs): the study's route to the nearest 33 kV substation, its HDD candidates and trench floor.
// A toggle, drawn alongside whatever else the block shows; nothing is loaded until it is first pressed.
async function showExport(on = !state.exp) {
if (state.busy) return null;
const btn = $('block-export');
if (!on) { state.exp = null; btn?.setAttribute('aria-pressed', 'false'); redraw(); say('Export route hidden.'); return null; }
state.busy = true;
try {
const site = (await ground.start()).site?.name;
say('Reading the export route…');
X ||= await import('./block-export.mjs');
const f = await X.loadExport(site), p = X.parseExport(f.route, f.witness);
const sample = ground.sampler(), at = (e, n) => { const h = sample(e, n); if (Number.isFinite(h)) return h; const [x, y] = local(e, n); return measuredAt(x, y); };
state.exp = { p, groups: X.buildExport(p, at), v: ++state.version };
btn?.setAttribute('aria-pressed', 'true');
const rows = X.exportRows(p, { n0, len: formatLength });
$('block-readout').replaceChildren(...rows.flatMap(([k, t]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = t; return [dt, dd]; }));
redraw(); say(X.EXPORT_LABEL);
return { points: p.pts.length, hdd: p.hdd.length, lengthM: p.lengthM, spoil: p.spoil.electron, groups: state.exp.groups.map(g => g.key) };
} catch (e) { say(e.message, true); return null; }
finally { state.busy = false; }
}
const exportBatches = () => (state.exp ? state.exp.groups.map(g => ({ key: 'block-export-' + g.key, version: `x${state.exp.v}`,
positions: g.v, color: X.COLORS[g.key], origin: o3(g.base) })) : []);
const gpuCounts = () => (state.gpu ? { steps: state.gpu.p.steps.length, groups: state.gpu.feed.groups.length, twisted: state.gpu.p.flags.twisted,
reveal: state.gpu.p.flags.reveal, unmeasured: state.gpu.feed.unmeasured } : null);
const gpuHour = () => clock.t() / TOTAL * state.gpu.p.hours;
function gpuBatches() {
const h = gpuHour(), out = [];
for (const g of state.gpu.feed.groups) out.push(prefix('gpu-' + g.key, { v: g.v, base: g.base }, G.countAt(g, h), G.COLORS[g.key]));
const s = G.feedStage(state.gpu.p, h);
if (s !== state.stageShown) { state.stageShown = s; $('block-stage').textContent = s; }
if (state.playing && !clock.playing()) { state.playing = false; clock.pause(); animate(); say(`${G.GPU_LABEL} Built.`); }
return out.filter(Boolean);
}
function showGpu({ p, feed }) {
const v = viewer(), c = toBng(origin(), v.pos[0], v.pos[1]), n = k => p.steps.filter(s => s.kind === k).length;
const tw = p.tables.map(t => t.twist).filter(Number.isFinite), f = p.flags;
const rows = [['Placed at', `${n1(p.origin[0])} E, ${n1(p.origin[1])} N · heading ${n0(p.heading)}° · ${formatLength(Math.hypot(p.origin[0] - c.e, p.origin[1] - c.n))} from you`],
['Mean slope', `${n2(p.slope.electron)} % (checked pair ${n2(p.slope.positron)} %)${p.photons.length ? ` · ${p.photons.length} disagreement (${p.photons.join(', ')}), counted` : ''}`],
['Tables', `${p.tables.length} · twist ${n2(Math.min(...tw))} to ${n2(Math.max(...tw))}° · ${f.twisted} over the assumed ${n1(p.tol)}° (drawn orange)`],
['Piles', f.piles ? `${n0(f.piles)} · ${f.reveal} with a reveal outside the assumed ±${n2(f.revealAdjust)} m adjustment` : 'reveal flags not staged'],
['Build feed', `${p.steps.length} steps over ${n0(p.hours)} working hours (assumed rates): ${Object.keys(G.WORDS).map(k => `${n(k)} ${G.WORDS[k].toLowerCase()}`).join(', ')}`],
['Ground', feed.unmeasured ? `${n0(feed.unmeasured)} points off the measured tiles were left out` : 'all on measured LiDAR ground'],
['Basis', G.GPU_LABEL + (p.receipt ? ` Receipt ${p.receipt.slice(0, 12)}.` : '')]];
$('block-readout').replaceChildren(...rows.flatMap(([k, t]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = t; return [dt, dd]; }));
}
// All cables of a kind as one line group; marks per inverter (DC, AC) or per circuit (MV).
function cableGroup(list, by) {
const v = [], marks = [], base = list[0].points[0];
list.forEach((c, i) => {
for (let k = 1; k < c.points.length; k++) for (const p of [c.points[k - 1], c.points[k]]) v.push(p[0] - base[0], p[1] - base[1], p[2] - base[2]);
if (!by || i === list.length - 1 || list[i + 1][by] !== c[by]) marks.push(v.length / 3);
});
return { base, v: new Float32Array(v), marks, items: by ? [...new Set(list.map(c => c[by]))].map(k => list.filter(c => c[by] === k)) : list.map(c => [c]) };
}
// ---- drawing: a prefix of each group for the time on the clock ----
const o3 = base => [base[0] - origin().e, base[1] - origin().n, base[2]];
const prefix = (key, G, count, color) => (count > 0 && G.v.length ? { key: 'block-' + key, version: `${state.version}:${count}`,
positions: G.v.subarray(0, count * 3), color, origin: o3(G.base) } : null);
const upto = (G, whole) => (whole > 0 ? G.marks[Math.min(whole, G.marks.length) - 1] : 0);
function pulling(key, F, r, color) { // the item being pulled in now: its cables so far
if (!r.part || r.whole >= F.items.length) return null;
const v = [], base = F.base;
for (const c of F.items[r.whole]) {
const pts = partial(c.points, r.part);
for (let k = 1; k < pts.length; k++) for (const p of [pts[k - 1], pts[k]]) v.push(p[0] - base[0], p[1] - base[1], p[2] - base[2]);
}
return v.length ? { key: 'block-pull-' + key, version: `${state.version}:${r.whole}:${r.part.toFixed(4)}`, positions: new Float32Array(v), color, origin: o3(base) } : null;
}
function batches() { return [...blockBatches(), ...exportBatches()]; }
function blockBatches() {
if (state.gpu) return gpuBatches();
const b = state.built;
if (!b) return [];
const P = progress(clock.t()), G = b.groups, out = [];
const whole = (k, f) => upto(G[k], reveal(G[k].marks.length, f).whole);
out.push(prefix('outline', G.outline, upto(G.outline, 1), C.outline), prefix('others', G.others, G.others.v.length / 3, C.others));
out.push(prefix('tables', G.tables, whole('tables', P.tables), C.tables), prefix('strings', G.strings, whole('strings', P.strings), C.strings));
out.push(prefix('inverters', G.inverters, whole('inverters', P.inverters), C.inverters));
const live = P.station >= 1, grid = P.grid >= 1;
for (const [k, f, col] of [['dc', P.dc, live ? C.dcLive : C.dc], ['ac', P.ac, live ? C.acLive : C.ac], ['mv', P.mv, grid ? C.mvLive : C.mv]]) {
const F = state.full[k], r = reveal(F.items.length, f);
out.push(prefix(k, F, upto(F, r.whole), col), pulling(k, F, r, col));
}
if (P.station > 0) out.push(prefix('station', G.station, upto(G.station, 1), C.station));
if (P.mv > 0) out.push(prefix('rmu', G.rmu, G.rmu.v.length / 3, C.rmu));
if (P.mv >= 1) out.push(prefix('open', G.open, G.open.v.length / 3, C.open));
if (P.grid > 0) out.push(prefix('grid', G.grid, G.grid.v.length / 3, grid ? C.mvLive : C.grid));
tick(); refreshItems();
return out.filter(Boolean);
}
// While playing: say the stage when it changes; at the end, stop asking for frames.
function tick() {
const s = stageAt(clock.t());
if (s.index !== state.stageShown) { state.stageShown = s.index; $('block-stage').textContent = `Stage ${s.index + 1} of ${STAGES.length}: ${s.label}`; }
if (state.playing && !clock.playing()) { state.playing = false; clock.pause(); animate(); say(`${BLOCK_LABEL} Built and energised.`); }
}
// Trenches open once their stage starts: DC and AC during the first stage, the ring trenches with the 33 kV stage.
// Called once a frame (batches) and on every control, never from the ground lookups: those only read items.
let items = { key: '', list: [] }, dcac = [], mvT = [];
function refreshItems() {
const b = state.built;
if (!b) { if (items.key) items = { key: '', list: [] }; return; }
if (items.version !== state.version) { dcac = b.trenches.filter(t => t.stage !== 'mv'); mvT = b.trenches.filter(t => t.stage === 'mv'); }
const P = progress(clock.t()), n = Math.min(dcac.length, reveal(dcac.length, P.trenches).whole + (P.trenches > 0 ? 1 : 0));
const k = `${state.version}:${n}:${P.mv > 0}`;
if (k !== items.key) items = { key: k, version: state.version, list: [...dcac.slice(0, n), ...(P.mv > 0 ? mvT : [])] };
}
// ---- controls ----
function play() {
if (!state.built && !state.gpu) { say('Place the block first.', true); return false; }
clock.play(); state.playing = true; refreshItems(); animate(); redraw(); return true;
}
function pause() { clock.pause(); state.playing = false; refreshItems(); animate(); redraw(); }
function step() { if (!state.built && !state.gpu) return; clock.step(); state.playing = false; refreshItems(); animate(); redraw(); }
function clear() {
state.built = null; state.gpu = null; state.version++; clock.finish(); state.playing = false; refreshItems(); animate();
$('block-readout').replaceChildren(); $('block-stage').textContent = ''; redraw();
}
const counts = () => (state.built ? blockCounts(state.built) : null);
// The cable check in the main readout (user test H6): read once from the staged schedule, said in neutral words.
let cableLine = null;
function readCableLine() {
if (cableLine !== null) return;
cableLine = 'reading the staged cable schedule…';
Promise.all([import('./cable-checks.mjs'), import('./cable-checks-ui.mjs')])
.then(async ([C, U]) => { cableLine = C.checkLine(C.parseChecks(await U.loadStaged())); })
.catch(() => { cableLine = 'no cable schedule is staged for this site'; })
.then(() => { if (state.built) showReadout(state.built); });
}
function showReadout(b) {
readCableLine();
const i = b.summary.inventory, s = b.summary, mv = b.mv, km = m => `${n2(m / 1000)} km`;
const tp = b.trenchPlan;
const pad = s.pads[0], cp = s.compoundPad;
const rows = [['Tables', `${i.tables} paired tables · ${n1(i.tableKwp)} kWp each · ${n0(s.blockKwp)} kWp DC`],
['Strings', `${i.totalStrings} (${i.connectedStrings} connected, ${i.spareStrings} spare) · ${i.modulesPerString} modules, ${n1(i.stringKwp)} kWp`],
...stringRows(state.string),
['Inverters', `${i.inverters} × ${i.inverterKVA} kVA · ${i.stringsPerInverter[0]} strings in parallel each (12 MPPT × 2), 48 DC conductors`],
['Station', `${i.transformers} × ${i.transformerMVA} MVA = ${i.aggregateTransformerMVA} MVA · ${i.invertersPerTransformer} inverters each`],
['AC phase cables', `${i.acPhaseCables} × ${i.acAreaMm2} mm² Al, 800 V, ${i.formation}`], ['DC home cables', n0(i.dcHomeCables)],
['Piles', `${n0(s.piles.count)} in station 1, automatic · ${n2(s.piles.min)} to ${n2(s.piles.max)} m out of the measured ground`],
['Pile metres', `${n0(s.piles.totalPileLengthM)} m in all; ${n0(s.piles.embeddedM)} m embedded (${n2(s.piles.embedM)} m each, provisional)`],
['Pile flags', `${n0(s.piles.revealAdjust)} outside ±${n2(s.piles.revealAdjustM)} m adjustment · ${n0(s.piles.outsideBand)} outside the band · `
+ `${n0(s.piles.twistTables)} twist over ${n1(s.piles.twistTolDeg)}° · ${n0(s.piles.gradingTables)} post lines need grading (illustrative rules)`],
['Lowest module edge', `${n2(s.lowEdgeMin)} m above the ground at its lowest`],
['Station pad', `level ${n2(pad.level)} m · cut ${n0(pad.cut)} m³, fill ${n0(pad.fill)} m³`],
['Trenches', `routes: DC ${km(tp.summary.dc?.metres || 0)} · AC ${km(tp.summary.ac?.metres || 0)} · 33 kV ${km(tp.summary.mv?.metres || 0)}; `
+ `${tp.totals.trenches} trenches dug, ${km(tp.totals.dugM)} in all (side-by-side trenches each counted)`],
...(tp?.rows || []),
['33 kV feeders', `${mv.rings.length} for ${mv.stations.length} stations (${mv.perRing} a feeder by the feeder limit)`],
...mv.rings.map(r => ['', `${r.id}: ${r.stations.join(' + ')} · ${[...new Set(r.hops.map(h => h.areaMm2))].join(' / ')} mm² Al · `
+ (r.openAt ? `ring, open at ${r.openAt} · drop ${n2(r.dropPct)} % (${n2(r.outageDropPct)} % one end out)` : `radial · drop ${n2(r.dropPct)} %`)]),
['MV board', `${mv.sections} section${mv.sections > 1 ? 's, normally-open bus tie' : ''} · ${mv.rings.reduce((t, r) => t + (r.openAt ? 2 : 1), 0)} feeder ways`],
['Grid transformer', `${mv.grid.units} × ${mv.grid.mva} MVA ${mv.poc.kv}/33 kV${mv.grid.smallest ? ' (smallest standard size)' : ''}`],
['Compound pad', `level ${n2(cp.level)} m · cut ${n0(cp.cut)} m³, fill ${n0(cp.fill)} m³${cp.source ? ' · ' + cp.source : ''}`],
['Connection', `${mv.poc.kv} kV (${n0(mv.exportMW)} MW export), `
+ (mv.poc.kv >= 275 ? 'HV cable, fully ducted and unjointed, to a substation bay: no tee at this voltage'
: 'cable to the network operator substation, or a tee into a 132 kV line where no substation is near')
+ '; the route and landing are in the Single-line diagram and Follow'],
...(s.overhead ? [['Overhead line', `${s.overhead.kv} kV line ${formatLength(s.overhead.distanceM)} from the nearest table corner` +
(s.overhead.distanceM < CLEAR_M ? ` (under ${CLEAR_M} m: move the block)` : '')]] : []),
['Ground', s.unmeasured ? `${n0(s.unmeasured)} points off the measured tiles took the nearest ground` : 'all on measured LiDAR ground'],
['Basis', `${BLOCK_LABEL} Geometry and counts from a generic 10 MVA station; ring sizes from generic rating rules.`]];
rows.push(['Cable check', cableLine]);
$('block-readout').replaceChildren(...rows.flatMap(([k, v, cls]) => {
const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = v; if (cls) dd.className = cls; return [dt, dd];
}));
}
function stringRows(d) {
if (!d) return [];
const w = stringWords(d);
return [['String voltage', w.string], ['', `Cold Voc ${w.bins}`], ['', STRING_ADVICE], ['', ILLUSTRATIVE]];
}
// A new string length or coldest cell: the block is rebuilt where it stands (tables are three strings long), or, before
// one is placed, the form keeps the values for the next placing.
async function strings({ modulesPerString, tempMinC } = {}) {
if (modulesPerString != null && $('block-mps')) $('block-mps').value = String(modulesPerString);
if (tempMinC != null && $('block-tmin')) $('block-tmin').value = String(tempMinC);
if (!state.built || state.busy) return null;
const p = { ...state.params, modulesPerString: formMps(), tempMinC: formTmin() };
if (p.modulesPerString !== state.params.modulesPerString) return place({ ...p, at: { e: state.anchor[0], n: state.anchor[1] } }).then(() => state.string);
state.params = p; state.string = await design(p); showReadout(state.built); redraw();
return state.string;
}
for (const id of ['block-mps', 'block-tmin']) $(id)?.addEventListener('change', () => { strings(); });
$('block-place').addEventListener('click', () => place({ frame: true }));
$('block-gpu').addEventListener('click', () => placeGpu());
$('block-export')?.addEventListener('click', () => showExport());
$('block-play').addEventListener('click', () => play());
$('block-pause').addEventListener('click', () => pause());
$('block-step').addEventListener('click', () => step());
$('block-clear').addEventListener('click', () => { clear(); say('Block cleared.'); });
say(BLOCK_LABEL);
// The sized trenches (trench-plan.mjs via block-build.mjs), all of them, for the X-ray view and the typed readouts.
const works = () => (state.built ? { version: state.version, items: state.built.trenches, pits: state.built.trenchPlan.pits,
joints: state.built.trenchPlan.joints, totals: state.built.trenchPlan.totals, faults: flagged(state.built.trenchPlan) } : null);
const flagged = tp => [...tp.faults.map(f => `Design fault: ${f}`), ...tp.unrated.map(f => `Not rated: ${f}`)];
const trenchRows = () => state.built?.trenchPlan.rows ?? null, trenchStages = () => state.built?.trenchPlan.summary ?? null;
// The placed block's plan extent (every trench and the anchor), for go block and the view after block 10mva.
function bounds() {
if (!state.built) return null;
const pts = [{ e: state.anchor[0], n: state.anchor[1] }, ...state.built.trenches.flatMap(t => t.path)];
const e0 = Math.min(...pts.map(p => p.e)), e1 = Math.max(...pts.map(p => p.e)), n0 = Math.min(...pts.map(p => p.n)), n1 = Math.max(...pts.map(p => p.n));
return { e: (e0 + e1) / 2, n: (n0 + n1) / 2, w: e1 - e0, h: n1 - n0, height: Math.min(1500, Math.max(150, 0.8 * Math.max(e1 - e0, n1 - n0))) };
}
return { offered: () => offered, place, strings, stringDesign: () => state.string,
placeGpu, showExport, gpuCounts, play, pause, step, clear, batches, trenchItems: () => items.list, counts, animating: () => state.playing,
works, trenchRows, trenchStages, bounds,
fps: FPS, key: () => items.key, // sld-mount.mjs; module-mount.mjs reads .built; hud-ui.mjs reads .params (modules in series, coldest cell)
built: () => (state.built ? { built: state.built, anchor: [...state.anchor], version: state.version, params: { ...state.params } } : null),
boqItems: () => (state.built ? [{ id: 'block-piles', kind: 'piles', pileType: 'block', results: { count: state.built.summary.piles.count,
totalEmbedmentM: state.built.summary.piles.embeddedM, totalPileLengthM: state.built.summary.piles.totalPileLengthM } }] : []),
snapshot: () => ({ placed: !!state.built, t: clock.t(), stage: stageAt(clock.t()).id, playing: state.playing, counts: counts(),
anchor: state.anchor ? [...state.anchor] : null, params: state.built && state.params ? { ...state.params } : null,
compound: state.built ? [state.anchor[0] + state.built.mv.compound.x, state.anchor[1] + state.built.mv.compound.y] : null, trenches: state.built ? state.built.trenches.length : 0,
piles: state.built ? { ...state.built.summary.piles } : null,
gpu: state.gpu ? gpuCounts() : null, exportRoute: state.exp ? { hdd: state.exp.p.hdd.length, lengthM: state.exp.p.lengthM } : null }) };
}