GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-bess-topology

Indexforgis Single-Line Diagram (SLD) and 5 more files

A map page in the solar BESS topology folder of GlobalGrid2050 that maps grid substations, sat s and l sat, and uses data from OpenStreetMap Nominatim. Published at https://globalgrid2050.com/solar-bess-topology/indexforgis-sld.html.

672 lines of JavaScript and HTML from globalgrid2050, in 6 files. Topic: Solar and storage design. Section 119 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. Indexforgis Single-Line Diagram (SLD) electrical · globalgrid2050 / solar-bess-topology/indexforgis-sld.html lines 1129–1454
  2. Camera transform · globalgrid2050 / solar-design-studio/202609262041-site-world/world/camera.mjs lines 1–37
  3. Device Budget transform · globalgrid2050 / solar-design-studio/202609262041-site-world/world/device-budget.mjs lines 1–27
  4. Frame Gate transform · globalgrid2050 / solar-design-studio/202609262041-site-world/world/frame-gate.mjs lines 1–40
  5. Terrain geodesy · globalgrid2050 / solar-design-studio/202609262041-site-world/world/layers/terrain.mjs lines 1–176
  6. Input transform · globalgrid2050 / solar-design-studio/202609262200-site-world/world/input.mjs lines 1–66

Indexforgis Single-Line Diagram (SLD)

A map page in the solar BESS topology folder of GlobalGrid2050 that maps grid substations, sat s and l sat, and uses data from OpenStreetMap Nominatim. Published at https://globalgrid2050.com/solar-bess-topology/indexforgis-sld.html.

electricalglobalgrid2050 / solar-bess-topology/indexforgis-sld.html · lines 1129–1454 of 1454 (continued from section 117) · Entry point · pattern triggerDownload (shared by 3 files)

What it does
It maps grid substations, sat s, l sat and l subs. Defines 47 functions or classes, including $, num, intVal, checked, setText. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV.
Inputs & outputs
In: data source: OpenStreetMap Nominatim; GeoJSON file grid_substations.geojson; JSON file style.json; form fields (user input). Out: web page; interactive map. Voltage levels named: 33kV.
Downstream impact
It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology/indexforgis-sld.html.
What it achieves
It sets text (`setText`), sets class (`setClass`) and picks prop (`pickProp`). GIS-SLD and Financial Sandbox. Its code works with 33 kV. It responds to click, keydown and change events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · solar-bess-topology · page
Uses
https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js, https://cdn.jsdelivr.net/npm/@turf/turf@6/turf.min.js
Used by
none found
Produces
$, num, intVal, checked, setText, setClass, money, debounce, isValidLngLat, pickProp, setFetchStatus, initMap
Defines here
exportGeoJSON, triggerDownload, switchTab, applyLogisticsPreset, autoFillBifacial, searchLocation, triggerDrawAtCenter, toggleBasemap, toggleSubs, wireEvents, boot
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-bess-topology/indexforgis-sld.html:1129-1454 · blob 727275a46deedb86e05835eaaee57a25219a78b6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
        }
    }

    // BESS
    const prefix = state.activeTab === "string" ? "fin_string" : "fin_central";
    const bess_mwh = num(prefix + "_bess_mwh");
    if (bess_mwh > 0) {
        const bess_area_km2 = (bess_mwh * CONSTANTS.BESS_M2_PER_MWH) / 1_000_000;
        const bess_w = Math.sqrt(bess_area_km2 * CONSTANTS.BESS_ASPECT);
        const bess_l = bess_area_km2 / bess_w;
        const bessCenter = turf.destination(turf.point(privateSubCoord), bess_w / 2 + 0.05, -90, { units: "kilometers" }).geometry.coordinates;
        features.push(getRectPolygon(bessCenter, bess_w, bess_l, "bess_footprint"));
        features.push(turf.point(bessCenter, { type: "bess_compound", mwh: bess_mwh }));
        features.push(turf.lineString([bessCenter, privateSubCoord], { type: "33kv_radial" }));
    }

    // Spine
    if (inverters.length > 0) {
        let spineN = -90, spineS = 90;
        inverters.forEach(inv => {
            if (inv.coords[1] > spineN) spineN = inv.coords[1];
            if (inv.coords[1] < spineS) spineS = inv.coords[1];
        });
        if (privateSubCoord[1] > spineN) spineN = privateSubCoord[1];
        if (privateSubCoord[1] < spineS) spineS = privateSubCoord[1];
        features.push(turf.lineString([[privateSubCoord[0], spineS], [privateSubCoord[0], spineN]], { type: "33kv_radial" }));
        inverters.forEach(inv => {
            features.push(turf.lineString([inv.coords, [privateSubCoord[0], inv.coords[1]]], { type: "33kv_radial" }));
        });
    }

    state.currentGeoJSON = turf.featureCollection(features);
    const src = map.getSource("topology");
    if (src) src.setData(state.currentGeoJSON);

    if (features.length > 0) {
        const bbox = turf.bbox(state.currentGeoJSON);
        map.fitBounds(bbox, { padding: 60, duration: 800 });
    }

    // Refresh side-panel values
    renderTechSummary(stats);
    const fin = computeFinance(prefix, stats);
    state.lastFinance[prefix] = fin;
    renderFinance(prefix, fin);
    renderFinanceWarnings(prefix, fin, stats);
}

// ============================================================
// EXPORT
// ============================================================
function exportGeoJSON() {
    if (state.currentGeoJSON.features.length === 0) return;
    const exportData = JSON.parse(JSON.stringify(state.currentGeoJSON));
    const boundary = exportData.features.find(f => f.properties.type === "array_boundary");
    if (!boundary) return triggerDownload(exportData);

    const stats = state.lastStats || computeStats();
    const prefix = state.activeTab === "string" ? "fin_string" : "fin_central";
    const fin = state.lastFinance[prefix] || computeFinance(prefix, stats);

    const suffix = state.activeTab === "string" ? "" : "_c";
    const logisticsPreset = $("logistics_preset" + suffix)?.value || "manual";
    const grossFactor = num("gross_factor" + suffix);
    const gcr = parseFloat($("mounting_type" + suffix)?.value) || 0;
    const moduleRatingWp = num("mod_wp" + suffix);

    const topologyProps = state.activeTab === "string" ? {
        tech_modules_per_string: intVal("x_mods"),
        tech_strings_per_inverter: intVal("z_strings"),
        tech_inverters_per_substation: intVal("y_invs"),
        tech_substations_per_33kv_ring: intVal("s_subs"),
        tech_33kv_rings: intVal("b_cols")
    } : {
        tech_central_ac_rating_mwac: num("inv_ac_mw_c"),
        tech_modules_per_string: intVal("x_mods_c"),
        tech_strings_per_combiner_box: intVal("str_per_cb_c"),
        tech_central_inverters_per_mv_station: intVal("inv_per_mv_c"),
        tech_mv_stations_per_33kv_ring: intVal("mv_per_ring_c"),
        tech_33kv_rings: intVal("rings_c"),
        tech_combiner_boxes_per_inverter: stats.combiner_boxes_per_inverter,
        tech_total_combiner_boxes: stats.total_combiner_boxes
    };

    boundary.properties = {
        ...boundary.properties,
        fin_active_tab: state.activeTab,
        fin_export_note: "Engineering screening output only. Not construction design, financial advice, EPC pricing, grid compliance, logistics planning or transport instruction. Electrical loss fields are assumption fields and require competent project specific verification. Selected substation is a public dataset reference point and does not confirm available capacity, connection rights, voltage  … [line shortened here: 434 characters; full line on GitHub]

        grid_selected_substation_name: state.selectedSubstation?.name || null,
        grid_selected_substation_voltage: state.selectedSubstation?.voltage || null,
        grid_selected_substation_lon: state.selectedSubstation?.coordinates?.[0] ?? null,
        grid_selected_substation_lat: state.selectedSubstation?.coordinates?.[1] ?? null,
        grid_selected_substation_properties: state.selectedSubstation?.properties || null,

        tech_module_rating_wp: moduleRatingWp,
        tech_module_length_m: num("mod_l" + suffix),
        tech_module_width_m: num("mod_w" + suffix),
        tech_ground_coverage_ratio: gcr,
        tech_gross_site_factor: grossFactor,

        tech_logistics_preset: logisticsPreset,
        tech_modules_per_packing_unit: stats.mods_pallet,
        tech_modules_per_40ft_container: stats.mods_container,
        tech_spare_allowance_percent: stats.spares_pct,
        tech_total_base_packing_units: stats.pallets,
        tech_total_base_containers: stats.containers,
        tech_total_modules_inc_spares: stats.modules_inc_spares,
        tech_total_packing_units_inc_spares: stats.pallets_inc_spares,
        tech_total_containers_inc_spares: stats.containers_inc_spares,
        tech_containers_per_mwp: stats.dc_mwp > 0 ? Number((stats.containers_inc_spares / stats.dc_mwp).toFixed(2)) : 0,

        ...topologyProps,

        tech_module_count: stats.module_count,
        tech_dc_capacity_mwp: stats.dc_mwp,
        tech_ac_capacity_mwac: stats.ac_mw,
        tech_net_mod_area_m2: stats.net_mod_area_m2,
        tech_net_array_area_m2: stats.net_array_area_m2,
        tech_gross_site_area_m2: stats.gross_site_area_m2,

        // Finance — numbers, not formatted strings
        fin_total_capex_gbp: Math.round(fin.totalCapex),
        fin_capex_per_wp_gbp: Number(fin.capexPerWp.toFixed(4)),
        fin_annual_rev_gbp: Math.round(fin.annualRevenue),
        fin_25yr_revenue_gbp: Math.round(fin.revenue25),
        fin_35yr_revenue_gbp: Math.round(fin.revenue35),
        fin_25yr_surplus_gbp: Math.round(fin.surplus25),
        fin_35yr_surplus_gbp: Math.round(fin.surplus35),

        fin_energy_price_gbp_mwh: fin.price,
        fin_other_income_gbp_mwh: fin.other,
        fin_yield_kwh_kwp: fin.yieldVal,
        fin_bifacial_gain: fin.bifacial,
        fin_flood_resilience: fin.floodActive,
        fin_flood_adder_gbp_wp: fin.floodRate,

        fin_base_losses_percent: fin.baseLoss,
        fin_loss_dc_string_percent: num(prefix + "_loss_dc_string"),
        fin_loss_lv_main_dc_percent: num(prefix + "_loss_lv_dc"),
        fin_loss_lv_ac_percent: num(prefix + "_loss_lv_ac"),
        fin_loss_transformer_percent: num(prefix + "_loss_tx"),
        fin_loss_other_electrical_percent: num(prefix + "_loss_other"),

        fin_opex_gbp_mwac_year: fin.opexRate,
        fin_epc_ex_modules_gbp_wp: fin.epcEx,
        fin_modules_gbp_wp: fin.modules,
        fin_other_capex_gbp_wp: fin.otherCapex,
        fin_fixed_capex_gbp: fin.fixedCapex,
        fin_contingency_percent: fin.cont,
        fin_bess_mw: fin.bessMw,
        fin_bess_mwh: fin.bessMwh,
        fin_bess_capex_gbp_mwh: fin.bessCapexRate,
        fin_bess_cycles_year: fin.bessCycles,
        fin_bess_spread_gbp_mwh: fin.bessSpread,
        fin_bess_efficiency_percent: fin.bessEff
    };

    triggerDownload(exportData);
}

function triggerDownload(data) {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `gis_sld_${state.activeTab}_neat_grid.geojson`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
}

// ============================================================
// TAB SWITCHING
// ============================================================
function switchTab(tab) {
    state.activeTab = tab;
    $("tabbtn_string")?.classList.toggle("active", tab === "string");
    $("tabbtn_central")?.classList.toggle("active", tab === "central");
    $("string_tab")?.classList.toggle("active", tab === "string");
    $("central_tab")?.classList.toggle("active", tab === "central");
    $("btn_draw")?.classList.toggle("central", tab === "central");
    document.querySelectorAll(".central-only").forEach(el => {
        el.style.display = tab === "central" ? "flex" : "none";
    });
    updateLegend();
    if (state.activeDrawCenter) computeAndDraw();
    else recalcAll();
}

// ============================================================
// LOGISTICS PRESET
// ============================================================
function applyLogisticsPreset(val, suffix) {
    const preset = CONSTANTS.LOGISTICS_PRESETS[val];
    if (!preset) return;
    const pEl = $("mods_pallet" + suffix);
    const cEl = $("mods_container" + suffix);
    if (pEl) pEl.value = preset.pallet;
    if (cEl) cEl.value = preset.container;
    recalcAll();
}

// ============================================================
// BIFACIAL AUTO-FILL
// ============================================================
function autoFillBifacial(gcrVal, targetId) {
    const bifacial = CONSTANTS.BIFACIAL_BY_GCR[gcrVal] ?? 0;
    const el = $(targetId);
    if (el) {
        el.value = bifacial;
        el.dispatchEvent(new Event("input", { bubbles: true }));
    }
}

// ============================================================
// LOCATION SEARCH
// ============================================================
async function searchLocation() {
    const q = $("loc_search")?.value;
    if (!q) return;
    try {
        const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&limit=1&q=${encodeURIComponent(q)}`);
        const data = await res.json();
        if (data && data.length > 0) {
            map.flyTo({ center: [parseFloat(data[0].lon), parseFloat(data[0].lat)], zoom: 14 });
        }
    } catch (e) {
        console.error("Geocoding failed:", e);
    }
}

// ============================================================
// DRAW BUTTON
// ============================================================
function triggerDrawAtCenter() {
    if (!map) return;
    state.selectedSubstation = null;
    state.activeDrawCenter = [map.getCenter().lng, map.getCenter().lat];
    computeAndDraw();
    updateSelectedSubstationDisplay();
}

// ============================================================
// BASEMAP / SUBS TOGGLES
// ============================================================
function toggleBasemap() {
    if (!map || !map.getLayer("l-sat")) return;
    state.satActive = !state.satActive;
    map.setLayoutProperty("l-sat", "visibility", state.satActive ? "visible" : "none");
    const btn = $("btn_basemap");
    if (btn) {
        btn.textContent = state.satActive ? "DARK MATTER VIEW" : "SATELLITE VIEW";
        btn.classList.toggle("active", state.satActive);
    }
}

function toggleSubs() {
    if (!map || !map.getLayer("l-subs")) return;
    state.subsVisible = !state.subsVisible;
    map.setLayoutProperty("l-subs", "visibility", state.subsVisible ? "visible" : "none");
    const btn = $("btn_subs_toggle");
    if (btn) {
        btn.textContent = state.subsVisible ? "SUBS ON" : "SUBS OFF";
        btn.classList.toggle("active", state.subsVisible);
    }
}

// ============================================================
// WIRE EVERYTHING UP
// ============================================================
function wireEvents() {
    // Tab buttons
    document.querySelectorAll(".tab-btn").forEach(btn => {
        btn.addEventListener("click", () => switchTab(btn.dataset.tab));
    });

    // Map toggles
    $("btn_basemap")?.addEventListener("click", toggleBasemap);
    $("btn_subs_toggle")?.addEventListener("click", toggleSubs);

    // Draw / Export
    $("btn_draw")?.addEventListener("click", triggerDrawAtCenter);
    $("btn_export")?.addEventListener("click", exportGeoJSON);

    // Search
    $("btn_search")?.addEventListener("click", searchLocation);
    $("loc_search")?.addEventListener("keydown", (e) => { if (e.key === "Enter") searchLocation(); });

    // Logistics presets
    document.querySelectorAll("[data-suffix]").forEach(sel => {
        sel.addEventListener("change", () => applyLogisticsPreset(sel.value, sel.dataset.suffix));
    });

    // Bifacial auto-fill
    $("mounting_type")?.addEventListener("change", (e) => autoFillBifacial(e.target.value, "fin_string_bifacial"));
    $("mounting_type_c")?.addEventListener("change", (e) => autoFillBifacial(e.target.value, "fin_central_bifacial"));

    // Global recalc on input changes (debounced)
    document.querySelectorAll("input, select").forEach(el => {
        el.addEventListener("input", recalcDebounced);
        el.addEventListener("change", recalcDebounced);
    });
}

// ============================================================
// BOOT
// ============================================================
function boot() {
    wireEvents();
    initMap();
    updateSelectedSubstationDisplay();
    renderBenchmark();
}

// Libraries loaded via defer, so DOMContentLoaded is the right signal.
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", boot);
} else {
    boot();
}
</script>

</body>
</html>

Camera

A JavaScript module in the world folder of GlobalGrid2050. It is built from the direction step (`direction`), the perspective step (`perspective`) and the view step (`view`).

transformglobalgrid2050 / solar-design-studio/202609262041-site-world/world/camera.mjs · lines 1–37 of 37 · version 2026-09-26 20:41 · Entry point · pattern direction (shared by 2 files)

What it does
It calculates its inputs. Defines direction, perspective, view, dot, multiply.
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 8 files: Print SVG (globalgrid2050); Xr Pose (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); and 4 more. Reached from 2 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/).
What it achieves
Pure: no DOM, no WebGL. Local east (x), north (y), up (z), metres.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by 6 files, including Print SVG, Xr Pose and Substrate, from Graphics Engines Open Source.
Application
globalgrid2050 · solar-design-studio/202609262041-site-world/world · JavaScript module
Uses
none found
Used by
imported by Print SVG (import), imported by Xr Pose (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Binoculars Lens (import), imported by Substrate (import), imported by Substrate (import), mentioned in Standalone (comment link)
Produces
direction, perspective, view, multiply
Defines here
direction, perspective, view, dot, multiply
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/202609262041-site-world/world/camera.mjs:1-37 · blob 4b86245c348490bfb781d73fbe9ad73e506e28de · 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
// Camera maths. Pure: no DOM, no WebGL. Local east (x), north (y), up (z), metres.
// Matrices are column-major Float32Array(16), as WebGL expects.

export function direction(yaw, pitch) {
  // yaw 0 looks north (+y), yaw +π/2 looks east (+x); pitch +π/2 looks straight up
  const c = Math.cos(pitch);
  return [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)];
}

export function perspective(fovy, aspect, near, far) {
  const f = 1 / Math.tan(fovy / 2), m = new Float32Array(16);
  m[0] = f / aspect; m[5] = f;
  m[10] = (far + near) / (near - far); m[11] = -1;
  m[14] = (2 * far * near) / (near - far);
  return m;
}

export function view(pos, yaw, pitch) {
  const f = direction(yaw, pitch);
  const r = [Math.cos(yaw), -Math.sin(yaw), 0];
  const u = [r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]];
  const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  const m = new Float32Array(16);
  m[0] = r[0]; m[4] = r[1]; m[8] = r[2]; m[12] = -dot(r, pos);
  m[1] = u[0]; m[5] = u[1]; m[9] = u[2]; m[13] = -dot(u, pos);
  m[2] = -f[0]; m[6] = -f[1]; m[10] = -f[2]; m[14] = dot(f, pos);
  m[15] = 1;
  return m;
}

export function multiply(a, b) {
  const m = new Float32Array(16);
  for (let c = 0; c < 4; c++)
    for (let r = 0; r < 4; r++)
      m[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
  return m;
}

Device Budget

A JavaScript module in the world folder of GlobalGrid2050 that works with initial budget (`initialBudget`).

transformglobalgrid2050 / solar-design-studio/202609262041-site-world/world/device-budget.mjs · lines 1–27 of 27 · version 2026-09-26 20:41 · Entry point · pattern round (shared by 53 files)

What it does
It calculates its inputs. Defines initialBudget, adjust, round.
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 6 files: Xr Pose (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); and 2 more. Reached from 2 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/).
What it achieves
It is built from the initial budget helper (`initialBudget`), the adjust step (`adjust`) and the round step (`round`). Measure, never guess the device. Starts at the screen's pixel ratio (capped at 2), lowers the drawing resolution when frames arrive late, and raises it again when they keep up.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by 4 files, including Xr Pose and Substrate, from Graphics Engines Open Source.
Application
globalgrid2050 · solar-design-studio/202609262041-site-world/world · JavaScript module
Uses
none found
Used by
imported by Xr Pose (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import), imported by Substrate (import)
Produces
MIN_SCALE, LATE, LATE_RUN, ON_TIME_RUN, initialBudget, adjust
Defines here
initialBudget, adjust, round
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/202609262041-site-world/world/device-budget.mjs:1-27 · blob 22fbb6302ae3a51a4d4558ec5a9e13d791c9e846 · 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
// Device budget: measure, never guess the device. Starts at the screen's pixel ratio (capped at 2),
// lowers the drawing resolution when frames arrive late, and raises it again when they keep up.

export const MIN_SCALE = 0.5, MAX_SCALE = 2;
export const LATE = 1.5;         // a frame is late when it arrives 1.5 x later than its target
export const LATE_RUN = 20;      // this many late frames in a row lowers resolution
export const ON_TIME_RUN = 120;  // this many on-time frames in a row raises it

export function initialBudget(devicePixelRatio = 1) {
  const cap = Math.min(Math.max(devicePixelRatio || 1, 1), MAX_SCALE);
  return { scale: cap, cap, late: 0, onTime: 0 };
}

// intervalMs: time since the previous frame while moving; targetMs: 1000 / target fps.
export function adjust(b, intervalMs, targetMs) {
  if (!(intervalMs > 0)) return b;
  if (intervalMs > targetMs * LATE) {
    const late = b.late + 1;
    if (late < LATE_RUN) return { ...b, late, onTime: 0 };
    return { ...b, scale: Math.max(MIN_SCALE, round(b.scale * 0.8)), late: 0, onTime: 0 };
  }
  const onTime = b.onTime + 1;
  if (onTime < ON_TIME_RUN || b.scale >= b.cap) return { ...b, onTime, late: 0 };
  return { ...b, scale: Math.min(b.cap, round(b.scale * 1.1)), onTime: 0, late: 0 };
}

const round = v => Math.round(v * 100) / 100;

Frame Gate

A JavaScript module in the world folder of GlobalGrid2050 that draws only when something changed, and while moving no faster than the mode's target.

transformglobalgrid2050 / solar-design-studio/202609262041-site-world/world/frame-gate.mjs · lines 1–40 of 40 · version 2026-09-26 20:41 · Entry point · pattern schedule (shared by 22 files)

What it does
It calculates its inputs. Defines due, createFrameGate, tick, schedule.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 5 files: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050); and 1 more. Reached from 2 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/).
What it achieves
It is built from the schedule step (`schedule`). Defines `due`, `createFrameGate`, `tick` and 1 more. Its code works with 120 Hz.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by Substrate, from Graphics Engines Open Source.
Application
globalgrid2050 · solar-design-studio/202609262041-site-world/world · JavaScript module
Uses
none found
Used by
preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import), imported by Substrate (import)
Produces
TOLERANCE_MS, due, createFrameGate
Defines here
due, createFrameGate, tick, schedule
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/202609262041-site-world/world/frame-gate.mjs:1-40 · blob b47cf531a85748ce3806b5b4f1d0414549bf1f3e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// Frame gate: draw only when something changed, and while moving no faster than the mode's target.
// Standing still costs nothing: no frame is requested until the next change.

export const TOLERANCE_MS = 2; // a display tick can land a little early; 2 ms keeps 20 and 30 fps even on 60 and 120 Hz

export function due(now, last, fps) {
  return now - last >= 1000 / fps - TOLERANCE_MS;
}

export function createFrameGate(draw, { raf = requestAnimationFrame, clock = () => performance.now() } = {}) {
  let dirty = false, moving = false, fps = 20, last = -Infinity, pending = false;
  const drawn = [];

  function tick(now) {
    pending = false;
    if (!dirty && !moving) return;
    if (!due(now, last, fps)) { schedule(); return; }
    const interval = now - last;
    last = now; dirty = false;
    drawn.push(now);
    while (drawn.length && drawn[0] < now - 1000) drawn.shift();
    draw(now, Number.isFinite(interval) ? interval : 0);
    if (moving) schedule();
  }
  function schedule() { if (!pending) { pending = true; raf(tick); } }

  return {
    invalidate() { dirty = true; schedule(); },
    // starting from still counts the first step as one frame, so a tap never jumps and never reads as late
    setMoving(on, targetFps) {
      if (targetFps) fps = targetFps;
      if (on && !moving) last = Math.max(last, clock() - 1000 / fps);
      moving = on;
      if (on) schedule();
    },
    // frames actually drawn in the last second; 0 when standing still
    fps() { const now = clock(); while (drawn.length && drawn[0] < now - 1000) drawn.shift(); return drawn.length; },
    target() { return fps; }
  };
}

Terrain

A JavaScript module in the layers folder of GlobalGrid2050 that works with tiles and LiDAR terrain, using SHA-256. It sets index sha (`setIndexSha`), decodes tile (`decodeTile`) and loads index (`loadIndex`).

geodesyglobalgrid2050 / solar-design-studio/202609262041-site-world/world/layers/terrain.mjs · lines 1–176 of 176 · version 2026-09-26 20:41 · Entry point · pattern createTerrain (shared by 2 files)

What it does
It calculates tiles and LiDAR terrain. Defines 12 functions or classes, including setIndexSha, decodeTile, sampleTile, rectDist, createTerrain.
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'terrain'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: JSON file tiles.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 2 files: Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Plant Ground (globalgrid2050).
What it achieves
Ground heights from LiDAR tiles (.ght, written by the LiDAR pipeline).
Why it matters
Loaded by the Site World page at https://globalgrid2050.com/solar-design-studio/202609271853-site-world/. Also imported by Plant Ground.
Application
globalgrid2050 · solar-design-studio/202609262041-site-world/world/layers · JavaScript module
VEDIC
DECODE (GG2050-VEDIC-000009): Solar Design Studio / 3D terrain · Computer science / Binary decoding. terrain_tile_bytes → terrain_grid
VEDIC
SAMPLE (GG2050-VEDIC-000010): Solar Design Studio / 3D terrain · Mathematics / Bilinear interpolation. terrain_grid, local_x_m, local_y_m → height_m_or_nan
Uses
none found
Used by
preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Plant Ground (import)
Produces
setIndexSha, HEADER_BYTES, NODATA, LOAD_RADIUS, decodeTile, sampleTile, createTerrain
Defines here
setIndexSha, decodeTile, sampleTile, rectDist, createTerrain, now, place, loadIndex, wanted, request, pump, evict
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/202609262041-site-world/world/layers/terrain.mjs:1-176 · blob 7eae752d4a650a8a07bcf6ac337e5ab252b9bd66 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: production_core
// Layer: terrain. Ground heights from LiDAR tiles (.ght, written by the lidar pipeline). It draws no lines
// of its own: the ground grid drapes on heightAt. Each frame's lines(ctx) call only asks for the tiles
// within LOAD_RADIUS of the viewer, nearest first, a couple at a time, and forgets the least recently used
// when it holds too many. Every file is fetched through the substrate's hash check (api.fetchVerified).
// Heights are in local metres from the site origin; tiles are placed in British National Grid metres.
//
// Tile format (.ght, little-endian). 32-byte header:
//   0 magic "GGH1" | 4 u16 version=1 | 6 u16 samples=257 | 8 u16 spacing_mm | 10 u16 flags
//   12 i32 origin_e_m | 16 i32 origin_n_m (south-west corner) | 20 i32 base_cm | 24 u16 min_q | 26 u16 max_q
//   28 u32 nodata_count. Body: samples*samples u16, rows south to north, each row west to east.
//   height_m = (base_cm + q) / 100; q = 0xFFFF is no data.

const INDEX_PATH = 'terrain/tiles.json';
// Filled by the build tool with the SHA-256 of tiles.json. Until then the layer loads nothing.
let INDEX_SHA256 = '__TERRAIN_TILES_SHA256__';
export function setIndexSha(sha) { INDEX_SHA256 = sha; }

export const HEADER_BYTES = 32;
export const NODATA = 0xffff;
export const LOAD_RADIUS = 350, MAX_IN_FLIGHT = 2, MAX_TILES = 48;

// Pure: bytes -> { version, samples, spacing, flags, e0, n0, baseCm, minQ, maxQ, nodata, q: Uint16Array }.
export function decodeTile(buffer) {
  const bytes = buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  if (bytes.byteLength < HEADER_BYTES) throw Error('terrain tile shorter than its header');
  const dv = new DataView(bytes);
  const magic = String.fromCharCode(dv.getUint8(0), dv.getUint8(1), dv.getUint8(2), dv.getUint8(3));
  if (magic !== 'GGH1') throw Error(`terrain tile magic "${magic}" is not GGH1`);
  const version = dv.getUint16(4, true);
  if (version !== 1) throw Error(`terrain tile version ${version} is not 1`);
  const samples = dv.getUint16(6, true), spacingMm = dv.getUint16(8, true);
  if (samples < 2 || spacingMm === 0) throw Error('terrain tile has no usable grid');
  const need = HEADER_BYTES + samples * samples * 2;
  if (bytes.byteLength !== need) throw Error(`terrain tile is ${bytes.byteLength} bytes, expected ${need}`);
  const q = new Uint16Array(samples * samples);
  for (let i = 0; i < q.length; i++) q[i] = dv.getUint16(HEADER_BYTES + 2 * i, true); // endian-safe copy
  return {
    version, samples, spacing: spacingMm / 1000, flags: dv.getUint16(10, true),
    e0: dv.getInt32(12, true), n0: dv.getInt32(16, true), baseCm: dv.getInt32(20, true),
    minQ: dv.getUint16(24, true), maxQ: dv.getUint16(26, true), nodata: dv.getUint32(28, true), q
  };
}

// Pure: bilinear height at a point given in the tile's own metres (0..size from the south-west corner).
// NaN outside the tile, or where a sample that carries weight has no data.
export function sampleTile(t, u, v) {
  const s = t.samples - 1, gx = u / t.spacing, gy = v / t.spacing;
  if (!(gx >= 0 && gy >= 0 && gx <= s && gy <= s)) return NaN;
  const i = Math.min(Math.floor(gx), s - 1), j = Math.min(Math.floor(gy), s - 1);
  const fx = gx - i, fy = gy - j;
  const w = [(1 - fx) * (1 - fy), fx * (1 - fy), (1 - fx) * fy, fx * fy];
  const k = [j * t.samples + i, j * t.samples + i + 1, (j + 1) * t.samples + i, (j + 1) * t.samples + i + 1];
  let sum = 0;
  for (let c = 0; c < 4; c++) {
    if (w[c] === 0) continue;
    const q = t.q[k[c]];
    if (q === NODATA) return NaN;
    sum += w[c] * q;
  }
  return (t.baseCm + sum) / 100;
}

// Distance from a point to an axis-aligned rectangle (0 inside).
const rectDist = (x, y, x0, y0, x1, y1) => Math.hypot(Math.max(x0 - x, 0, x - x1), Math.max(y0 - y, 0, y - y1));

export function createTerrain() {
  let api = null, origin = { e: 0, n: 0 };
  let index = null, indexState = 'idle'; // idle | loading | ready | failed
  const loaded = new Map();   // key -> { tile, x0, y0, size, used }
  const inFlight = new Set(); // keys
  const failed = new Set();   // keys never retried this session
  let clock = 0;
  // Local position of a tile, read from the live origin every time, so it stays right when the origin moves.
  const now = () => (api && typeof api.origin === 'function' ? api.origin() : origin);
  const place = o => Object.defineProperties(o, {
    x0: { get: () => o.e0 - now().e, enumerable: true }, y0: { get: () => o.n0 - now().n, enumerable: true } });
  const stats = { requested: [], evicted: [] };

  function loadIndex() {
    if (indexState !== 'idle' || !api) return;
    const sha = api.config?.sha256 || INDEX_SHA256;
    const path = api.config?.index || INDEX_PATH;
    if (!sha || sha.startsWith('__')) { indexState = 'failed'; layer.status = 'no tiles.json hash configured'; return; }
    indexState = 'loading';
    Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
      if (!j || !Array.isArray(j.tiles)) throw Error('tiles.json has no tiles list');
      const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '';
      index = j.tiles.map(t => ({
        ...t, path: dir + t.file,
        size: j.tile_m || 256
      })).map(place);
      indexState = 'ready';
      layer.status = `index: ${index.length} tiles`;
      api.invalidate();
    }).catch(e => { indexState = 'failed'; layer.status = 'tiles.json failed: ' + e.message; });
  }

  // Tiles within LOAD_RADIUS of (x, y), nearest first (edge distance, then centre distance).
  function wanted(x, y) {
    if (!index) return [];
    return index
      .map(t => ({ t, d: rectDist(x, y, t.x0, t.y0, t.x0 + t.size, t.y0 + t.size),
        c: Math.hypot(x - t.x0 - t.size / 2, y - t.y0 - t.size / 2) }))
      .filter(o => o.d <= LOAD_RADIUS)
      .sort((a, b) => a.d - b.d || a.c - b.c)
      .map(o => o.t);
  }

  function request(entry) {
    inFlight.add(entry.key);
    stats.requested.push(entry.key);
    Promise.resolve().then(() => api.fetchVerified(entry.path, entry.sha256)).then(buf => {
      const tile = decodeTile(buf);
      const size = (tile.samples - 1) * tile.spacing;
      loaded.set(entry.key, place({ tile, e0: tile.e0, n0: tile.n0, size, used: ++clock }));
      evict();
      api.invalidate();
    }).catch(e => { failed.add(entry.key); layer.status = `tile ${entry.key} failed: ${e.message}`; })
      .finally(() => { inFlight.delete(entry.key); pump(); });
  }

  let lastPos = null;
  function pump() {
    if (!lastPos || indexState !== 'ready') return;
    for (const t of wanted(lastPos[0], lastPos[1])) {
      if (inFlight.size >= MAX_IN_FLIGHT) break;
      if (loaded.has(t.key)) { loaded.get(t.key).used = ++clock; continue; }
      if (inFlight.has(t.key) || failed.has(t.key)) continue;
      request(t);
    }
  }

  function evict() {
    while (loaded.size > MAX_TILES) {
      let oldest = null;
      for (const [k, v] of loaded) if (!oldest || v.used < loaded.get(oldest).used) oldest = k;
      loaded.delete(oldest);
      stats.evicted.push(oldest);
    }
  }

  const layer = {
    id: 'terrain',
    status: 'waiting for init',
    init(a) {
      api = a;
      const o = typeof a.origin === 'function' ? a.origin() : null;
      if (o) origin = { e: o.e, n: o.n };
      layer.status = 'ready to load';
      loadIndex();
    },
    // Finest loaded tile containing the point wins; NaN where no tile is loaded (the substrate falls back).
    heightAt(x, y) {
      let best = null;
      for (const t of loaded.values()) {
        if (x < t.x0 || y < t.y0 || x > t.x0 + t.size || y > t.y0 + t.size) continue;
        if (!best || t.tile.spacing < best.tile.spacing) best = t;
      }
      if (!best) return NaN;
      best.used = ++clock;
      return sampleTile(best.tile, x - best.x0, y - best.y0);
    },
    lines(ctx) {
      if (!api) return [];
      lastPos = ctx.pos;
      if (indexState === 'idle') loadIndex();
      pump();
      return [];
    },
    // For tests and the console.
    debug: () => ({ loaded: [...loaded.keys()], inFlight: [...inFlight], failed: [...failed], indexState, ...stats })
  };
  return layer;
}

export default createTerrain();

Input

A JavaScript module in the world folder of GlobalGrid2050. It is built from the set step (`set`), the any step (`any`) and the axis step (`axis`).

transformglobalgrid2050 / solar-design-studio/202609262200-site-world/world/input.mjs · lines 1–66 of 66 · version 2026-09-26 22:00 · Entry point · pattern attachInput (shared by 2 files)

What it does
It calculates its inputs. Defines 6 functions or classes, including attachInput, set, up, any, axis.
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 2 files: Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
Keyboard, mouse and touch turned into one small state. It responds to keydown, keyup and blur events.
Why it matters
Loaded by the Site World page at https://globalgrid2050.com/solar-design-studio/202609271853-site-world/. Also imported by Substrate.
Application
globalgrid2050 · solar-design-studio/202609262200-site-world/world · JavaScript module
Uses
none found
Used by
preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import)
Produces
attachInput
Defines here
attachInput, set, up, any, axis, clamp
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/202609262200-site-world/world/input.mjs:1-66 · blob 8922d23ab7c1642b4469f5309b42f6f40386174d · 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
// Input: keyboard, mouse and touch turned into one small state. Knows nothing about the world.
// Keys: W A S D or arrows move (left/right arrows turn), Shift held = slow and precise,
// C crouched, V raised, F aerial (Space / E up, Q down). Mouse: drag to look.
// Touch: left half of the screen is a thumbstick, right half looks.

const VIEW_KEYS = { KeyC: 'crouched', KeyV: 'raised', KeyF: 'aerial' };
const MOVE_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'KeyE', 'KeyQ', 'Space', 'ShiftLeft', 'ShiftRight',
  'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);
const LOOK_PER_PX = 0.004, TURN_PER_S = 1.8, STICK_PX = 60;

export function attachInput(canvas, { onChange, onLook, onView }) {
  const keys = new Set();
  let stick = null, lookPtr = null, mouse = null;

  const set = (k, down) => { const had = keys.has(k); down ? keys.add(k) : keys.delete(k); if (had !== down) onChange(); };
  addEventListener('keydown', e => {
    if (e.target instanceof HTMLButtonElement && (e.code === 'Space' || e.code === 'Enter')) return;
    if (e.ctrlKey || e.metaKey || e.altKey) return; // leave browser shortcuts such as Ctrl+F alone
    if (VIEW_KEYS[e.code] && !e.repeat) { onView(VIEW_KEYS[e.code]); return; }
    if (MOVE_KEYS.has(e.code)) { set(e.code, true); e.preventDefault(); }
  });
  addEventListener('keyup', e => set(e.code, false));
  addEventListener('blur', () => { keys.clear(); stick = lookPtr = mouse = null; onChange(); });

  canvas.addEventListener('pointerdown', e => {
    canvas.setPointerCapture(e.pointerId);
    if (e.pointerType === 'touch' && e.clientX < canvas.clientWidth / 2 && !stick) stick = { id: e.pointerId, x0: e.clientX, y0: e.clientY, dx: 0, dy: 0 };
    else if (e.pointerType === 'touch') lookPtr = { id: e.pointerId, x: e.clientX, y: e.clientY };
    else mouse = { x: e.clientX, y: e.clientY };
    onChange();
  });
  canvas.addEventListener('pointermove', e => {
    if (stick && e.pointerId === stick.id) { stick.dx = e.clientX - stick.x0; stick.dy = e.clientY - stick.y0; onChange(); return; }
    const p = lookPtr && e.pointerId === lookPtr.id ? lookPtr : mouse;
    if (!p) return;
    if (p === mouse && e.buttons === 0) { mouse = null; return; } // released outside the window
    onLook((e.clientX - p.x) * LOOK_PER_PX, -(e.clientY - p.y) * LOOK_PER_PX);
    p.x = e.clientX; p.y = e.clientY;
  });
  const up = e => {
    if (stick && e.pointerId === stick.id) stick = null;
    else if (lookPtr && e.pointerId === lookPtr.id) lookPtr = null;
    else mouse = null;
    onChange();
  };
  canvas.addEventListener('pointerup', up); canvas.addEventListener('pointercancel', up);

  const any = list => list.some(k => keys.has(k));
  const axis = (plus, minus) => (any(plus) ? 1 : 0) - (any(minus) ? 1 : 0);
  return {
    // forward, strafe, rise in [-1, 1]; turn in radians per second; slow = precise movement
    get() {
      const s = stick ? [clamp(stick.dx / STICK_PX), clamp(-stick.dy / STICK_PX)] : [0, 0];
      return {
        forward: clamp(axis(['KeyW', 'ArrowUp'], ['KeyS', 'ArrowDown']) + s[1]),
        strafe: clamp(axis(['KeyD'], ['KeyA']) + s[0]),
        rise: axis(['Space', 'KeyE'], ['KeyQ']),
        turn: axis(['ArrowRight'], ['ArrowLeft']) * TURN_PER_S,
        slow: any(['ShiftLeft', 'ShiftRight'])
      };
    },
    active() { const i = this.get(); return !!(i.forward || i.strafe || i.rise || i.turn); }
  };
}

const clamp = v => Math.max(-1, Math.min(1, v));