GLOBALGRID2050 / EXPLORE CODE

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

Buggy Physics and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that steps euler (`stepEuler`) and calculates planar distances and angles.

631 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 176 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. Buggy Physics ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/buggy-physics.mjs lines 1–245
  2. Buggy UI geodesy · globalgrid2050 / solar-design-studio/202609271853-site-world/world/buggy-ui.mjs lines 1–185
  3. Build Cmd ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/build-cmd.mjs lines 1–51
  4. Build Geom transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/build-geom.mjs lines 1–98
  5. Build Mount render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/build-mount.mjs lines 1–52

Buggy Physics

A JavaScript module in the world folder of GlobalGrid2050 that steps euler (`stepEuler`) and calculates planar distances and angles.

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/buggy-physics.mjs · lines 1–245 of 245 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern contacts (shared by 2 files)

What it does
Defines 16 functions or classes, including wheels, clamp, params, createBuggy, contacts.
Why it exists in the grid workflow
Domain stage experimental (path word 'buggy'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: Buggy UI (globalgrid2050).
What it achieves
It creates buggy (`createBuggy`) and is built from the wheels step (`wheels`) and the clamp step (`clamp`). The site buggy, a generic utility vehicle, as a small rigid body on the measured ground.
Why it matters
Imported by Buggy UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Views (import)
Used by
imported by Buggy UI (import)
Produces
G, BUGGY, GROUNDS, SIDE_WARN_DEG, X, params, createBuggy, contacts, controls, deriv, release, engage
Defines here
wheels, clamp, params, createBuggy, contacts, controls, deriv, drag, release, engage, tipCheck, stepEuler, hits, advance, parked, readout
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/buggy-physics.mjs:1-245 · blob 4362db9d1e2fdc82f5ec46ee44d05d4d299c9cf1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
// buggy-physics.mjs: the site buggy, a generic utility vehicle, as a small rigid body on the measured ground.
// Pure: no DOM, no WebGL. The same state, inputs, ground and solids give the same result, bit for bit.
//
// The engine (kept simple, robust and cheap, the way small vehicle games do it):
//  * four wheel contacts sample the ground at the wheel positions; the plane through them gives the gradient
//    along the heading (sA, rise over run) and across it (sS, left side higher is positive);
//  * planar motion: speed v along the ground, a kinematic bicycle for the heading (turning circle turnCircleM,
//    the yaw rate capped by grip so a fast turn understeers), gravity along the slope (slows it uphill, rolls it
//    downhill), drive force limited by power and by grip (mu x normal load), so a slope steeper than the grip
//    or the engine can take stalls it and it rolls back; brakes and an automatic park brake, also grip-limited;
//  * sideways: a side slope steeper than the grip makes it slide downhill (u, to the right), else it holds;
//  * suspension: a spring-damper per wheel on the body's height, pitch and roll (small angles), for the view;
//  * fixed steps at hz (120) whatever the frame rate; a hold latch parks it exactly (no creep), and a parked,
//    settled buggy asks for no frames at all.
// Numbers are ASSUMED typical values for a two-seat utility vehicle on site, illustrative, not a make or model.
// The GPU pair check (tools/gpu/buggy_pair.py) runs this same model with two integrators on real ground.

import { blocked } from './views.mjs';

export const G = 9.81;
export const BUGGY = Object.freeze({
  mass: 700, wheelbase: 2.0, track: 1.3, length: 2.9, width: 1.5, // kg (with driver), metres
  turnCircleM: 7.0, maxKmh: 25, reverseKmh: 8,                      // kerb-to-kerb diameter; governed speeds
  driveG: 0.4, powerW: 12000, brakeG: 0.8, engineBrake: 0.6,        // drive force cap (x m g), power, brakes (x g), m/s2
  k: 15500, damp: 1320, rideM: 0.45, Iyy: 400, Ixx: 150,            // per-wheel spring N/m and damper N s/m; inertias kg m2
  steerRate: 5, slideDamp: 3, hz: 960,                              // 1/s steering lag, 1/s sliding friction, physics steps/s
  cgM: 0.75, dragK: 0.05, slideCapKmh: 30,                          // centre of mass height (m); ploughing drag (1/m); slide cap
  riskMargin: 0.6                                                   // "Rollover risk" at this fraction of the tip limit
});
// Grip (friction coefficient mu) and rolling resistance per surface: ASSUMED typical values, editable ("buggy grip 0.4").
export const GROUNDS = Object.freeze({
  grass: { mu: 0.45, crr: 0.06, label: 'dry grass' },
  wet: { mu: 0.3, crr: 0.07, label: 'wet grass' },
  gravel: { mu: 0.6, crr: 0.03, label: 'gravel track' }
});
// A typical side-slope limit printed in utility-vehicle handbooks: 15 degrees (about 27 %). Illustrative only.
export const SIDE_WARN_DEG = 15;
// Tip-over (static stability, ASSUMED centre of mass): it rolls when the sideways pull (gravity across the slope plus
// the turn) over the normal pull passes track / (2 cgM), and pitches over when the slope passes (wheelbase / 2) / cgM.
// Past the limit it stops tipped (no flying); getting on again rights it. Illustrative, not a rollover simulation.

// State vector: positions X Y PSI Z TH PH, velocities V U D VZ WTH WPH (D is the steering angle, lagged).
export const X = 0, Y = 1, PSI = 2, V = 3, U = 4, D = 5, Z = 6, VZ = 7, TH = 8, WTH = 9, PH = 10, WPH = 11, N = 12;
const VEL = [V, U, D, VZ, WTH, WPH], POS = [X, Y, PSI, Z, TH, PH];
// Wheels: front-left, front-right, rear-left, rear-right; a forward of the centre, b to the right.
const wheels = P => { const a = P.wheelbase / 2, b = P.track / 2; return [[a, -b], [a, b], [-a, -b], [-a, b]]; };
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);

export function params(over = {}) {
  const P = { ...BUGGY, ...GROUNDS.grass, ...over };
  P.vmax = P.maxKmh / 3.6; P.vrev = P.reverseKmh / 3.6;
  // turning circle: the outer front wheel's path, kerb to kerb; the body's centre (the reference point, moving along
  // the heading) turns on radius Rc = wheelbase / tan(steer)
  const Rc = Math.sqrt((P.turnCircleM / 2) ** 2 - (P.wheelbase / 2) ** 2) - P.track / 2;
  P.deltaMax = Math.atan(P.wheelbase / Rc);
  P.rest = P.rideM + (P.mass * G) / (4 * P.k);                            // unloaded spring: loaded, the body sits at rideM
  P.dt = 1 / P.hz; P.vcap = P.slideCapKmh / 3.6;
  P.tipSide = P.track / (2 * P.cgM); P.tipAlong = P.wheelbase / 2 / P.cgM;
  return P;
}

// A new buggy at (x, y) facing yaw (0 north, +pi/2 east), settled on the ground.
export function createBuggy(x, y, yaw, heightAt, over = {}) {
  const P = params(over), s = new Float64Array(N);
  s[X] = x; s[Y] = y; s[PSI] = yaw;
  const c = contacts(s, P, heightAt);
  s[Z] = c.mean + P.rideM;
  s[TH] = Math.atan(c.sA); s[PH] = Math.atan(c.sS); // lean with the ground: nose up on a rise, left side up on a side slope
  const bug = { P, s, held: true, uHeld: true, acc: 0, steps: 0, stalled: false, gripLimited: false, hit: false, last: null,
    tipped: false, risk: 0, capped: false };
  deriv(s, { t: 0, steer: 0, b: 0 }, bug, heightAt);
  return bug;
}

// Ground under the four wheels, and the plane through them.
export function contacts(s, P, heightAt) {
  const sp = Math.sin(s[PSI]), cp = Math.cos(s[PSI]), h = [0, 0, 0, 0];
  const W = wheels(P);
  for (let i = 0; i < 4; i++) {
    const [a, b] = W[i];
    h[i] = heightAt(s[X] + a * sp + b * cp, s[Y] + a * cp - b * sp);
  }
  const sA = ((h[0] + h[1]) - (h[2] + h[3])) / (2 * P.wheelbase), sS = ((h[0] + h[2]) - (h[1] + h[3])) / (2 * P.track);
  return { h, sA, sS, mean: (h[0] + h[1] + h[2] + h[3]) / 4 };
}

// Driver input to the model's controls: forward in [-1, 1], steer in [-1, 1], brake 0 or 1. Pulling back while
// rolling forward (or pushing while rolling back) brakes first; from rest it reverses.
export function controls(v, forward, steer, brake) {
  let t = clamp(forward, -1, 1), b = brake ? 1 : 0;
  if ((t < 0 && v > 0.3) || (t > 0 && v < -0.3)) { b = Math.max(b, Math.abs(t)); t = 0; }
  if (b) t = 0;
  return { t, steer: clamp(steer, -1, 1), b };
}

// The continuous model: d(state)/dt, with the controls held for the step. held / uHeld pin v / u at zero.
export function deriv(s, c, bug, heightAt, out = new Float64Array(N)) {
  const P = bug.P, k = contacts(s, P, heightAt);
  const cosA = 1 / Math.sqrt(1 + k.sA * k.sA), sinA = k.sA * cosA, cosB = 1 / Math.sqrt(1 + k.sS * k.sS), sinB = k.sS * cosB;
  const gN = G * cosA * cosB, muN = P.mu * gN, v = s[V];
  // along the ground: drive (power and governor limited), resistance, grip cap, gravity
  let F = 0;
  if (c.t > 0) F = c.t * Math.min(P.driveG * G, P.powerW / (P.mass * Math.max(Math.abs(v), 1))) * clamp((P.vmax - v) / 0.25, 0, 1);
  else if (c.t < 0) F = c.t * P.driveG * G * clamp((P.vrev + v) / 0.25, 0, 1);
  const R = c.b * P.brakeG * G + (c.t === 0 ? P.engineBrake : 0) + P.crr * gN;
  const gov = Math.max(0, Math.abs(v) - P.vmax) * 6 * Math.sign(v); // held at the governed speed downhill too
  const Fx = clamp(F - R * clamp(v / 0.1, -1, 1) - gov, -muN, muN);
  // Past the governed speed the grip has gone (the governor holds it otherwise): the tyres plough (ground drag, dragK
  // times the excess squared, assumed) and past the slide cap a stiff pull holds it there, so a slide stays physical.
  const drag = (w, from) => { const e = Math.max(0, Math.abs(w) - from); return (P.dragK * e * e + Math.max(0, Math.abs(w) - P.vcap) * 60) * Math.sign(w); };
  out[V] = bug.held ? 0 : Fx - G * sinA - drag(v, P.vmax);
  // across: a side slope past the grip slides it downhill; sliding friction settles it
  const ex = Math.max(0, Math.abs(sinB) - P.mu * cosB) * G * Math.sign(k.sS);
  out[U] = bug.uHeld ? 0 : ex - P.slideDamp * s[U] - drag(s[U], 0);
  out[D] = P.steerRate * (c.steer * P.deltaMax - s[D]);
  // heading: kinematic bicycle, capped where the turn would need more grip than the ground has
  const vh = v * cosA, cap = muN / Math.max(Math.abs(vh), 0.5);
  const r = clamp(vh * Math.tan(s[D]) / P.wheelbase, -cap, cap);
  const sp = Math.sin(s[PSI]), cp = Math.cos(s[PSI]);
  out[X] = vh * sp + s[U] * cp; out[Y] = vh * cp - s[U] * sp; out[PSI] = r;
  // suspension: four spring-dampers push the body up; small angles
  const W = wheels(P);
  let Fz = 0, Mt = 0, Mp = 0;
  for (let i = 0; i < 4; i++) {
    const [a, b] = W[i];
    const comp = k.h[i] + P.rest - (s[Z] + a * s[TH] - b * s[PH]);
    const rate = s[VZ] + a * s[WTH] - b * s[WPH];
    const f = Math.max(0, P.k * comp - P.damp * rate);
    Fz += f; Mt += a * f; Mp -= b * f;
  }
  out[Z] = s[VZ]; out[VZ] = Fz / P.mass - G;
  out[TH] = s[WTH]; out[WTH] = Mt / P.Iyy;
  out[PH] = s[WPH]; out[WPH] = Mp / P.Ixx;
  bug.last = { k, cosA, sinA, sinB, gN, muN, Fx, F, R, ex, r, vh };
  return out;
}

// Between steps: the hold latches (park brake and side grip), so a parked buggy stays exactly put. bug.last is the
// model at the current place. Before a step a latch lets go (throttle, or a pull past the hold); after it, one engages.
export function release(bug, c) {
  const { sinA, muN, ex } = bug.last, P = bug.P;
  if (bug.held && (c.t !== 0 || G * Math.abs(sinA) >= Math.min(P.brakeG * G, muN))) bug.held = false;
  if (bug.uHeld && ex !== 0) bug.uHeld = false;
}
export function engage(bug, c) {
  const { sinA, muN, ex, Fx } = bug.last, s = bug.s, P = bug.P;
  if (!bug.held && c.t === 0 && Math.abs(s[V]) < 0.05 && G * Math.abs(sinA) < Math.min(P.brakeG * G, muN)) { bug.held = true; s[V] = 0; }
  if (!bug.uHeld && ex === 0 && Math.abs(s[U]) < 0.02) { bug.uHeld = true; s[U] = 0; }
  bug.gripLimited = !bug.held && muN > 0 && Math.abs(Fx) >= muN - 1e-9;
  bug.capped = Math.hypot(s[V], s[U]) > P.vcap - 0.1;
  tipCheck(bug);
}
// Tip-over from the centre of mass and the track: margin 1 is the limit; past it the buggy stops, tipped.
export function tipCheck(bug) {
  const { sinA, sinB, gN, r, vh } = bug.last, s = bug.s, P = bug.P;
  const side = (G * sinB - vh * r) / gN, along = G * sinA / gN; // + right; a right turn throws the load left
  const mSide = Math.abs(side) / P.tipSide, mAlong = Math.abs(along) / P.tipAlong;
  bug.risk = Math.max(mSide, mAlong);
  if (bug.risk < 1) return false;
  bug.tipped = true; bug.held = bug.uHeld = true;
  s[V] = s[U] = s[VZ] = s[WTH] = s[WPH] = s[D] = 0;
  if (mSide >= mAlong) s[PH] = 1.2 * Math.sign(side || 1); else s[TH] = 1.2 * Math.sign(along || 1); // on its side, or its nose / tail
  return true;
}

const k1 = new Float64Array(N), k2 = new Float64Array(N);
// One fixed step, semi-implicit (symplectic) Euler: velocities first, then positions with the new velocities.
export function stepEuler(bug, c, heightAt) {
  const s = bug.s, dt = bug.P.dt;
  bug.steps++;
  if (bug.tipped) return; // lies where it tipped until someone rights it
  release(bug, c);
  deriv(s, c, bug, heightAt, k1);
  for (const i of VEL) s[i] += dt * k1[i];
  deriv(s, c, bug, heightAt, k2);
  for (const i of POS) s[i] += dt * k2[i];
  s[PSI] = Math.atan2(Math.sin(s[PSI]), Math.cos(s[PSI]));
  deriv(s, c, bug, heightAt, k1); // bug.last at the new place: for the latches and the readout
  engage(bug, c);
}

// Collisions: the buggy's outline (corners and mid-sides) against solid boxes (tables, compounds, fences).
export function hits(s, P, heightAt, solids) {
  if (!solids?.length) return false;
  const sp = Math.sin(s[PSI]), cp = Math.cos(s[PSI]), a = P.length / 2, b = P.width / 2;
  const body = { radius: 0.15, below: -0.15, above: 1.9 }; // from 0.15 m above the ground to 2.05 m (roll cage)
  for (const [f, r] of [[a, -b], [a, 0], [a, b], [0, -b], [0, b], [-a, -b], [-a, 0], [-a, b]]) {
    const x = s[X] + f * sp + r * cp, y = s[Y] + f * cp - r * sp;
    if (blocked([x, y, heightAt(x, y)], body, solids)) return true;
  }
  return false;
}

// Advances the buggy by a frame of dtS seconds in fixed steps (at most 0.1 s a frame). A step that would put it
// into a solid is undone and the buggy stops against it. Returns the number of steps taken.
export function advance(bug, input, dtS, heightAt, solids = []) {
  bug.acc += Math.min(Math.max(dtS, 0), 0.1) * bug.P.hz; // counted in steps, so 30 and 120 fps frames give the same steps
  const steps = Math.floor(bug.acc + 1e-9);
  bug.acc = Math.max(0, bug.acc - steps);
  const prev = new Float64Array(N);
  let n = 0;
  for (; n < steps; n++) {
    const c = controls(bug.s[V], input.forward || 0, input.steer || 0, input.brake);
    prev.set(bug.s);
    stepEuler(bug, c, heightAt);
    bug.stalled = (input.forward || 0) > 0 && bug.s[V] < -0.05; // pressing on, rolling back
    bug.hit = hits(bug.s, bug.P, heightAt, solids);
    if (bug.hit) {
      bug.s[X] = prev[X]; bug.s[Y] = prev[Y]; bug.s[PSI] = prev[PSI];
      bug.s[V] = 0; bug.s[U] = 0; bug.held = c.t === 0; bug.uHeld = true;
      deriv(bug.s, c, bug, heightAt);
    }
  }
  return n;
}

// Parked: held on both axes, steering still and the suspension settled. Then no frame is needed.
export function parked(bug, input = {}) {
  const s = bug.s, q = 2e-3;
  if (bug.tipped) return true;
  return bug.held && bug.uHeld && !input.forward && !input.steer &&
    Math.abs(s[VZ]) < q && Math.abs(s[WTH]) < q && Math.abs(s[WPH]) < q && Math.abs(s[D]) < q;
}

const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
// What the driver reads: speed, heading, the gradient under the wheels, and the warnings.
export function readout(bug) {
  const s = bug.s, k = bug.last?.k || { sA: 0, sS: 0 };
  const deg = ((s[PSI] * 180 / Math.PI) % 360 + 360) % 360;
  const along = 100 * k.sA * Math.sign(s[V] || 1), side = 100 * Math.abs(k.sS);
  const sideDeg = Math.atan(Math.abs(k.sS)) * 180 / Math.PI;
  const warn = [];
  if (sideDeg > SIDE_WARN_DEG) warn.push(`Side slope ${Math.round(side)} % (${sideDeg.toFixed(0)}°) is past a typical ${SIDE_WARN_DEG}° utility-vehicle limit (illustrative)`);
  if (bug.stalled) warn.push('Stalled: too steep for the grip or the engine, rolling back');
  else if (!bug.uHeld) warn.push('Sliding sideways: the side slope is steeper than the grip');
  else if (bug.gripLimited && !bug.held) warn.push('Wheels at the grip limit');
  if (bug.capped) warn.push(`Sliding at the ${bug.P.slideCapKmh} km/h slide cap (illustrative)`);
  if (bug.hit) warn.push('Stopped against a solid');
  const danger = bug.tipped ? ['Rolled over: the buggy is on its side. Get off (E) and on again to right it']
    : bug.risk >= bug.P.riskMargin ? [`Rollover risk: ${Math.round(100 * bug.risk)} % of the tip limit (illustrative)`] : [];
  return {
    danger, risk: bug.risk, tipped: bug.tipped, kmh: Math.hypot(s[V], s[U]) * 3.6, heading: deg, compass: COMPASS[Math.round(deg / 45) % 8],
    gradient: 100 * Math.hypot(k.sA, k.sS), along, side, sideDeg, warn
  };
}

Buggy UI

A JavaScript module in the world folder of GlobalGrid2050 that creates driver (`createDriver`), writes hud (`writeHud`) and calculates planar distances, covering LiDAR terrain.

geodesyglobalgrid2050 / solar-design-studio/202609271853-site-world/world/buggy-ui.mjs · lines 1–185 of 185 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern cameraFor (shared by 2 files)

What it does
It draws LiDAR terrain. Defines 20 functions or classes, including wrap, clamp, dir, buggyLines, P. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'buggy'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: LiDAR terrain.
Downstream impact
Used directly by 1 file: Buggy Mount (globalgrid2050).
What it achieves
It creates driver (`createDriver`) and writes hud (`writeHud`). Driving the site buggy (loaded on first use by `buggy-mount.mjs`). Its code works with 120 Hz. It responds to click, keydown and keyup events.
Why it matters
Imported by Buggy Mount.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
Buggy Physics (import), Views (import)
Used by
imported by Buggy Mount (dynamic import)
Produces
buggyLines, cameraFor, createDriver
Defines here
wrap, clamp, dir, buggyLines, P, seg, box, q, cameraFor, createDriver, heightAt, typing, follow, swapCam, mount, dismount, writeHud, frame, command, onText
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/buggy-ui.mjs:1-185 · blob 11a2723617db342d892ee0ffef34a40fc01e9154 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// buggy-ui.mjs: driving the site buggy (loaded on first use by buggy-mount.mjs). While mounted, the substrate hands
// each frame to this driver (api.setDriver): the physics steps at a fixed 120 Hz (buggy-physics.mjs) on the ground
// everyone stands on (api.heightAt: the LiDAR with the design's trenches cut in), the solids stop it, and the view
// is a chase camera or the driver's seat (C, or the chip in the readout). Keys: W / S or up / down drive and brake
// then reverse, A / D or left / right steer, Space brakes, E gets off. Phones: the joypad drives.
// A parked, settled buggy asks for no frames (0 fps); the buggy stays where it was left and is drawn there.

import { createBuggy, advance, parked, readout, params, GROUNDS, X, Y, PSI, V, Z, TH, PH } from './buggy-physics.mjs';
import { PITCH_LIMIT } from './views.mjs';

const TURN_PER_S = 1.8;                 // input.mjs: a full turn input reads 1.8 rad/s; the buggy reads it as full lock
const CHASE = { dist: 7, pitch: -0.22, aim: 0.8 }, SEAT = { fwd: -0.15, up: 1.0 }, EYE_WALK = 1.7;
const REACH_M = 8;                      // E within this of the parked buggy gets back on it; further, a new one comes
const COLOR = [1, 0.78, 0.45, 1];
const CSS = `#buggy-hud { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(var(--foot) + 8px); max-width: calc(100vw - 24px);
  box-sizing: border-box; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; padding: 4px 8px; font-size: 11px;
  display: flex; flex-wrap: wrap; gap: 2px 10px; align-items: center; }
#buggy-hud[hidden] { display: none; } #buggy-hud b { color: #ffc773; font-weight: 600; } #buggy-hud .dim { color: var(--dim); }
#buggy-hud .warn { flex-basis: 100%; color: #ffb27a; } #buggy-hud .danger { flex-basis: 100%; color: #ff5a5a; font-weight: 600; }
#buggy-hud .warn:empty, #buggy-hud .danger:empty { display: none; }
#buggy-hud button { background: none; color: var(--dim); border: 1px solid var(--edge); border-radius: 10px; font: inherit; padding: 1px 8px; cursor: pointer; }
@media (pointer: coarse) { #buggy-hud { bottom: auto; top: calc(var(--btn) + 40px); } #buggy-hud button { min-height: 32px; } }`;
const wrap = a => Math.atan2(Math.sin(a), Math.cos(a));
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const dir = (yaw, pitch) => [Math.sin(yaw) * Math.cos(pitch), Math.cos(yaw) * Math.cos(pitch), Math.sin(pitch)];

// The buggy as lines, relative to its body point; (a forward, b right, h up) in the body's frame, pitched and rolled.
export function buggyLines(bug) {
  const s = bug.s, sp = Math.sin(s[PSI]), cp = Math.cos(s[PSI]), th = s[TH], ph = s[PH], out = [];
  const P = (a, b, h) => [a * sp + b * cp, a * cp - b * sp, h + a * th - b * ph];
  const seg = (p, q) => out.push(...p, ...q);
  const box = (a0, a1, b, h0, h1) => { // an open frame: two side rectangles joined across
    for (const bb of [-b, b]) { seg(P(a0, bb, h0), P(a1, bb, h0)); seg(P(a0, bb, h1), P(a1, bb, h1)); seg(P(a0, bb, h0), P(a0, bb, h1)); seg(P(a1, bb, h0), P(a1, bb, h1)); }
    for (const [a, h] of [[a0, h0], [a1, h0], [a0, h1], [a1, h1]]) seg(P(a, -b, h), P(a, b, h));
  };
  const L = bug.P.length / 2, W = bug.P.width / 2;
  box(-L, L, W, -0.1, 0.25);            // chassis and bed sides
  box(0.55, L, W - 0.05, 0.25, 0.5);    // bonnet
  box(-0.55, 0.45, W - 0.05, 0.25, 1.55); // roll cage
  seg(P(0.45, -W + 0.05, 1.55), P(0.75, -W + 0.1, 0.5)); seg(P(0.45, W - 0.05, 1.55), P(0.75, W - 0.1, 0.5)); // windscreen posts
  const h = bug.last?.k?.h || [0, 0, 0, 0], a = bug.P.wheelbase / 2, b = bug.P.track / 2, r = 0.3;
  [[a, -b], [a, b], [-a, -b], [-a, b]].forEach(([wa, wb], i) => { // wheels stand on the ground under them
    const c = P(wa, wb, 0), cz = h[i] + r - s[Z];
    for (let k = 0; k < 10; k++) {
      const q = t => { const u = Math.cos(t) * r, w = Math.sin(t) * r; return [c[0] + u * sp, c[1] + u * cp, cz + w]; };
      seg(q(k * Math.PI / 5), q((k + 1) * Math.PI / 5));
    }
  });
  return new Float32Array(out);
}

// The view: chase (behind and above, easing round to the heading) or the driver's seat. The walker's yaw and pitch
// carry what the mouse or a finger dragged; the camera eases back to the heading while the buggy moves.
export function cameraFor(bug, view, cam, dt, heightAt, userPitch) {
  const s = bug.s, moving = Math.abs(s[V]) > 0.3;
  let yaw = view.yaw;
  if (moving) yaw = wrap(yaw + wrap(s[PSI] - yaw) * Math.min(1, 3 * dt));
  if (cam === 'seat') {
    const sp = Math.sin(s[PSI]), cp = Math.cos(s[PSI]);
    const pos = [s[X] + SEAT.fwd * sp, s[Y] + SEAT.fwd * cp, s[Z] + SEAT.up + SEAT.fwd * s[TH]];
    return { pos, yaw, pitch: clamp(userPitch + Math.atan(s[TH]), -PITCH_LIMIT, PITCH_LIMIT) };
  }
  const pitch = clamp(view.pitch, -1.2, 0.2), d = dir(yaw, pitch), aim = [s[X], s[Y], s[Z] + CHASE.aim];
  const pos = [aim[0] - CHASE.dist * d[0], aim[1] - CHASE.dist * d[1], aim[2] - CHASE.dist * d[2]];
  pos[2] = Math.max(pos[2], heightAt(pos[0], pos[1]) + 0.6); // never under a hill behind
  return { pos, yaw, pitch };
}

// deps: { api (substrate: state, setPose, setView, setDriver, heightAt, measuredAt, solids, origin, hooks, resumeGate), doc, chip }
export function createDriver({ api, doc = document, chip = null }) {
  let bug = null, mounted = false, cam = 'chase', over = {}, brake = false, userPitch = -0.08, lastOutPitch = 0;
  let seen = null, version = 0, cached = null, lastInput = {}, was = false;
  const heightAt = (x, y) => api.heightAt(x, y);
  const style = doc.createElement('style'); style.textContent = CSS; doc.head.append(style);
  const hud = doc.createElement('div'); hud.id = 'buggy-hud'; hud.hidden = true; hud.setAttribute('role', 'status');
  hud.innerHTML = '<b>Buggy</b><span class="read"></span><button type="button" class="cam"></button><span class="danger"></span><span class="warn"></span>';
  doc.body.append(hud);
  const camBtn = hud.querySelector('.cam');
  camBtn.addEventListener('click', () => { swapCam(); (doc.getElementById('view') || doc.body).focus?.(); });
  const typing = t => t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || t?.isContentEditable;
  addEventListener('keydown', e => {
    if (!mounted || e.ctrlKey || e.metaKey || e.altKey || typing(e.target)) return;
    if (e.code === 'Space') { brake = true; api.gate.invalidate(); }
    if (e.code === 'KeyC' && !e.repeat) swapCam();
  });
  addEventListener('keyup', e => { if (e.code === 'Space') brake = false; });
  addEventListener('blur', () => { brake = false; });

  // setOrigin moves the site origin under us: the buggy keeps its place in the world.
  function follow() {
    const o = api.origin();
    if (bug && seen && (o.e !== seen.e || o.n !== seen.n)) { bug.s[X] -= o.e - seen.e; bug.s[Y] -= o.n - seen.n; version++; }
    seen = o;
  }
  function swapCam() {
    cam = cam === 'chase' ? 'seat' : 'chase';
    if (mounted) api.setPose({ pitch: cam === 'chase' ? CHASE.pitch : 0 });
    userPitch = -0.08; lastOutPitch = api.state().pitch;
    writeHud(); api.gate.invalidate();
  }
  function mount() {
    if (mounted) return;
    if (api.state().view !== 'standing') api.setView('standing');
    follow();
    const st = api.state();
    if (!bug || bug.tipped || Math.hypot(bug.s[X] - st.pos[0], bug.s[Y] - st.pos[1]) > REACH_M) { // a tipped one is righted
      bug = bug?.tipped && Math.hypot(bug.s[X] - st.pos[0], bug.s[Y] - st.pos[1]) <= REACH_M
        ? createBuggy(bug.s[X], bug.s[Y], bug.s[PSI], heightAt, over) : createBuggy(st.pos[0], st.pos[1], st.yaw, heightAt, over);
      version++;
    }
    mounted = true;
    api.setPose({ yaw: bug.s[PSI], pitch: cam === 'chase' ? CHASE.pitch : 0 });
    lastOutPitch = api.state().pitch; userPitch = -0.08;
    api.setDriver(driver);
    chip?.setAttribute('aria-pressed', 'true'); if (chip) chip.textContent = 'Get off';
    hud.hidden = false; writeHud();
  }
  // Getting off: the walker stands beside the driver's door, facing the way the buggy faces.
  function dismount(place = true) {
    if (!mounted) return;
    mounted = false; brake = false;
    api.setDriver(null);
    if (place && bug) {
      const s = bug.s, sp = Math.sin(s[PSI]), cp = Math.cos(s[PSI]), x = s[X] - 1.4 * cp, y = s[Y] + 1.4 * sp;
      api.setPose({ pos: [x, y, heightAt(x, y) + EYE_WALK], yaw: s[PSI], pitch: -0.12 });
    }
    chip?.setAttribute('aria-pressed', 'false'); if (chip) chip.textContent = 'Buggy';
    hud.hidden = true; api.gate.invalidate();
  }
  function writeHud() {
    if (!bug || hud.hidden) return;
    const r = readout(bug), P = bug.P, g = over.ground ? GROUNDS[over.ground].label : 'dry grass';
    const measured = Number.isFinite(api.measuredAt?.(bug.s[X], bug.s[Y]));
    hud.querySelector('.read').textContent = `${r.kmh.toFixed(0)} km/h (limit ${P.maxKmh}) · ${r.heading.toFixed(0).padStart(3, '0')}° ${r.compass} · ` +
      `gradient ${r.gradient.toFixed(0)} % (along ${r.along >= 0 ? '+' : ''}${r.along.toFixed(0)} %, side ${r.side.toFixed(0)} %) · ` +
      `${g}, grip ${P.mu} · ${measured ? 'LiDAR ground' : 'ground not measured here'} · illustrative`;
    hud.querySelector('.warn').textContent = r.warn.join(' · ');
    hud.querySelector('.danger').textContent = r.danger.join(' · ');
    camBtn.textContent = cam === 'chase' ? 'Seat view (C)' : 'Chase view (C)';
  }
  // Each frame while mounted (the substrate's draw calls this instead of the walk step).
  function frame(state, inp, intervalMs) {
    follow();
    lastInput = { forward: inp.forward || 0, steer: (inp.turn || 0) / TURN_PER_S, brake };
    const dt = Math.min(intervalMs / 1000, 0.1);
    if (advance(bug, lastInput, dt, heightAt, api.solids())) version++;
    if (cam === 'seat') { userPitch = clamp(userPitch + (state.pitch - lastOutPitch), -1.2, 1.2); }
    const c = cameraFor(bug, state, cam, dt, heightAt, userPitch);
    lastOutPitch = c.pitch;
    writeHud();
    const now = !parked(bug, lastInput);
    if (was && !now) queueMicrotask(() => api.resumeGate()); // settled: the frame gate stops asking for frames
    was = now;
    return { ...state, ...c };
  }
  const driver = { frame, moving: () => mounted && !!bug && !parked(bug, lastInput) };
  api.hooks.before.add(() => { if (mounted && api.state().view !== 'standing') dismount(false); }); // Drone takes over
  api.hooks.batches.add(() => {
    if (!bug) return [];
    follow();
    if (!cached || cached.version !== version) cached = { version, positions: buggyLines(bug) };
    return [{ key: 'buggy', version, positions: cached.positions, color: COLOR, origin: [bug.s[X], bug.s[Y], bug.s[Z]] }];
  });

  function command(p) {
    if (p.act === 'toggle') { mounted ? dismount() : mount(); return mounted ? onText() : 'Off the buggy; it stays parked where you left it.'; }
    if (p.act === 'on') { mount(); return onText(); }
    if (p.act === 'off') { dismount(); return 'Off the buggy; it stays parked where you left it.'; }
    if (p.act === 'seat' || p.act === 'chase') { if (cam !== p.act) swapCam(); return `${p.act === 'seat' ? "Driver's seat" : 'Chase'} view.`; }
    if (p.act === 'speed') over = { ...over, maxKmh: p.value };
    if (p.act === 'grip') over = { ...over, mu: p.value };
    if (p.act === 'ground') over = { ...over, ground: p.value, mu: GROUNDS[p.value].mu, crr: GROUNDS[p.value].crr };
    if (bug) { bug.P = params(over); writeHud(); }
    const P = params(over);
    return `Buggy: top speed ${P.maxKmh} km/h, ${over.ground ? GROUNDS[over.ground].label : 'dry grass'} grip ${P.mu}, rolling resistance ${P.crr} (assumed, illustrative).`;
  }
  const onText = () => { const P = bug.P; return `On the buggy: W / S or the pad drive, A / D steer, Space brakes, C swaps seat and chase views, E gets off. ` +
    `Top speed ${P.maxKmh} km/h, turning circle ${P.turnCircleM} m, grip ${P.mu} (assumed, illustrative).`; };

  return {
    toggle: () => (mounted ? dismount() : mount()), mount, dismount, command,
    debug: () => ({ mounted, loaded: true, cam, parked: bug ? parked(bug, lastInput) : null, steps: bug?.steps ?? 0,
      state: bug ? Array.from(bug.s) : null, readout: bug ? readout(bug) : null, params: bug ? { maxKmh: bug.P.maxKmh, mu: bug.P.mu, crr: bug.P.crr } : null })
  };
}

Build Cmd

A JavaScript module in the world folder of GlobalGrid2050 that works with setting lines (`settingLines`). It parses build (`parseBuild`) and is built from the setting lines helper (`settingLines`).

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/build-cmd.mjs · lines 1–51 of 51 · version 2026-09-27 18:53

What it does
It lists and searches its content. Defines no, parseBuild, settingLines.
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.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Build UI (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
The typed side of build mode.
Why it matters
Imported by Build UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Cmd Grammar (import)
Used by
imported by Build UI (import)
Produces
BUILD_USAGE, parseBuild, settingLines
Defines here
no, parseBuild, settingLines
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/build-cmd.mjs:1-51 · blob d2e8b57e810e9e724cd805df2d710f9e3654789d · 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
// build-cmd.mjs: the typed side of build mode. Every click in build mode has a line, and every line can be typed:
//   build table [at E N] · build inverter [at E N] · build undo · build clear · build done · build (status)
//   build string N (modules in series) · build mppt N (MPPT inputs an inverter) · build trench W (DC trench, m) · build slope N (%)
// parseBuild(line) -> null when the line is not a build line (the command line's own grammar takes it), else
// { ok: true, act, kind?, at?, key?, value? } or { ok: false, why }. Values are guarded by cmd-grammar.mjs's own table,
// so a slip reads the same ("trench width must be a number from 0.25 to 3 m; you typed 45. Did you mean 0.45 m?").
// Pure: no DOM.

import { guard } from './cmd-grammar.mjs';

export const BUILD_USAGE = ['build table', 'build table at 399121 208440', 'build inverter at 399160 208430', 'build undo', 'build clear',
  'build done', 'build string 28', 'build mppt 12', 'build trench 0.55', 'build slope 15'];
const SETTINGS = { string: ['mps', 'modules in series'], mppt: ['mppt', 'MPPT inputs an inverter'], trench: ['width', 'DC trench width'], slope: ['slope', 'slope limit'] };
const no = why => ({ ok: false, why: `${why} Nothing was changed.` });

export function parseBuild(line) {
  const t = String(line || '').toLowerCase().replace(/#.*$/, '').replace(/,/g, ' ').trim().split(/\s+/).filter(Boolean);
  if (t[0] !== 'build' && t[0] !== 'place') return null;
  const [, w, ...rest] = t;
  if (!w || w === 'status') return { ok: true, act: 'status' };
  if (['undo', 'clear', 'done', 'off'].includes(w)) return rest.length ? no(`build ${w} takes nothing after it.`) : { ok: true, act: w === 'off' ? 'done' : w };
  if (w === 'table' || w === 'tables' || w === 'inverter' || w === 'inverters') {
    const kind = w.startsWith('table') ? 'table' : 'inverter';
    if (!rest.length) return { ok: true, act: 'place', kind, at: null };
    const nums = rest[0] === 'at' ? rest.slice(1).map(Number) : [];
    if (nums.length !== 2 || !nums.every(Number.isFinite)) return no(`build ${kind} takes "at" and an easting and northing in metres, e.g. build ${kind} at 399121 208440.`);
    const [e, n] = nums;
    if (!(e > 0 && e < 700000 && n > 0 && n < 1300000)) return no('the easting and northing are national-grid metres (easting 0 to 700000).');
    return { ok: true, act: 'place', kind, at: { e, n } };
  }
  if (SETTINGS[w]) {
    const [key, label] = SETTINGS[w], m = String(rest.find(x => x !== 'width' && x !== 'min' && x !== 'max') || '').match(/^(-?\d+(?:\.\d+)?)(m|cm|mm|%)?$/);
    if (!m) return no(`build ${w} needs a number (${label}), e.g. ${BUILD_USAGE.find(u => u.startsWith('build ' + w))}.`);
    let v = Number(m[1]);
    if (key === 'width' && (m[2] === 'cm' || m[2] === 'mm')) v /= m[2] === 'cm' ? 100 : 1000;
    if (key === 'mppt') { if (!(Number.isInteger(v) && v >= 1 && v <= 24)) return no(`MPPT inputs an inverter must be a whole number from 1 to 24; you typed ${v}.`); }
    else { const g = guard(key, v); if (g) return no(g.replace('trench width', 'DC trench width') + '.'); }
    return { ok: true, act: 'set', key: { mps: 'mps', mppt: 'mppt', width: 'trenchW', slope: 'slopePct' }[key], value: v };
  }
  return no(`build does not read "${w}". Try ${BUILD_USAGE.slice(0, 3).join(', ')}, build undo.`);
}

/** The typed lines for settings that differ from the defaults (a saved design replays them first). */
export function settingLines(P, D) {
  const out = [];
  if (P.mps !== D.mps) out.push(`build string ${P.mps}`);
  if (P.mppt !== D.mppt) out.push(`build mppt ${P.mppt}`);
  if (P.trenchW !== D.trenchW) out.push(`build trench ${P.trenchW}`);
  if (P.slopePct !== D.slopePct) out.push(`build slope ${P.slopePct}`);
  return out;
}

Build Geom

A JavaScript module in the world folder of GlobalGrid2050 that works with table frame (`tableFrame`) and inverter box (`inverterBox`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/build-geom.mjs · lines 1–98 of 98 · version 2026-09-27 18:53 · pattern group (shared by 18 files)

What it does
It calculates its inputs. Defines 11 functions or classes, including group, put, seg, done, tableFrame.
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.
Downstream impact
Used directly by 1 file: Build UI (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 group step (`group`), the put step (`put`) and the seg step (`seg`). What build mode draws, as line groups in national-grid metres ({ base: [e, n, z], v: Float32Array relative to base }), and the piles of the built tables on the plant's own engine (`plant-piles.mjs`).
Why it matters
Imported by Build UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Plant Piles (import), Build Rules (import)
Used by
imported by Build UI (import)
Produces
tableFrame, inverterBox, outline, run, sceneGroups, ghostGroup, builtPiles
Defines here
group, put, seg, done, tableFrame, inverterBox, outline, run, sceneGroups, ghostGroup, builtPiles
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/build-geom.mjs:1-98 · blob b3a20fb5aa19105cb572810aeda60fe452cc3e5d · 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
// build-geom.mjs: what build mode draws, as line groups in national-grid metres ({ base: [e, n, z], v: Float32Array
// relative to base }), and the piles of the built tables on the plant's own engine (plant-piles.mjs). Pure: no DOM.
// ground(e, n) is the ground to draw on (the design's ground; never NaN). Light: a table is 15 segments, a pile 1.

import { planTables, pileSummary, STRIDE } from './plant-piles.mjs';
import { tableOf } from './build-rules.mjs';

function group() { return { base: null, v: [] }; }
const put = (G, p) => { if (!G.base) G.base = [p[0], p[1], p[2]]; G.v.push(p[0] - G.base[0], p[1] - G.base[1], p[2] - G.base[2]); };
const seg = (G, a, b) => { put(G, a); put(G, b); };
const done = G => ({ base: G.base || [0, 0, 0], v: new Float32Array(G.v), count: G.v.length / 3 });

/** A table's frame on the ground: low edge, high edge, end rafters, the row joint (one string a row), posts at the ends. */
export function tableFrame(G, t, T, ground) {
  const e0 = t.e, e1 = t.e + T.len, n0 = t.n, n1 = t.n + T.depth, xs = [0, 0.25, 0.5, 0.75, 1].map(k => e0 + (e1 - e0) * k);
  const low = xs.map(e => [e, n0, ground(e, n0) + T.lowEdge]), high = xs.map(e => [e, n1, ground(e, n0) + T.lowEdge + T.rise]);
  const mid = xs.map((e, i) => [e, (n0 + n1) / 2, (low[i][2] + high[i][2]) / 2]);
  for (let i = 1; i < xs.length; i++) { seg(G, low[i - 1], low[i]); seg(G, high[i - 1], high[i]); seg(G, mid[i - 1], mid[i]); }
  for (const i of [0, xs.length - 1]) {
    seg(G, low[i], high[i]);
    seg(G, [xs[i], n0 + 0.2 * T.depth, ground(xs[i], n0 + 0.2 * T.depth)], [xs[i], n0 + 0.2 * T.depth, low[i][2] + 0.2 * T.rise]);
  }
}
/** A string inverter on its pole: a 1 x 0.5 x 1 m box, top 2.2 m up. */
export function inverterBox(G, v, ground) {
  const g = ground(v.e, v.n), z0 = g + 1.2, z1 = g + 2.2, c = [[-0.5, -0.25], [0.5, -0.25], [0.5, 0.25], [-0.5, 0.25]].map(([x, y]) => [v.e + x, v.n + y]);
  for (let i = 0; i < 4; i++) { const a = c[i], b = c[(i + 1) % 4]; seg(G, [...a, z0], [...b, z0]); seg(G, [...a, z1], [...b, z1]); seg(G, [...a, z0], [...a, z1]); }
  seg(G, [v.e, v.n + 0.3, g], [v.e, v.n + 0.3, z0]);
}
/** A plan outline a little above the ground (the ghost's footprint). */
export function outline(G, rect, ground, lift = 0.15) {
  const q = [[rect[0], rect[1]], [rect[2], rect[1]], [rect[2], rect[3]], [rect[0], rect[3]]];
  for (let i = 0; i < 4; i++) {
    const a = q[i], b = q[(i + 1) % 4], k = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 8));
    for (let j = 0; j < k; j++) {
      const p = [a[0] + (b[0] - a[0]) * j / k, a[1] + (b[1] - a[1]) * j / k], r = [a[0] + (b[0] - a[0]) * (j + 1) / k, a[1] + (b[1] - a[1]) * (j + 1) / k];
      seg(G, [...p, ground(...p) + lift], [...r, ground(...r) + lift]);
    }
  }
}
/** A home run on the ground (the DC trench line), a point every 5 m. */
export function run(G, pts, ground) {
  for (let i = 1; i < pts.length; i++) {
    const a = pts[i - 1], b = pts[i], k = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 5));
    for (let j = 0; j < k; j++) {
      const p = [a[0] + (b[0] - a[0]) * j / k, a[1] + (b[1] - a[1]) * j / k], r = [a[0] + (b[0] - a[0]) * (j + 1) / k, a[1] + (b[1] - a[1]) * (j + 1) / k];
      seg(G, [...p, ground(...p) + 0.05], [...r, ground(...r) + 0.05]);
    }
  }
}

/**
 * sceneGroups(items, W, P, ground) -> { tables, inverters, strings, loose, runs } groups. strings: each connected string along its row;
 * loose: the strings of tables no inverter took (drawn red); runs: home runs to the inverters.
 */
export function sceneGroups(items, W, P, ground) {
  const T = tableOf(P), G = { tables: group(), inverters: group(), strings: group(), loose: group(), runs: group() };
  const byId = new Map(W.tables.map(t => [t.id, t]));
  for (const it of items) {
    if (it.kind === 'inverter') { inverterBox(G.inverters, it, ground); continue; }
    tableFrame(G.tables, it, T, ground);
    const w = byId.get(it.id), L = w && w.inverter !== null ? G.strings : G.loose;
    for (let r = 0; r < T.strings; r++) {                          // a string a row, 5 cm above the module face
      const f = (r + 0.5) / Math.max(1, T.strings), n = it.n + f * T.depth, z = e => ground(e, it.n) + T.lowEdge + f * T.rise + 0.05;
      seg(L, [it.e + 0.3, n, z(it.e)], [it.e + T.len - 0.3, n, z(it.e + T.len)]);
    }
    if (w?.run) run(G.runs, w.run, ground);
  }
  return Object.fromEntries(Object.entries(G).map(([k, g]) => [k, done(g)]));
}
/** The ghost: its footprint and, for a table, its frame. */
export function ghostGroup(check, P, ground) {
  const G = group();
  outline(G, check.rect, ground);
  if (check.kind === 'table') tableFrame(G, { e: check.at.e, n: check.at.n }, tableOf(P), ground);
  else inverterBox(G, check.at, ground);
  return done(G);
}

/**
 * Piles for the built tables on the plant's rules (plant-piles.mjs planTables: front and rear posts, reveal band, grading,
 * twist). measured(e, n): NaN where the ground is not measured (flagged, never filled in). Returns { summary, groups: { ok, flagged } }.
 */
export function builtPiles(items, P, measured) {
  const T = tableOf(P), tabs = items.filter(i => i.kind === 'table');
  if (!tabs.length) return null;
  const input = tabs.map(t => ({ length: T.len, depth: T.depth, rise: T.rise, lowEdgeM: T.lowEdge, eastWest: false, key: [t.n, t.e, t.e + T.len],
    lineAt: f => [[t.e, t.n + f * T.depth], [t.e + T.len, t.n + f * T.depth]] }));
  const it = planTables(input, { groundAt: measured, system: 'fixed', posts: 2, along: 'ew' });
  let r = it.next();
  while (!r.done) r = it.next();
  const res = r.value, summary = pileSummary(res, { mwp: tabs.length * T.kWp / 1000 }), ok = group(), flagged = group();
  for (const t of res.tables) for (let i = 0; i < t.n; i++) {
    const o = i * STRIDE, a = t.pa;
    seg(t.pf[i] & ~8 ? flagged : ok, [a[o], a[o + 1], a[o + 4]], [a[o], a[o + 1], a[o + 3]]); // 8: lengthened for lateral load, routine
  }
  return { summary, groups: { ok: done(ok), flagged: done(flagged) } };
}

Build Mount

A JavaScript module in the world folder of GlobalGrid2050 covering overhead lines (OHL) and solar. It is built from the mount build helper (`mountBuild`) and the load step (`load`).

renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/build-mount.mjs · lines 1–52 of 52 · version 2026-09-27 18:53

What it does
It draws overhead lines (OHL) and solar. Defines mountBuild, load. 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: overhead lines (OHL), solar.
Downstream impact
Used directly by 1 file: Cmd 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
The only part of build mode that loads with the world (just after the first frame, from `cmd-mount.mjs`). It responds to click events.
Why it matters
Imported by Cmd Mount.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Links (import), Build UI (dynamic import)
Used by
imported by Cmd Mount (dynamic import)
Produces
mountBuild
Defines here
mountBuild, load
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/build-mount.mjs:1-52 · blob 12b078ff946b8ce2466d021ecdc9e2a1605e078b · 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
// build-mount.mjs: the only part of build mode that loads with the world (just after the first frame, from cmd-mount.mjs).
// It adds a Place row (Table, Inverter) to Design > Build, answers "build ..." lines in the command line, saves what was
// built in the design file as its typed lines ({ kind: 'build', params: { lines } }) and replays them on open, and reads
// ?build=1 (with lat/lon or e/n, the link GridAtlas can send) to fly there and start placing. Everything else
// (build-ui.mjs and the rules, geometry and piles it imports) loads the first time any of these is used.

import { parseWorldUrl } from './links.mjs';

// deps: { api (substrate extension api), world (window.world), ohl, doc }
export function mountBuild({ api, world, ohl = null, doc = document, loc = globalThis.location }) {
  let ui = null, loading = null, kept = null;
  const tab = doc.getElementById('design-tab-build'), row = doc.createElement('div');
  row.className = 'row'; row.setAttribute('role', 'group'); row.setAttribute('aria-label', 'Place');
  row.innerHTML = '<button type="button" data-place="table" aria-pressed="false" title="Place a solar table on the grid over the ground">Place table</button>'
    + '<button type="button" data-place="inverter" aria-pressed="false" title="Place a string inverter; strings wire themselves">Place inverter</button>';
  tab?.prepend(row);
  const load = () => (loading ||= import('./build-ui.mjs')
    .then(m => (ui = m.createBuild({ api, world, ohl, doc, row })))
    .catch(e => { loading = null; console.warn('build mode: ' + e.message); throw e; }));
  for (const b of row.querySelectorAll('[data-place]')) {
    b.addEventListener('click', () => load().then(u => u.setTool(b.getAttribute('aria-pressed') === 'true' ? null : b.dataset.place)).catch(() => {}));
  }
  // A Design drawing tool chosen puts Place down (one tool at a time).
  for (const b of doc.querySelectorAll('#design [data-tool]')) b.addEventListener('click', () => { if (ui && b.getAttribute('aria-pressed') === 'true') ui.setTool(null); });

  // The command line asks this first: "build ..." lines, and "piles auto" once something is built.
  (api.hooks.commands ||= new Set()).add(async line => {
    const s = String(line).trim().toLowerCase();
    if (/^(build|place)\b/.test(s)) return (await load()).exec(line);
    if (/^piles?\s+auto\b/.test(s) && ui && ui.script().some(l => / at /.test(l))) return ui.pilesAuto();
    return null;
  });
  api.hooks.items?.add(() => {
    const lines = ui ? ui.script() : kept;
    return lines && lines.length ? [{ id: 'build-1', kind: 'build', params: { lines: lines.slice() }, points_bng: [] }] : [];
  });
  api.hooks.open?.add(d => {
    const it = (d?.items || []).find(i => i.kind === 'build' && Array.isArray(i.params?.lines));
    kept = it ? it.params.lines.filter(s => typeof s === 'string').slice(0, 5000) : null;
    if (kept || ui) load().then(u => u.replay(kept || [])).catch(() => {});
  });
  // ?build=1: the door from the national map. Fly to the place the link names (if any), open Design, start placing tables.
  const q = new URLSearchParams(loc?.search || '');
  if (q.has('build')) {
    const at = parseWorldUrl(q);
    if (at) world.flyTo?.(at.e, at.n, { pitch: -60 * Math.PI / 180, back: 60 });
    const dt = doc.getElementById('design-toggle');
    if (dt && dt.getAttribute('aria-expanded') !== 'true') dt.click();
    load().then(u => u.setTool('table')).catch(() => {});
  }
  return { load, ui: () => ui, row };
}