GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/24-electrification-model

Iterations — 26 Apps Layers Substrate and 1 more file

A JavaScript module in Galaxies Wafers that draws lines meta and families, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/26-apps-layers-substrate/.

700 lines of JavaScript from galaxies-wafers, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1196 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. Seven interaction · galaxies-wafers / iterations/24-electrification-model/seven.mjs lines 1–347
  2. Iterations — 26 Apps Layers Substrate render · galaxies-wafers / iterations/26-apps-layers-substrate/app.mjs lines 1–353

Seven

A JavaScript module in the iterations folder of Galaxies Wafers that sets val, shows bar and lane note and calculates planar distances. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/24-electrification-model/.

interactiongalaxies-wafers / iterations/24-electrification-model/seven.mjs · lines 1–347 of 347 · Entry point · pattern attachDrag (shared by 2 files)

What it does
It draws its content. Defines 20 functions or classes, including $, el, fmt, show, read. Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 24 Electrification Model Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/24-electrification-model/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/24-electrification-model/.
What it achieves
It sets val (`setVal`), shows bar (`showBar`) and shows lane note (`showLaneNote`). Draws `engine/electrification-model.js`. Every value comes from the module; the page formats, scales and places. It responds to input, pointerdown and pointermove events.
Why it matters
Loaded by the 24 Electrification Model page at https://ventusltd.github.io/galaxies-wafers/iterations/24-electrification-model/.
Application
galaxies-wafers · iterations/24-electrification-model · JavaScript module
Uses
none found
Used by
loaded by Iterations — 24 Electrification Model Page (script src)
Produces
$, el, fmt, show, read, attempt, compute, draw, setVal, schedule, laneOf, showBar
Defines here
$, el, fmt, show, read, attempt, compute, draw, setVal, schedule, laneOf, showBar, showLaneNote, attachDrag, end, laneAt, tryAdd, hidePop, workedExample, dim
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/24-electrification-model/seven.mjs:1-347 · blob 252ffcb1136128a0de52ddb71c2b154f203c8480 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Seven Meanings. Draws engine/electrification-model.js. Every value comes from
   the module; the page formats, scales and places. Nothing here re-derives a
   formula the module owns. */

const PIN = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
const SRC = `https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${PIN}/engine/electrification-model.js`;

const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const fmt = (n, d = 3) => Number(n).toLocaleString('en-GB', { maximumFractionDigits: d });
$('pin').textContent = PIN.slice(0, 12);

let M; // the module
try {
  M = await import(SRC);
} catch (e) {
  $('status').textContent = `FAIL — the electrification model could not be loaded from the engine: ${e.message}`;
  throw e;
}

/* ── the seven lanes, keyed by the module's own MEANING names ──────────────── */
const LANES = [
  { key: 'THERMAL_OUTPUT',   top: 'THERMAL',  sub: 'output',    c: '#ff9f43', axis: 'home' },
  { key: 'ELECTRICAL_INPUT', top: 'ELECTRIC', sub: 'input',     c: '#3d7bff', axis: 'home' },
  { key: 'NAMEPLATE',        top: 'NAME',     sub: 'plate',     c: '#b48cff', axis: 'fleet' },
  { key: 'AFTER_DIVERSITY',  top: 'AFTER',    sub: 'diversity', c: '#62d8ff', axis: 'fleet' },
  { key: 'PRIMARY_ENERGY',   top: 'PRIMARY',  sub: 'energy',    c: '#ffd54a', axis: 'year' },
  { key: 'FINAL_ENERGY',     top: 'FINAL',    sub: 'energy',    c: '#e8e8e8', axis: 'year' },
  { key: 'USEFUL_WORK',      top: 'USEFUL',   sub: 'work',      c: '#f4f4f4', axis: 'year' }
];
const AXES = { home: 'kW / home', fleet: 'GW fleet', year: 'TWh / yr' };
const meaningKeys = Object.keys(M.MEANING);
const missing = LANES.filter(L => !(L.key in M.MEANING)).map(L => L.key);
$('status').textContent = missing.length
  ? `FAIL — the module does not declare: ${missing.join(', ')}`
  : `OK — ${M.schema} loaded; ${meaningKeys.length} meanings declared by the module, one lane each.`;
$('notForecast').textContent = M.NOT_A_FORECAST;

/* ── scenario inputs ──────────────────────────────────────────────────────── */
const SLIDERS = [
  { id: 'heat',  label: 'heat demand per home', unit: 'kW thermal', min: 1, max: 20, step: 0.25, value: 12.25,
    hint: 'THERMAL_OUTPUT: heat delivered to one home.' },
  { id: 'scop',  label: 'SCOP', unit: '', min: 1, max: 6, step: 0.05, value: 3.5,
    hint: 'Seasonal coefficient of performance. The module carries none, and refuses 1 or less.' },
  { id: 'units', label: 'number of heat pumps', unit: 'units', min: 0, max: 40000000, step: 100000, value: 28000000,
    hint: 'A whole number of units, one per home.' },
  { id: 'div',   label: 'after-diversity demand per home', unit: 'kW', min: 0.1, max: 6, step: 0.1, value: 1.7,
    hint: 'The module takes diversity as a measured after-diversity kW per unit, never as a factor it chooses, and reports its ratio to nameplate.' },
  { id: 'mwh',   label: 'useful heat per home per year', unit: 'MWh', min: 1, max: 30, step: 0.5, value: 12,
    hint: 'USEFUL_WORK: heat actually obtained in a year. Feeds the primary-energy lane.' },
  { id: 'boil',  label: 'incumbent gas boiler efficiency', unit: '', min: 0.5, max: 1, step: 0.01, value: 0.85,
    hint: 'The chain being replaced. The heat-pump chain uses the SCOP above as its efficiency.' }
];
const S = {};
for (const s of SLIDERS) {
  const wrap = el('div', 'slider');
  const lab = el('label');
  lab.htmlFor = 'in-' + s.id;
  const left = el('span');
  left.append(el('span', 'si', 'scenario input'), ' ', s.label);
  const out = el('output');
  lab.append(left, out);
  const inp = document.createElement('input');
  Object.assign(inp, { type: 'range', min: s.min, max: s.max, step: s.step, value: s.value, id: 'in-' + s.id });
  const show = () => { out.textContent = `${fmt(+inp.value)} ${s.unit}`.trim(); };
  inp.addEventListener('input', () => { show(); schedule(); });
  wrap.append(lab, inp, el('div', 'hint', s.hint));
  $('sliders').append(wrap);
  S[s.id] = { inp, show };
  show();
}
const read = id => +S[id].inp.value;

/* ── lane DOM, built once; updates touch only the changed nodes ─────────────── */
const laneEls = {};
for (const L of LANES) {
  const lane = el('div', 'lane');
  lane.dataset.meaning = L.key;
  const h = el('h3'); h.append(el('b', null, L.top), L.sub);
  const track = el('div', 'track');
  const val = el('div', 'val');
  lane.append(h, track, val);
  lane.style.setProperty('--c', L.c);
  $('lanes').append(lane);
  laneEls[L.key] = { lane, track, val, sig: '' };
  $('axes').append(el('div', null, AXES[L.axis]));
}

/* ── compute: call the module; each lane gets bars or a refusal ─────────────── */
function attempt(fn) { try { return { ok: fn() }; } catch (e) { return { err: e.message }; } }

function compute() {
  const q = M.MEANING, heat = read('heat'), scop = read('scop'), units = read('units'), div = read('div');
  const out = {};
  const thermal = attempt(() => M.quantity(heat, 'kW', q.THERMAL_OUTPUT));
  const elec = thermal.ok ? attempt(() => M.electricalInputFromHeat({ thermal: thermal.ok, scop })) : thermal;
  const back = elec.ok ? attempt(() => M.heatFromElectricalInput({ electrical: elec.ok, scop })) : elec;

  out.THERMAL_OUTPUT = thermal.ok
    ? { bars: [{ id: 'thermal', value: thermal.ok.value, show: fmt(thermal.ok.value), u: 'kW', obj: thermal.ok,
        call: `quantity(${heat}, 'kW', MEANING.THERMAL_OUTPUT)`,
        text: [back.ok ? `Round trip through heatFromElectricalInput at SCOP ${scop}: ${fmt(back.ok.value, 6)} kW, meaning ${back.ok.meaning}. ${back.ok.basis}` : ''] }] }
    : { refused: thermal.err, call: 'quantity' };

  out.ELECTRICAL_INPUT = elec.ok
    ? { bars: [{ id: 'elec', value: elec.ok.value, show: fmt(elec.ok.value), u: 'kW', obj: elec.ok,
        call: `electricalInputFromHeat({ thermal, scop: ${scop} })`, text: [elec.ok.basis, `not computed: ${elec.ok.not_computed}`] }] }
    : { refused: elec.err, call: 'electricalInputFromHeat' };

  let fleet = { err: elec.err }, plateOnly = { err: elec.err };
  if (elec.ok) {
    fleet = attempt(() => M.fleetDemand({ units, perUnitNameplate: elec.ok,
      perUnitAfterDiversity: M.quantity(div, 'kW', q.AFTER_DIVERSITY) }));
    plateOnly = attempt(() => M.fleetDemand({ units, perUnitNameplate: elec.ok }));
  }
  // The nameplate bar carries the module's nameplate-only fleet result, so
  // nothing dragged from it can smuggle an after-diversity figure along.
  if (plateOnly.ok) {
    const f = plateOnly.ok;
    out.NAMEPLATE = { bars: [{ id: 'plate', value: f.simultaneous.value, show: fmt(f.simultaneous.value / 1e6, 2), u: 'GW',
      obj: f, call: `fleetDemand({ units: ${units}, perUnitNameplate })`,
      text: [`label: ${f.simultaneous.label}`, f.basis, `never added: ${f.never_added}`] }] };
  } else out.NAMEPLATE = { refused: plateOnly.err, call: elec.ok ? 'fleetDemand' : 'electricalInputFromHeat, upstream' };
  if (fleet.ok) {
    const f = fleet.ok;
    out.AFTER_DIVERSITY = { bars: [{ id: 'div', value: f.diversified.value, show: fmt(f.diversified.value / 1e6, 2), u: 'GW',
      obj: f, call: `fleetDemand({ units: ${units}, perUnitNameplate, perUnitAfterDiversity: ${div} kW })`,
      text: [`label: ${f.diversified.label}`, f.basis, `ratio to nameplate reported by the module: ${fmt(f.diversified.ratio * 100, 1)}%`, `not computed: ${f.not_computed}`] }] };
  } else out.AFTER_DIVERSITY = { refused: fleet.err, call: elec.ok ? 'fleetDemand' : 'electricalInputFromHeat, upstream' };

  const useful = attempt(() => M.quantity(units * read('mwh'), 'MWh', q.USEFUL_WORK));
  out.USEFUL_WORK = useful.ok
    ? { bars: [{ id: 'useful', value: useful.ok.value, show: fmt(useful.ok.value / 1e6, 1), u: 'TWh', obj: useful.ok,
        call: `quantity(${units} × ${read('mwh')}, 'MWh', MEANING.USEFUL_WORK)`, text: ['The scenario inputs, typed by the module as useful work.'] }] }
    : { refused: useful.err, call: 'quantity' };

  const prim = useful.ok ? attempt(() => M.primaryEnergyForWork({ usefulWork: useful.ok, incumbentEfficiency: read('boil'), electrifiedEfficiency: scop })) : useful;
  out.PRIMARY_ENERGY = prim.ok
    ? { bars: ['before', 'after'].map(k => ({ id: 'prim-' + k, tag: k === 'before' ? 'boiler' : 'pump',
        value: prim.ok[k].value, show: fmt(prim.ok[k].value / 1e6, 1), u: 'TWh', obj: prim.ok[k],
        call: `primaryEnergyForWork({ usefulWork, incumbentEfficiency: ${read('boil')}, electrifiedEfficiency: ${scop} }).${k}`,
        text: [prim.ok.basis, `reduction ratio reported by the module: ${fmt(prim.ok.reductionRatio * 100, 1)}%`, `not computed: ${prim.ok.not_computed}`] })),
        valText: `${fmt(prim.ok.before.value / 1e6, 0)}→${fmt(prim.ok.after.value / 1e6, 0)}` }
    : { refused: prim.err, call: useful.ok ? 'primaryEnergyForWork' : 'quantity, upstream' };

  out.FINAL_ENERGY = { empty: `The module declares the meaning ${M.MEANING.FINAL_ENERGY}, but none of its exported functions returns a quantity carrying it, so there is nothing computed to draw in this lane.` };
  return out;
}

/* each bar is scaled against the largest value in its axis group */
let current = {};
let selected = null;
function draw() {
  current = compute();
  const maxBy = {};
  for (const L of LANES) for (const b of current[L.key].bars || []) maxBy[L.axis] = Math.max(maxBy[L.axis] || 0, b.value);
  const refusals = [];
  for (const L of LANES) {
    const r = current[L.key], E = laneEls[L.key];
    const sig = r.bars ? 'bars:' + r.bars.map(b => b.id).join(',') : r.refused ? 'refused' : 'empty';
    if (sig !== E.sig) {           // structure changed: rebuild this one lane's track only
      E.track.textContent = '';
      if (r.bars) {
        for (const b of r.bars) {
          const bar = el('div', 'bar');
          bar.dataset.meaning = L.key; bar.dataset.bar = b.id; bar.tabIndex = 0;
          bar.setAttribute('role', 'button');
          if (b.tag) bar.append(el('span', 'tag', b.tag));
          attachDrag(bar);
          E.track.append(bar);
        }
        E.lane.onclick = null;
      } else {
        const n = el('div', 'note');
        n.append(el('b', null, r.refused ? 'REFUSED' : 'EMPTY'), 'tap to read');
        E.track.append(n);
        E.lane.onclick = () => showLaneNote(L);
      }
      E.sig = sig;
    }
    if (r.bars) {
      [...E.track.querySelectorAll('.bar')].forEach((bar, i) => {
        const b = r.bars[i];
        bar.style.height = `${maxBy[L.axis] > 0 ? Math.max(0.6, 100 * b.value / (maxBy[L.axis] * 1.12)) : 0.6}%`;
        bar.setAttribute('aria-label', `${L.top} ${L.sub}${b.tag ? ' ' + b.tag : ''}: ${b.show} ${b.u}. Drag onto another lane to try adding.`);
      });
      setVal(E.val, r.valText || r.bars[0].show, r.bars[0].u);
    } else setVal(E.val, r.refused ? 'REFUSED' : 'EMPTY', 'reason ↓');
    if (r.refused) refusals.push(`${L.top} ${L.sub}: ${r.call} threw: ${r.refused}`);
  }
  const list = $('refusals');
  const joined = refusals.join('\n');
  if (list.dataset.sig !== joined) {
    list.textContent = '';
    for (const t of refusals) list.append(el('li', null, t));
    list.dataset.sig = joined;
    $('refusedList').hidden = refusals.length === 0;
  }
  if (selected) showBar(selected.meaning, selected.id, false);
}
function setVal(node, v, u) {
  const s = v + '|' + u;
  if (node.dataset.sig === s) return;
  node.textContent = v; node.append(el('span', 'u', u)); node.dataset.sig = s;
}

let raf = 0;
function schedule() { if (!raf) raf = requestAnimationFrame(() => { raf = 0; draw(); }); }

/* ── detail panel ─────────────────────────────────────────────────────────── */
const laneOf = key => LANES.find(L => L.key === key);
function showBar(meaningKey, id, scroll = true) {
  const r = current[meaningKey]; const b = r && r.bars && r.bars.find(x => x.id === id);
  document.querySelectorAll('.bar.sel').forEach(n => n.classList.remove('sel'));
  if (!b) { selected = null; return; }
  selected = { meaning: meaningKey, id };
  document.querySelector(`.bar[data-bar="${id}"]`)?.classList.add('sel');
  const L = laneOf(meaningKey), d = $('detail');
  d.textContent = '';
  d.append(el('h2', null, `${L.top} ${L.sub}${b.tag ? ' · ' + b.tag : ''}`));
  const p = el('p'); p.append(el('b', null, `${b.show} ${b.u}`), `  meaning: ${M.MEANING[meaningKey]}`); d.append(p);
  d.append(el('p', 'k', b.call));
  for (const t of b.text) if (t) d.append(el('p', null, t));
  if (scroll && innerWidth < 760) d.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
function showLaneNote(L) {
  const r = current[L.key], d = $('detail');
  if (r.bars) return;
  document.querySelectorAll('.bar.sel').forEach(n => n.classList.remove('sel'));
  selected = null;
  d.textContent = '';
  d.append(el('h2', null, `${L.top} ${L.sub} · ${r.refused ? 'REFUSED' : 'EMPTY'}`));
  d.append(el('p', null, r.refused ? `${r.call} threw: ${r.refused}` : r.empty));
  if (innerWidth < 760) d.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}

/* ── drag a bar onto another lane: the module's summing path is asked ────── */
const ghost = $('ghost'), pop = $('refusal');
let drag = null;
function attachDrag(bar) {
  bar.addEventListener('pointerdown', e => {
    if (e.button > 0) return;
    e.preventDefault();
    try { bar.setPointerCapture(e.pointerId); } catch { /* synthetic pointers have no capture */ }
    drag = { bar, x0: e.clientX, y0: e.clientY, moved: false };
  });
  bar.addEventListener('pointermove', e => {
    if (!drag || drag.bar !== bar) return;
    if (!drag.moved && Math.hypot(e.clientX - drag.x0, e.clientY - drag.y0) < 8) return;
    if (!drag.moved) {
      drag.moved = true; bar.classList.add('dragging');
      ghost.style.setProperty('--c', getComputedStyle(bar.closest('.lane')).getPropertyValue('--c'));
      ghost.style.height = Math.min(120, Math.max(24, bar.offsetHeight)) + 'px';
      ghost.hidden = false; hidePop();
    }
    ghost.style.left = e.clientX + 'px'; ghost.style.top = e.clientY + 'px';
    const lane = laneAt(e.clientX, e.clientY);
    document.querySelectorAll('.lane.over').forEach(n => { if (n !== lane) n.classList.remove('over'); });
    if (lane && lane.dataset.meaning !== bar.dataset.meaning) lane.classList.add('over');
  });
  const end = e => {
    if (!drag || drag.bar !== bar) return;
    const d = drag; drag = null;
    bar.classList.remove('dragging'); ghost.hidden = true;
    document.querySelectorAll('.lane.over').forEach(n => n.classList.remove('over'));
    if (e.type === 'pointercancel') return;
    if (!d.moved) { showBar(bar.dataset.meaning, bar.dataset.bar); return; }
    const lane = laneAt(e.clientX, e.clientY);
    if (!lane || lane.dataset.meaning === bar.dataset.meaning) return;
    tryAdd(bar.dataset.meaning, bar.dataset.bar, lane.dataset.meaning, e.clientX, e.clientY);
  };
  bar.addEventListener('pointerup', end);
  bar.addEventListener('pointercancel', end);
  bar.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); showBar(bar.dataset.meaning, bar.dataset.bar); } });
}
function laneAt(x, y) {
  for (const n of document.elementsFromPoint(x, y)) { const l = n.closest && n.closest('.lane'); if (l) return l; }
  return null;
}

/* The module's only summing path is combinedPeak({ fleets }). The page hands it
   the two things being dropped together, exactly as the module produced them,
   and shows whatever comes back. */
function tryAdd(fromKey, fromId, toKey, x, y) {
  const a = current[fromKey].bars.find(b => b.id === fromId);
  const target = current[toKey];
  const b = target.bars ? target.bars[0] : null;
  const A = laneOf(fromKey), B = laneOf(toKey);
  pop.textContent = '';
  pop.append(el('div', 'h', `ADD ${A.top} ${A.sub} + ${B.top} ${B.sub}?`));
  let outcome;
  if (!b) {
    outcome = 'nothing';
    pop.append(el('div', 'said', target.refused ? `Nothing to add to: ${target.call} threw: ${target.refused}` : target.empty));
  } else {
    const res = attempt(() => M.combinedPeak({ fleets: [a.obj, b.obj] }));
    if (res.err) {
      outcome = 'refused';
      pop.append(el('div', 'said', M.NEVER_ADDED));
      pop.append(el('div', 'thrown', `combinedPeak({ fleets: [${M.MEANING[fromKey]}, ${M.MEANING[toKey]}] }) threw: ${res.err}`));
    } else {
      outcome = 'summed';
      pop.append(el('div', 'said', `combinedPeak returned ${fmt(res.ok.value / 1e6, 2)} GW, meaning ${res.ok.meaning}. It assumes ${res.ok.assumes}`));
    }
  }
  const close = el('button', 'close', 'close'); close.type = 'button'; close.onclick = hidePop;
  pop.append(close);
  Object.assign(pop.dataset, { from: fromKey, to: toKey, outcome, x: Math.round(x), y: Math.round(y) });
  pop.hidden = false;
  const w = pop.offsetWidth, h = pop.offsetHeight;
  pop.style.left = Math.max(12, Math.min(innerWidth - w - 12, x - w / 2)) + 'px';
  pop.style.top = Math.max(12, Math.min(innerHeight - h - 12, y + 14)) + 'px';
}
function hidePop() { pop.hidden = true; }
document.addEventListener('pointerdown', e => { if (!pop.hidden && !pop.contains(e.target) && !e.target.closest('.bar')) hidePop(); });

/* ── the worked example, computed by the module from its scenario inputs ──── */
const EXAMPLE = { heat: 12.25, scop: 3.5, units: 28000000, div: 1.7 };
function workedExample() {
  const box = $('exampleOut'); box.textContent = ''; box.classList.remove('dim');
  const q = M.MEANING;
  const r = attempt(() => {
    const thermal = M.quantity(EXAMPLE.heat, 'kW', q.THERMAL_OUTPUT);
    const elec = M.electricalInputFromHeat({ thermal, scop: EXAMPLE.scop });
    const fleet = M.fleetDemand({ units: EXAMPLE.units, perUnitNameplate: elec,
      perUnitAfterDiversity: M.quantity(EXAMPLE.div, 'kW', q.AFTER_DIVERSITY) });
    return { thermal, elec, fleet };
  });
  const dim = t => el('p', 'dim', t);
  box.append(dim(`scenario input: ${fmt(EXAMPLE.heat)} kW thermal per home · SCOP ${fmt(EXAMPLE.scop)} · ${fmt(EXAMPLE.units)} heat pumps · ${fmt(EXAMPLE.div)} kW after diversity per home`));
  if (r.err) { box.append(el('p', null, `The module refused the worked example: ${r.err}`)); return; }
  const { thermal, elec, fleet } = r.ok;
  box.append(el('p', null, `${fmt(thermal.value)} ${thermal.unit} thermal = ${fmt(elec.value, 6)} ${elec.unit} electrical at SCOP ${fmt(EXAMPLE.scop)}.`));
  box.append(el('p', null, `${fmt(fleet.units)} heat pumps: ${fmt(fleet.simultaneous.value / 1e6, 3)} GW flat out vs ${fmt(fleet.diversified.value / 1e6, 3)} GW after diversity.`));
  box.append(dim(`flat out, as the module labels it: ${fleet.simultaneous.label}.`));
  box.append(dim(`module basis: ${elec.basis}`));
  box.append(dim(`module basis: ${fleet.basis}`));
  box.append(dim('Computed on this device when the page loaded; no result above is typed into the page. The page divides kW by 1,000,000 to print GW.'));
}
$('loadExample').addEventListener('click', () => {
  for (const [k, v] of Object.entries(EXAMPLE)) { S[k].inp.value = v; S[k].show(); }
  draw();
});

workedExample();
draw();
window.__seven = { ready: true, current: () => current };

Iterations — 26 Apps Layers Substrate

A JavaScript module in Galaxies Wafers that draws lines meta and families, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/26-apps-layers-substrate/.

Set aside from the main view: 95% of its lines are the same as iterations/31-code-card-everywhere/app.mjs (galaxies-wafers), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Iterations — 31 Code Card Everywhere; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9455 to galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/31-code-card-everywhere/app.mjs:1-583 f469a8112fc2ad6e45e0695624b1e21f9647bd0a
  • sha256 cb055b5dea0ec719fefd66b2442971a2f0294c648e817544ff0e8032fc08e8ca
  • target sha256 26624832f9452671a5e7da874b43588975adc4ac8c134efe1f130cff94c815fc
  • group of 7 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

rendergalaxies-wafers / iterations/26-apps-layers-substrate/app.mjs · lines 1–353 of 575 · Entry point · pattern nearestKeyAt (shared by 16 files)

What it does
It draws lines meta and families. Defines 31 functions or classes, including $, snapshot, indexOfKey, bin, tier1. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: JSON file all-lines.meta.json; JSON file families.json. Out: WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: Iterations — 26 Apps Layers Substrate Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/26-apps-layers-substrate/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/26-apps-layers-substrate/.
What it achieves
It indexes key (`indexOfKey`), builds gl (`buildGL`) and draws marks (`drawMarks`). This file is iteration 21's `app.mjs` (the dark substrate) with one change: `writeURL` keeps every other parameter. It responds to pointerdown, pointermove and pointerup events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/26-apps-layers-substrate/.
Application
galaxies-wafers · iterations/26-apps-layers-substrate · JavaScript module
Uses
Galaxies Wafers — Lib (import)
Used by
loaded by Iterations — 26 Apps Layers Substrate Page (script src)
Produces
$, snapshot, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL, put, resize
Defines here
$, snapshot, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL, put, resize, ensureOverlay, drawMarks, toScreen, render, draw, home, flyTo, nearestKeyAt, famsOf, paintPanel
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/26-apps-layers-substrate/app.mjs:1-353 · blob 11e8ee718335b7cecf3de33ce78be9f00164ffa8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: duplicate_candidate
/* Apps, Layers, Substrate (iteration 26). This file is iteration 21's app.mjs
 * (the dark substrate) with one change: writeURL keeps every other parameter.
 *
 * Dark Pixels: the Line Wafer with its ground switched off.
 *
 * This is the root wafer's app.mjs, copied because the root reads its data by
 * relative path. Three things differ and nothing else: the import path of
 * lib.mjs, the fragment shader (every line point is drawn near-black, faint
 * enough that the spiral still reads), and drawMarks() only resizes its canvas
 * when the size changes. The layers that wake points are in layers-panel.mjs.
 *
 * What follows is the root's own description, unchanged.
 *
 * The Line Wafer.
 *
 * WHAT THIS IS. Every line of code in the estate that has been given a
 * permanent number is one point on one surface. There are 250,174 of them and
 * they are numbered 1 to 342,795: the number is the line's permanent key, it
 * never changes and it is never reused, and numbers missing from the sequence
 * were never issued. Those gaps are drawn as gaps.
 *
 * WHY THE NUMBER IS THE ADDRESS. A point's position here is a pure function of
 * its own permanent key and of nothing else:
 *
 *     r = SPACING * sqrt(key)        theta = key * GOLDEN
 *
 * so line 8,285 is in the same place on every device, in every session, for
 * ever, and the surface can be reconstituted from the numbers alone. Nothing
 * about a position is stored, fetched or remembered. That is what makes the
 * surface unbounded rather than large: the estate can issue line 400,000
 * tomorrow and the wafer already has somewhere to put it.
 *
 * THE BEAM. The camera is a beam. It steers over the wafer and focuses, and
 * where it focuses the structure resolves — one line, its length, whether any
 * function family carries it, and which. Focus is the only instrument; there
 * are no levels and nothing is pre-rendered.
 *
 * THE RULE THIS PAGE EXISTS TO MEET. It must be able to connect any two
 * uniquely numbered lines in the estate. Type two numbers and it answers: the
 * families that carry both, or a refusal naming which of the two no family
 * carries.
 *
 * TWO RELATIONS, AND THE FIRST VERSION OF THIS PAGE CONFUSED THEM.
 * FANOUT is one number appearing in several families: the same text sitting in
 * several places, which is duplication. CO-MEMBERSHIP is two different numbers
 * appearing in one family: two lines of the same function, which is
 * neighbourhood and is NOT the same text. Connecting uses co-membership, so a
 * line carried by exactly one family is perfectly connectable — to another line
 * of that family. The page originally claimed the opposite and a reviewer was
 * right to reject it. See lib.mjs.
 *
 * WHAT IS NOT CLAIMED. Neither relation is a dependency and neither means one
 * line calls the other. Triviality is visible rather than hidden: a line's
 * fanout is printed, so line 2, an empty line in 2,281 families, looks exactly
 * as meaningless as it is.
 */

import { place, placeAll, parseKey, indexOfKey as findKey, ownersOf, fanoutCount,
         connectAnswer, esc, fmt, SPACING } from '../../lib.mjs';

const DATA = 'https://globalgrid2050.com/testcode/202609142202/data/';

const $ = id => document.getElementById(id);
let stage = $("stage");

const U = {
  fanout: null,        /* lines carried by MORE THAN ONE family; counted, never typed */
  keys: null,        /* Uint32Array, sorted: every permanent line number issued */
  lens: null,        /* Uint16Array: characters in that line */
  inFam: null,       /* Uint8Array: 1 when at least one family carries it */
  pos: null,         /* Float32Array 2N: the pure function of the key */
  n: 0,
  families: null,    /* tier 2 */
  famLines: null,
  ownerOf: null,     /* Map<key, number[]> family indexes, built once on demand */
  meta: null
};

const view = { x: 0, y: 0, zoom: 1, w: 0, h: 0, dpr: 1, focus: -1, link: null };
/* The one read-only hook for layers: the live camera, and listeners called after every frame. */
/* Listeners get a frozen scalar snapshot, never the live object: a listener that
   mutates what it received cannot move the wafer's camera. (Codex review.) */
const snapshot = () => Object.freeze({ x: view.x, y: view.y, zoom: view.zoom, w: view.w, h: view.h, dpr: view.dpr });
window.__wafer = Object.freeze({ get view() { return snapshot(); }, onDraw: new Set() });

/* ── the surface ─────────────────────────────────────────────────────────── */

const placeOne = place;                       /* where a number sits, issued or not */
const indexOfKey = key => findKey(U.keys, key);

/* ── loading ─────────────────────────────────────────────────────────────── */

async function bin(name, Kind) {
  const r = await fetch(DATA + name, { cache: 'default' });
  if (!r.ok) throw new Error(DATA + name + ' returned HTTP ' + r.status);
  return new Kind(await r.arrayBuffer());
}

async function tier1() {
  const [meta, keys, lens, inFam] = await Promise.all([
    fetch(DATA + 'all-lines.meta.json').then(r => r.json()),
    bin('all-lines.bin', Uint32Array),
    bin('all-lines.len.bin', Uint16Array),
    bin('all-lines.family.bin', Uint8Array)
  ]);
  U.meta = meta; U.keys = keys; U.lens = lens; U.inFam = inFam; U.n = keys.length;
  U.pos = placeAll(keys);

  let carried = 0;
  for (let i = 0; i < inFam.length; i++) carried += inFam[i];
  $('count').textContent =
    `${fmt(U.n)} numbered lines · 1 to ${fmt(meta.max)} · ${fmt(carried)} carried by a family`;
  $('prov').textContent =
    `numbered database built ${meta.built_utc.slice(0, 16).replace('T', ' ')} UTC · pack ${meta.source.sha256.slice(0, 12)}`;
}

async function tier2() {
  const [families, famLines] = await Promise.all([
    fetch(DATA + 'families.json').then(r => r.json()),
    bin('lines.bin', Uint32Array)
  ]);
  U.families = families; U.famLines = famLines;
  const owner = ownersOf(families, famLines);
  U.ownerOf = owner;
  U.fanout = fanoutCount(owner);
  if (view.focus >= 0) paintPanel(view.focus);
  if (view.link) connect(view.link[0], view.link[1]);
}

/* ── drawing ─────────────────────────────────────────────────────────────── */

const VS = `#version 300 es
precision highp float;
in vec2 a_pos; in float a_len; in float a_fam;
uniform vec2 u_res; uniform vec2 u_cam; uniform float u_zoom; uniform float u_dpr;
uniform float u_focusKey;
out float v_fam; out float v_len; out float v_focus;
void main(){
  vec2 p = (a_pos - u_cam) * u_zoom;
  gl_Position = vec4(p / (u_res * 0.5), 0.0, 1.0);
  float base = 1.0 + min(a_len, 120.0) * 0.012;
  gl_PointSize = clamp(base * sqrt(u_zoom) * u_dpr, 1.0, 26.0 * u_dpr);
  v_fam = a_fam; v_len = a_len; v_focus = 0.0;
}`;

const FS = `#version 300 es
precision highp float;
in float v_fam; in float v_len; in float v_focus;
out vec4 o;
void main(){
  vec2 d = gl_PointCoord - 0.5;
  float r = length(d);
  if (r > 0.5) discard;
  float edge = smoothstep(0.5, 0.42, r);
  /* dark pixels: the ground is dead but still faintly there */
  vec3 carried = vec3(0.16, 0.18, 0.23);
  vec3 alone   = vec3(0.09, 0.10, 0.13);
  vec3 c = mix(alone, carried, v_fam);
  o = vec4(c, edge * (0.45 + 0.30 * v_fam));
}`;

let gl = null, prog = null, loc = {}, vao = null, ctx2d = null;

function compile(g, type, src) {
  const s = g.createShader(type); g.shaderSource(s, src); g.compileShader(s);
  if (!g.getShaderParameter(s, g.COMPILE_STATUS)) throw new Error(g.getShaderInfoLog(s));
  return s;
}

/* If anything after acquiring the context fails — a shader that will not compile
   on some driver, a program that will not link — the page must fall back, not
   half-run. A canvas cannot hand out a 2D context once it has given out a WebGL
   one, so the canvas itself is replaced. The first version left `gl` non-null on
   failure and then asked the same canvas for a 2D context, which returns null:
   the fallback it advertised did not exist. */
function initGL() {
  gl = stage.getContext('webgl2', { antialias: true, alpha: false });
  if (!gl) { gl = null; return fallback2d(); }
  try { return buildGL(); }
  catch (e) { gl = null; console.warn('WebGL setup failed, falling back:', e.message); return fallback2d(); }
}

function fallback2d() {
  const fresh = stage.cloneNode(false);
  stage.replaceWith(fresh);
  stage = fresh;
  ctx2d = stage.getContext('2d');
  $('hint').textContent = ctx2d
    ? 'drawn without the GPU: at low zoom one line in seven is plotted'
    : 'this browser gave neither a GPU nor a 2D canvas; nothing can be drawn';
  return false;
}

function buildGL() {
  prog = gl.createProgram();
  gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, VS));
  gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, FS));
  gl.linkProgram(prog);
  if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
  gl.useProgram(prog);
  for (const u of ['u_res', 'u_cam', 'u_zoom', 'u_dpr', 'u_focusKey']) loc[u] = gl.getUniformLocation(prog, u);

  vao = gl.createVertexArray(); gl.bindVertexArray(vao);
  const put = (data, name, size, Kind, norm) => {
    const b = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, b);
    gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
    const l = gl.getAttribLocation(prog, name);
    gl.enableVertexAttribArray(l);
    gl.vertexAttribPointer(l, size, Kind, !!norm, 0, 0);
  };
  put(U.pos, 'a_pos', 2, gl.FLOAT, false);
  put(U.lens, 'a_len', 1, gl.UNSIGNED_SHORT, false);
  put(U.inFam, 'a_fam', 1, gl.UNSIGNED_BYTE, false);
  gl.enable(gl.BLEND);
  gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  return true;
}

function resize() {
  view.dpr = Math.min(window.devicePixelRatio || 1, 2);
  view.w = stage.clientWidth; view.h = stage.clientHeight;
  stage.width = Math.round(view.w * view.dpr);
  stage.height = Math.round(view.h * view.dpr);
  if (gl) gl.viewport(0, 0, stage.width, stage.height);
}

let overlay = null;
function ensureOverlay() {
  if (overlay) return overlay;
  overlay = document.createElement('canvas');
  overlay.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:1';
  document.body.appendChild(overlay);
  return overlay;
}

function drawMarks() {
  const o = ensureOverlay();
  if (o.width !== stage.width || o.height !== stage.height) { o.width = stage.width; o.height = stage.height; }
  const c = o.getContext('2d');
  c.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);
  c.clearRect(0, 0, view.w, view.h);
  const toScreen = ([x, y]) => [
    (x - view.x) * view.zoom + view.w / 2,
    view.h / 2 - ((y - view.y) * view.zoom)
  ];
  if (view.link) {
    const [ka, kb] = view.link;
    const A = toScreen(placeOne(ka)), B = toScreen(placeOne(kb));
    c.strokeStyle = '#5ec8f2'; c.lineWidth = 1.2; c.setLineDash([5, 4]);
    c.beginPath(); c.moveTo(A[0], A[1]);
    c.quadraticCurveTo((A[0] + B[0]) / 2, (A[1] + B[1]) / 2 - 40, B[0], B[1]);
    c.stroke(); c.setLineDash([]);
    for (const P of [A, B]) {
      c.strokeStyle = '#5ec8f2'; c.beginPath(); c.arc(P[0], P[1], 9, 0, 6.2832); c.stroke();
    }
  }
  if (view.focus >= 0) {
    const P = toScreen(placeOne(view.focus));
    c.strokeStyle = '#ffd54a'; c.lineWidth = 1.4;
    c.beginPath(); c.arc(P[0], P[1], 11, 0, 6.2832); c.stroke();
    c.beginPath(); c.moveTo(P[0] - 18, P[1]); c.lineTo(P[0] - 13, P[1]);
    c.moveTo(P[0] + 13, P[1]); c.lineTo(P[0] + 18, P[1]);
    c.moveTo(P[0], P[1] - 18); c.lineTo(P[0], P[1] - 13);
    c.moveTo(P[0], P[1] + 13); c.lineTo(P[0], P[1] + 18);
    c.stroke();
  }
}

function render() {
  if (gl) {
    gl.clearColor(0.012, 0.014, 0.020, 1); gl.clear(gl.COLOR_BUFFER_BIT);
    gl.useProgram(prog); gl.bindVertexArray(vao);
    gl.uniform2f(loc.u_res, stage.width, stage.height);
    gl.uniform2f(loc.u_cam, view.x, view.y);
    gl.uniform1f(loc.u_zoom, view.zoom * view.dpr);
    gl.uniform1f(loc.u_dpr, view.dpr);
    gl.uniform1f(loc.u_focusKey, view.focus);
    gl.drawArrays(gl.POINTS, 0, U.n);
  } else if (ctx2d) {
    const c = ctx2d;
    c.setTransform(1, 0, 0, 1, 0, 0);
    c.fillStyle = '#030406'; c.fillRect(0, 0, stage.width, stage.height);
    c.fillStyle = '#1e222c';
    const step = view.zoom < 0.5 ? 7 : 1;
    for (let i = 0; i < U.n; i += step) {
      const x = (U.pos[i * 2] - view.x) * view.zoom * view.dpr + stage.width / 2;
      const y = stage.height / 2 - (U.pos[i * 2 + 1] - view.y) * view.zoom * view.dpr;
      if (x < 0 || y < 0 || x > stage.width || y > stage.height) continue;
      c.fillRect(x, y, view.dpr, view.dpr);
    }
  }
  drawMarks();
  { const snap = snapshot(); for (const f of window.__wafer.onDraw) { try { f(snap); } catch (e) { console.warn('onDraw listener failed:', e); } } }
}

let pending = false;
function draw() { if (!pending) { pending = true; requestAnimationFrame(() => { pending = false; render(); }); } }

/* ── the beam: steering and focusing ─────────────────────────────────────── */

function home() {
  const maxR = SPACING * Math.sqrt(U.meta.max);
  view.x = 0; view.y = 0;
  view.zoom = Math.min(view.w, view.h) / (maxR * 2.15);
  draw();
}

function flyTo(key, zoom) {
  const [x, y] = placeOne(key);
  const z0 = view.zoom, x0 = view.x, y0 = view.y;
  const z1 = zoom ?? Math.max(view.zoom, 9);
  const t0 = performance.now(), ms = 620;
  (function step(t) {
    const u = Math.min(1, (t - t0) / ms);
    const e = u < .5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2;
    view.x = x0 + (x - x0) * e; view.y = y0 + (y - y0) * e;
    view.zoom = Math.exp(Math.log(z0) + (Math.log(z1) - Math.log(z0)) * e);
    render();
    if (u < 1) requestAnimationFrame(step);
  })(t0);
}

function nearestKeyAt(cx, cy) {
  const wx = (cx - view.w / 2) / view.zoom + view.x;
  const wy = (view.h / 2 - cy) / view.zoom + view.y;
  const reach = 22 / view.zoom;
  let best = -1, bestD = reach * reach;
  for (let i = 0; i < U.n; i++) {
    const dx = U.pos[i * 2] - wx, dy = U.pos[i * 2 + 1] - wy;
    const d = dx * dx + dy * dy;
    if (d < bestD) { bestD = d; best = i; }
  }
  return best < 0 ? -1 : U.keys[best];
}

/* ── the panel: what the beam found ──────────────────────────────────────── */

function famsOf(key) {
  if (!U.ownerOf) return null;
  return U.ownerOf.get(key) || [];
}

function paintPanel(key) {
  const i = indexOfKey(key);
  const p = $('panelbody');
  if (i < 0) {
    p.innerHTML =
      `<h2>Line <span class="n">${fmt(key)}</span></h2>
       <p class="refuse">This number was never issued. The numbering runs 1 to ${fmt(U.meta.max)} and
       ${fmt(U.meta.max - U.n)} of those numbers were skipped, so a gap is a real answer rather than a
       missing record. The surface still has a place for it, and the beam is pointing at it.</p>`;
    $('panel').hidden = false; return;