GLOBALGRID2050 / EXPLORE CODE

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

Module Mount and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that mounts modules (`mountModules`), finds pick (`findPick`) and calculates planar distances (units: °C), covering solar and cables.

593 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 165 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Hud Drops transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/hud-drops.mjs lines 1–40
  2. Ground Grid render · globalgrid2050 / solar-design-studio/202609271740-site-world/world/layers/ground-grid.mjs lines 1–158
  3. Legend UI render · globalgrid2050 / solar-design-studio/202609271740-site-world/world/legend-ui.mjs lines 1–95
  4. Measure Format electrical · globalgrid2050 / solar-design-studio/202609271740-site-world/world/measure-format.mjs lines 1–112
  5. Module Mount render · globalgrid2050 / solar-design-studio/202609271740-site-world/world/module-mount.mjs lines 1–188

Hud Drops

A JavaScript module in the world folder of GlobalGrid2050 that works with cables and solar.

transformglobalgrid2050 / solar-design-studio/202609271740-site-world/world/hud-drops.mjs · lines 1–40 of 40 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review)

What it does
It calculates cables and solar. Defines len, dcDrop, acDrop, blockDrops.
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, solar.
Downstream impact
Used directly by 1 file: Hud UI (globalgrid2050).
What it achieves
It is built from the len step (`len`), the dc drop helper (`dcDrop`) and the ac drop helper (`acDrop`). The voltage drops the check HUD shows for the placed solar block, worked out the way Follow works them (`sld-follow.mjs`), so the HUD and Follow give one answer: DC each connected string.
Why it matters
Imported by Hud UI.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Single-Line Diagram (SLD) Source (import), Single-Line Diagram (SLD) Graph (import), Single-Line Diagram (SLD) Calc (import), Single-Line Diagram (SLD) Rules (import)
Used by
imported by Hud UI (dynamic import)
Produces
dcDrop, acDrop, blockDrops
Defines here
len, dcDrop, acDrop, blockDrops
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/hud-drops.mjs:1-40 · blob b6a5cb54aa86dd77d411a008a450af6e4c2cd77b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// hud-drops.mjs: the voltage drops the check HUD shows for the placed solar block, worked out the way Follow works them
// (sld-follow.mjs), so the HUD and Follow give one answer:
//   DC  each connected string: the series loop through its modules and its two home cables, at the string current of the
//       generic module class, over the string's own Vmp (modules in series x module Vmp: the typed series length)
//   AC  each inverter's AC cable, read from the block's single-line network solved in sld-calc.mjs (the Follow AC stop)
// Plan lengths (the ground's rise is left out; Follow adds it, a fraction of a percent of the length on a field).
// Illustrative: cable sizes and module values are the SLD's stated assumptions (sld-rules.mjs). Pure: no DOM.

import { sourceFromBlock } from './sld-source.mjs';
import { buildGraph } from './sld-graph.mjs';
import { solve, readouts } from './sld-calc.mjs';
import { SLD_DEFAULTS } from './sld-rules.mjs';

const len = pts => pts.reduce((t, q, i) => (i ? t + Math.hypot(q[0] - pts[i - 1][0], q[1] - pts[i - 1][1]) : 0), 0);

/** The worst DC string drop of station 1 (every station is the same block moved): { pct, string, lengthM, mps } or null. */
export function dcDrop(built, d = SLD_DEFAULTS) {
  const M = d.module, R = d.dcOhmKm20 / 1000 * (1 + 0.00393 * (d.dcTempC - 20)), dc = built?.cables?.dc || [];
  let worst = null;
  (built?.station?.strings || []).forEach((s, i) => {
    const neg = dc[2 * i], pos = dc[2 * i + 1];
    if (!s.connected || !neg || !pos) return;
    const L = len(s.modules.map(m => m.terminal)) + len(pos.points) + len(neg.points), pct = M.imp * R * L / (M.vmp * s.modules.length) * 100;
    if (!worst || pct > worst.pct) worst = { pct, string: i, lengthM: L, mps: s.modules.length };
  });
  return worst;
}

/** The worst inverter AC cable drop from the block's solved network: { pct, id, lengthM } or null. */
export function acDrop(built, anchor) {
  try {
    const g = buildGraph(sourceFromBlock(built, anchor)), ro = readouts(g, solve(g));
    let worst = null;
    for (const b of g.branches) if (b.kind === 'ac-cable') { const r = ro.branches.get(b.id); if (r && (!worst || r.dropPct > worst.pct)) worst = { pct: r.dropPct, id: b.id, lengthM: b.lengthM }; }
    return worst;
  } catch { return null; }   // a network that does not solve says nothing here; the SLD says why
}

/** Both, for the HUD: { dc, ac } (each may be null). */
export const blockDrops = (built, anchor) => ({ dc: dcDrop(built), ac: acDrop(built, anchor) });

Ground Grid

A JavaScript module in the layers folder of GlobalGrid2050 that works with height store (`heightStore`).

renderglobalgrid2050 / solar-design-studio/202609271740-site-world/world/layers/ground-grid.mjs · lines 1–158 of 158 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern heightStore (shared by 3 files)

What it does
Defines 6 functions or classes, including later, grid, wrap, slotOf, heightStore.
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.
What it achieves
It is built from the later step (`later`), the grid step (`grid`) and the wrap step (`wrap`). A 1 m grid near the viewer and a 10 m grid to the horizon, draped on whatever ground the world has (flat until a terrain layer supplies `heightAt`).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world/layers · JavaScript module
Uses
none found
Used by
none found
Produces
DETAIL, REACH, grid
Defines here
later, grid, wrap, slotOf, heightStore, finite
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/layers/ground-grid.mjs:1-158 · blob ccb2f775cb9dcf7a424e23e6370d8242611c2f16 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Layer: ground grid. A 1 m grid near the viewer and a 10 m grid to the horizon, draped on whatever
// ground the world has (flat until a terrain layer supplies heightAt). The grid follows the viewer in
// 10 m steps, so it looks endless but only ever holds a few thousand lines.
// Within 100 m of the viewer every segment is split to 2 m or less, so the grid follows real banks and
// ditches rather than bridging them. Batches carry an origin at the centre of the viewer's 10 m cell and
// positions relative to it, so they stay sharp on the GPU. The grid is rebuilt on a new cell or new ground.
//
// Cost: every grid point is a heightAt call, and real terrain makes those dear (about 45,000 per rebuild
// before, when each segment asked for both ends). Now each point is asked for once: heights are kept in
// a store for one ground (one heightAt and groundVersion), so stepping into a new 10 m cell only asks for
// the strip of points that came into view. New ground starts a new store and nothing old is trusted: the
// first frame asks again for everything within 50 m (the 1 m grid and the nearest banks and ditches), and
// the next few frames widen that to 150 m, 300 m and the horizon. Until a far point is asked again it is
// drawn at its height on the previous ground, so a new tile never stalls a walk for a whole rebuild.
//
// Measured ground only (v05, phantom plateau): past the loaded terrain tiles the world's heightAt keeps the
// last height it knew, and a grid drawn there is a flat plateau that is not on the ground (up to 59 px of false
// horizon over a valley, GPU ray-cast check). When the page says which ground is measured (ctx.known) and the
// viewer stands on measured ground, a segment is drawn only if both its ends are measured: the grid ends at the
// loaded edge. With no measured ground under the viewer (the empty world) the flat grid is the only ground.

const MINOR = { spacing: 1, radius: 30, color: [156 / 255, 219 / 255, 1, 0.16] };  // #9cdbff
const MAJOR = { spacing: 10, radius: 400, color: [156 / 255, 219 / 255, 1, 0.42] };
const FOLLOW = 10;
export const DETAIL = { radius: 100, step: 2 }; // near the viewer, no segment is longer than 2 m
export const REACH = [50, 150, 300, Infinity];  // metres asked again on the frames after new ground
let cached = { version: null, batches: [] };
let store = null, api = null;

export default {
  id: 'ground-grid',
  init(a) { api = a; },
  // ctx: { pos, heightAt, known?(x, y) -> measured ground there, groundVersion?, origin? }
  lines({ pos, heightAt, known = null, groundVersion = 0 }) {
    const cx = Math.floor(pos[0] / FOLLOW) * FOLLOW, cy = Math.floor(pos[1] / FOLLOW) * FOLLOW;
    const clip = typeof known === 'function' && !!known(cx + FOLLOW / 2, cy + FOLLOW / 2) ? known : null;
    const version = cx + ',' + cy + '@' + groundVersion + (clip ? '/m' : ''), same = cached.version === version && cached.heightAt === heightAt;
    if (same && cached.pass === store.pass) return cached.batches; // new cell, new ground or a wider reach only
    if (!store || !store.fits(heightAt, groundVersion, clip)) store = heightStore(heightAt, groundVersion, cx, cy, api ? store : null, clip);
    const mx = cx + FOLLOW / 2, my = cy + FOLLOW / 2, sample = store.begin(mx, my), mz = sample(mx, my);
    const origin = [mx, my, mz], opts = { origin, near: [mx, my], sample, known: clip && store.knownAt };
    const step = store.pass ? '#' + store.pass : '', tag = version + step;
    const minor = same && cached.minorWhole ? cached.batches[0]
      : { key: 'ground-grid/minor', version: tag, origin, color: MINOR.color, positions: grid(cx, cy, MINOR, heightAt, opts) };
    const minorWhole = !store.partial;
    const major = { key: 'ground-grid/major', version: tag, origin, color: MAJOR.color, positions: grid(cx, cy, MAJOR, heightAt, opts) };
    // No mark at the cell centre (UI polish): its white cross and 10 m staff stood in front of the walker as a white centre
    // line, marked only the middle of a 10 m cell (not the viewer, not any design item) and read as a feature.
    cached = { version, heightAt, pass: store.pass, minorWhole, batches: [minor, major] };
    if (store.partial) later(store); // after this frame: widen the reach and ask for another frame
    return cached.batches;
  }
};

// Only with a live page (init gave an api to ask for frames) does new ground arrive in steps; without
// one, every rebuild asks for every point it lacks.
function later(s) {
  setTimeout(() => { if (s === store && s.partial) { s.widen(); api.invalidate({ ground: false }); } }, 0);
}

// Lines of the grid centred on (cx, cy). Positions are relative to opts.origin ([0, 0, 0] by default).
// Segments whose midpoint lies within DETAIL.radius of opts.near are split to DETAIL.step or less.
// opts.sample(x, y, guess), if given, is used in place of heightAt and must return a finite height; guess is
// the height of the point before it on the line (the origin's for the first), for a sampler that may guess.
// opts.known(x, y), if given, says where ground is measured: a segment is left out unless both its ends are.
export function grid(cx, cy, { spacing, radius }, heightAt, { origin = [0, 0, 0], near = null, sample = null, known = null } = {}) {
  const h = sample || ((x, y) => finite(heightAt(x, y)));
  const n = Math.round(radius / spacing), pieces = spacing > DETAIL.step ? Math.ceil(spacing / DETAIL.step) : 1;
  const [ox, oy, oz] = origin, r2 = DETAIL.radius * DETAIL.radius;
  // How many pieces the segment from b0 to b0 + spacing along a line at offset a is cut into.
  const split = pieces > 1 && near
    ? (ax, ay, bx, by) => { const dx = (ax + bx) / 2 - near[0], dy = (ay + by) / 2 - near[1]; return dx * dx + dy * dy <= r2 ? pieces : 1; }
    : () => 1;
  let count = 0;
  for (let i = -n; i <= n; i++) {
    const a = i * spacing;
    for (let j = -n; j < n; j++) {
      const b0 = j * spacing, b1 = b0 + spacing;
      count += split(cx + a, cy + b0, cx + a, cy + b1) + split(cx + b0, cy + a, cx + b1, cy + a);
    }
  }
  const out = new Float32Array(count * 6);
  let w = 0;
  for (let i = -n; i <= n; i++) {
    const a = i * spacing;
    for (let dir = 0; dir < 2; dir++) { // 0: north-south line at x = cx + a; 1: east-west line at y = cy + a
      let px = dir ? cx - n * spacing : cx + a, py = dir ? cy + a : cy - n * spacing, pz = h(px, py, oz);
      let pk = !known || !!known(px, py);
      for (let j = -n; j < n; j++) {
        const b0 = j * spacing, b1 = b0 + spacing;
        const x0 = dir ? cx + b0 : cx + a, y0 = dir ? cy + a : cy + b0, x1 = dir ? cx + b1 : cx + a, y1 = dir ? cy + a : cy + b1;
        const k = split(x0, y0, x1, y1);
        for (let p = 0; p < k; p++) {
          const qx = x0 + (x1 - x0) * (p + 1) / k, qy = y0 + (y1 - y0) * (p + 1) / k, qz = h(qx, qy, pz); // whole metres stay whole
          const qk = !known || !!known(qx, qy);
          if (pk && qk) {
            out[w++] = px - ox; out[w++] = py - oy; out[w++] = pz - oz;
            out[w++] = qx - ox; out[w++] = qy - oy; out[w++] = qz - oz;
          }
          px = qx; py = qy; pz = qz; pk = qk;
        }
      }
    }
  }
  return w < out.length ? out.slice(0, w) : out;
}

// Heights asked for once per ground, kept in fixed typed arrays that wrap around as the viewer walks
// (no Map, nothing to trim). A whole-metre point on a 10 m line has a slot in one of two line planes;
// any other whole-metre point near the viewer has one in the inner plane; each slot remembers which point
// and which ground it holds. Other points go straight to heightAt. A store serves one heightAt and one
// groundVersion (and one known, whose answers it keeps beside the heights). When the store before it had the same heightAt, a new store asks only within its reach
// of the centre and answers further points from older ground (or the guess), marking itself partial.
const LINES = 2 * Math.ceil(MAJOR.radius / MAJOR.spacing) + 4, ALONG = 2 * MAJOR.radius + 4 * FOLLOW, INNER = 2 * MINOR.radius + 12;
let slots = null, generation = 0;
const wrap = (v, m) => ((v % m) + m) % m;
function slotOf(x, y) {
  if ((x | 0) !== x || (y | 0) !== y) return -1;
  if (x % MAJOR.spacing === 0) return wrap(x / MAJOR.spacing, LINES) * ALONG + wrap(y, ALONG);
  if (y % MAJOR.spacing === 0) return (LINES + wrap(y / MAJOR.spacing, LINES)) * ALONG + wrap(x, ALONG);
  return 2 * LINES * ALONG + wrap(x, INNER) * INNER + wrap(y, INNER);
}
function heightStore(heightAt, groundVersion, cx, cy, before, known = null) {
  if (!slots) {
    const n = 2 * LINES * ALONG + INNER * INNER;
    slots = { z: new Float64Array(n), x: new Int32Array(n).fill(-0x80000000), y: new Int32Array(n), gen: new Uint32Array(n), k: new Uint8Array(n) };
  }
  const { z, x: sx, y: sy, gen, k: kn } = slots, g = ++generation;
  const guessing = !!before && before.heightAt === heightAt;
  let pass = guessing ? 0 : REACH.length - 1, reach2 = REACH[pass] ** 2, mx = 0, my = 0;
  const self = {
    heightAt, partial: false,
    get pass() { return pass; },
    sample(x, y, guess = 0) {
      const k = slotOf(x, y);
      if (k < 0) return finite(heightAt(x, y));
      const held = sx[k] === x && sy[k] === y;
      if (held && gen[k] === g) return z[k];
      if ((x - mx) ** 2 + (y - my) ** 2 > reach2) { self.partial = true; return held ? z[k] : guess; } // older ground
      const h = finite(heightAt(x, y));
      z[k] = h; sx[k] = x; sy[k] = y; gen[k] = g; kn[k] = known && known(x, y) ? 1 : 0;
      return h;
    },
    // Whether (x, y) is measured, for a point sample has just answered: a slot keeps the answer with its height;
    // a far point answered from older ground is taken as unmeasured until it is asked again.
    knownAt(x, y) {
      const k = slotOf(x, y);
      if (k < 0) return !!known(x, y);
      return sx[k] === x && sy[k] === y && gen[k] === g ? kn[k] === 1 : false;
    },
    begin(x, y) { mx = x; my = y; self.partial = false; return self.sample; },
    widen() { pass = Math.min(pass + 1, REACH.length - 1); reach2 = REACH[pass] ** 2; },
    fits: (f, gv, kf = null) => f === heightAt && gv === groundVersion && kf === known && g === generation
  };
  return self;
}

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

Legend UI

A JavaScript module in the world folder of GlobalGrid2050 that works with legend rows (`legendRows`) (units: kV), covering solar and cables.

renderglobalgrid2050 / solar-design-studio/202609271740-site-world/world/legend-ui.mjs · lines 1–95 of 95 · version 2026-09-27 17:40 · pattern labelFor (shared by 10 files)

What it does
It draws solar and cables. Defines 8 functions or classes, including same, rgbOf, words, labelFor, legendRows. Side effects: changes the web page (DOM).
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: solar, cables.
Downstream impact
Used directly by 1 file: Substrate (globalgrid2050). Reached from 1 other entry point, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/).
What it achieves
It is built from the same step (`same`), the RGB of helper (`rgbOf`) and the words step (`words`). The compact key. One small "Key" fold at the bottom left; opened, it lists what the last frame drew, one row per colour: a swatch (dashed for earth) and plain words. It responds to toggle events.
Why it matters
Imported by Substrate.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Layers Panel (import), Grid (import), Elec Style (import)
Used by
imported by Substrate (dynamic import)
Produces
labelFor, legendRows, mountLegend
Defines here
same, rgbOf, words, labelFor, legendRows, css, mountLegend, draw
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/legend-ui.mjs:1-95 · blob 6ce62baaeeb67a3e6aa1f6ef10797fa21caf534e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// legend-ui.mjs: the compact key. One small "Key" fold at the bottom left; opened, it lists what the last frame drew, one
// row per colour: a swatch (dashed for earth) and plain words. Built from the drawn line batches themselves, so it names
// only what is on screen. Electrical classes take their words from the one table
// (elec-style.mjs); grid lines their voltage from the grid layer's own colour table. Nothing is drawn for it: it reads
// the batches only after a frame the world drew anyway, and only while open (0 fps when still).
// Loaded just after the first frame (substrate.mjs).

import { OPTIONAL_LAYERS } from './layers-panel.mjs';
import { COLORS as GRID_COLORS } from './layers/grid.mjs';
import { ELEC } from './elec-style.mjs';

const MAX_ROWS = 14;
const BASE = { 'ground-grid': 'Ground grid, 1 m and 10 m', terrain: 'Ground', 'place-pin': 'Place found', sld: 'Single-line symbols',
  block: 'Solar block', plant: 'Plant layout', design: 'Design', piles: 'Piles', module: 'Module detail' };
// Words for the parts of the solar block and the single-line symbols, by the electrical class they belong to.
const PART = { strings: 'dc', dc: 'dc', 'pull-dc': 'dc', 'gpu-dc-cables-pulled': 'dc', ac: 'lv', 'pull-ac': 'lv', 'gpu-ac-cables-pulled': 'lv',
  lv: 'lv', mv: 'mv', 'pull-mv': 'mv', hv: 'hv', rmu: 'mv', open: 'open', earth: 'earth', glow: 'glow' };
const LABELS = new Map(OPTIONAL_LAYERS.map(l => [l.id, l.label]));
const same = (a, b) => a && b && [0, 1, 2].every(i => Math.abs(a[i] - b[i]) < 0.02);
const SKIP = /^(zone|line|minor|major|ticks|origin)$/; // parts of a key that say how it is drawn, not what it is
const rgbOf = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255);
const words = s =>s.replace(/[-_]+/g, ' ').replace(/ILLUSTRATIVE|HYPOTHETICAL/g, '').trim();

/** One batch's words for the key, or null for batches the key leaves out (a design's own labels say what they are). */
export function labelFor(b) {
  const key = String(b?.key || ''), parts = key.split('/'), head = parts[0];
  if (head === 'grid' && parts[1] === 'line') {
    const kv = Object.keys(GRID_COLORS).find(k => same(GRID_COLORS[k], b.color));
    return `Grid line${kv ? ', ' + kv.replace('kV', ' kV') : ''}`;
  }
  if (head === 'grid') return 'Substation';
  if (BASE[key]) return BASE[key];
  const dash = key.indexOf('-'), stem = dash > 0 ? key.slice(0, dash) : key;
  if (BASE[stem] && dash > 0 && !key.includes('/')) {                 // sld-mv, block-pull-dc, plant-tables
    const part = key.slice(dash + 1), cls = (stem === 'sld' || stem === 'block') && ELEC[PART[part]];
    if (!cls) return `${BASE[stem]}: ${words(part)}`;
    // A cable drawn grey is not energised yet (the block's build): the key says so rather than borrow the live colour.
    return same(rgbOf(cls.hex), b.color) ? cls.label : `${cls.label}, not yet energised`;
  }
  const layer = LABELS.get(head) || BASE[head] || BASE[stem];
  if (!layer) return null;
  const last = parts.length > 1 ? parts.at(-1) : '', sub = /^[a-z][a-z -]*$/i.test(last) && !SKIP.test(last) ? words(last) : '';
  return sub ? `${layer}: ${sub}` : layer;
}

/** legendRows(batches) -> [{ label, color: [r, g, b, a], dash }]: one row per label, in the order first drawn. */
export function legendRows(batches) {
  const out = new Map();
  for (const b of batches || []) {
    if (!b?.color || out.size >= MAX_ROWS) continue;
    const label = labelFor(b);
    if (label && !out.has(label)) out.set(label, { label, color: b.color, dash: /earth|bond/i.test(label) });
  }
  return [...out.values()];
}

const CSS = `#legend { position: fixed; left: 10px; bottom: calc(var(--foot, 20px) + 30px); z-index: 3; max-width: min(280px, calc(100vw - 20px));
  background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; color: var(--dim); font-size: 11px; }
#legend > summary { cursor: pointer; list-style: none; min-height: var(--btn); display: flex; align-items: center; padding: 0 10px; color: var(--text); }
#legend > summary::-webkit-details-marker { display: none; }
#legend ul { list-style: none; margin: 0; padding: 0 10px 8px; max-height: 40vh; overflow: auto; display: grid; gap: 3px; }
#legend li { display: flex; align-items: center; gap: 8px; }
#legend i { flex: none; width: 18px; height: 0; border-top: 3px solid; } #legend i.dash { border-top-style: dashed; }
body[data-panel] #legend, body[data-cmd] #legend, body:has(#sld-follow:not([hidden])) #legend { display: none; }
body.sun-on #legend { bottom: calc(var(--foot, 20px) + var(--sun-h, 0px) + 34px); } /* above the time bar */
/* Touch: right of the move pad, level with it (the plan inset sits above the pad, Up and Down on the right). */
@media (pointer: coarse) { #legend { left: 156px; bottom: calc(var(--foot, 33px) + 36px); max-width: calc(100vw - 230px); }
  body.sun-on #legend { bottom: calc(var(--foot, 33px) + var(--sun-h, 0px) + 16px); } }
@media print { #legend { display: none; } }`;

const css = c => `rgba(${c.slice(0, 3).map(v => Math.round(v * 255)).join(', ')}, ${Math.max(0.6, c[3] ?? 1)})`;

// deps: { api (substrate: batches(), hooks.after), doc }
export function mountLegend({ api, doc = document }) {
  if (!doc.getElementById('legend-style')) { const s = doc.createElement('style'); s.id = 'legend-style'; s.textContent = CSS; doc.head.append(s); }
  const box = doc.createElement('details'), sum = doc.createElement('summary'), list = doc.createElement('ul');
  box.id = 'legend'; sum.textContent = 'Key'; sum.title = 'What the colours on screen mean'; box.append(sum, list);
  doc.body.append(box);
  let shown = '', last = 0;
  const draw = () => {
    const rows = legendRows(api.batches()), key = rows.map(r => r.label + css(r.color)).join('|');
    sum.textContent = `Key · ${rows.length}`;
    if (key === shown) return;
    shown = key;
    list.replaceChildren(...rows.map(r => {
      const li = doc.createElement('li'), sw = doc.createElement('i'), t = doc.createElement('span');
      sw.style.borderTopColor = css(r.color); if (r.dash) sw.className = 'dash';
      t.textContent = r.label; li.append(sw, t); return li;
    }));
  };
  box.addEventListener('toggle', () => { if (box.open) draw(); });
  // After frames the world drew anyway: at most twice a second, and only while the key is open.
  api.hooks.after.add(now => { if (box.open && now - last > 500) { last = now; draw(); } });
  return { element: box, rows: () => legendRows(api.batches()), open: on => { box.open = on !== false; if (box.open) draw(); return legendRows(api.batches()); } };
}

Measure Format

A JavaScript module in the world folder of GlobalGrid2050 that works with cables. It formats number (`formatNumber`), formats length (`formatLength`) and formats area (`formatArea`).

electricalglobalgrid2050 / solar-design-studio/202609271740-site-world/world/measure-format.mjs · lines 1–112 of 112 · version 2026-09-27 17:40 · pattern fmtVolt (shared by 3 files)

What it does
It calculates cables. Defines 16 functions or classes, including formatNumber, formatLength, formatArea, formatVolume, formatGradient.
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.
Downstream impact
Used directly by 11 files: Design Earthworks (globalgrid2050); Block UI (globalgrid2050); Single-Line Diagram (SLD) Follow (globalgrid2050); Single-Line Diagram (SLD) Mount (globalgrid2050); and 7 more. Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
Plain British English lines from the numbers `measure.mjs` returns.
Why it matters
Imported by 11 files, including Design Earthworks, Block UI and Single-Line Diagram (SLD) Follow.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
none found
Used by
imported by Design Earthworks (import), imported by Block UI (import), imported by Single-Line Diagram (SLD) Follow (import), imported by Single-Line Diagram (SLD) Mount (import), imported by Cmd Model (import), imported by Cmd Run (import), imported by Design Sections (import), imported by Design UI (import), and 3 more
Produces
formatNumber, formatLength, formatArea, formatVolume, formatGradient, formatTrenchLine, formatCableLine, formatPlatformLine, formatProfileLine, NONE, fmtSig, fmtQ
Defines here
formatNumber, formatLength, formatArea, formatVolume, formatGradient, plural, belowPhrase, formatTrenchLine, formatCableLine, formatPlatformLine, formatProfileLine, fmtSig, fmtQ, fmtPct, fmtLen, fmtVolt
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/measure-format.mjs:1-112 · blob 204916217d9f503d91e3f322b1e0cf925916aa37 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// measure-format.mjs: plain British English lines from the numbers measure.mjs
// returns. Pure: no imports, no DOM. Parts are joined with " · ", for example
//   "Trench 124.6 m (3D 125.1 m) · spoil 98.4 m³ · 1 bend below 1.05 m"
// Inputs are the summary objects from measure.mjs (trenchSummary, cableSummary,
// cutFillForPlatform, profile); nothing is recomputed here.

const SEP = ' · ';

/** 1234.56 -> "1,234.6" (comma thousands, point decimal). */
export function formatNumber(x, dp = 1) {
  if (x == null || !Number.isFinite(x)) return 'n/a';
  const v = Math.abs(x) < 0.5 * 10 ** -dp ? 0 : x;   // no "-0.0"
  // Rounded as written in decimal (0.825 -> "0.83"), not as the nearest binary double happens to fall (toFixed gives 0.82).
  const [i, f] = Math.abs(v).toLocaleString('en-GB', { minimumFractionDigits: dp, maximumFractionDigits: dp, useGrouping: false }).split('.');
  const grouped = i.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return (v < 0 ? '-' : '') + grouped + (f ? '.' + f : '');
}

export const formatLength = (m, dp = 1) => `${formatNumber(m, dp)} m`;
export const formatArea = (m2, dp = 1) => `${formatNumber(m2, dp)} m²`;
export const formatVolume = (m3, dp = 1) => `${formatNumber(m3, dp)} m³`;

/** 0.05 -> "5.0 % (1 in 20)"; 0 -> "level". */
export function formatGradient(g, dp = 1) {
  if (g == null || !Number.isFinite(g)) return 'n/a';
  if (Math.abs(g) < 1e-6) return 'level';
  return `${formatNumber(g * 100, dp)} % (1 in ${formatNumber(1 / Math.abs(g), 0)})`;
}

const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;

// "1 bend below 1.05 m", "no bends below 1.05 m", or "" when no rule applies.
function belowPhrase(cs) {
  if (!cs || cs.required.radius == null) return '';
  const r = formatNumber(cs.required.radius, 2);
  return cs.below.length ? `${plural(cs.below.length, 'bend', 'bends')} below ${r} m` : `no bends below ${r} m`;
}

/**
 * "Trench 124.6 m (3D 125.1 m) · spoil 98.4 m³ · 1 bend below 1.05 m"
 * ts from trenchSummary; cs (optional) from cableSummary for the cable it carries.
 */
export function formatTrenchLine(ts, cs = null) {
  let head = `Trench ${formatLength(ts.length2d)}`;
  if (ts.length3d != null) head += ` (3D ${formatLength(ts.length3d)})`;
  const parts = [head];
  if (ts.spoil != null) parts.push(`spoil ${formatVolume(ts.spoil)}`);
  const b = belowPhrase(cs);
  if (b) parts.push(b);
  return parts.join(SEP);
}

/** "Cable 132.4 m (3D 133.0 m) · final radius 0.77 m (15 × OD 51.5 mm) · no bends below 0.77 m" */
export function formatCableLine(cs) {
  const parts = [`Cable ${formatLength(cs.length2d)} (3D ${formatLength(cs.length3d)})`];
  const r = cs.required;
  if (r.radius == null) {
    parts.push(`no ${r.when} bend rule for this cable`);
  } else {
    let od = `OD ${formatNumber(cs.cable.odMm, 1)} mm`;
    if (cs.cable.odStatus === 'estimated') od += ' estimated';
    parts.push(`${r.when} radius ${formatNumber(r.radius, 2)} m (${formatNumber(r.multiple, 3).replace(/\.?0+$/, '')} × ${od})`);
    parts.push(belowPhrase(cs));
  }
  return parts.join(SEP);
}

/** "Platform 600.0 m² at 12.30 m · cut 410.2 m³ · fill 388.9 m³ · net 21.3 m³ cut" */
export function formatPlatformLine(cf) {
  const net = cf.cut - cf.fill;
  const netText = Math.abs(net) < 0.05 ? 'balanced' : `net ${formatVolume(Math.abs(net))} ${net > 0 ? 'cut' : 'fill'}`;
  return [
    `Platform ${formatArea(cf.area)} at ${formatNumber(cf.level, 2)} m`,
    `cut ${formatVolume(cf.cut)}`,
    `fill ${formatVolume(cf.fill)}`,
    netText,
  ].join(SEP);
}

/** "Profile 100.0 m (3D 100.1 m) · ground 0.00 to 5.00 m · steepest 5.0 % (1 in 20)" */
export function formatProfileLine(p) {
  return [
    `Profile ${formatLength(p.length2d)} (3D ${formatLength(p.length3d)})`,
    `ground ${formatNumber(p.min, 2)} to ${formatNumber(p.max, 2)} m`,
    `steepest ${formatGradient(p.gradient.max)}`,
  ].join(SEP);
}

// ---- One number rule for readouts (UI polish; e4 UI spec section 5) ----
// Significant figures, not decimal places: a figure is shown only as well as its inputs are known. Thousands commas,
// no "-0", and an em dash when a value cannot be computed (never NaN, never n/a in a readout).
export const NONE = '—';

/** fmtSig(1234.5) -> "1,230"; fmtSig(0.4213, 2) -> "0.42"; fmtSig(20.44) -> "20.4"; fmtSig(NaN) -> "—". */
export function fmtSig(x, sf = 3) {
  if (typeof x !== 'number' || !Number.isFinite(x)) return NONE;
  if (x === 0) return '0';
  const r = Number(x.toPrecision(sf)), mag = Math.floor(Math.log10(Math.abs(r)));
  return formatNumber(r, Math.max(0, sf - 1 - mag));
}

/** fmtQ(412.3, 'A') -> "412 A": a quantity to sf significant figures with its unit after a space. */
export const fmtQ = (v, unit = '', sf = 3) => (unit && Number.isFinite(v) ? `${fmtSig(v, sf)} ${unit}` : fmtSig(v, sf));

/** Percentages (voltage drop, rise, tap): 2 decimal places below 10 %, 1 above. fmtPct(0.842) -> "0.84 %". */
export const fmtPct = p => (Number.isFinite(p) ? `${formatNumber(p, Math.abs(p) < 10 ? 2 : 1)} %` : NONE);

/** Lengths: whole metres, or km to 2 places above 10 km. fmtLen(1284.4) -> "1,284 m". */
export const fmtLen = m => (!Number.isFinite(m) ? NONE : Math.abs(m) > 10000 ? `${formatNumber(m / 1000, 2)} km` : `${formatNumber(m, 0)} m`);

/** Volts: four figures below 1,000 V, whole volts with a comma above (a string's volts matter to the volt near its limit). */
export const fmtVolt = v => (!Number.isFinite(v) ? NONE : Math.abs(v) < 1000 ? fmtQ(v, 'V', 4) : `${formatNumber(v, 0)} V`);

Module Mount

A JavaScript module in the world folder of GlobalGrid2050 that mounts modules (`mountModules`), finds pick (`findPick`) and calculates planar distances (units: °C), covering solar and cables.

renderglobalgrid2050 / solar-design-studio/202609271740-site-world/world/module-mount.mjs · lines 1–188 of 188 · version 2026-09-27 17:40 · pattern counts (shared by 9 files)

What it does
It draws solar and cables. Defines 22 functions or classes, including n1, mountModules, src, redraw, load. 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: solar, cables.
Inputs & outputs
In: JSON file modules.json.
Downstream impact
Used directly by 1 file: Substrate (globalgrid2050). Reached from 1 other entry point, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/).
What it achieves
It finds pick (`findPick`) and is built from the mount modules helper (`mountModules`) and the src step (`src`). Module detail on zoom, wired into the world. It reads `./world/data/modules.json`. It responds to change events.
Why it matters
Imported by Substrate.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Pick (import), Module View (dynamic import), Module Geometry (dynamic import), Module Catalogue (dynamic import)
Used by
imported by Substrate (dynamic import)
Produces
ANIM_MS, mountModules
Defines here
n1, mountModules, src, redraw, load, refresh, eyeDir, batches, K_cost, builtMps, mpsFor, draw, inspect, findPick, tap, laid, counts, asBuilt, use, panel, show, debug
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/module-mount.mjs:1-188 · blob c3b8468b105ec903b07c9ae813d3c346e9166b30 · 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: production_core
// module-mount.mjs: module detail on zoom, wired into the world. Close to the Solar block or a plant layout, the
// few modules nearest where you look open into their front and back (module-view.mjs chooses, module-geometry.mjs
// draws, data/modules.json holds the generic classes). Tap a detailed module, or world.module.inspect(id), for its
// datasheet values, its place in the string and its cold open-circuit voltage; the class picker, or
// world.module.use('B'), changes the class and the table and string counts follow.
// Nothing loads until a block or layout exists; nothing draws when still; a level opening plays for ANIM_MS, then stops.

import { rayFromScreen } from './pick.mjs';

export const ANIM_MS = 280;
const COLOUR = { frame: [0.84, 0.86, 0.9, 0.95], cells: [0.36, 0.52, 0.88, 0.75], bus: [0.72, 0.76, 0.84, 0.45], split: [0.96, 0.74, 0.3, 0.95],
  back: [0.7, 0.71, 0.74, 0.85], cable: [0.92, 0.36, 0.28, 0.95], holes: [0.96, 0.94, 0.6, 0.95] };
const n1 = v => v.toFixed(1), n2 = v => v.toFixed(2);

export function mountModules(api, sources, doc = document) {
  let V = null, G = null, K = null, cat = null, cls = null, loading = null;
  const st = { sig: '', faces: [], box: null, cache: new Map(), prev: new Map(), since: new Map(), picks: [], out: [], pose: '', verts: 0, pinned: null };
  const src = () => ({ block: sources.block?.built?.()?.built ?? null, plant: sources.plant?.result?.() ?? null });
  const redraw = () => api.gate.invalidate();

  function load() {
    return (loading ||= (async () => {
      [V, G, K] = await Promise.all([import('./module-view.mjs'), import('./module-geometry.mjs'), import('./module-catalogue.mjs')]);
      const doc2 = await (await fetch('./world/data/modules.json', { cache: 'no-cache' })).json(), bad = K.checkCatalogue(doc2);
      if (bad.length) throw Error('module catalogue: ' + bad.join('; '));
      cat = doc2; cls = cat.classes[0]; panel(); redraw();
      return true;
    })().catch(e => { console.warn(e.message); return false; }));
  }
  function refresh() {
    const s = src(), v = sources.plant?.version?.() ?? 0;
    const sig = `${s.block ? 'b' + s.block.groups?.tables?.base : ''}|${s.plant ? 'p' + v + ':' + s.plant.tables.length + ':' + s.plant.tables[0] : ''}`;
    if (sig === st.sig) return;
    st.sig = sig; st.cache.clear(); st.prev.clear(); st.since.clear(); st.pose = '';
    st.faces = [...V.blockFaces(s.block), ...V.plantFaces(s.plant)].map(f => ({ ...f, box: V.faceBox(f) }));
    st.box = st.faces.length ? [0, 1, 2, 3, 4, 5].map(i => (i % 2 ? Math.max : Math.min)(...st.faces.map(f => f.box[i]))) : null;
    st.grid = V.faceGrid(st.faces);                          // faces by 50 m cell: a frame visits only those near the eye
  }
  const eyeDir = () => {
    const s = api.state(), o = api.origin(), c = Math.cos(s.pitch);
    return { eye: [s.pos[0] + o.e, s.pos[1] + o.n, s.pos[2]], dir: [Math.sin(s.yaw) * c, Math.cos(s.yaw) * c, Math.sin(s.pitch)], s, o };
  };

  function batches() {
    const s = src();
    if (!s.block && !s.plant) { if (st.picks.length) { st.picks = []; st.out = []; show(); } return []; }
    if (!cat) { load(); return []; }
    refresh();
    const { eye, dir, s: pose, o } = eyeDir(), now = performance.now();
    const key = `${cls.id}|${o.e},${o.n}|${pose.pos.map(v => v.toFixed(2))}|${pose.yaw.toFixed(3)}|${pose.pitch.toFixed(3)}|${st.sig}`;
    const animating = st.picks.some(p => [1, 2, 3].some(l => l <= p.level && now - (st.since.get(p.key + l) ?? 0) < ANIM_MS));
    if (key === st.pose && !animating) return st.out;
    st.pose = key;
    const near = st.box && Math.hypot(Math.max(st.box[0] - eye[0], 0, eye[0] - st.box[1]), Math.max(st.box[2] - eye[1], 0, eye[1] - st.box[3])) < 40;
    // Only the faces in the cells round the eye, and none when the eye is well above the highest table (the detail opens
    // within about 26 m): no scan of every face on a moving frame over a large plant.
    const low = near && eye[2] - st.box[5] < 30, picks = low ? V.choose(V.facesNear(st.grid, eye), eye, dir, cls, st.prev, st.cache) : [];
    // The vertex budget: nearest first; a module that would pass it opens fewer levels, or none.
    const cost = K_cost(), kept = [];
    let verts = 0;
    for (const p of picks) {
      let l = p.level;
      while (l > 0 && verts + cost[l - 1] > G.VERTEX_BUDGET) l--;
      if (l) { kept.push({ ...p, level: l }); verts += cost[l - 1]; }
    }
    const was = st.picks.map(p => p.key + p.level).join(), prev = new Map();
    for (const p of kept) {                                   // each new level opens 120 ms after the one below it
      const p0 = st.prev.get(p.key) || 0;
      prev.set(p.key, p.level);
      for (let l = 1; l <= p.level; l++) if (!st.since.has(p.key + l)) st.since.set(p.key + l, now + Math.max(0, l - p0 - 1) * 120);
    }
    for (const k of [...st.since.keys()]) { const m = k.match(/^(.*)(\d)$/); if (!(prev.get(m[1]) >= Number(m[2]))) st.since.delete(k); }
    st.prev = prev; st.picks = kept; st.verts = verts;
    st.out = draw(kept, now, o);
    if (kept.some(p => [1, 2, 3].some(l => l <= p.level && now - st.since.get(p.key + l) < ANIM_MS))) redraw(); // play the opening, then stop
    if (was !== kept.map(p => p.key + p.level).join()) show();
    return st.out;
  }
  let costOf = null;
  const K_cost = () => (costOf?.id === cls.id ? costOf.n : (costOf = { id: cls.id, n: G.levelCost(cls) }).n);

  // One source of truth for the string length (user test H7): the block's and the plant's own strings as built; the
  // class's own limit is said beside it, never used in its place.
  const builtMps = face => V.builtStringLength(face, src());
  const mpsFor = face => builtMps(face) || K.modulesPerString(cls, cat.coldest_cell_C, cat.system_voltage_V);
  function draw(picks, now, o) {
    if (!picks.length) return [];
    const out = Object.fromEntries(G.PARTS.map(p => [p, []])), base = G.placeModule(picks[0].face, picks[0].row, picks[0].col, cls).centre;
    for (const p of picks) {
      const mps = mpsFor(p.face);
      const grow = {};
      for (let l = 1; l <= p.level; l++) grow[l] = Math.max(0, (now - st.since.get(p.key + l)) / ANIM_MS);
      G.moduleLines(G.placeModule(p.face, p.row, p.col, cls), cls, p.level, out, base, grow, p.face.stringOf(p.row, p.col, mps, cls));
    }
    const origin = [base[0] - o.e, base[1] - o.n, base[2]], v = Math.round(now);
    return G.PARTS.filter(k => out[k].length).map(k => ({ key: 'module-' + k, version: `${st.pose}|${v}`, positions: new Float32Array(out[k]), color: COLOUR[k], origin }));
  }

  // ---- readout: datasheet values, string position, cold Voc ----
  function inspect(id = null) {
    if (!cat) return null;
    const p = id ? findPick(id) : st.picks[0];
    if (!p) return null;
    const b = K.nominal(cls), hi = K.highestVoc(cls), cold = cat.coldest_cell_C, mps = mpsFor(p.face), classMps = K.modulesPerString(cls, cold, cat.system_voltage_V);
    const s = p.face.stringOf(p.row, p.col, mps, cls), vCold = K.coldVoc(cls, cold, b), vColdHi = K.coldVoc(cls, cold, hi); // the stricter of the cell and Voc x 1.15
    st.pinned = p.key;
    const r = { id: p.key, class: { id: cls.id, label: cls.label, source: cls.source, technology: cls.technology, construction: cls.construction },
      datasheet: { pmaxW: b.pmax, vmpV: b.vmp, impA: b.imp, vocV: b.voc, iscA: b.isc, tempCoeffPctPerK: { ...cls.temp_coeff }, bifaciality: cls.bifaciality,
        sizeMm: [...cls.size_mm], weightKg: cls.weight_kg, cells: `${cls.cells.count} (${cls.cells.columns} x ${cls.cells.rows}, ${cls.cells.cut}-cut)`,
        junctionBoxes: cls.junction_boxes.count, bypassDiodes: cls.junction_boxes.bypass_diodes, leadsMm: [cls.cable.plus_mm, cls.cable.minus_mm] },
      string: { table: p.face.table, half: p.face.half, string: s.string, position: s.position, of: s.of, modulesPerString: mps, asBuilt: !!builtMps(p.face), classAllows: classMps },
      cold: { cellC: cold, moduleVocV: +n2(vCold), highestBinVocV: +n2(vColdHi), stringVocV: +n1(vColdHi * s.of), limitV: cat.system_voltage_V, ok: vColdHi * s.of <= cat.system_voltage_V },
      level: p.level, distanceM: +n1(p.d), assumed: [...cls.assumed] };
    show(r);
    return r;
  }
  function findPick(id) {
    const hit = st.picks.find(p => p.key === id);
    if (hit) return hit;
    const m = /^(.*)\/(\d+)\/(\d+)$/.exec(String(id)), f = m && st.faces.find(x => x.key === m[1]);
    return f ? { key: id, face: f, row: +m[2], col: +m[3], level: 0, d: NaN } : null;
  }
  function tap(x, y) {
    if (!st.picks.length || !cat) return false;
    const { eye, s } = eyeDir(), r = api.canvas.getBoundingClientRect();
    const ray = rayFromScreen(x, y, r.width, r.height, eye, s.yaw, s.pitch, api.FOV), p = V.hitModule(st.picks, cls, ray.origin, ray.dir);
    if (!p) return false;
    inspect(p.key);
    return true;
  }
  // The plant's modules and MWp as laid out (the plant readout's own figures: one MWp across the panels); the class's
  // fit on the same tables is kept beside them as drawn.
  const laid = c => { const r = src().plant; if (!r?.built?.tables || !c.modules) return c; const m = r.built.tables * r.table.modules;
    return { ...c, drawn: c.modules, modules: m, strings: Math.floor(m / (c.modulesPerString || 1)), kWp: r.built.mwp * 1000, laidOut: true }; };
  function counts() {
    if (!cat) return null;
    const faces = st.faces.length ? st.faces : [], by = k => faces.filter(f => f.key.startsWith(k));
    const asBuilt = (list, c) => { const m = builtMps(list[0]); return m ? { ...c, modulesPerString: m, strings: Math.floor(c.modules / m),
      stringed: Math.floor(c.modules / m) * m, asBuilt: true, classAllows: c.modulesPerString } : c; };
    return { class: cls.id, block: asBuilt(by('block:'), K.countsFor(cls, by('block:'), cat.coldest_cell_C, cat.system_voltage_V)),
      plant: laid(asBuilt(by('plant:'), K.countsFor(cls, by('plant:'), cat.coldest_cell_C, cat.system_voltage_V))) };
  }
  async function use(id) {
    await load();
    const c = cat && K.classOf(cat, String(id).toUpperCase());
    if (!c) return null;
    cls = c; st.pose = ''; st.since.clear(); st.prev.clear();
    if (st.sig === '' && V) refresh();
    const sel = doc.getElementById('module-class'); if (sel) sel.value = c.id;
    show(); redraw();
    return counts();
  }

  // ---- the small panel: the class picker and the readout; shown while modules are detailed or one is inspected ----
  let box = null;
  function panel() {
    if (box || !doc.body) return;
    box = doc.createElement('section');
    box.id = 'module-panel'; box.hidden = true; box.setAttribute('aria-label', 'Module detail');
    box.style.cssText = 'position:fixed;right:12px;bottom:12px;max-width:min(340px,calc(100vw - 32px));max-height:45vh;overflow:auto;z-index:5;'
      + 'background:#111;color:#ddd;border:1px solid #333;border-radius:6px;padding:8px 10px;font:12px/1.4 system-ui,sans-serif';
    const sel = doc.createElement('select'); sel.id = 'module-class'; sel.setAttribute('aria-label', 'Module class');
    sel.style.cssText = 'width:100%;background:#1a1a1a;color:#ddd;border:1px solid #444;border-radius:4px;padding:3px;margin-bottom:4px';
    for (const c of cat.classes) { const o = doc.createElement('option'); o.value = c.id; o.textContent = c.label; sel.append(o); }
    sel.addEventListener('change', () => use(sel.value));
    const out = doc.createElement('div'); out.id = 'module-readout';
    box.append(sel, out); doc.body.append(box);
  }
  function show(r = null) {
    if (!box) return;
    box.hidden = !st.picks.length && !r;
    const c = counts(), rows = [];
    if (c) for (const k of ['block', 'plant']) if (c[k].modules) rows.push(`${k === 'block' ? 'Solar block' : 'Plant layout'}: ${c[k].modules} modules, ${c[k].strings} strings of `
      + `${c[k].modulesPerString}${c[k].asBuilt ? ' as built' : ''}, ${n1(c[k].kWp / 1000)} MWp`
      + (c[k].asBuilt && c[k].classAllows < c[k].modulesPerString ? ` (this class allows ${c[k].classAllows} a string at ${cat.coldest_cell_C} °C)` : ''));
    if (r) rows.push(`Module ${r.id} · ${r.class.source}`, `Pmax ${r.datasheet.pmaxW} W · Vmp ${r.datasheet.vmpV} V · Imp ${r.datasheet.impA} A`,
      `Voc ${r.datasheet.vocV} V · Isc ${r.datasheet.iscA} A · β Voc ${r.datasheet.tempCoeffPctPerK.voc} %/K`,
      `Table ${r.string.table} ${r.string.half} · string ${r.string.string} · module ${r.string.position} of ${r.string.of}`,
      `Cold (the stricter of ${r.cold.cellC} °C and Voc × 1.15): module Voc ${r.cold.moduleVocV} V; string ${r.cold.stringVocV} V (highest bin) ${r.cold.ok ? 'within' : 'OVER'} ${r.cold.limitV} V`);
    else rows.push(`${st.picks.length} module(s) in detail · tap one for its values`);
    const out = doc.getElementById('module-readout');
    out.replaceChildren(...rows.map(t => { const d = doc.createElement('div'); d.textContent = t; return d; }));
  }

  const debug = () => ({ loaded: !!cat, class: cls?.id ?? null, faces: st.faces.length, detailed: st.picks.length, vertices: st.verts,
    budget: G?.VERTEX_BUDGET ?? null, picks: st.picks.map(p => ({ key: p.key, level: p.level, d: +n2(p.d), off: +n2(p.off) })), pinned: st.pinned });
  return { batches, tap, api: Object.freeze({ inspect, use, counts, debug, classes: () => (cat ? cat.classes.map(c => ({ id: c.id, label: c.label })) : []), load }) };
}