In this section
- Module View transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/module-view.mjs lines 1–161
- Nav Chips transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/nav-chips.mjs lines 1–57
- Nav Flight transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/nav-flight.mjs lines 1–178
- Nav Path ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/nav-path.mjs lines 1–172
Module View
A JavaScript module in the world folder of GlobalGrid2050 that works with solar.
transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/module-view.mjs · lines 1–161 of 161 · version 2026-09-27 18:53 · pattern boxDist (shared by 4 files)
- What it does
- It calculates solar. Defines 16 functions or classes, including lerp3, blockFaces, at, plantFaces, c.
- 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.
- Downstream impact
- Used directly by 1 file: Module Mount (globalgrid2050). 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
- It is built from the lerp3 step (`lerp3`), the block faces helper (`blockFaces`) and the plant faces helper (`plantFaces`). Which modules are drawn in detail, and how far each has opened, from where the viewer looks.
- Why it matters
- Imported by Module Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Module Geometry (import), Module Catalogue (import), Station (import)
- Used by
- imported by Module Mount (dynamic import)
- Produces
- CAP, ENTER_M, LEAVE, KEEP, blockFaces, plantFaces, faceBox, CELL_M, faceGrid, facesNear, centresOf, levelAt
- Defines here
- lerp3, blockFaces, at, plantFaces, c, face, faceBox, boxDist, faceGrid, facesNear, centresOf, levelAt, choose, hitModule, rayTri, builtStringLength
- 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/202609271853-site-world/world/module-view.mjs:1-161 · blob bc3e52867d80fee8151c715a675fc2c413005c12 · 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
// module-view.mjs: which modules are drawn in detail, and how far each has opened, from where the viewer looks.
//
// Like the zoom of the early map versions, detail opens where you look: at most CAP modules at once, those nearest
// the view ray (the screen centre) and the eye, nearest first; every other module stays the table's plain outline.
// Each chosen module opens in steps as the eye comes closer (module-geometry.mjs levels 1-3), with hysteresis on the
// choice and on every step, so nothing flickers at a boundary. Ties break on the module key, so the choice is the
// same every time for the same pose. Faces come from the Solar block (block-build.mjs) or the plant layout
// (plant-layout.mjs), read as they are: nothing per module is stored. Pure: no DOM.
import { placeModule, moduleCount } from './module-geometry.mjs';
import { faceFit } from './module-catalogue.mjs';
import { tableOrigin, tableShape } from './station.mjs';
export const CAP = 10;
export const ENTER_M = Object.freeze([22, 12, 7]); // level 1 (frame, cells), 2 (busbars, split), 3 (the back)
export const LEAVE = 1.2; // a level stays until the eye is 1.2 x its entry distance away
export const KEEP = 1.1; // a chosen module stays chosen until another scores 1.1 x better
const lerp3 = (A, B, C, D, a, b) => [0, 1, 2].map(i => A[i] * (1 - a) * (1 - b) + B[i] * a * (1 - b) + D[i] * (1 - a) * b + C[i] * a * b);
/** Faces of the placed Solar block's drawn station: both faces of every table, riding the ground as drawn. */
export function blockFaces(built) {
if (!built?.onTable || !built.station) return [];
const s = built.station.params, T = tableShape(s), t = s.tilt * Math.PI / 180, out = [];
for (let n = 0; n < s.tables; n++) for (const side of [-1, 1]) {
const [x0, y0] = tableOrigin(n, s);
const at = (u, v) => built.onTable(n, x0 + side * (T.halfRidgeGap + T.depth - v * Math.cos(t)), y0 + u);
out.push({ key: `block:T${n + 1}:${side < 0 ? 'W' : 'E'}`, table: n + 1, half: side < 0 ? 'west half' : 'east half', span: T.span, run: T.run, at,
stringOf: (row, col, mps, c) => { const f = faceFit(c, T.span, T.run), groups = Math.ceil(f.columns / mps);
const r = side > 0 ? f.rows - 1 - row : row, g = Math.floor(col / mps);
return { string: ((n * 2 + (side > 0 ? 1 : 0)) * f.rows + r) * groups + g + 1, position: col % mps + 1, of: Math.min(mps, f.columns - g * mps) }; } });
}
return out;
}
/** Faces of a plant layout: one per south-facing table, two per east-west table (either side of the ridge). */
export function plantFaces(r) {
if (!r?.tables || !r.frame || !r.table) return [];
const F = r.frame, T = r.table, lo = r.params.lowEdgeM, hi = lo + T.rise, out = [], tb = r.tables, orient = T.orient || 'portrait';
const c = (u, v, z) => { const [e, n] = F.en(u, v); return [e, n, z]; };
for (let q = 0, i = 0; q < tb.length; q += 6, i++) {
const L = r.tableLen?.[i] ?? T.lenU; // a half table closing a row end is shorter
const [ua, va, h0, h1, h2, h3] = tb.subarray(q, q + 6), ub = ua + L, vb = va + T.depth;
const face = (key, A, B, C, D, k) => ({ key: `plant:T${i + 1}${key}`, table: i + 1, half: key ? (key === ':a' ? 'first side' : 'second side') : '',
span: L, run: T.slope, orient, at: (u, v) => lerp3(A, B, C, D, u / L, v / T.slope),
stringOf: (row, col, mps, cls) => { const f = faceFit(cls, L, T.slope, undefined, orient), groups = Math.max(1, Math.ceil(f.columns / mps)), g = Math.floor(col / mps);
return { string: ((i * 2 + k) * f.rows + row) * groups + g + 1, position: col % mps + 1, of: Math.min(mps, f.columns - g * mps) }; } });
// On its piles (v09, plant-piles.mjs): the fitted module edge heights [first, middle, far] as the plant draws them.
const pe = r.piles?.tables?.[i]?.edges, vm = (va + vb) / 2;
if (pe && (T.south || T.tracker)) out.push(face('', c(ua, va, pe[0][0]), c(ub, va, pe[0][1]), c(ub, vb, pe[2][1]), c(ua, vb, pe[2][0]), 0));
else if (pe) {
const M = c(ua, vm, pe[1][0]), N = c(ub, vm, pe[1][1]);
out.push(face(':a', c(ua, va, pe[0][0]), c(ub, va, pe[0][1]), N, M, 0), face(':b', c(ua, vb, pe[2][0]), c(ub, vb, pe[2][1]), N, M, 1));
} else if (T.south || T.tracker) out.push(face('', c(ua, va, h0 + lo), c(ub, va, h1 + lo), c(ub, vb, h2 + (T.tracker ? lo : hi)), c(ua, vb, h3 + (T.tracker ? lo : hi)), 0));
else {
const M = c(ua, vm, (h0 + h3) / 2 + hi), N = c(ub, vm, (h1 + h2) / 2 + hi);
out.push(face(':a', c(ua, va, h0 + lo), c(ub, va, h1 + lo), N, M, 0), face(':b', c(ua, vb, h3 + lo), c(ub, vb, h2 + lo), N, M, 1));
}
}
return out;
}
/** Axis-aligned box round a face (its corners and the middle of each edge), for a quick reach test. */
export function faceBox(f) {
const p = [[0, 0], [0.5, 0], [1, 0], [0, 1], [0.5, 1], [1, 1], [0, 0.5], [1, 0.5]].map(([a, b]) => f.at(a * f.span, b * f.run));
return [0, 1, 2].flatMap(i => [Math.min(...p.map(x => x[i])), Math.max(...p.map(x => x[i]))]);
}
const boxDist = (b, e) => Math.hypot(Math.max(b[0] - e[0], 0, e[0] - b[1]), Math.max(b[2] - e[1], 0, e[1] - b[3]), Math.max(b[4] - e[2], 0, e[2] - b[5]));
/** Faces by 50 m plan cell (a face in every cell its box touches), so a frame visits only the faces near the eye (PERF.md 1). */
export const CELL_M = 50;
export function faceGrid(faces, cell = CELL_M) {
const g = new Map();
for (const f of faces) {
const [x0, x1, y0, y1] = f.box;
for (let i = Math.floor(x0 / cell); i <= Math.floor(x1 / cell); i++) for (let j = Math.floor(y0 / cell); j <= Math.floor(y1 / cell); j++) {
const k = `${i},${j}`; (g.get(k) || g.set(k, []).get(k)).push(f);
}
}
return { cell, g };
}
/** The faces whose cells lie within r (plan) of the eye; each face once. */
export function facesNear(grid, eye, r = ENTER_M[0] * LEAVE) {
const { cell, g } = grid, out = new Set();
for (let i = Math.floor((eye[0] - r) / cell); i <= Math.floor((eye[0] + r) / cell); i++) {
for (let j = Math.floor((eye[1] - r) / cell); j <= Math.floor((eye[1] + r) / cell); j++) for (const f of g.get(`${i},${j}`) || []) out.add(f);
}
return [...out];
}
/** Module centres of a face for a class, [x, y, z] per module in row order; cached by the caller. */
export function centresOf(f, c) {
const n = moduleCount(f, c), fit = faceFit(c, f.span, f.run, undefined, f.orient), out = new Float64Array(n * 3);
for (let r = 0; r < fit.rows; r++) for (let q = 0; q < fit.columns; q++) out.set(placeModule(f, r, q, c).centre, (r * fit.columns + q) * 3);
return { centres: out, columns: fit.columns, rows: fit.rows };
}
/** The level a module shows at eye distance d, given the level it showed last frame (hysteresis on each step). */
export function levelAt(d, prev = 0) {
let l = 0;
for (let k = 1; k <= 3; k++) if (d < ENTER_M[k - 1] * (k <= prev ? LEAVE : 1)) l = k;
return l;
}
/**
* Choose the modules to detail. faces with .box (faceBox); eye and dir (unit) in the faces' metres;
* prev: Map key -> level from the last choice; cache: Map for centres. Returns at most CAP picks, best first:
* { key, face, row, col, level, d, off } (d: eye distance, off: distance from the view ray).
*/
export function choose(faces, eye, dir, c, prev = new Map(), cache = new Map(), cap = CAP) {
const reach = ENTER_M[0] * LEAVE, found = [];
for (const f of faces) {
if (boxDist(f.box, eye) > reach) continue;
const ck = `${f.key}|${c.id}`;
let C = cache.get(ck);
if (!C) cache.set(ck, (C = centresOf(f, c)));
const P = C.centres;
for (let i = 0; i < P.length; i += 3) {
const vx = P[i] - eye[0], vy = P[i + 1] - eye[1], vz = P[i + 2] - eye[2], along = vx * dir[0] + vy * dir[1] + vz * dir[2];
if (along <= 0) continue;
const d = Math.hypot(vx, vy, vz), m = i / 3, row = Math.floor(m / C.columns), col = m % C.columns, key = `${f.key}/${row}/${col}`;
const was = prev.get(key) || 0, level = levelAt(d, was);
if (!level) continue;
const off = Math.hypot(vx - along * dir[0], vy - along * dir[1], vz - along * dir[2]);
found.push({ key, face: f, row, col, level, d, off, score: (off / along + 0.002 * d) / (was ? KEEP : 1) }); // angle off centre, then nearness
}
}
found.sort((a, b) => a.score - b.score || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
return found.slice(0, cap);
}
/** The first chosen module a ray passes through (its quad, split in two triangles), or null. */
export function hitModule(picks, c, origin, dir) {
let best = null;
for (const p of picks) {
const M = placeModule(p.face, p.row, p.col, c);
for (const [A, B, C] of [[M.P00, M.P10, M.P11], [M.P00, M.P11, M.P01]]) {
const t = rayTri(origin, dir, A, B, C);
if (t !== null && (!best || t < best.t)) best = { pick: p, t };
}
}
return best?.pick || null;
}
function rayTri(o, d, a, b, c) { // Moller-Trumbore
const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
const p = [d[1] * e2[2] - d[2] * e2[1], d[2] * e2[0] - d[0] * e2[2], d[0] * e2[1] - d[1] * e2[0]], det = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2];
if (Math.abs(det) < 1e-12) return null;
const s = [o[0] - a[0], o[1] - a[1], o[2] - a[2]], u = (s[0] * p[0] + s[1] * p[1] + s[2] * p[2]) / det;
if (u < 0 || u > 1) return null;
const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]], v = (d[0] * q[0] + d[1] * q[1] + d[2] * q[2]) / det;
if (v < 0 || u + v > 1) return null;
const t = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) / det;
return t > 0 ? t : null;
}
/** The string length as built for a face (user test H7): the block's inventory or the plant's template; null elsewhere. */
export function builtStringLength(face, { block = null, plant = null } = {}) {
if (face?.key?.startsWith('block:')) return block?.summary?.inventory?.modulesPerString || null;
if (face?.key?.startsWith('plant:')) return plant?.template?.counts?.modulesPerString || null;
return null;
}Nav Chips
A JavaScript module in the world folder of GlobalGrid2050 that works with chip strip (`chipStrip`) and history step (`historyStep`).
transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/nav-chips.mjs · lines 1–57 of 57 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern depth (shared by 2 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including esc, chipStrip, chipHtml, keyMove, historyStep.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'nav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- It is built from the esc step (`esc`), the chip strip helper (`chipStrip`) and the chip HTML helper (`chipHtml`). The breadcrumb bar and the phone chip strip, as data and as markup; the keys that move between levels; and what the browser history should do on each move.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Nav Path (import)
- Used by
- none found
- Produces
- chipStrip, chipHtml, keyMove, historyStep, pathFromLocation
- Defines here
- esc, chipStrip, chipHtml, keyMove, historyStep, depth, pathFromLocation
- 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/202609271853-site-world/world/nav-chips.mjs:1-57 · blob 276be0b6c6537fea7f3b8a4e3d85954d0c1fc4c0 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// The breadcrumb bar and the phone chip strip, as data and as markup; the keys that move between levels; and what the
// browser history should do on each move. Pure: imports only nav-path.mjs, no DOM (the caller sets innerHTML and
// listens for clicks on [data-hash]).
import { crumbs, up, toHash, levelOf, samePath, fromHash, clean } from './nav-path.mjs';
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
const SHORT = { plant: 'Plant', block: 'B', row: 'R', table: 'T', string: 'S' };
// { chips: [{ level, label, hash, current }], up: { hash } | null, scrollTo } for the path.
// phone: short labels ('B12') so five chips fit a 360 px strip; the strip scrolls sideways to the current (last) chip.
export function chipStrip(path, { phone = false } = {}) {
const list = crumbs(path);
const chips = list.map((c, i) => ({
level: c.level, hash: c.hash, current: i === list.length - 1,
label: phone && c.level !== 'plant' ? SHORT[c.level] + c.label.split(' ')[1] : c.label
}));
const p = clean(path);
return { chips, up: levelOf(p) === 'plant' ? null : { hash: toHash(up(p)) }, scrollTo: chips.length - 1 };
}
// Markup for the strip. Desktop: 'Plant > Block 12 > Row 7' as buttons. Phone: 44 px chips and a big Up button first.
// Every button carries data-hash; the current place is aria-current and not a button (nothing to fly to).
export function chipHtml(strip, { phone = false } = {}) {
const parts = strip.chips.map(c => (c.current
? `<span class="nav-chip nav-here" aria-current="location">${esc(c.label)}</span>`
: `<button type="button" class="nav-chip" data-hash="${esc(c.hash)}">${esc(c.label)}</button>`));
const upBtn = phone && strip.up ? `<button type="button" class="nav-up" data-hash="${esc(strip.up.hash)}" aria-label="Up one level">Up</button>` : '';
const sep = phone ? '' : '<span class="nav-sep" aria-hidden="true"> > </span>';
return `<nav class="nav-crumbs${phone ? ' nav-phone' : ''}" aria-label="Where you are">${upBtn}${parts.join(sep)}</nav>`;
}
// Desktop keys: Escape or Backspace goes up one level; 1-5 go to that level of the current path (1 is the plant).
// Returns the new path, or null when the key is not ours (or would not move). Typing in a box is the caller's to skip.
export function keyMove(key, path) {
const p = clean(path);
if (key === 'Escape' || key === 'Backspace') return levelOf(p) === 'plant' ? null : up(p);
if (/^[1-5]$/.test(key)) {
const c = crumbs(p)[Number(key) - 1];
return c && !samePath(c.path, p) ? c.path : null;
}
return null;
}
// History: going down a level pushes (so a phone's back gesture goes up); going up, or across at the same level, replaces
// (so back never bounces between sibling blocks); the same place does nothing.
// Returns { op: 'push' | 'replace' | 'none', hash }.
export function historyStep(from, to) {
const a = clean(from), b = clean(to), hash = toHash(b);
if (samePath(a, b)) return { op: 'none', hash };
const depth = p => crumbs(p).length;
const below = depth(b) > depth(a) && crumbs(b).some(c => samePath(c.path, a));
return { op: below ? 'push' : 'replace', hash };
}
// On popstate or a pasted link: the path the hash names (the caller normalises it against the layout before flying).
export const pathFromLocation = hash => fromHash(hash);Nav Flight
A JavaScript module in the world folder of GlobalGrid2050 that picks block (`pickBlock`), fits view (`fitView`) and calculates planar distances and angles. It picks block (`pickBlock`) and fits view (`fitView`).
transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/nav-flight.mjs · lines 1–178 of 178 · version 2026-09-27 18:53 · pattern finished (shared by 2 files)
- What it does
- It calculates its inputs. Defines 24 functions or classes, including ease, clamp, turn, boxCentre, boxGrow.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'nav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 2 files: Plant UI (globalgrid2050); 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
- Flying about the plant: the start view that frames it all, the camera for each level, which block a tap is on, whether a flight may glide instead of the far-place origin jump, and a descent that eases through log(height). Its code works with 500 MW.
- Why it matters
- Imported by Plant UI and Substrate.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Plant UI (import), imported by Substrate (dynamic import)
- Produces
- DOWN, JUMP_M, boxCentre, boxGrow, inBox, boxOfPoints, blockSlices, blockBox, pickBlock, fitView, plantView, blockView
- Defines here
- ease, clamp, turn, boxCentre, boxGrow, inBox, boxOfPoints, blockSlices, blockBox, pickBlock, screenOf, fitView, fits, need, plantView, blockView, rowView, tableView, stringStand, glides, flightSeconds, descend, finished, pose
- 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/202609271853-site-world/world/nav-flight.mjs:1-178 · blob 2f25ea920735b90835bcadfc738ada342a1f44a5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// Flying about the plant: the start view that frames it all, the camera for each level, which block a tap is on,
// whether a flight may glide instead of the far-place origin jump, and a descent that eases through log(height).
// Pure: no imports, no DOM. Local metres (x east, y north), yaw 0 looks north (+y), pitch negative looks down;
// the same conventions as substrate.mjs flyTo and arrival.mjs.
const DEG = Math.PI / 180;
export const DOWN = -(Math.PI / 2 - 0.01); // arrival.mjs: straight down, as far as the look controls hold
export const JUMP_M = 3000; // substrate.mjs: further than this, Find moves the origin and drops in
const ease = u => u * u * u * (u * (u * 6 - 15) + 10); // arrival.mjs: zero speed and acceleration at both ends
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const turn = (from, to) => { const d = (to - from) % (2 * Math.PI); return d > Math.PI ? d - 2 * Math.PI : d < -Math.PI ? d + 2 * Math.PI : d; };
// ---- boxes ----
// box: [minX, minY, maxX, maxY]
export const boxCentre = b => [(b[0] + b[2]) / 2, (b[1] + b[3]) / 2];
export const boxGrow = (b, m) => [b[0] - m, b[1] - m, b[2] + m, b[3] + m];
export const inBox = (b, x, y) => x >= b[0] && x <= b[2] && y >= b[1] && y <= b[3];
export function boxOfPoints(pts) {
const b = [Infinity, Infinity, -Infinity, -Infinity];
for (const [x, y] of pts) { b[0] = Math.min(b[0], x); b[1] = Math.min(b[1], y); b[2] = Math.max(b[2], x); b[3] = Math.max(b[3], y); }
return b;
}
// Blocks are contiguous in the layout's tables (plant-layout.mjs: filled in station order), so block k (from 1) is the
// slice starting at the sum of the earlier stations' table counts. Returns [{ block, id, start, count }].
export function blockSlices(stations) {
let at = 0;
return stations.map((s, i) => { const r = { block: i + 1, id: s.id, start: at, count: s.tables }; at += s.tables; return r; });
}
// The local box round one block's tables. tables: Float64 x6 per table (ua, va, 4 corner heights);
// toLocal(u, v) -> [x, y]; lenU, depth: the table's size along u and v.
export function blockBox(tables, slice, toLocal, lenU, depth) {
const pts = [];
for (let q = slice.start; q < slice.start + slice.count; q++) {
const u = tables[q * 6], v = tables[q * 6 + 1];
pts.push(toLocal(u, v), toLocal(u + lenU, v), toLocal(u + lenU, v + depth), toLocal(u, v + depth));
}
return boxOfPoints(pts);
}
// Which block a ground point is on. blocks: [{ block, box }]. Inside a box wins (the smallest box where they overlap);
// otherwise the nearest box edge within tolM (a finger's width on the ground); else null (the tap was not on a block).
export function pickBlock(blocks, x, y, tolM = 0) {
let best = null, bestArea = Infinity, near = null, nearD = Infinity;
for (const b of blocks) {
const [x0, y0, x1, y1] = b.box;
if (inBox(b.box, x, y)) { const a = (x1 - x0) * (y1 - y0); if (a < bestArea) { bestArea = a; best = b.block; } continue; }
const d = Math.hypot(Math.max(x0 - x, 0, x - x1), Math.max(y0 - y, 0, y - y1));
if (d <= tolM && d < nearD) { nearD = d; near = b.block; }
}
return best ?? near;
}
// ---- framing ----
// Where a ground point lands on screen (-1..1 each way) from a camera 'distance' out along the view line through the
// box centre (flat ground at the centre's height). Perspective is exact: the near edge of a plant seen at 45 degrees
// is wider on screen than the far edge, and that is what decides the fit.
function screenOf(px, py, cx, cy, yaw, pitch, distance, tv, th) {
const cp = Math.cos(pitch), sp = Math.sin(pitch), sy = Math.sin(yaw), cyw = Math.cos(yaw);
const f = [sy * cp, cyw * cp, sp], r = [cyw, -sy, 0], u = [-sy * sp, -cyw * sp, cp]; // forward, right, up
const eye = [cx - f[0] * distance, cy - f[1] * distance, -f[2] * distance];
const d = [px - eye[0], py - eye[1], -eye[2]], z = d[0] * f[0] + d[1] * f[1] + d[2] * f[2];
if (z <= 0) return [Infinity, Infinity];
return [(d[0] * r[0] + d[1] * r[1]) / z / th, (d[0] * u[0] + d[1] * u[1] + d[2] * u[2]) / z / tv];
}
// The stand-off that fits a ground box on screen, looking down at pitch, from yaw 0 or 90 degrees (whichever fits closer:
// on a portrait phone the long side of the plant runs away from the viewer). fovy: vertical field of view (radians);
// aspect: width / height; margin 1.1 leaves a tenth of the screen round the box. Returns flyTo opts plus the centre:
// { x, y, yaw, pitch, back, height, distance }, with height = back * tan(-pitch) as flyTo computes it.
export function fitView(box, { fovy = 70 * DEG, aspect = 16 / 9, pitch = -45 * DEG, margin = 1.1, minDistance = 50, yaw = null } = {}) {
const [cx, cy] = boxCentre(box), tv = Math.tan(fovy / 2), th = tv * aspect, lim = 1 / margin;
const corners = [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], [box[0], box[3]]];
const fits = (a, D) => corners.every(([x, y]) => { const [sx, sy] = screenOf(x, y, cx, cy, a, pitch, D, tv, th); return Math.abs(sx) <= lim && Math.abs(sy) <= lim; });
const need = a => { // the corners only get closer to the middle as the camera backs off: bisect for the nearest fit
let hi = Math.max(minDistance, 1);
while (!fits(a, hi) && hi < 1e7) hi *= 2;
let lo = hi / 2;
if (fits(a, lo) && lo < minDistance) return minDistance;
for (let i = 0; i < 50; i++) { const mid = (lo + hi) / 2; if (fits(a, mid)) hi = mid; else lo = mid; }
return Math.max(minDistance, hi);
};
let pick = yaw, distance;
if (pick == null) { const n = need(0), e = need(Math.PI / 2); pick = e < n * 0.98 ? Math.PI / 2 : 0; distance = pick ? e : n; }
else distance = need(pick);
const back = distance * Math.cos(-pitch);
return { x: cx, y: cy, yaw: pick, pitch, back, height: back * Math.tan(-pitch), distance };
}
// The start view: the whole plant, 45 degrees down (500 MW: about 3.2 km out on a desktop, about 5 km on a portrait phone).
export const plantView = (plantBox, screen = {}) => fitView(plantBox, { ...screen, pitch: -45 * DEG, margin: 1.1 });
// A block: 50 degrees down, framed with room round it, never closer than 150 m out.
export const blockView = (box, screen = {}) => {
const v = fitView(box, { ...screen, pitch: -50 * DEG, margin: 1.25, minDistance: 150 / Math.cos(50 * DEG) });
return v;
};
// A row: from its first table, looking along it, 35 degrees down from 40 m up. start, end: local [x, y].
export function rowView(start, end) {
const yaw = Math.atan2(end[0] - start[0], end[1] - start[1]), pitch = -35 * DEG, height = 40;
const back = height / Math.tan(-pitch);
// stand off behind the start, so flyTo's 'at' is the start and the row runs away up the screen
return { x: start[0], y: start[1], yaw, pitch, back, height };
}
// A table: in front of it, 8 m up, 12 m back, facing it. centre: [x, y]; facing: the yaw that looks at the table's face.
export function tableView(centre, facing) {
const back = 12, height = 8;
return { x: centre[0], y: centre[1], yaw: facing, pitch: -Math.atan2(height, back), back, height };
}
// A string: stand in the aisle 1.5 m in front of the table and face it (Walk). blocked(x, y) -> true inside a solid;
// the spot is nudged away from the table 0.5 m at a time (up to 6 m) until it is clear. Returns { walk, x, y, yaw } or null.
export function stringStand(centre, facing, blocked = () => false) {
const dx = -Math.sin(facing), dy = -Math.cos(facing);
for (let d = 1.5; d <= 6 + 1e-9; d += 0.5) {
const x = centre[0] + dx * d, y = centre[1] + dy * d;
if (!blocked(x, y)) return { walk: true, x, y, yaw: facing };
}
return null;
}
// ---- the jump ----
// substrate.mjs flyTo moves the origin and drops in from above when a target is more than JUMP_M away. Across one plant
// that is wrong: block to block should glide. A flight glides when the target is on the plant (with toM round it) and
// the camera is within reachM of the plant (the start view stands up to about 5-6 km out). Otherwise the jump rule stands.
export function glides(from, to, plantBox, { jumpM = JUMP_M, toM = 500, reachM = 7000 } = {}) {
if (Math.hypot(to[0] - from[0], to[1] - from[1]) <= jumpM) return true;
if (!plantBox) return false;
return inBox(boxGrow(plantBox, toM), to[0], to[1]) && inBox(boxGrow(plantBox, reachM), from[0], from[1]);
}
// ---- the descent ----
// How long a flight takes: 2 s, plus half a second per halving (or doubling) of the height, plus a little for distance;
// never more than 5 s. h0, h1: heights above the ground (m); d: ground distance (m).
export const flightSeconds = (h0, h1, d = 0) =>
clamp(2 + 0.5 * Math.abs(Math.log2(Math.max(h0, 0.5) / Math.max(h1, 0.5))) + 0.25 * Math.log2(1 + d / 1000), 2, 5);
// A flight that eases through log(height above the ground), so a drop from 2 km to 8 m spends its time evenly per
// halving instead of 99 % of it high up with a snap at the end. The ground position arrives a little ahead of the height
// (80 % of the time), so the last part is a straight settle. A long flight at the same height rises in a gentle arc
// (peak about 40 % of the distance) so the plant stays in view.
// state: { pos: [x, y, z], yaw, pitch }; target: [x, y, groundZ]; opts: flyTo opts { back, pitch, yaw, height }
// plus groundFrom (the ground under the camera now; default the target's) and seconds (default flightSeconds).
// Returns pose(t) -> { pos, yaw, pitch }, with pose.done(t), pose.end and pose.seconds, as arrival.mjs arrive does.
export function descend(state, target, opts = {}) {
const yaw = opts.yaw ?? state.yaw, pitch = opts.pitch ?? DOWN, back = opts.back ?? 0;
const g1 = target[2] ?? 0, g0 = opts.groundFrom ?? g1;
const height = back && opts.pitch ? back * Math.tan(-pitch) : (opts.height ?? 80);
const end = Object.freeze({
pos: Object.freeze([target[0] - back * Math.sin(yaw), target[1] - back * Math.cos(yaw), g1 + height]), yaw, pitch });
const from = { pos: [...state.pos], yaw: state.yaw, pitch: state.pitch };
const h0 = Math.max(0.5, from.pos[2] - g0), h1 = Math.max(0.5, height);
const d = Math.hypot(end.pos[0] - from.pos[0], end.pos[1] - from.pos[1]);
const seconds = opts.seconds ?? flightSeconds(h0, h1, d);
const l0 = Math.log(h0), l1 = Math.log(h1), hi = Math.max(h0, h1);
const bump = 0.4 * d > hi ? Math.log(0.4 * d) - (l0 + l1) / 2 : 0; // an arc only when the flight is long for its height
const dyaw = turn(from.yaw, yaw);
const finished = t => !(seconds > 0) || t >= seconds;
const pose = t => {
if (finished(t)) return { pos: [...end.pos], yaw: end.yaw, pitch: end.pitch };
const u = Math.max(0, t) / seconds, k = ease(u), kx = ease(Math.min(1, u / 0.8));
const lh = l0 + (l1 - l0) * k + bump * Math.sin(Math.PI * k);
const g = g0 + (g1 - g0) * kx;
return {
pos: [from.pos[0] + (end.pos[0] - from.pos[0]) * kx, from.pos[1] + (end.pos[1] - from.pos[1]) * kx, g + Math.exp(lh)],
yaw: from.yaw + dyaw * kx,
pitch: from.pitch + (end.pitch - from.pitch) * k
};
};
pose.done = finished;
pose.end = end;
pose.seconds = seconds;
return pose;
}Nav Path
A JavaScript module in the world folder of GlobalGrid2050 that converts to hash (`toHash`).
ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/nav-path.mjs · lines 1–172 of 172 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern crumbs (shared by 2 files)
- What it does
- It lists and searches its content. Defines 16 functions or classes, including whole, lower, clean, levelOf, up.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'nav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 1 file: Nav Chips (globalgrid2050).
- What it achieves
- It parses nav (`parseNav`) and is built from the whole step (`whole`) and the lower step (`lower`). Where the viewer is in the plant: Plant > Block > Row > Table > String.
- Why it matters
- Imported by Nav Chips.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Nav Chips (import)
- Produces
- LEVELS, PLANT, clean, levelOf, up, samePath, toHash, fromHash, crumbs, crumbText, normalise, parseNav
- Defines here
- whole, lower, clean, levelOf, up, samePath, toHash, fromHash, crumbs, crumbText, range, normalise, parseNav, resolve, fromGoArg, navigate
- 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/202609271853-site-world/world/nav-path.mjs:1-172 · blob 9041fa8e53d70f0a4d3337e4cfa87536568ec7c1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// Where the viewer is in the plant: Plant > Block > Row > Table > String.
// Pure: no imports, no DOM. A path is { b, r, t, s }: whole numbers counted from 1, or null below the level reached.
// Rows are counted within their block, tables within their row, strings within their table.
// A table typed without a row ("go block 12 table 3") is counted across the whole block; normalise() finds its row.
//
// counts (from the layout, supplied by the caller): { blocks: n, rows(b), tables(b, r), strings(b, r, t) } -> whole numbers.
export const LEVELS = ['plant', 'block', 'row', 'table', 'string'];
const KEYS = ['b', 'r', 't', 's'];
const NAMES = { b: 'Block', r: 'Row', t: 'Table', s: 'String' };
export const PLANT = Object.freeze({ b: null, r: null, t: null, s: null });
const whole = v => Number.isInteger(v) && v >= 1;
const lower = k => NAMES[k].toLowerCase();
// Cuts a path at its first missing number, so a string never hangs under a missing table.
export function clean(p = {}) {
const out = { ...PLANT };
for (const k of KEYS) { if (!whole(p[k])) break; out[k] = p[k]; }
return out;
}
// 'plant' | 'block' | 'row' | 'table' | 'string'
export const levelOf = p => LEVELS[KEYS.filter(k => clean(p)[k] != null).length];
// One level up; the plant stays the plant.
export function up(p) {
const c = clean(p), last = [...KEYS].reverse().find(k => c[k] != null);
return last ? { ...c, [last]: null } : { ...PLANT };
}
export const samePath = (a, b) => { const x = clean(a), y = clean(b); return KEYS.every(k => x[k] === y[k]); };
// '#b12/r7/t3/s14'; the plant is '#'.
export function toHash(p) {
const c = clean(p);
return '#' + KEYS.filter(k => c[k] != null).map(k => k + c[k]).join('/');
}
// Reads '#b12/r7/t3/s14', 'b12/r7', or '#b12/t30' (a block-wide table, row not yet known).
// Anything else is the plant: a bad link lands on the whole view, never on an error page.
export function fromHash(hash) {
const text = String(hash ?? '').trim().replace(/^#/, '').toLowerCase();
const out = { b: null, r: null, t: null, s: null };
if (!text) return out;
let last = -1;
for (const part of text.split('/').filter(Boolean)) {
const m = /^([brts])(\d{1,6})$/.exec(part), i = m ? KEYS.indexOf(m[1]) : -1;
if (!m || i <= last || Number(m[2]) < 1) return { ...PLANT };
out[m[1]] = Number(m[2]); last = i;
}
if (out.b == null) return { ...PLANT };
if (out.r == null && out.t != null) return { ...out, blockTable: true };
return clean(out);
}
// Breadcrumbs: [{ level, label, path, hash }] from the plant down to where the viewer is; each is a place to fly back to.
export function crumbs(p) {
const c = clean(p), acc = { ...PLANT }, out = [{ level: 'plant', label: 'Plant', path: { ...PLANT }, hash: '#' }];
KEYS.forEach((k, i) => {
if (c[k] == null) return;
acc[k] = c[k];
out.push({ level: LEVELS[i + 1], label: `${NAMES[k]} ${c[k]}`, path: { ...acc }, hash: toHash(acc) });
});
return out;
}
// 'Plant > Block 12 > Row 7 > Table 3 > String 14'
export const crumbText = p => crumbs(p).map(x => x.label).join(' > ');
const range = (where, what, n) => (n > 0 ? `${where}${what} ${n === 1 ? 'is' : 'are'} 1-${n}.` : `${where}there are no ${what.toLowerCase()} yet.`);
// Checks a path against the layout and fills in the row of a block-wide table.
// Returns { ok: true, path } or { ok: false, message, path } with path the deepest valid part (fly there and say why).
export function normalise(p, counts) {
if (!counts) return { ok: false, message: 'No plant is laid out yet: type plant 50 to lay one out.', path: { ...PLANT } };
const out = { ...PLANT };
if (p.b == null) return { ok: true, path: out };
if (!whole(p.b) || p.b > counts.blocks) return { ok: false, message: range('', 'Blocks', counts.blocks), path: out };
out.b = p.b;
let r = p.r, t = p.t;
if (r == null && t != null) { // a block-wide table number: walk the rows to find it
const rows = counts.rows(p.b);
let left = t, total = 0;
for (let i = 1; i <= rows; i++) {
const n = counts.tables(p.b, i); total += n;
if (r == null && whole(left) && left <= n) { r = i; t = left; } else if (r == null) left -= n;
}
if (r == null) return { ok: false, message: range(`Block ${p.b}: `, 'Tables', total), path: { ...out } };
}
if (r == null) return { ok: true, path: out };
const rows = counts.rows(out.b);
if (!whole(r) || r > rows) return { ok: false, message: range(`Block ${out.b}: `, 'Rows', rows), path: { ...out } };
out.r = r;
if (t == null) return { ok: true, path: out };
const tables = counts.tables(out.b, r);
if (!whole(t) || t > tables) return { ok: false, message: range(`Block ${out.b} row ${r}: `, 'Tables', tables), path: { ...out } };
out.t = t;
if (p.s == null) return { ok: true, path: out };
const strings = counts.strings(out.b, r, t);
if (!whole(p.s) || p.s > strings) return { ok: false, message: range(`Table ${t}: `, 'Strings', strings), path: { ...out } };
out.s = p.s;
return { ok: true, path: out };
}
// ---- typed navigation ----
// Navigation needs 'go' first, a compact 'b12 ...', or a '#b12/...' link, so it never takes the design commands
// 'string 28' (modules in series) or 'block 10mva' (block size). parseNav returns null when the line is not navigation
// (so Find can try it as a place). Forms:
// go block 12 table 3 · go b12 r7 t3 s14 · b12 r7 t3 s14 · b12/r7/t3/s14 · #b12/r7 · go row 7 · go string 14 · up · plant
// Result: { kind: 'up' } | { kind: 'plant' } | { kind: 'go', path, relative } | { kind: 'error', message }
const WORD = { b: 'b', blk: 'b', block: 'b', r: 'r', row: 'r', t: 't', tbl: 't', table: 't', s: 's', str: 's', string: 's' };
export function parseNav(line) {
const text = String(line ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
if (!text) return null;
if (/^(go )?up$/.test(text)) return { kind: 'up' };
if (/^(go )?(plant|top|home|whole plant)$/.test(text)) return { kind: 'plant' };
const link = /^#?(b\d+(?:\/[rts]\d+)*)$/.exec(text);
if (link) {
const path = fromHash(link[1]);
return path.b ? { kind: 'go', path, relative: false } : { kind: 'error', message: 'That link does not read as a place, such as #b12/r7/t3/s14.' };
}
const go = /^(?:go to|goto|fly to|fly|go) (.*)$/.exec(text);
const body = go ? go[1] : /^b\d/.test(text) ? text : null;
if (body == null) return null;
const words = body.replace(/([a-z])(\d)/g, '$1 $2').replace(/[,/]/g, ' ').split(' ').filter(Boolean);
const p = {};
for (let i = 0; i < words.length; i++) {
const k = WORD[words[i]];
if (!k) return null; // not a level word: a place name for Find (go compound, go <town>), not ours
const n = words[i + 1];
if (!/^\d{1,6}$/.test(n ?? '')) return { kind: 'error', message: `${lower(k)} needs a number, such as go ${lower(k)} 3` };
if (p[k] != null) return { kind: 'error', message: `${lower(k)} is typed twice` };
p[k] = Number(n); i++;
}
if (!Object.keys(p).length) return null;
const path = { b: p.b ?? null, r: p.r ?? null, t: p.t ?? null, s: p.s ?? null };
if (path.b != null && path.r == null && path.t != null) path.blockTable = true;
if (path.t == null && path.s != null && (path.b != null || path.r != null)) return { kind: 'error', message: 'a string sits on a table: type go block 12 table 3 string 14' };
if (path.b != null && path.r == null && path.t == null && path.s != null) return { kind: 'error', message: 'a string sits on a table: type go block 12 table 3 string 14' };
return { kind: 'go', path, relative: path.b == null };
}
// A relative go ('go row 7', 'go table 3', 'go string 14') keeps the levels above the first one typed from the current path.
// 'go table 3' in a block with no row chosen counts the table across the block.
export function resolve(cmd, current = PLANT) {
if (!cmd) return null;
const c = clean(current);
if (cmd.kind === 'up') return { ok: true, path: up(c) };
if (cmd.kind === 'plant') return { ok: true, path: { ...PLANT } };
if (cmd.kind === 'error') return { ok: false, message: cmd.message, path: c };
const p = cmd.path;
if (!cmd.relative) return { ok: true, path: { b: p.b, r: p.r, t: p.t, s: p.s } };
const first = KEYS.findIndex(k => p[k] != null), out = { ...PLANT };
KEYS.forEach((k, i) => { out[k] = i < first ? c[k] : p[k]; });
if (KEYS[first] === 't' && c.b != null && c.r == null) return { ok: true, path: out }; // block-wide table
const need = KEYS.slice(0, first).find(k => out[k] == null);
if (need) return { ok: false, message: `Go to a ${lower(need)} first, or type the whole place, such as go block 12 table 3.`, path: c };
return { ok: true, path: out };
}
// The existing command grammar's go (cmd-grammar.mjs arg { block, table }) as a path; its table is block-wide.
export const fromGoArg = arg => (arg && whole(arg.block) ? { b: arg.block, r: null, t: whole(arg.table) ? arg.table : null, s: null } : null);
// parse + resolve + normalise: { ok, path, message? }, or null when the line is not navigation.
export function navigate(line, current, counts) {
const cmd = parseNav(line);
if (!cmd) return null;
const r = resolve(cmd, current);
return r.ok ? normalise(r.path, counts) : r;
}