In this section
- Measure transform · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/measure.mjs lines 1–369
- Phases Design transform · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/phases-design.mjs lines 1–83
- Plan Inset render · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/plan-inset.mjs lines 1–248
Measure
A JavaScript module in the world folder of GlobalGrid2050 that works with cables, 33kV, solar and LiDAR terrain, using point in polygon.
transformglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/measure.mjs · lines 1–369 of 369 · version 2026-09-27 00:56 · pattern signedArea (shared by 2 files)
- What it does
- It calculates cables, 33kV, solar and LiDAR terrain. Defines 15 functions or classes, including distance2d, distance3d, polylineLength2d, signedArea, areaOfPolygon.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV, solar, LiDAR terrain.
- Inputs & outputs
- Voltage levels named: 33kV.
- Downstream impact
- Used directly by 5 files: Design Earthworks (globalgrid2050); Design UI (globalgrid2050); Design Earthworks (globalgrid2050); Design UI (globalgrid2050); and 1 more. Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
- What it achieves
- It opens ring (`openRing`) and is built from the distance2d step (`distance2d`) and the distance3d step (`distance3d`). What the design tools and panels say about the real ground. Its code works with 33 kV.
- Why it matters
- Imported by 5 files, including Design Earthworks and Design UI, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Design Earthworks (import), imported by Design UI (import), imported by Design Earthworks (import), imported by Design UI (import), imported by Design UI (import), mentioned in Standalone (comment link)
- Produces
- distance2d, distance3d, polylineLength2d, signedArea, areaOfPolygon, profile, slopeAlong, cutFillForPlatform, trenchSummary, bendRule, cableSummary, DESIGN_DEFAULTS
- Defines here
- distance2d, distance3d, polylineLength2d, signedArea, areaOfPolygon, openRing, insidePoly, profile, slopeAlong, cutFillForPlatform, pathBends, trenchSummary, bendRule, cableSummary, coverAchieved
- 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/202609270056-site-world-v3/world/measure.mjs:1-369 · blob ea0cf2aa54f4548b1687696e538103c802326534 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// measure.mjs: what the design tools and panels say about the real ground.
//
// Local metres: x east, y north, z up, as camera.mjs. The ground is any function
// groundAt(x, y). Every function here is pure: no imports, no DOM, no WebGL.
// Callers pass in what they have: a groundAt, a trench from trench.mjs, a route
// from cable-route.mjs, the parsed web/world/data/cables.json.
//
// Numbers come back raw (metres, cubic metres, fractions). measure-format.mjs
// turns them into plain British English lines, joined with " · ", for example
// "Trench 124.6 m (3D 125.1 m) · spoil 98.4 m³ · 1 bend below 1.05 m"
const EPS = 1e-9;
// ---------------------------------------------------------------- distances
/** Plan distance between [x, y(, z)] points. */
export function distance2d(a, b) {
return Math.hypot(b[0] - a[0], b[1] - a[1]);
}
/** Slope distance between [x, y, z] points (a missing z counts as 0). */
export function distance3d(a, b) {
return Math.hypot(b[0] - a[0], b[1] - a[1], (b[2] ?? 0) - (a[2] ?? 0));
}
/** Plan length of a polyline [[x, y], ...]. */
export function polylineLength2d(points) {
let s = 0;
for (let k = 1; k < points.length; k++) s += distance2d(points[k - 1], points[k]);
return s;
}
// ---------------------------------------------------------------- areas
/** Signed plan area by the shoelace formula: positive anticlockwise. */
export function signedArea(polygon) {
let a = 0;
const n = polygon.length;
for (let i = 0; i < n; i++) {
const p = polygon[i], q = polygon[(i + 1) % n];
a += p[0] * q[1] - q[0] * p[1];
}
return a / 2;
}
/** Plan area of a simple polygon [[x, y], ...], either winding, closed or not. */
export function areaOfPolygon(polygon) {
const pts = openRing(polygon);
if (pts.length < 3) return 0;
return Math.abs(signedArea(pts));
}
// Drop a repeated closing vertex so the ring is listed once.
function openRing(polygon) {
const pts = polygon.map((p) => [Number(p[0]), Number(p[1])]);
if (pts.length > 1) {
const a = pts[0], b = pts[pts.length - 1];
if (Math.abs(a[0] - b[0]) < EPS && Math.abs(a[1] - b[1]) < EPS) pts.pop();
}
return pts;
}
// Even-odd point in polygon, the same crossing test as lidar/src/earthworks_pair.py
// inside_poly: edge (i, i-1), skip horizontal edges, count crossings to the right.
function insidePoly(x, y, vx, vy) {
let ins = false;
const n = vx.length;
for (let i = 0; i < n; i++) {
const j = (i - 1 + n) % n;
const x1 = vx[i], y1 = vy[i], x2 = vx[j], y2 = vy[j];
if (y1 === y2) continue;
if ((y1 > y) !== (y2 > y) && x < x1 + (y - y1) * (x2 - x1) / (y2 - y1)) ins = !ins;
}
return ins;
}
// ---------------------------------------------------------------- profiles
/**
* profile(groundAt, points, step = 1)
* Samples the ground along a plan polyline every `step` metres and at every
* vertex. Returns
* samples [{ chainage, x, y, z }]
* pairs [[chainage, z]]
* length2d, length3d (along the sampled ground)
* min, max lowest and highest ground, with chainageOfMin / chainageOfMax
* start, end, rise (total climbing), fall (total descending, positive)
* gradient { net, maxUp, maxDown, max }: fractions (0.05 = 5 %); net is
* (end - start) / length2d, maxUp the steepest climb between two
* samples, maxDown the steepest descent (positive), max the larger.
*/
export function profile(groundAt, points, step = 1) {
if (typeof groundAt !== 'function') throw new Error('profile: groundAt must be a function');
if (!Array.isArray(points) || points.length < 2) throw new Error('profile: needs at least two points');
if (!(step > 0)) throw new Error('profile: step must be positive');
const samples = [];
let s0 = 0;
for (let k = 0; k < points.length - 1; k++) {
const a = points[k], b = points[k + 1];
const len = distance2d(a, b);
if (len < EPS) continue;
const pieces = Math.max(1, Math.ceil(len / step - 1e-9));
for (let j = samples.length ? 1 : 0; j <= pieces; j++) {
const u = j / pieces;
const x = a[0] + (b[0] - a[0]) * u, y = a[1] + (b[1] - a[1]) * u;
samples.push({ chainage: s0 + len * u, x, y, z: groundAt(x, y) });
}
s0 += len;
}
if (!samples.length) throw new Error('profile: path needs two distinct points');
let min = Infinity, max = -Infinity, sMin = 0, sMax = 0;
let rise = 0, fall = 0, maxUp = 0, maxDown = 0, len3 = 0;
for (let k = 0; k < samples.length; k++) {
const p = samples[k];
if (p.z < min) { min = p.z; sMin = p.chainage; }
if (p.z > max) { max = p.z; sMax = p.chainage; }
if (k === 0) continue;
const q = samples[k - 1];
const ds = p.chainage - q.chainage, dz = p.z - q.z;
len3 += Math.hypot(ds, dz);
if (dz > 0) rise += dz; else fall -= dz;
if (ds > EPS) {
const g = dz / ds;
if (g > maxUp) maxUp = g;
if (-g > maxDown) maxDown = -g;
}
}
const start = samples[0].z, end = samples[samples.length - 1].z;
return {
samples,
pairs: samples.map((p) => [p.chainage, p.z]),
length2d: s0,
length3d: len3,
min, max, chainageOfMin: sMin, chainageOfMax: sMax,
start, end, rise, fall,
gradient: { net: s0 > 0 ? (end - start) / s0 : 0, maxUp, maxDown, max: Math.max(maxUp, maxDown) },
};
}
/**
* slopeAlong(groundAt, at, direction, h = 0.5)
* Ground gradient at plan point `at` = [x, y] in plan direction `direction` =
* [dx, dy] (any length), by central difference over +/- h metres. Positive
* means the ground climbs that way. A fraction: 0.05 is 5 %, 1 in 20.
*/
export function slopeAlong(groundAt, at, direction, h = 0.5) {
const l = Math.hypot(direction[0], direction[1]);
if (!(l > 0)) throw new Error('slopeAlong: direction must be non-zero');
if (!(h > 0)) throw new Error('slopeAlong: h must be positive');
const ux = direction[0] / l, uy = direction[1] / l;
const zf = groundAt(at[0] + ux * h, at[1] + uy * h);
const zb = groundAt(at[0] - ux * h, at[1] - uy * h);
return (zf - zb) / (2 * h);
}
// ---------------------------------------------------------------- platforms
/**
* cutFillForPlatform(groundAt, polygon, level, cell = 0.5) -> { cut, fill, area, ... }
* A flat platform at `level` over a plan polygon. Ground above the level is cut,
* ground below is filled. Midpoint rule over square cells of side `cell`.
*
* The same shape as the electron count in lidar/src/earthworks_pair.py
* platform_pair, so the browser and the GPU agree when the cell matches its
* step (CELL / SUB = 0.025 m): grid anchored at floor(min x), floor(min y);
* nx = ceil((max x - x0) / cell) columns; cell centres at x0 + (i + 0.5) cell;
* the same even-odd crossing test; cut = sum max(ground - level, 0) x cell²,
* fill = sum max(level - ground, 0) x cell².
*
* Returns cut and fill (m³), area (m², the counted cells, the plan area the
* volumes stand on), polygonArea (exact shoelace), cells, meanGround, level.
*/
export function cutFillForPlatform(groundAt, polygon, level, cell = 0.5) {
if (typeof groundAt !== 'function') throw new Error('cutFillForPlatform: groundAt must be a function');
if (!Number.isFinite(level)) throw new Error('cutFillForPlatform: level must be a number');
if (!(cell > 0)) throw new Error('cutFillForPlatform: cell must be positive');
const pts = openRing(polygon);
if (pts.length < 3) throw new Error('cutFillForPlatform: polygon needs three points');
const vx = pts.map((p) => p[0]), vy = pts.map((p) => p[1]);
const x0 = Math.floor(Math.min(...vx)), y0 = Math.floor(Math.min(...vy));
const nx = Math.ceil((Math.max(...vx) - x0) / cell), ny = Math.ceil((Math.max(...vy) - y0) / cell);
let cut = 0, fill = 0, cells = 0, sumZ = 0;
for (let j = 0; j < ny; j++) {
const y = y0 + (j + 0.5) * cell;
for (let i = 0; i < nx; i++) {
const x = x0 + (i + 0.5) * cell;
if (!insidePoly(x, y, vx, vy)) continue;
const z = groundAt(x, y);
const dz = z - level;
if (dz > 0) cut += dz; else fill -= dz;
sumZ += z;
cells++;
}
}
const a = cell * cell;
return {
cut: cut * a,
fill: fill * a,
area: cells * a,
polygonArea: Math.abs(signedArea(pts)),
cells,
cell,
level,
meanGround: cells ? sumZ / cells : NaN,
};
}
// ---------------------------------------------------------------- trenches
// Plan turn at each interior vertex of a path, degrees (0 = straight on).
function pathBends(path) {
const bends = [];
for (let i = 1; i < path.length - 1; i++) {
const a = path[i - 1], b = path[i], c = path[i + 1];
const d1x = b[0] - a[0], d1y = b[1] - a[1], d2x = c[0] - b[0], d2y = c[1] - b[1];
if (Math.hypot(d1x, d1y) < EPS || Math.hypot(d2x, d2y) < EPS) continue;
const t = Math.atan2(d1x * d2y - d1y * d2x, d1x * d2x + d1y * d2y);
const deg = Math.abs(t) * 180 / Math.PI;
if (deg > 1e-6) bends.push({ index: i, turnDeg: deg, direction: t > 0 ? 'left' : 'right' });
}
return bends;
}
/**
* trenchSummary(trench, groundAt?) using createTrench from trench.mjs.
* groundAt defaults to the one the trench was made with; without either, the
* 3D length and spoil come back null rather than guessed.
* Returns { length2d, length3d, width, depth, benchSlope, spoil, floorArea, bends }.
* Bends are the mitred plan corners of the centreline (a trench has no radius).
*/
export function trenchSummary(trench, groundAt = null) {
if (!trench || !Array.isArray(trench.path)) throw new Error('trenchSummary: needs a trench from createTrench');
let length3d = null, spoil = null;
if (groundAt) {
length3d = trench.length3dOn(groundAt);
spoil = trench.spoilVolumeOn(groundAt);
} else {
try { length3d = trench.length3d; spoil = trench.spoilVolumeM3; } catch { /* no ground: leave null */ }
}
return {
length2d: trench.length2d,
length3d,
width: trench.width,
depth: trench.depth,
benchSlope: trench.benchSlope,
spoil,
floorArea: trench.length2d * trench.width,
bends: pathBends(trench.path),
};
}
// ---------------------------------------------------------------- cables
/**
* bendRule(cables, { voltageKv, construction?, when, odMm })
* The governing (largest) minimum bend radius from cables.json rules that match
* the voltage and the chosen stage. `when` must be 'final' or 'installation';
* there is no default, because the two differ by a third or more.
* With no construction, every construction at that voltage is considered and
* the largest wins (the safe side). Rules with no multiple are listed as skipped.
*/
export function bendRule(cables, { voltageKv, construction = null, when, odMm }) {
if (when !== 'final' && when !== 'installation') {
throw new Error("bendRule: choose when: 'final' or 'installation'");
}
if (!(odMm > 0)) throw new Error('bendRule: odMm must be positive');
const rules = (cables && cables.rules) || [];
const match = rules.filter((r) => r.voltage_kv === voltageKv && r.when === when
&& (construction == null || r.construction === construction));
const usable = match.filter((r) => Number.isFinite(r.multiple_of_od));
const skipped = match.filter((r) => !Number.isFinite(r.multiple_of_od));
if (!usable.length) return { when, multiple: null, radius: null, rule: null, considered: 0, skipped };
const rule = usable.reduce((a, b) => (b.multiple_of_od > a.multiple_of_od ? b : a));
return {
when,
multiple: rule.multiple_of_od,
radius: rule.multiple_of_od * odMm / 1000,
rule,
considered: usable.length,
skipped,
};
}
/**
* cableSummary(route, { cables, cableId | (voltageKv, odMm), construction?, when })
* route: the output of routeCable in cable-route.mjs.
* cables: the parsed web/world/data/cables.json.
* when: 'final' or 'installation', required.
* Each arc is checked at its tightest core axis (the centreline radius less the
* core offset on the inside of the turn) and at the centreline. A bend is below
* the rule when its tightest core radius is under the required radius.
* Returns { length2d, length3d, formation, cable, required, bends, below, compliant,
* routeViolations }. compliant is null when no rule applies.
*/
export function cableSummary(route, opts = {}) {
if (!route || !Array.isArray(route.segments)) throw new Error('cableSummary: needs a route from routeCable');
const { cables = null, cableId = null, construction = null, when } = opts;
if (when !== 'final' && when !== 'installation') {
throw new Error("cableSummary: choose when: 'final' or 'installation'");
}
let cable = null;
if (cableId != null) {
cable = ((cables && cables.cables) || []).find((c) => c.id === cableId) || null;
if (!cable) throw new Error(`cableSummary: unknown cable ${cableId}`);
}
const voltageKv = opts.voltageKv ?? cable?.voltage_kv;
const odMm = opts.odMm ?? cable?.od_mm;
const required = (voltageKv != null && odMm > 0)
? bendRule(cables, { voltageKv, construction, when, odMm })
: { when, multiple: null, radius: null, rule: null, considered: 0, skipped: [] };
const cores = route.cores || [];
const leftMost = Math.max(0, ...cores.map((c) => c.lateral));
const rightMost = Math.max(0, ...cores.map((c) => -c.lateral));
const bends = route.segments.filter((g) => g.type === 'arc').map((g) => {
const inner = g.radius - (g.turn > 0 ? leftMost : rightMost);
const ok = required.radius == null ? null : inner >= required.radius - 1e-9;
return {
index: g.index,
chainage: (g.s0 + g.s1) / 2,
turnDeg: Math.abs(g.turn) * 180 / Math.PI,
radius: g.radius,
innerRadius: inner,
ok,
};
});
const below = bends.filter((b) => b.ok === false);
return {
length2d: route.length2d,
length3d: route.length3d,
formation: route.formation,
cable: cable ? { id: cable.id, voltageKv: cable.voltage_kv, csaMm2: cable.csa_mm2, odMm: cable.od_mm, odStatus: cable.od_status }
: { id: null, voltageKv: voltageKv ?? null, csaMm2: null, odMm: odMm ?? null, odStatus: null },
required,
bends,
below,
compliant: required.radius == null ? null : below.length === 0,
routeViolations: route.violations || [],
};
}
// ---------------------------------------------------------------- trench cover
// The trench section and cable the Design panel starts with. The section is the good agricultural land cover for
// 33 kV (0.91 m), since a solar site is farmland; its depth leaves room for the default cable (tests check it).
export const DESIGN_DEFAULTS = Object.freeze({ section: '33kv-1-agri', cable: '33kv-1c-al-xlpe-300' });
/**
* coverAchieved(section, odMm?) -> { cover, required, ok, basis }
* Depth from finished ground to the top of the cable (or duct) as laid in this section: trench depth, less the
* bed, less the height of the formation. A ducted section is set by its duct; a direct-buried one by the cable
* OD given (else the section's own assumed phase spacing). Trefoil height is OD x (1 + sqrt(3)/2).
* With no size to go on, the section's stated cover is returned as it is.
*/
export function coverAchieved(section, odMm = null) {
const required = Number(section.cover_to_top_m);
const duct = Number(section.duct_od_mm) > 0 ? Number(section.duct_od_mm) : null;
const unit = duct ?? (Number(odMm) > 0 ? Number(odMm) : Number(section.phase_spacing_mm) > 0 ? Number(section.phase_spacing_mm) : null);
if (unit == null) return { cover: required, required, ok: true, basis: 'section cover as stated' };
const trefoil = /trefoil/i.test(section.formation || '');
const height = trefoil ? unit * (1 + Math.sqrt(3) / 2) : unit;
const bed = Number(section.bedding?.thickness_mm) || 0;
const cover = section.trench_depth_m - bed / 1000 - height / 1000;
const what = duct ? `${duct} mm duct` : Number(odMm) > 0 ? `${unit} mm cable` : `${unit} mm cable (section's assumed size)`;
return { cover, required, ok: cover >= required - 5e-4,
basis: `${section.trench_depth_m} m deep, less ${bed} mm bed, less ${Math.round(height)} mm ${trefoil ? 'trefoil' : 'layer'} of ${what}` };
}Phases Design
A JavaScript module in the world folder of GlobalGrid2050 that works with cables and solar.
Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609270439-site-world/world/phases-design.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Phases Design; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9839 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/phases-design.mjs:1-84 6a35fe793a364e7535fbd2e74c8e9a2d532b1091
- sha256 730b7974296de3de65185733c5281961ac92633c75ec6e16e99abb000573bdce
- target sha256 e720f810bc3b4bbbe2f6c916604643f51df1a8abca476ead0042864adf05830e
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/phases-design.mjs · lines 1–83 of 83 · version 2026-09-27 00:56 · Not reached from any entry point (candidate for review) · pattern itemsFromDesign (shared by 2 files)
- What it does
- It calculates cables and solar. Defines itemsFromStore, itemsFromDesign.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, solar.
- Downstream impact
- Used directly by 1 file: Project UI (globalgrid2050).
- What it achieves
- It is built from the items from store helper (`itemsFromStore`) and the items from design helper (`itemsFromDesign`). Derive construction items from a design.
- Why it matters
- Imported by Project UI.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Project UI (import)
- Produces
- itemsFromStore, itemsFromDesign
- Defines here
- itemsFromStore, itemsFromDesign
- 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/202609270056-site-world-v3/world/phases-design.mjs:1-83 · blob 9620424c8623abb194da55d74fc50e47020e4070 · 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: duplicate_candidate
// phases-design.mjs: derive construction items from a design. Pure: no imports, no DOM.
// itemsFromStore reads the viewer's own saved design (world.design.v1, design-store.mjs);
// itemsFromDesign reads an imported layout (the output of importDesign in design-import.mjs).
//
// What the design carries becomes items directly:
// each cable run -> a trench and the cable laid in it
// each equipment solid -> a pad and the equipment set on it
// solar tables -> one pile item per table
// array boundary rings -> a fence per outer ring
// What the design does not carry (roads, HDD bores, deliveries) is passed in
// by the caller as `roads`, `hdd` and `extra`; nothing is invented.
const EQUIPMENT_TYPES = new Set(['skid', 'inverter', 'transformer_compound', 'bess_container']);
const PHASE_KINDS = new Set(['road', 'pad', 'fence', 'pile', 'delivery', 'equipment', 'trench', 'hdd', 'cable']);
const LINKS = ['trench', 'hdd', 'pad', 'via', 'after'];
// A world.design.v1 document -> phases items. Links live in each item's params (trench, hdd, pad, via, after)
// and are lifted to the top level, so the ordering rules run on real designs. A cable with neither a trench nor
// a bore is laid in a trench of its own route ("<id>-trench"), as the viewer draws it. Kinds the phases do not
// sequence (a measurement, a note) are left out; opts.extra items are appended as given.
export function itemsFromStore(doc, opts = {}) {
if (!doc || doc.schema !== 'world.design.v1' || !Array.isArray(doc.items)) {
throw new Error('itemsFromStore: expected a world.design.v1 document');
}
const items = [];
for (const it of doc.items) {
const kind = it.kind === 'piles' ? 'pile' : it.kind; // the Design panel stores pile rows as 'piles'
if (!PHASE_KINDS.has(kind)) continue;
const p = it.params || {}, item = { id: it.id, kind, geometry: it.points_bng };
for (const k of LINKS) if (p[k] != null) item[k] = p[k];
if (it.kind === 'cable' && item.trench == null && item.hdd == null) {
items.push({ id: `${it.id}-trench`, kind: 'trench', geometry: it.points_bng });
item.trench = `${it.id}-trench`;
}
items.push(item);
}
items.push(...(opts.extra || []));
return items;
}
// opts.roads: [{ id?, points }]; opts.hdd: [{ id?, points, cables?: [cable index] }]
// (cables that pass through a bore are drawn in the bore instead of a trench);
// opts.extra: items in the phases.mjs shape, appended as given.
export function itemsFromDesign(design, opts = {}) {
if (!design || typeof design !== 'object') throw new Error('itemsFromDesign: expected the importDesign result');
const items = [];
const roads = (opts.roads || []).map((r, i) => ({ id: r.id || `road-${i + 1}`, kind: 'road', geometry: r.points || null }));
items.push(...roads);
const boreOf = new Map();
(opts.hdd || []).forEach((h, i) => {
const id = h.id || `hdd-${i + 1}`;
items.push({ id, kind: 'hdd', geometry: h.points || null });
for (const c of h.cables || []) boreOf.set(c, id);
});
(design.outlines || []).filter(o => o.type === 'array_boundary' && !o.hole)
.forEach((o, i) => items.push({ id: `fence-${i + 1}`, kind: 'fence', geometry: o.points }));
(design.cables || []).forEach((c, i) => {
const n = i + 1, bore = boreOf.get(i);
const cable = { id: `cable-${n}`, kind: 'cable', role: c.role, geometry: c.points, lengthM: c.lengthM };
if (bore) cable.hdd = bore;
else {
items.push({ id: `trench-${n}`, kind: 'trench', geometry: c.points, lengthM: c.lengthM });
cable.trench = `trench-${n}`;
}
items.push(cable);
});
let e = 0;
for (const s of design.solids || []) {
if (!EQUIPMENT_TYPES.has(s.type)) continue;
e++;
items.push({ id: `pad-${e}`, kind: 'pad', geometry: s.quad || null, forType: s.type });
items.push({ id: `equipment-${e}`, kind: 'equipment', pad: `pad-${e}`, type: s.type, geometry: s.quad || null });
}
(design.tables?.solids || []).forEach((t, i) => items.push({ id: `piles-${i + 1}`, kind: 'pile', geometry: t.quad || null }));
items.push(...(opts.extra || []));
return items;
}Plan Inset
A JavaScript module in the world folder of GlobalGrid2050 that converts to world (`toWorld`), scales bar (`scaleBar`), formats distance (`formatDistance`) and calculates planar distances.
renderglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/plan-inset.mjs · lines 1–248 of 248 · version 2026-09-27 00:56 · Not reached from any entry point (candidate for review) · pattern signature (shared by 2 files)
- What it does
- It draws its content. Defines 18 functions or classes, including finite2, extentOf, add, fit, toPlan. 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.
- Inputs & outputs
- Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: Plan Wire (globalgrid2050).
- What it achieves
- It formats distance (`formatDistance`) and starts collapsed (`startCollapsed`). A small top-down plan in a corner, drawn on a 2D canvas (not WebGL). It responds to click, pointerdown and pointercancel events.
- Why it matters
- Imported by Plan Wire.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Plan Wire (import), mentioned in Standalone (comment link)
- Produces
- MIN_SPAN_M, PAD_PX, TAP_PX, extentOf, fit, toPlan, toWorld, headingOnPlan, scaleBar, formatDistance, signature, planSize
- Defines here
- finite2, extentOf, add, fit, toPlan, toWorld, headingOnPlan, scaleBar, formatDistance, signature, planSize, startCollapsed, createPlanInset, isCoarse, layout, draw, paint, P
- 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/202609270056-site-world-v3/world/plan-inset.mjs:1-248 · blob a724789d386524bc1a670104da58c6698bf647bc · 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: unreached_review
// Plan inset: a small top-down plan in a corner, drawn on a 2D canvas (not WebGL). North is always up.
// It shows the site boundary, the terrain tiles (known and loaded), any drawn design items, the viewer's
// position and heading, and a scale bar. A tap or click on the plan calls onFly(x, y) in local metres.
// It draws only when what it would show has changed, so it costs nothing while the viewer stands still.
//
// The first half is pure (no DOM) and tested under node:test; createPlanInset is the thin DOM part.
// Positions are local metres from the site origin: x east, y north. Yaw 0 looks north, +pi/2 looks east.
//
// Data handed to set():
// viewer { x, y, yaw } required
// boundary [[x, y], ...] optional closed ring (the site boundary)
// tiles [{ x0, y0, size, loaded }] optional; loaded: true draws brighter
// items [{ points: [[x, y], ...], closed, kind }] optional drawn design items; one point = a marker
export const MIN_SPAN_M = 200; // the plan never shows less than this across, so a lone viewer is not a dot on nothing
export const PAD_PX = 8;
export const TAP_PX = 6; // a pointer that moves this far or more between down and up is a drag, not a tap // clear border inside the canvas
const NICE = [1, 2, 5];
const finite2 = p => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]);
// Bounding box of everything the plan shows. Returns { x0, y0, x1, y1 } or null when there is nothing.
// The site (boundary, tiles, items) sets the frame; the viewer widens it only when they stand outside it.
export function extentOf({ viewer, boundary, tiles, items } = {}) {
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
const add = (x, y) => { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; };
for (const p of boundary || []) if (finite2(p)) add(p[0], p[1]);
for (const t of tiles || []) if (Number.isFinite(t?.x0) && Number.isFinite(t?.y0) && t.size > 0) { add(t.x0, t.y0); add(t.x0 + t.size, t.y0 + t.size); }
for (const it of items || []) for (const p of it?.points || []) if (finite2(p)) add(p[0], p[1]);
if (viewer && Number.isFinite(viewer.x) && Number.isFinite(viewer.y)) add(viewer.x, viewer.y);
return x0 <= x1 && y0 <= y1 ? { x0, y0, x1, y1 } : null;
}
// Fits an extent into a w x h pixel canvas, north up, same scale on both axes, grown to at least MIN_SPAN_M.
// Returns { scale (px per metre), cx, cy (world centre), w, h }.
export function fit(extent, w, h, { pad = PAD_PX, minSpan = MIN_SPAN_M } = {}) {
const e = extent || { x0: 0, y0: 0, x1: 0, y1: 0 };
const spanX = Math.max(e.x1 - e.x0, minSpan), spanY = Math.max(e.y1 - e.y0, minSpan);
const iw = Math.max(1, w - 2 * pad), ih = Math.max(1, h - 2 * pad);
const scale = Math.min(iw / spanX, ih / spanY);
return { scale, cx: (e.x0 + e.x1) / 2, cy: (e.y0 + e.y1) / 2, w, h };
}
// World metres to canvas pixels (y grows downwards on screen, so north is up).
export function toPlan(f, x, y) {
return [f.w / 2 + (x - f.cx) * f.scale, f.h / 2 - (y - f.cy) * f.scale];
}
// Canvas pixels back to world metres: the exact inverse of toPlan.
export function toWorld(f, px, py) {
return [f.cx + (px - f.w / 2) / f.scale, f.cy - (py - f.h / 2) / f.scale];
}
// Unit screen direction of a heading: yaw 0 points up the screen (north), +pi/2 points right (east).
export function headingOnPlan(yaw) {
return [Math.sin(yaw), -Math.cos(yaw)];
}
// The longest 1, 2 or 5 x 10^k metre bar no longer than maxPx. Returns { metres, px, label }.
export function scaleBar(scale, maxPx) {
if (!(scale > 0) || !(maxPx > 0)) return { metres: 0, px: 0, label: '' };
const limit = maxPx / scale;
let k = Math.floor(Math.log10(limit)), best = 0;
for (let tries = 0; tries < 3 && !best; tries++, k--) {
for (const n of NICE) { const m = n * 10 ** k; if (m <= limit + 1e-9 && m > best) best = m; }
}
return { metres: best, px: best * scale, label: formatDistance(best) };
}
export function formatDistance(m) {
if (m >= 1000) return `${+(m / 1000).toFixed(2)} km`;
if (m >= 1) return `${+m.toFixed(0)} m`;
return `${+m.toFixed(2)} m`;
}
// A short text that changes only when the drawing would: the viewer is rounded to whole plan pixels
// and the heading to whole degrees, so moving within a pixel never costs a redraw.
export function signature(data, w, h) {
const f = fit(extentOf(data), w, h);
const v = data?.viewer || {};
const [px, py] = Number.isFinite(v.x) ? toPlan(f, v.x, v.y) : [NaN, NaN];
const deg = Number.isFinite(v.yaw) ? Math.round((((v.yaw * 180) / Math.PI) % 360 + 360) % 360) % 360 : 'x';
const tiles = (data?.tiles || []).map(t => `${t.x0 | 0},${t.y0 | 0},${t.size | 0},${t.loaded ? 1 : 0}`).join(';');
const bound = (data?.boundary || []).map(p => `${Math.round(p[0])},${Math.round(p[1])}`).join(';');
const items = (data?.items || []).map(it => `${it.kind || ''}:${it.closed ? 1 : 0}:` +
(it.points || []).map(p => `${Math.round(p[0] * 10)},${Math.round(p[1] * 10)}`).join(' ')).join('|');
return [w, h, f.scale.toFixed(6), f.cx.toFixed(1), f.cy.toFixed(1), Math.round(px), Math.round(py), deg, tiles, bound, items].join('#');
}
// Canvas size from the room it has, in CSS pixels: a square, smaller on phones.
export function planSize(vw, vh, coarse) {
const short = Math.min(vw, vh);
const side = coarse ? Math.round(short * 0.36) : Math.round(short * 0.24);
return Math.max(112, Math.min(coarse ? 180 : 200, side));
}
// Start collapsed where the screen is too small to spare the room (a small phone).
export const startCollapsed = (vw, vh) => Math.min(vw, vh) < 430 || Math.max(vw, vh) < 700;
// ---------------------------------------------------------------------------------------------------------
// DOM part. doc is passed in; nothing runs on import.
const CSS = `
#plan { position: fixed; left: 8px; top: 8px; display: flex; flex-direction: column; align-items: flex-start;
background: var(--panel, rgba(10,10,10,0.86)); border: 1px solid var(--edge, #1c2c3a); border-radius: 6px; overflow: hidden; }
#plan-toggle { min-height: 26px; min-width: 44px; padding: 0 10px; border: 0; background: transparent; color: var(--dim, #6f8ea6);
font: inherit; font-size: 11px; text-align: left; cursor: pointer; }
#plan-toggle[aria-expanded="true"] { color: var(--text, #cfe9ff); width: 100%; border-bottom: 1px solid var(--edge, #1c2c3a); }
#plan canvas { display: block; cursor: crosshair; touch-action: none; }
#plan canvas[hidden] { display: none; }
@media (pointer: coarse) {
/* Touch: bottom-left, just above the joypad, clear of the position readout however it wraps. */
#plan { top: auto; bottom: calc(var(--foot, 20px) + 180px); } /* 16 px clear of the joypad's top */
#plan-toggle { min-height: 44px; min-width: 64px; font-size: 12px; }
/* A panel opened as a sheet takes the screen; the plan steps aside until it closes. */
body:has(.panel:not([hidden])) #plan, body:has(.find-panel:not([hidden])) #plan { display: none; }
}`;
const COLOURS = { tileKnown: 'rgba(111,142,166,0.35)', tileLoaded: 'rgba(156,219,255,0.14)', tileEdge: 'rgba(156,219,255,0.35)',
boundary: '#cfe9ff', item: '#ffcf7a', viewer: '#ffffff', text: '#cfe9ff', dim: '#6f8ea6' };
// Mounts the plan into doc.body. onFly(x, y) is called with local metres when the plan is tapped.
// Returns { set(data), refresh(), collapsed(), setCollapsed(on), element, redraws() }.
export function createPlanInset(doc, { onFly = () => {}, coarse, win = doc.defaultView } = {}) {
const style = doc.createElement('style');
style.textContent = CSS;
doc.head.appendChild(style);
const box = doc.createElement('section');
box.id = 'plan';
box.setAttribute('aria-label', 'Plan');
const toggle = doc.createElement('button');
toggle.id = 'plan-toggle'; toggle.type = 'button'; toggle.textContent = 'Plan';
toggle.setAttribute('aria-controls', 'plan-canvas');
const canvas = doc.createElement('canvas');
canvas.id = 'plan-canvas';
canvas.setAttribute('role', 'img');
canvas.setAttribute('aria-label', 'Plan of the site, north up. Tap a place to go there.');
box.append(toggle, canvas);
doc.body.appendChild(box);
const isCoarse = () => (coarse ?? win.matchMedia?.('(pointer: coarse)').matches) === true;
let data = null, last = '', frame = null, redraws = 0, side = 0;
let collapsed = startCollapsed(win.innerWidth, win.innerHeight);
function layout() {
side = planSize(win.innerWidth, win.innerHeight, isCoarse());
const dpr = Math.min(win.devicePixelRatio || 1, 3);
canvas.style.width = canvas.style.height = side + 'px';
if (canvas.width !== Math.round(side * dpr)) { canvas.width = canvas.height = Math.round(side * dpr); last = ''; }
canvas.hidden = collapsed;
toggle.setAttribute('aria-expanded', String(!collapsed));
toggle.setAttribute('aria-label', collapsed ? 'Show plan' : 'Hide plan');
box.style.width = collapsed ? '' : side + 'px';
}
function draw() {
if (!data || collapsed) return;
const sig = signature(data, side, side);
if (sig === last) return;
last = sig; redraws++;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const k = canvas.width / side;
frame = fit(extentOf(data), side, side);
ctx.setTransform(k, 0, 0, k, 0, 0);
ctx.clearRect(0, 0, side, side);
paint(ctx, frame, data, side);
}
toggle.addEventListener('click', () => { collapsed = !collapsed; layout(); draw(); });
// A tap (pointer up within TAP_PX of where it went down) goes there; a drag that starts on the plan does not.
let down = null;
canvas.addEventListener('pointerdown', e => { e.preventDefault(); e.stopPropagation(); down = { x: e.clientX, y: e.clientY, id: e.pointerId }; });
canvas.addEventListener('pointercancel', () => { down = null; });
canvas.addEventListener('pointerup', e => {
const d = down; down = null;
if (!frame || !d || d.id !== e.pointerId || Math.hypot(e.clientX - d.x, e.clientY - d.y) >= TAP_PX) return;
e.preventDefault(); e.stopPropagation();
const r = canvas.getBoundingClientRect();
const [x, y] = toWorld(frame, (e.clientX - r.left) * (side / r.width), (e.clientY - r.top) * (side / r.height));
onFly(x, y);
});
win.addEventListener('resize', () => { layout(); draw(); });
layout();
return {
element: box,
set(next) { data = next; draw(); },
refresh() { last = ''; draw(); },
collapsed: () => collapsed,
setCollapsed(on) { collapsed = !!on; layout(); draw(); },
redraws: () => redraws
};
}
function paint(ctx, f, data, side) {
const P = (x, y) => toPlan(f, x, y);
ctx.lineJoin = 'round'; ctx.lineCap = 'round';
// Tiles: every known tile faintly, loaded ones filled.
for (const t of data.tiles || []) {
const [ax, ay] = P(t.x0, t.y0 + t.size), s = t.size * f.scale;
if (t.loaded) { ctx.fillStyle = COLOURS.tileLoaded; ctx.fillRect(ax, ay, s, s); }
ctx.strokeStyle = t.loaded ? COLOURS.tileEdge : COLOURS.tileKnown; ctx.lineWidth = 1;
ctx.strokeRect(ax + 0.5, ay + 0.5, Math.max(0, s - 1), Math.max(0, s - 1));
}
// Site boundary.
const ring = (data.boundary || []).filter(finite2);
if (ring.length > 2) {
ctx.beginPath();
ring.forEach((p, i) => { const [x, y] = P(p[0], p[1]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
ctx.closePath(); ctx.strokeStyle = COLOURS.boundary; ctx.lineWidth = 1.5; ctx.setLineDash([5, 3]); ctx.stroke(); ctx.setLineDash([]);
}
// Design items: lines, closed shapes, or single-point markers.
ctx.strokeStyle = ctx.fillStyle = COLOURS.item; ctx.lineWidth = 1.5;
for (const it of data.items || []) {
const pts = (it.points || []).filter(finite2).map(p => P(p[0], p[1]));
if (pts.length === 1) { ctx.fillRect(pts[0][0] - 2, pts[0][1] - 2, 4, 4); continue; }
if (pts.length < 2) continue;
ctx.beginPath();
pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));
if (it.closed) ctx.closePath();
ctx.stroke();
}
// Viewer: a dot with a heading wedge.
const v = data.viewer;
if (v && Number.isFinite(v.x) && Number.isFinite(v.y)) {
const [vx, vy] = P(v.x, v.y), [hx, hy] = headingOnPlan(v.yaw || 0), L = 14, W = 5;
ctx.fillStyle = COLOURS.viewer;
ctx.beginPath();
ctx.moveTo(vx + hx * L, vy + hy * L);
ctx.lineTo(vx - hy * W, vy + hx * W);
ctx.lineTo(vx + hy * W, vy - hx * W);
ctx.closePath(); ctx.globalAlpha = 0.85; ctx.fill(); ctx.globalAlpha = 1;
ctx.beginPath(); ctx.arc(vx, vy, 3, 0, 2 * Math.PI); ctx.fill();
}
// North arrow and scale bar.
ctx.font = '11px system-ui, sans-serif'; ctx.fillStyle = COLOURS.text; ctx.textBaseline = 'top';
ctx.fillText('N', side - 16, 6);
ctx.beginPath(); ctx.moveTo(side - 12.5, 19); ctx.lineTo(side - 12.5, 30); ctx.strokeStyle = COLOURS.text; ctx.lineWidth = 1; ctx.stroke();
ctx.beginPath(); ctx.moveTo(side - 12.5, 18); ctx.lineTo(side - 15.5, 23); ctx.lineTo(side - 9.5, 23); ctx.closePath(); ctx.fill();
const bar = scaleBar(f.scale, side * 0.4);
if (bar.px > 0) {
const x0 = 8, y = side - 8;
ctx.strokeStyle = COLOURS.text; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(x0, y - 4); ctx.lineTo(x0, y); ctx.lineTo(x0 + bar.px, y); ctx.lineTo(x0 + bar.px, y - 4); ctx.stroke();
ctx.textBaseline = 'bottom'; ctx.fillText(bar.label, x0 + 2, y - 3);
}
}