In this section
- Pilot Dark geodesy · cosmic / tools/explore/theme/pilot-dark.js lines 411–487
- Pilot Darkfx render · cosmic / tools/explore/theme/pilot-darkfx.css lines 1–4
- Pilot Darkfx render · cosmic / tools/explore/theme/pilot-darkfx.js lines 1–476
Pilot Dark
A JavaScript file in the theme folder of Cosmic that maps the Renewable Energy Planning Database (REPD) register, substations and 66kV, using SHA-256.
geodesycosmic / tools/explore/theme/pilot-dark.js · lines 411–487 of 487 (continued from section 1143) · Entry point · pattern refreshNear (shared by 2 files)
- What it does
- It maps the REPD register, substations and 66kV. Defines 39 functions or classes, including bandOf, colOf, wOf, grid, finite. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: the REPD register, substations, 66kV, 11kV.
- Inputs & outputs
- In: browser storage (getItem). Out: interactive map; canvas drawing. Voltage levels named: 66kV, 11kV.
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- It wires grid (`wireGrid`), refreshes halos (`refreshHalos`) and refreshes near (`refreshNear`). Pilot module "dark" (DARK GRID 1 / UMBRA-63): DARK GRID view for Drone View. Its code works with 66 kV and 11 kV. It responds to click and keydown events.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · script
- VEDIC
- HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
- Uses
- none found
- Used by
- loaded by Pilot (script src)
- Produces
- bandOf, colOf, wOf, grid, finite, reduced, effR, focusCentre, dxy, fade, ingest, pack
- Defines here
- renderStatus, onClick, writeHash, set, setRadius, setGround
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-dark.js:411-487 · blob a6dd228dee452314d90281fcaa6445490a7cd07a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unknown
if (S.on) {
h += RADII.map(function (k) {
return '<button type="button" class="p-dark-chip" data-p-dark-km="' + k + '" aria-pressed="' + (S.km === k) + '" aria-label="Focus radius ' + k + ' km">' + k + ' km</button>';
}).join('') +
'<button type="button" class="p-dark-chip" data-p-dark="wire" aria-pressed="' + (S.ground === 'wire') + '" aria-label="Wireframe ground instead of darkened imagery">WIRE</button>';
if (S.fx) h += '<button type="button" class="p-dark-chip" data-p-dark="fx" aria-pressed="' + (S.fx.on !== false) + '" aria-label="Effects">FX</button>';
}
h += '</div>';
var el = P.hud('top:dark', h);
if (el && !el.__pDark) { el.__pDark = 1; el.addEventListener('click', onClick); }
renderStatus();
}
function renderStatus() {
if (!S.on) { P.hud('status:dark', null); return; }
var n = S.near, auto = S.R > S.km * 1000 + 1;
var focus = 'Focus ' + S.km + ' km' + (auto ? ' (auto ' + fmtD(S.R) + ')' : '');
var near = '—';
if (n) {
var c = P.camLL(), br = P.bearing ? P.bearing(c.lat, c.lon, n.lat, n.lon) : 0;
near = esc(n.name) + (n.kv && n.kind !== 'line' ? ' · ' + esc(n.kv) + ' kV' : '') + ' · ' + fmtD(n.d) + ' ' + HDG[Math.round(((br % 360) + 360) % 360 / 45) % 8];
}
P.hud('status:dark', '<span class="p-dark-status"><b>DARK GRID</b> ' + esc(focus) + ' · <span class="p-dark-near">Nearest grid: ' + near + '</span> <span class="p-dark-cav">straight line</span></span>');
}
function onClick(e) {
var b = e.target && e.target.closest ? e.target.closest('button') : null; if (!b) return;
var a = b.getAttribute('data-p-dark'), km = b.getAttribute('data-p-dark-km');
if (a === 'toggle') set(!S.on);
else if (km) setRadius(+km);
else if (a === 'wire') setGround(S.ground === 'wire' ? 'dim' : 'wire');
else if (a === 'fx') P.emit('darkfx:set', { on: !(S.fx && S.fx.on !== false) });
}
// ---- S11 public behaviour (through events + hash; no globals)
function writeHash() {
if (!P.hash) return;
P.hash('dark', S.on ? String(S.km) : null);
P.hash('darkg', S.on && S.ground === 'wire' ? 'wire' : null);
}
function set(on) {
on = !!on; if (on === S.on) return;
S.on = on;
if (on) { LINE_KINDS.forEach(function (k) { if (ready[k]) ingest(k); }); if (P.camLL) { var c = P.camLL(); S.R = effR(c); S.c = focusCentre(c, S.R); } S.haloT = S.nearT = S.focusT = 0; }
LAYERS.forEach(function (l) { l.visible = on; });
if (P.setLayerVisible) P.setLayerVisible('dark-ground', on); // core refreshes credits
D.documentElement.classList.toggle('p-dark-on', on);
if (!on) { S.near = null; lastFocus = null; }
writeHash(); render(); emitState(true);
}
function setRadius(km) { if (RADII.indexOf(km) < 0) return; S.km = km; writeHash(); render(); emitState(true); }
function setGround(gm) { S.ground = gm === 'wire' ? 'wire' : 'dim'; wire.key = ''; writeHash(); render(); emitState(true); }
P.on('dark:set', function (d) {
if (!d) return;
if (d.km != null) setRadius(+d.km);
if (d.ground) setGround(d.ground);
if (d.on != null) set(!!d.on);
});
D.addEventListener('keydown', function (e) {
if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return;
var t = e.target; if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
if (e.key === 'k' || e.key === 'K') { set(!S.on); }
});
// test hook (QA): numbers only, no internals to mutate
P.on('dark:debug', function (q) {
if (q && typeof q.reply === 'function') q.reply({ on: S.on, km: S.km, R: S.R, ground: S.ground, c: S.c, near: S.near,
lines: Object.keys(LN).filter(function (k) { return LN[k] && LN[k].n; }).map(function (k) { return [k, LN[k].n]; }),
halos: { subs: S.halos.subs.length, ukpn: S.halos.ukpn.length, repd: S.halos.repd.length },
ms: { ground: +S.msGround.toFixed(2), grid: +S.msGrid.toFixed(2), mask: +S.msMask.toFixed(2) } });
});
// ---- S12 start: hash wins (#dark=<km>, &darkg=wire)
P.ready(function () {
var h = P.hash ? P.hash('dark') : null, gm = P.hash ? P.hash('darkg') : null;
if (gm === 'wire') S.ground = 'wire';
if (h != null && h !== '') { var km = +h; if (RADII.indexOf(km) >= 0) S.km = km; set(true); }
else render();
});
})();Pilot Darkfx
A style sheet in the theme folder of Cosmic.
rendercosmic / tools/explore/theme/pilot-darkfx.css · lines 1–4 of 4 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- Pilot module "darkfx" (DARK GRID 2, NOCTILUCENT-27): caption for the dark Pilot effects.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · style sheet
- Uses
- none found
- Used by
- loaded by Pilot (stylesheet)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-darkfx.css:1-4 · blob fbfd2a2236909c80fd83ab5650c04e196678478f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Pilot module "darkfx" (DARK GRID 2, NOCTILUCENT-27): caption for the dark Pilot effects. Prefix p-darkfx-. */
.p-darkfx-cap { display: inline-block; max-width: 100%; color: #b9c8e6; font-size: 11px; line-height: 1.35; letter-spacing: .01em; text-shadow: 0 0 6px rgba(80,140,255,.35); }
.p-darkfx-cap b { color: #dff6ff; font-weight: 600; }
@media (prefers-reduced-motion: reduce) { .p-darkfx-cap { text-shadow: none; } }Pilot Darkfx
A JavaScript file in the theme folder of Cosmic that maps substations. It sets focus (`setFocus`), adds line path (`addLinePath`) and starts pulse (`startPulse`).
rendercosmic / tools/explore/theme/pilot-darkfx.js · lines 1–476 of 476 · Entry point · pattern startPulse (shared by 2 files)
- What it does
- It maps substations. Defines 39 functions or classes, including active, kvCls, rgba, mApprox, hash. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: substations.
- Inputs & outputs
- In: browser storage (getItem). Out: browser storage (setItem); canvas drawing.
- Downstream impact
- Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
- What it achieves
- Pilot module "darkfx" (DARK GRID 2, NOCTILUCENT-27): the effects layer of the dark Pilot mode.
- Why it matters
- Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
- Application
- cosmic · tools/explore/theme · script
- Uses
- none found
- Used by
- loaded by Pilot (script src)
- Produces
- active, kvCls, rgba, mApprox, hash, canvas, setFocus, sprite, flashSprite, dotSprite, stars, bandCanvas
- Defines here
- active, kvCls, rgba, mApprox, hash, canvas, setFocus, sprite, flashSprite, dotSprite, stars, bandCanvas, bloomBuf, project, segVisible, addLinePath, along, part, poseKey, flush, t0, spent, finishFrame, horizonY, nodeR, endOf, adjacency, startPulse, drawPulse, flashesNow
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-darkfx.js:1-476 · blob c90bbf33ce02d3e3a59a2cd94e4a65108bcef788 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unknown
/* Pilot module "darkfx" (DARK GRID 2, NOCTILUCENT-27): the effects layer of the dark Pilot mode.
pilot-dark.js (DARK GRID 1) owns the 'dark' mode, the darkened base and the radius focus; this file only
decorates what that module puts in focus:
- glowing lines (additive blending, soft bloom from a quarter-resolution offscreen canvas, Canvas 2D only)
- substations as light nodes sized by voltage class (pre-rendered glow sprites)
- a gentle "energy flow" animation: short glowing dashes (pre-rendered dot sprites, far cheaper than
setLineDash on a phone) drifting along lines. DECORATIVE ONLY, not measured power flow; their direction is
the mapped drawing order of the line, not a direction of power; speed and spacing are constants
- a pulse when a substation is tapped: lines whose mapped ends meet, lit hop by hop. This is a picture of
NETWORK ADJACENCY ONLY (mapped geometry), never a power flow, rating or fault path
- lightning (pilot-lightning, when on): brief white strokes that stop well above the ground, captioned
"optical flash, not a ground strike" and "risk screening"
- a night-sky gradient and horizon glow
API agreed with UMBRA-63 (DARK GRID 1) 21:43Z: dark is an overlay over any ground mode, not a mode.
Honesty: no implied power flows, ratings or fault paths. Under prefers-reduced-motion nothing animates.
Budget: every draw is timed; quality steps down if the effects cost more than ~3 ms a frame (target < 4 ms
on 390x844). Built against /tmp/vk/pilot200/CONTRACT.md v1; talks to other modules only through events:
in : 'dark:state' {on, lat, lon, radiusM, glowByDark}; 'dark:focus' {lat, lon, radiusM, lines:[{id, kv, ll}], subs:[{id, name, kv, lat, lon}]}
core 'pick' (item.id 'grid-sub-*') and 'ukpn:select' {id, lat, lon} start the pulse;
'lightning:flashes' {on, lat:[], lon:[], t:[], id:[]}; 'darkfx:set' {on}
out: 'darkfx:status' {on, active, reduced, ms, budgetMs, quality}; 'dark:query' {reply} once at start
No globals besides window.PILOT (PILOT.darkfx is this module's namespaced handle). */
(function () {
'use strict';
if (!window.PILOT) return;
var P = window.PILOT, D = document, W = window;
var TEXT = {
FLOW: 'Moving dashes are decorative, not measured power flow',
FLOW_DIR: 'their direction is the mapped drawing order, not a power direction',
PULSE: 'Pulse = network adjacency only (mapped line ends that meet near this substation); not a power flow, rating or fault path',
FLASH: 'optical flash, not a ground strike',
SCREEN: 'risk screening',
FLASH_LONG: 'White strokes: optical flashes seen from orbit, drawn stopped above the ground (optical flash, not a ground strike). Lightning here is risk screening only.',
OFF_REDUCED: 'Reduced motion: effects are still, nothing animates'
};
var BUDGET_MS = 4, STEP_DOWN_MS = 3.0, STEP_UP_MS = 1.4;
var COL = { 400: [64, 128, 255], 275: [255, 77, 77], 132: [51, 230, 102], 66: [255, 171, 46], 33: [217, 217, 217] };
var CLASSES = [400, 275, 132, 66, 33];
var ADJ_M = 600, MAX_HOPS = 4, MAX_PULSE_LINES = 48, HOP_S = 0.7, HOLD_S = 1.4, FADE_S = 0.8;
var VERT_CAP = [1500, 3000, 6000]; // vertices projected per frame by quality
var SKY_BAND = 170, GLOW_K = 2.2, FLOW_SPACING_M = 160, FLOW_SPEED_M = 40, FLOW_MAX_DOTS = 180; // decorative constants, nothing measured
var FLASH_PERIOD = 7000, FLASH_MS = 240, FLASH_MAX = 24, BOLT_TOP = 2600, BOLT_STOP = 380; // metres above ground
var rad = Math.PI / 180;
// ---- state
var REDUCED = !!P.reduced;
var st = {
dark: false, glowByDark: false, userOn: true, quality: 1, fps: 60, fpsN: 0, ms: 0, frameMs: 0, lastFrame: -1, slow: 0, fast: 0,
focus: null, pulse: null, flashes: null, flashSrc: 'none', cand: [], candT: 0, drawnBolts: 0, minBoltAgl: null,
samples: [], bolts: 0, parts: {}, bloomKey: '', focusSerial: 0, stars: null, band: null, bloom: null, sprites: {}, proj: null, caption: ''
};
try { if (localStorage.getItem('p-darkfx-on') === '0') st.userOn = false; } catch (e) { /* private mode */ }
try { if (P.hash && P.hash('fx') === '0') st.userOn = false; } catch (e) { /* ignore */ }
function active() { return st.dark && st.userOn; }
function kvCls(kv) { kv = +kv || 0; return kv >= 350 ? 400 : kv >= 200 ? 275 : kv >= 100 ? 132 : kv >= 50 ? 66 : 33; }
function rgba(c, a) { return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')'; }
function mApprox(la1, lo1, la2, lo2) { var x = (lo2 - lo1) * Math.cos((la1 + la2) * 0.5 * rad) * 111320, y = (la2 - la1) * 111320; return Math.sqrt(x * x + y * y); }
function hash(s) { s = String(s); var h = 2166136261; for (var i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
function canvas(w, h) { var c = D.createElement('canvas'); c.width = Math.max(1, w | 0); c.height = Math.max(1, h | 0); return c; }
// ---- focus ingest (from pilot-dark.js): pack once, project per frame
function setFocus(f) {
if (!f || !Array.isArray(f.lines)) { st.focus = null; st.focusSig = ''; return; }
// pilot-dark.js re-sends the focus about twice a second: repack (and drop a running pulse) only when it changed
var sig = f.lines.length + '|' + (Array.isArray(f.subs) ? f.subs.length : 0) + '|' + f.lines.map(function (L) { return L && (L.id + ':' + (L.ll ? L.ll.length : 0)); }).join(',');
if (sig === st.focusSig && st.focus) return;
st.focusSig = sig;
var lines = [], nv = 0;
f.lines.forEach(function (L, i) {
var ll = L && L.ll; if (!ll || ll.length < 4) return;
var n = ll.length >> 1, cum = new Float32Array(n), a = new Float64Array(n * 2);
for (var k = 0; k < n; k++) { a[k * 2] = +ll[k * 2]; a[k * 2 + 1] = +ll[k * 2 + 1]; if (k) cum[k] = cum[k - 1] + mApprox(a[k * 2 - 2], a[k * 2 - 1], a[k * 2], a[k * 2 + 1]); }
lines.push({ id: L.id != null ? String(L.id) : 'l' + i, cls: kvCls(L.kv), ll: a, n: n, cum: cum, len: cum[n - 1], v0: nv });
nv += n;
});
var subs = (Array.isArray(f.subs) ? f.subs : []).filter(function (s) { return s && isFinite(+s.lat) && isFinite(+s.lon); })
.map(function (s, i) { return { id: s.id != null ? String(s.id) : 's' + i, name: s.name || '', cls: kvCls(s.kv), lat: +s.lat, lon: +s.lon }; });
st.focus = { lat: +f.lat, lon: +f.lon, radiusM: +f.radiusM || 0, lines: lines, subs: subs, nv: nv };
st.focusSerial++;
st.proj = { x: new Float32Array(nv), y: new Float32Array(nv), ok: new Uint8Array(nv) };
if (st.pulse) st.pulse = null; // geometry changed: an old pulse would point at the wrong lines
}
// ---- sprites, sky and bloom buffers (pre-rendered; rebuilt only on resize)
function sprite(cls, far) { // pre-sized per class (no scaling at draw time)
var key = cls + (far ? 'f' : 'n'); if (st.sprites[key]) return st.sprites[key];
var r = nodeR(cls) * (far ? 0.6 : 1), S = Math.ceil(r * 2 * GLOW_K) + 2, c = canvas(S, S), g = c.getContext('2d'), col = COL[cls];
var gr = g.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2);
gr.addColorStop(0, 'rgba(255,255,255,0.95)'); gr.addColorStop(0.16, rgba(col, 0.9)); gr.addColorStop(0.42, rgba(col, 0.3)); gr.addColorStop(1, rgba(col, 0));
g.fillStyle = gr; g.fillRect(0, 0, S, S);
return (st.sprites[key] = c);
}
function flashSprite() {
if (st.sprites.flash) return st.sprites.flash;
var S = 28, c = canvas(S, S), g = c.getContext('2d'), gr = g.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2);
gr.addColorStop(0, 'rgba(255,255,255,0.9)'); gr.addColorStop(0.3, 'rgba(200,215,255,0.35)'); gr.addColorStop(1, 'rgba(160,180,255,0)');
g.fillStyle = gr; g.fillRect(0, 0, S, S);
return (st.sprites.flash = c);
}
function dotSprite() {
if (st.sprites.dot) return st.sprites.dot;
var S = 9, c = canvas(S, S), g = c.getContext('2d'), gr = g.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2);
gr.addColorStop(0, 'rgba(255,255,255,0.85)'); gr.addColorStop(0.45, 'rgba(220,240,255,0.35)'); gr.addColorStop(1, 'rgba(200,230,255,0)');
g.fillStyle = gr; g.fillRect(0, 0, S, S);
return (st.sprites.dot = c);
}
function stars(w, h) { // fixed star field (positions in a 0..1 box), drawn as tiny rects: no image upload
var k = w + 'x' + h; if (st.stars && st.stars.k === k) return st.stars;
var rnd = 1234567; function r() { rnd = (Math.imul(rnd, 1103515245) + 12345) >>> 0; return rnd / 4294967296; }
var n = Math.min(140, Math.round(w * h / 2600)), a = [];
for (var i = 0; i < n; i++) a.push([r(), r(), r() < 0.1 ? 1.6 : 1, (0.3 + r() * 0.6).toFixed(2)]);
return (st.stars = { k: k, a: a });
}
function bandCanvas(w) { // the glow just below the horizon (thin, additive)
if (st.band && st.band.w === w) return st.band;
var H = 26, c = canvas(w, H), g = c.getContext('2d'), gr = g.createLinearGradient(0, 0, 0, H);
gr.addColorStop(0, 'rgba(90,160,235,0.30)'); gr.addColorStop(1, 'rgba(40,80,160,0)');
g.fillStyle = gr; g.fillRect(0, 0, w, H);
return (st.band = { w: w, c: c, H: H });
}
function bloomBuf(w, h) {
var b = st.bloom, bw = Math.max(1, Math.ceil(w / 4)), bh = Math.max(1, Math.ceil(h / 4));
if (!b || b.c.width !== bw || b.c.height !== bh) { var c = canvas(bw, bh); b = st.bloom = { c: c, g: c.getContext('2d') }; }
return b;
}
// ---- per-frame projection of the focus vertices (shared by glow, core, flow and the pulse)
function project(v) {
var F = st.focus, pr = st.proj; if (!F) return 0;
var cap = VERT_CAP[st.quality], used = 0, x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
for (var i = 0; i < F.lines.length; i++) {
var L = F.lines[i];
for (var k = 0; k < L.n; k++) {
var j = L.v0 + k;
if (used >= cap) { pr.ok[j] = 0; continue; }
var p = v.project(L.ll[k * 2], L.ll[k * 2 + 1], null); used++;
if (p) { pr.x[j] = p.x; pr.y[j] = p.y; pr.ok[j] = 1; if (p.x < x0) x0 = p.x; if (p.x > x1) x1 = p.x; if (p.y < y0) y0 = p.y; if (p.y > y1) y1 = p.y; } else pr.ok[j] = 0;
}
}
pr.box = [Math.max(0, x0 - 24), Math.max(0, y0 - 24), Math.min(v.w, x1 + 24), Math.min(v.h, y1 + 24)];
return used;
}
function segVisible(x1, y1, x2, y2, w, h) {
return !((x1 < -40 && x2 < -40) || (y1 < -40 && y2 < -40) || (x1 > w + 40 && x2 > w + 40) || (y1 > h + 40 && y2 > h + 40));
}
// screen-space decimation: vertices closer than minPx to the last kept one add nothing visible
function addLinePath(path, L, w, h, minPx) {
var pr = st.proj, pen = false, segs = 0, lx = 0, ly = 0, m2 = minPx * minPx, last = L.v0 + L.n - 1;
for (var k = 0; k < L.n; k++) {
var j = L.v0 + k;
if (!pr.ok[j]) { pen = false; continue; }
var x = pr.x[j], y = pr.y[j];
if (pen) {
var dx = x - lx, dy = y - ly;
if (dx * dx + dy * dy < m2 && j !== last) continue;
if (segVisible(lx, ly, x, y, w, h)) { path.lineTo(x, y); segs++; } else path.moveTo(x, y);
} else path.moveTo(x, y);
pen = true; lx = x; ly = y;
}
return segs;
}
// a point at distance d (metres) along a line, on screen, or null when that stretch is not projected
function along(L, d) {
var c = L.cum, lo = 0, hi = L.n - 1;
while (hi - lo > 1) { var m = (lo + hi) >> 1; if (c[m] <= d) lo = m; else hi = m; }
var pr = st.proj, a = L.v0 + lo, b = L.v0 + hi; if (!pr.ok[a] || !pr.ok[b]) return null;
var u = (d - c[lo]) / Math.max(1e-6, c[hi] - c[lo]);
return [pr.x[a] + (pr.x[b] - pr.x[a]) * u, pr.y[a] + (pr.y[b] - pr.y[a]) * u];
}
// ---- timing: every fx draw adds into this frame's cost
function part(k, ms) { st.parts[k] = (st.parts[k] || 0) * 0.9 + ms * 0.1; }
function poseKey(v) { // the bloom buffer is valid while the camera and the focus set have not changed
var c = P.cam || {};
return [Math.round(c.x * 2), Math.round(c.y * 2), Math.round(c.z * 2), Math.round(c.yaw * 2000), Math.round(c.pitch * 2000), v.w, v.h, st.focusSerial].join(',');
}
// measured mode (tests): flush queued drawing before and after each fx layer so the time includes rasterising
function flush(g) { if (st.measure) try { g.getImageData(0, 0, 1, 1); } catch (e) { /* tainted or lost */ } }
function t0(g) { flush(g); return performance.now(); }
function spent(t, now, g) {
if (g) flush(g);
if (now !== st.lastFrame) { finishFrame(); st.lastFrame = now; st.frameMs = 0; }
st.frameMs += performance.now() - t;
}
// adaptive quality: step down when the effects cost > 3 ms (script) or the page drops under 45 fps for ~1 s
// while effects are on; step up after ~4 s of headroom. Quality 0 = no glow, no flow (core lines and nodes only).
function finishFrame() {
if (st.lastFrame < 0) return;
st.ms = st.ms * 0.9 + st.frameMs * 0.1;
st.samples.push(st.frameMs); if (st.samples.length > 600) st.samples.shift();
if (st.lockQ) return;
if (++st.fpsN >= 15) { st.fpsN = 0; try { st.fps = P.debug ? +P.debug().fps || 60 : 60; } catch (e) { st.fps = 60; } }
var slow = st.ms > STEP_DOWN_MS || st.fps < 45, roomy = st.ms < STEP_UP_MS && st.fps > 56;
if (slow) { st.fast = 0; if (++st.slow > 60 && st.quality > 0) { st.quality--; st.slow = 0; st.bloomKey = ''; } }
else if (roomy) { st.slow = 0; if (++st.fast > 240 && st.quality < 2) { st.quality++; st.fast = 0; st.bloomKey = ''; } }
else { st.slow = 0; st.fast = 0; }
}
// the horizon: a far point straight ahead on the ground (falls back to the pitch formula when it cannot project)
function horizonY(v) {
var c = P.cam, D = 2e5;
if (c && v.projectXYZ) { var p = v.projectXYZ(c.x + Math.sin(c.yaw) * D, c.y + Math.cos(c.yaw) * D, 0); if (p) return p.y; }
return v.h / 2 - Math.tan(v.cam.pitch || 0) * v.f;
}
// ---- layer: night sky + horizon glow (above the horizon; a thin additive glow just below it)
var skyLayer = { id: 'darkfx-sky', title: 'Dark Pilot: night sky (decorative)', order: 2, visible: false,
draw: function (g, v, now) {
if (!active()) return; var t = t0(g);
var hy = Math.round(horizonY(v));
if (hy > 0) { // core already paints a near-black sky: add stars, then a blue night gradient over its lowest band
var S = stars(v.w, v.h).a, lim = hy - 24;
for (var i = 0; i < S.length; i++) { var y = S[i][1] * v.h; if (y > lim) continue; g.fillStyle = 'rgba(220,230,255,' + S[i][3] + ')'; g.fillRect(S[i][0] * v.w, y, S[i][2], S[i][2]); }
var top = Math.max(0, hy - SKY_BAND), gr = g.createLinearGradient(0, hy - SKY_BAND, 0, hy);
gr.addColorStop(0, 'rgba(4,14,44,0)'); gr.addColorStop(0.6, 'rgba(10,32,78,0.75)'); gr.addColorStop(1, 'rgba(42,90,140,0.95)');
g.fillStyle = gr; g.fillRect(0, top, v.w, hy - top);
}
if (hy > -30 && hy < v.h) { var B = bandCanvas(v.w); g.globalCompositeOperation = 'lighter'; g.drawImage(B.c, 0, hy); }
spent(t, now, g);
} };
// ---- layer: glowing lines (additive), decorative flow dots, adjacency pulse
var lineLayer = { id: 'darkfx', title: 'Dark Pilot: line glow and decorative moving dots (not measured power flow)', order: 34, visible: false,
_segs: 0, _verts: 0, _dots: 0,
draw: function (g, v, now) {
this._segs = 0; this._verts = 0; this._dots = 0;
if (!active() || !st.focus) return; var t = t0(g);
var F = st.focus, w = v.w, h = v.h, q = st.quality;
var tP = performance.now(); this._verts = project(v);
var paths = {}, glow = {}, self = this, doBloom = !st.glowByDark && q === 2, doGlow = !st.glowByDark && q >= 1;
var key = doBloom ? poseKey(v) : '', reuse = doBloom && key === st.bloomKey;
CLASSES.forEach(function (c) { paths[c] = new Path2D(); glow[c] = new Path2D(); });
F.lines.forEach(function (L) {
var n = addLinePath(paths[L.cls], L, w, h, 1.5); if (!n) return;
self._segs += n;
if (doGlow && !reuse) addLinePath(glow[L.cls], L, w, h, 5);
});
var tA = performance.now(); part('proj', tA - tP);
if (!this._segs && !st.pulse) { spent(t, now, g); return; }
// 1) glow, additive. Quality 2: soft bloom = decimated thick strokes in a quarter-res buffer (re-rasterised only
// when the view or focus changes), scaled up over the lines' screen box only. Quality 1: one wide stroke.
g.save(); g.globalCompositeOperation = 'lighter'; g.lineCap = 'butt'; g.lineJoin = 'bevel';
if (doBloom) {
var b1 = bloomBuf(w, h), bx = st.proj.box;
if (!reuse) {
var bg = b1.g; bg.setTransform(1, 0, 0, 1, 0, 0); bg.clearRect(0, 0, b1.c.width, b1.c.height);
bg.setTransform(0.25, 0, 0, 0.25, 0, 0); bg.lineCap = 'butt'; bg.lineJoin = 'bevel'; bg.lineWidth = 14;
CLASSES.forEach(function (c) { bg.strokeStyle = rgba(COL[c], 0.8); bg.stroke(glow[c]); });
st.bloomKey = key;
}
var sx = Math.floor(bx[0] / 4), sy = Math.floor(bx[1] / 4), sw = Math.min(b1.c.width - sx, Math.ceil((bx[2] - bx[0]) / 4) + 1), sh = Math.min(b1.c.height - sy, Math.ceil((bx[3] - bx[1]) / 4) + 1);
if (sw > 0 && sh > 0) { g.imageSmoothingEnabled = true; g.globalAlpha = 0.95; g.drawImage(b1.c, sx, sy, sw, sh, sx * 4, sy * 4, sw * 4, sh * 4); g.globalAlpha = 1; }
} else if (doGlow) {
g.lineWidth = 7; CLASSES.forEach(function (c) { g.strokeStyle = rgba(COL[c], 0.24); g.stroke(glow[c]); });
}
var tB = performance.now(); part('glow', tB - tA);
// 2) core: additive voltage-class colour
CLASSES.forEach(function (c) { g.strokeStyle = rgba(COL[c], 0.95); g.lineWidth = c >= 275 ? 2.2 : 1.7; g.stroke(paths[c]); });
// 3) decorative flow: small dots drifting along each line in its mapped drawing order (never under reduced
// motion). Speed and spacing are constants: they show nothing measured.
if (!REDUCED && q >= 1) {
var tot = 0; F.lines.forEach(function (L) { tot += L.len; });
var sp = Math.max(FLOW_SPACING_M, tot / FLOW_MAX_DOTS), off = (now / 1000) * FLOW_SPEED_M % sp, dot = dotSprite(), n = 0;
for (var i = 0; i < F.lines.length && n < FLOW_MAX_DOTS; i++) {
var L = F.lines[i];
for (var d = off; d < L.len && n < FLOW_MAX_DOTS; d += sp) {
var p = along(L, d); if (!p || p[0] < -8 || p[1] < -8 || p[0] > w + 8 || p[1] > h + 8) continue;
g.drawImage(dot, p[0] - 4.5, p[1] - 4.5); n++;
}
}
this._dots = n;
}
g.restore(); part('core', performance.now() - tB);
// 4) adjacency pulse
if (st.pulse) drawPulse(g, v, now);
spent(t, now, g);
} };
// ---- layer: substations as light nodes sized by voltage class
function nodeR(cls) { return 5 + 11 * Math.pow(cls / 400, 0.6); }
var nodeLayer = { id: 'darkfx-nodes', title: 'Dark Pilot: substation light nodes (size = voltage class)', order: 54, visible: false, _n: 0,
draw: function (g, v, now) {
this._n = 0;
if (!active() || !st.focus) return; var t = t0(g);
var subs = st.focus.subs, n = 0;
g.globalCompositeOperation = 'lighter';
for (var i = 0; i < subs.length && n < 600; i++) {
var s = subs[i], p = v.project(s.lat, s.lon, null);
if (!p || p.x < -30 || p.y < -30 || p.x > v.w + 30 || p.y > v.h + 30) continue;
var spr = sprite(s.cls, p.d > 15000);
g.drawImage(spr, Math.round(p.x - spr.width / 2), Math.round(p.y - spr.height / 2)); n++;
}
this._n = n;
spent(t, now, g);
} };
// ---- the pulse: hop-by-hop adjacency of mapped line ends (geometry only)
function endOf(L, which) { var k = which ? L.n - 1 : 0; return [L.ll[k * 2], L.ll[k * 2 + 1]]; }
function adjacency(lat, lon) {
var F = st.focus; if (!F) return [];
var used = {}, seq = [], front = [[lat, lon]];
for (var hop = 0; hop < MAX_HOPS && front.length && seq.length < MAX_PULSE_LINES; hop++) {
var next = [];
F.lines.forEach(function (L, li) {
if (used[li] || seq.length >= MAX_PULSE_LINES) return;
for (var q = 0; q < front.length; q++) {
var a = endOf(L, 0), b = endOf(L, 1), da = mApprox(front[q][0], front[q][1], a[0], a[1]), db = mApprox(front[q][0], front[q][1], b[0], b[1]);
if (Math.min(da, db) <= ADJ_M) { used[li] = 1; var rev = db < da; seq.push({ li: li, hop: hop, rev: rev }); next.push(rev ? a : b); return; }
}
});
front = next;
}
return seq;
}
function startPulse(sel) {
if (!active() || !sel || !isFinite(+sel.lat) || !isFinite(+sel.lon)) return null;
var seq = adjacency(+sel.lat, +sel.lon), hops = seq.reduce(function (m, s) { return Math.max(m, s.hop + 1); }, 0);
st.pulse = { lat: +sel.lat, lon: +sel.lon, name: sel.name || '', seq: seq, hops: hops, t0: performance.now(), dur: (hops * HOP_S + HOLD_S + FADE_S) * 1000 };
caption();
P.note && P.note(seq.length ? 'Pulse: ' + seq.length + ' mapped line section' + (seq.length === 1 ? '' : 's') + ' adjacent in ' + hops + ' hop' + (hops === 1 ? '' : 's') + '. Network adjacency only, not a power flow, rating or fault path.'
: 'Pulse: no mapped line ends within ' + ADJ_M + ' m of this substation in the focus area (adjacency only).', 4500);
return st.pulse;
}
function drawPulse(g, v, now) {
var Pu = st.pulse, F = st.focus, el = (performance.now() - Pu.t0) / 1000;
if (el * 1000 > Pu.dur) { st.pulse = null; caption(); return; }
var fade = Math.max(0, Math.min(1, (Pu.dur / 1000 - el) / FADE_S)), pr = st.proj;
g.save(); g.globalCompositeOperation = 'lighter'; g.lineCap = 'round'; g.lineJoin = 'round';
var heads = [];
Pu.seq.forEach(function (s) {
var L = F.lines[s.li]; if (!L) return;
var f = REDUCED ? 1 : Math.max(0, Math.min(1, (el - s.hop * HOP_S) / HOP_S)); if (f <= 0) return;
var target = f * L.len, path = new Path2D(), pen = false, hx = null, hy = null;
for (var q = 0; q < L.n; q++) {
var k = s.rev ? L.n - 1 - q : q, j = L.v0 + k, d = s.rev ? L.len - L.cum[k] : L.cum[k];
if (!pr.ok[j]) { pen = false; continue; }
if (d > target && q) { // interpolate the head inside this segment
var kp = s.rev ? k + 1 : k - 1, jp = L.v0 + kp, dp = s.rev ? L.len - L.cum[kp] : L.cum[kp];
if (pen && pr.ok[jp]) { var u = (target - dp) / Math.max(1e-6, d - dp); hx = pr.x[jp] + (pr.x[j] - pr.x[jp]) * u; hy = pr.y[jp] + (pr.y[j] - pr.y[jp]) * u; path.lineTo(hx, hy); }
break;
}
if (pen) path.lineTo(pr.x[j], pr.y[j]); else path.moveTo(pr.x[j], pr.y[j]);
pen = true; hx = pr.x[j]; hy = pr.y[j];
}
g.strokeStyle = 'rgba(160,240,255,' + (0.25 * fade).toFixed(3) + ')'; g.lineWidth = 9; g.stroke(path);
g.strokeStyle = 'rgba(235,255,255,' + (0.95 * fade).toFixed(3) + ')'; g.lineWidth = 2.6; g.stroke(path);
if (f < 1 && hx != null) heads.push([hx, hy]);
});
var sp = flashSprite();
heads.forEach(function (hd) { g.drawImage(sp, hd[0] - 14, hd[1] - 14, 28, 28); });
var o = v.project(Pu.lat, Pu.lon, null);
if (o) { var rr = REDUCED ? 18 : 10 + 30 * ((el % 1.2) / 1.2); g.strokeStyle = 'rgba(200,250,255,' + (0.7 * fade).toFixed(3) + ')'; g.lineWidth = 2; g.beginPath(); g.arc(o.x, o.y, rr, 0, 6.2832); g.stroke(); }
g.restore();
}
// ---- lightning: brief white strokes that stop above the ground (never touching it)
function flashesNow() {
if (st.flashSrc === 'event') return st.flashes;
try { // guarded read-only fallback until pilot-lightning emits 'lightning:flashes' (requested from FLASHOVER-31)
var L = P.layer && P.layer('lightning');
if (L && L.visible !== false && L._api && L._api.S && L._api.S.F && L._api.S.ctx !== 'none') { st.flashSrc = 'fallback'; return L._api.S.F; }
} catch (e) { /* ignore */ }
return null;
}
function bolt(lat, lon, id) {
var h = hash(id + ':' + lat.toFixed(5) + lon.toFixed(5)), pts = [], N = 8, kx = 1 / (111320 * Math.cos(lat * rad)), ky = 1 / 111320;
var g0 = P.ground ? +P.ground(lat, lon) || 0 : 0, dx = 0, dy = 0;
for (var i = 0; i <= N; i++) {
var f = i / N, alt = g0 + BOLT_TOP - (BOLT_TOP - BOLT_STOP) * f;
if (i && i < N) { h = (Math.imul(h, 1103515245) + 12345) >>> 0; dx += ((h & 1023) / 1023 - 0.5) * 260; dy += (((h >> 10) & 1023) / 1023 - 0.5) * 260; }
pts.push([lat + dy * ky, lon + dx * kx, alt]);
}
return { pts: pts, ground: g0, off: hash(id || lat + ',' + lon) % FLASH_PERIOD, agl: BOLT_STOP };
}
function pickCandidates(v) {
var F = flashesNow(); st.cand = [];
if (!F || !F.n || !v.bbox) return;
var c = v.cam, list = [];
for (var i = 0; i < F.n; i++) {
var la = F.lat[i], lo = F.lon[i];
if (la < v.bbox.s || la > v.bbox.n || lo < v.bbox.w || lo > v.bbox.e) continue;
list.push([mApprox(c.lat, c.lon, la, lo), i]);
}
list.sort(function (a, b) { return a[0] - b[0]; });
st.cand = list.slice(0, FLASH_MAX).map(function (x) { var i = x[1]; return bolt(F.lat[i], F.lon[i], F.id ? F.id[i] : String(i)); });
}
var flashLayer = { id: 'darkfx-flash', title: 'Dark Pilot: optical lightning flashes (optical flash, not a ground strike; risk screening)', order: 76, visible: false,
draw: function (g, v, now) {
st.drawnBolts = 0;
if (!active()) return; var t = t0(g);
var pn = performance.now();
if (pn - st.candT > 1000) { st.candT = pn; var had = st.cand.length; pickCandidates(v); if (!!had !== !!st.cand.length) caption(); }
if (REDUCED || !st.cand.length) { spent(t, now, g); return; }
g.save(); g.globalCompositeOperation = 'lighter'; g.lineCap = 'round'; g.lineJoin = 'round';
var sp = flashSprite(), minA = null;
for (var i = 0; i < st.cand.length; i++) {
var B = st.cand[i], ph = (now + B.off) % FLASH_PERIOD; if (ph > FLASH_MS) continue;
var I = ph < 60 ? 1 : ph < 110 ? 0.35 : ph < 150 ? 0.9 : 1 - (ph - 150) / (FLASH_MS - 150);
var path = new Path2D(), pen = false, last = null;
for (var k = 0; k < B.pts.length; k++) { var q = B.pts[k], p = v.project(q[0], q[1], q[2]); if (!p) { pen = false; continue; } if (pen) path.lineTo(p.x, p.y); else path.moveTo(p.x, p.y); pen = true; last = p; }
if (!last) continue;
g.strokeStyle = 'rgba(190,205,255,' + (0.28 * I).toFixed(3) + ')'; g.lineWidth = 7; g.stroke(path);
g.strokeStyle = 'rgba(255,255,255,' + I.toFixed(3) + ')'; g.lineWidth = 1.6; g.stroke(path);
g.globalAlpha = I; g.drawImage(sp, last.x - 10, last.y - 10, 20, 20); g.globalAlpha = 1; // the stroke's end: in the air
var a = B.pts[B.pts.length - 1][2] - B.ground; minA = minA == null ? a : Math.min(minA, a);
st.drawnBolts++; st.bolts++;
}
if (minA != null) st.minBoltAgl = minA;
g.restore();
spent(t, now, g);
} };
// ---- captions (honesty lines) in the shared status slot, only while dark is on
function caption() {
var html = '';
if (st.dark) {
var bits = [];
if (!st.userOn) bits.push('Effects off');
else {
bits.push(REDUCED ? TEXT.OFF_REDUCED + '. ' + 'Glow is decorative.' : TEXT.FLOW + ' (' + TEXT.FLOW_DIR + ').');
if (st.pulse) bits.push('<b>' + TEXT.PULSE + '</b>.');
if (st.cand.length && !REDUCED) bits.push('Lightning: ' + TEXT.FLASH + ' · ' + TEXT.SCREEN + '.');
}
html = '<span class="p-darkfx-cap" data-p-darkfx-cap="1">' + bits.join(' ') + '</span>';
}
if (html === st.caption) return;
st.caption = html;
if (P.hud) P.hud('status:darkfx', html);
}
// ---- on / off
var LAYERS = [skyLayer, lineLayer, nodeLayer, flashLayer];
function apply() {
var on = active();
LAYERS.forEach(function (l) { if (P.setLayerVisible) P.setLayerVisible(l.id, on); else l.visible = on; });
if (!on) { st.pulse = null; st.cand = []; }
caption(); status(true);
}
function setDark(on) { on = !!on; if (on === st.dark) return; st.dark = on; if (on && !st.focus) query(); apply(); }
function setUser(on) { st.userOn = !!on; try { localStorage.setItem('p-darkfx-on', on ? '1' : '0'); } catch (e) { /* ignore */ } apply(); }
function query() { try { P.emit('dark:query', { reply: function (f, s) { if (f) setFocus(f); if (s && 'glowByDark' in s) st.glowByDark = !!s.glowByDark; if (s && s.on && !st.dark) setDark(true); } }); } catch (e) { /* no dark module */ } }
var lastStatus = 0;
function status(force) {
var s = { on: st.userOn, active: active(), reduced: REDUCED, ms: Math.round(st.ms * 1000) / 1000, budgetMs: BUDGET_MS, quality: st.quality,
lines: st.focus ? st.focus.lines.length : 0, subs: st.focus ? st.focus.subs.length : 0, pulse: !!st.pulse,
bolts: st.cand.length, flashSource: st.flashSrc, animating: active() && !REDUCED };
var n = Date.now(); if (force || n - lastStatus > 1000) { lastStatus = n; try { P.emit('darkfx:status', s); } catch (e) { /* ignore */ } }
return s;
}
// ---- events
P.on('dark:state', function (d) { if (!d) return; if ('glowByDark' in d) st.glowByDark = !!d.glowByDark; if ('on' in d) setDark(!!d.on); });
P.on('dark:focus', function (d) { setFocus(d); });
P.on('ukpn:select', function (d) { if (d) startPulse({ lat: d.lat, lon: d.lon, name: d.id }); });
P.on('pick', function (d) { var it = d && d.item; if (it && /^(grid-sub-|dark-sub)/.test(String(it.id || ''))) startPulse({ lat: it.lat, lon: it.lon, name: it.title }); });
P.on('lightning:flashes', function (d) {
if (!d) return;
st.flashSrc = 'event';
st.flashes = d.on === false || !Array.isArray(d.lat) ? null : { lat: d.lat, lon: d.lon, t: d.t || [], id: d.id || [], n: Math.min(d.lat.length, (d.lon || []).length) };
st.candT = 0;
});
P.on('darkfx:set', function (d) { if (d && 'on' in d) setUser(!!d.on); });
P.onFrame(function () { if (active()) status(false); });
LAYERS.forEach(function (l) { P.addLayer(l); });
P.module('darkfx', { version: '1', owner: 'DARK GRID 2 (NOCTILUCENT-27)' });
P.darkfx = {
TEXT: TEXT, status: status, set: setUser,
_test: { focus: setFocus, dark: setDark, pulse: startPulse, adjacency: adjacency, bolt: bolt, state: st, nodeR: nodeR,
layers: function () { return LAYERS.map(function (l) { return { id: l.id, segs: l._segs, verts: l._verts, n: l._n }; }); } }
};
function start() { var on = false; try { on = !!(P.dark && P.dark.on && P.dark.on()); } catch (e) { /* no dark module */ } if (on) setDark(true); else query(); apply(); }
if (P.ready) P.ready(start); else start();
})();