// ── Almanac: every active satellite ── // The Earth view's "all satellites" layer, loaded on its first use (almanac-earth.js _aeSatsAllSet) and never otherwise: // - the catalogue (satcatalog.py, /almanac-satellites?all=1): about fifteen thousand satellites as columns of // orbital elements, with owner, launch date and radar size; // - one THREE.Points for all of them, a vertex shader that carries each a second or so past its last sample along its // velocity, and a Web Worker that runs SGP4 for the lot, so the main thread only copies two arrays now and then; // - filters (constellation, orbit, owner), the tapped satellite's card, and its orbit; // - the passes: sunlit satellites over the person's place while the sky is dark, listed in a sheet, drawn as moving // points in the live sky (almanac-sky.js _skyPaintActors, from the one registry: almanac-onesky.js _osPaintObjects), with the GPS satellites overhead. // The elements fade by age: a set a few days old is as good as exact, one a month old is a rough guess, and past // AS_AGE_GONE_DAYS the satellite is not drawn. Brightness is an estimate (a diffuse sphere the size of the satellite's // radar cross-section, or a stated size for the big constellations) and the sheet says so. // Shares almanac-earth.js's global scope: its helpers (_aeT, _aeProject, _aeLine ...) and the page's (_getLocation ...). // ── The catalogue ── var AS_URL = '/almanac-satellites?all=1'; var AS_REFRESH_URL = '/manage/satellites/refresh'; var AS_COLS = ['norad', 'name', 'epoch', 'mm', 'ecc', 'inc', 'raan', 'argp', 'ma', 'bstar', 'owner', 'launch', 'rcs']; var AS_EPOCH_ORIGIN_MS = Date.UTC(2000, 0, 1); // satcatalog.py EPOCH_ORIGIN: the epoch column counts days from here var AS_LAUNCH_ORIGIN_MS = Date.UTC(1957, 0, 1); // satcatalog.py LAUNCH_ORIGIN var AS_MU_KM3_S2 = 398600.4418; // Earth's GM: the semi-major axis from the mean motion var AS_LEO_MAX_KM = AE_SATS_REF.leoMaxKm, AS_GEO_MIN_KM = AE_SATS_REF.geoMinKm; // the orbit classes, by mean altitude var AS_ORBITS = ['leo', 'meo', 'geo']; var AS_GROUPS = ['starlink', 'oneweb', 'iridium', 'gnss', 'other']; var AS_GROUP_RE = [/^STARLINK/, /^ONEWEB/, /^IRIDIUM/, /^(GPS |NAVSTAR|GLONASS|GALILEO|BEIDOU|QZS|IRNSS|NAVIC)/]; var AS_GROUP_COLOR = { starlink: [0.43, 0.91, 0.85], oneweb: [0.72, 0.6, 1.0], iridium: [1.0, 0.62, 0.35], gnss: [0.55, 0.85, 1.0], other: [0.93, 0.93, 0.9] }; var AS_GROUP_TERM = { starlink: 'term:starlink', oneweb: 'term:oneweb', iridium: 'term:iridium', gnss: 'term:gnss', other: 'term:satellite_constellation' }; var AS_ORBIT_TERM = { leo: 'term:leo', meo: 'term:meo', geo: 'term:geo' }; // The owners SATCAT names, as the country whose flag stands for them (the rest show their code). var AS_OWNER_ISO = { US: 'US', UK: 'GB', PRC: 'CN', CIS: 'RU', JPN: 'JP', IND: 'IN', FR: 'FR', GER: 'DE', IT: 'IT', CA: 'CA', ESA: 'EU', SKOR: 'KR', ISRA: 'IL', AUS: 'AU', BRAZ: 'BR', SPN: 'ES', TURK: 'TR', UAE: 'AE', ARGN: 'AR', LUXE: 'LU', NETH: 'NL', SWTZ: 'CH', SWED: 'SE', NOR: 'NO', TWN: 'TW', THAI: 'TH', INDO: 'ID', SAUD: 'SA', EGYP: 'EG', MEX: 'MX', POL: 'PL', ISS: 'US' }; var AS_OWNER_TBD = 'TBD'; // SATCAT's code for an owner not yet assigned var AS_OWNER_CHIPS = 6; // the most numerous owners get a chip of their own var AS_GPS_KEY = 'zimi_ae_sats_gps', AS_ON = '1'; // the layer's own choice is SK.ALM_SATS_ALL (app.js) // ── Drawing ── var AS_POINT_PX = 2.6, AS_POINT_GEO_PX = 3.4, AS_POINT_SELECTED_PX = 9; var AS_AGE_FRESH_DAYS = AE_SATS_REF.ageFreshDays, AS_AGE_GONE_DAYS = AE_SATS_REF.ageGoneDays; // element age: fully drawn up to the first, gone by the second var AS_LEO_GONE_DAYS = AE_SATS_REF.leoGoneDays; // a low-orbit satellite is gone by this age of its elements var AS_ALPHA_FLOOR = 0.12; var AS_RESAMPLE_MS = 1000; // a fresh sample of every satellite this often (display time) var AS_EXTRAP_MAX_S = 30; // the shader's carry past a sample never exceeds this var AS_FAST_RATE = 600; // a clock running faster than this (x real time) hides the dots var AS_ALPHA_REFRESH_MS = 5000; // Coming down to the Earth, the swarm thins and dims so the ground shows through it ("when zooming towards earth the onslaught of // satellites is worth considering, hiding or dimming"): from AS_NEAR_FAR_RE out (Earth radii from its middle) all are drawn as they are; by AS_NEAR_RE // a share AS_NEAR_KEEP of them, at that share of their brightness. Stepped in AS_NEAR_STEPS, so a zoom repaints the alphas a few times, not every frame. var AS_NEAR_RE = 1.25, AS_NEAR_FAR_RE = 8, AS_NEAR_KEEP = 0.2, AS_NEAR_STEPS = 8; var AS_HASH = 2654435761, AS_HASH_MOD = 4294967296; // Knuth's multiplicative hash: which satellites stay when the swarm thins (the same ones every time) function _asNearK() { var d = _ae && _ae.target === 'earth' ? _ae.dist : AS_NEAR_FAR_RE, u = _aeClamp((d - AS_NEAR_RE) / (AS_NEAR_FAR_RE - AS_NEAR_RE), 0, 1); return Math.round((AS_NEAR_KEEP + (1 - AS_NEAR_KEEP) * u) * AS_NEAR_STEPS) / AS_NEAR_STEPS; } function _asKept(i, k) { return k >= 1 || (i * AS_HASH % AS_HASH_MOD) / AS_HASH_MOD < k; } var AS_GEO_RE = 6.6107, AS_GEO_RING_POINTS = 180, AS_GEO_RING_COLOR = 0xb8c4d6, AS_GEO_RING_ALPHA = 0.16; // the geostationary radius (42,164 km) in Earth radii var AS_ORBIT_POINTS = 144, AS_ORBIT_COLOR = 0xffd27a, AS_ORBIT_ALPHA = 0.55, AS_ORBIT_REFRESH_MS = 10 * 60 * 1000; var AS_TAP_RADIUS_PX = 22; var AS_EARTH_RE_KM = 6371; // AE_EARTH_RADIUS_KM, which the worker is given // ── The passes ── var AS_PASS_HOURS = 30, AS_PASS_STEP_S = 60, AS_PASS_REFINE_S = 10, AS_PASS_MIN_EL = AE_SATS_REF.passMinEl, AS_PASS_SUN_ALT = AE_SATS_REF.passSunAlt; var AS_PASS_MAG_LIMIT = AE_SATS_REF.passMag, AS_PASS_MAX = AE_SATS_REF.passMax, AS_PASS_LONE_STARLINKS = AE_SATS_REF.loneStarlinks; var AS_PASS_EL_WEIGHT_DEG = 60; // a pass is worth one magnitude more for each this many degrees of height var AS_PASS_AREA_M2 = AE_SATS_REF.areaM2; // used where SATCAT has no radar size var AS_PASS_MIN_RCS_M2 = AE_SATS_REF.minRcsM2; // a satellite with a radar size below this is not offered var AS_PASS_LEO_MM = 11; // revolutions a day: a pass needs an orbit this low var AS_TRAIN_GAP_S = AE_SATS_REF.trainGapS, AS_TRAIN_MIN = 3, AS_TRAIN_RAAN_DEG = AE_SATS_REF.trainRaanDeg; var AS_ISS_NORAD = 25544, AS_ISS_MODULE = /^ISS \(/; var AS_ISS_SAME_ORBIT = { inc: 0.05, mm: 0.05 }; // what is docked to the station (POISK, NAUKA, a Soyuz...) has its orbit: it is the same thing in the sky var AS_PASS_SKY_FRAME_MS = 500; var AS_TRAIL_STEPS = 8, AS_TRAIL_STEP_S = 4, AS_TRAIL_ALPHA = 0.7; // the sky's trail behind a satellite: eight steps of four seconds, fading var AS_GPS_MIN_EL = AE_SATS_REF.gpsMinEl; var _as = { on: false, state: 'idle', // idle | loading | ready | failed data: null, lib: null, worker: null, workerReady: false, cloud: null, scene: null, sel: -1, selLine: null, geoRing: null, selAt: 0, filter: { group: {}, orbit: {}, owner: {} }, sampleMs: 0, posting: false, alphaAt: -Infinity, shown: 0, passes: null, passPlace: null, passBusy: false, sheet: false, gps: false, bar: null }; function _asPref(on) { _prefWrite(SK.ALM_SATS_ALL, on ? AS_ON : null); } function _asGpsOn() { try { return localStorage.getItem(AS_GPS_KEY) === AS_ON; } catch (e) { return false; } } // ── Reading the catalogue ── function _asDecode(payload) { var cols = payload.cols || [], rows = payload.sats || [], n = rows.length, ix = {}; AS_COLS.forEach(function (c) { ix[c] = cols.indexOf(c); }); if (AS_COLS.some(function (c) { return ix[c] < 0; }) || !n) return null; var d = { n: n, fetched: payload.fetched, source: payload.source, stale: !!payload.stale, norad: new Int32Array(n), epoch: new Float64Array(n), mm: new Float64Array(n), ecc: new Float64Array(n), inc: new Float64Array(n), raan: new Float64Array(n), argp: new Float64Array(n), ma: new Float64Array(n), bstar: new Float64Array(n), launch: new Int32Array(n), rcs: new Float32Array(n), alt: new Float32Array(n), group: new Uint8Array(n), orbit: new Uint8Array(n), owner: new Uint8Array(n), name: new Array(n), owners: [], ownerCount: {} }; var ownerIx = {}; for (var i = 0; i < n; i++) { var r = rows[i]; d.norad[i] = r[ix.norad]; d.name[i] = r[ix.name]; d.epoch[i] = r[ix.epoch]; d.mm[i] = r[ix.mm]; d.ecc[i] = r[ix.ecc]; d.inc[i] = r[ix.inc]; d.raan[i] = r[ix.raan]; d.argp[i] = r[ix.argp]; d.ma[i] = r[ix.ma]; d.bstar[i] = r[ix.bstar]; d.launch[i] = r[ix.launch] == null ? -1 : r[ix.launch]; d.rcs[i] = r[ix.rcs] == null ? NaN : r[ix.rcs]; d.alt[i] = _asAltitudeKm(d.mm[i], d.ecc[i]); d.orbit[i] = d.alt[i] < AS_LEO_MAX_KM ? 0 : d.alt[i] < AS_GEO_MIN_KM ? 1 : 2; var g = 0; while (g < AS_GROUP_RE.length && !AS_GROUP_RE[g].test(d.name[i])) g++; d.group[i] = g; var o = r[ix.owner] || ''; if (!(o in ownerIx)) { ownerIx[o] = d.owners.length; d.owners.push(o); d.ownerCount[o] = 0; } d.owner[i] = ownerIx[o]; d.ownerCount[o]++; } d.topOwners = d.owners.filter(Boolean).sort(function (a, b) { return d.ownerCount[b] - d.ownerCount[a]; }).slice(0, AS_OWNER_CHIPS); return d; } // The catalogue the capability level allows (capability.js ZimiCap 'satMax'): the ISS and the GPS first, then the largest by radar // cross-section (the brightest; none last), kept in the file's order. Cut before the worker, the cloud and the filters see it, so // their work, the buffers and the count all shrink with it. var AS_CAP_FIRST = /^(GPS |NAVSTAR)/; function _asCapData(d) { var max = typeof ZimiCap !== 'undefined' ? ZimiCap.get('satMax') : Infinity; if (!(max < d.n)) return d; var weight = function (j) { if (d.norad[j] === AS_ISS_NORAD || AS_CAP_FIRST.test(d.name[j])) return Infinity; return d.rcs[j] === d.rcs[j] ? d.rcs[j] : -1; }; var w = [], keep = [], i; for (i = 0; i < d.n; i++) { w.push(weight(i)); keep.push(i); } keep = keep.sort(function (a, b) { return w[b] === w[a] ? a - b : w[b] > w[a] ? 1 : -1; }).slice(0, max).sort(function (a, b) { return a - b; }); var o = { n: keep.length, fetched: d.fetched, source: d.source, stale: d.stale, owners: d.owners, ownerCount: d.ownerCount, topOwners: d.topOwners, name: keep.map(function (j) { return d.name[j]; }) }; ['norad', 'epoch', 'mm', 'ecc', 'inc', 'raan', 'argp', 'ma', 'bstar', 'launch', 'rcs', 'alt', 'group', 'orbit', 'owner'].forEach(function (k) { var src = d[k], out = new src.constructor(keep.length); for (var t = 0; t < keep.length; t++) out[t] = src[keep[t]]; o[k] = out; }); return o; } // Mean altitude (km) from the mean motion in revolutions a day: the orbit's size, not its height at a moment. function _asAltitudeKm(mm, ecc) { var nRad = mm * 2 * Math.PI / 86400, a = Math.cbrt(AS_MU_KM3_S2 / (nRad * nRad)); return a - AS_EARTH_RE_KM; } function _asOmm(d, i) { return { OBJECT_NAME: d.name[i], NORAD_CAT_ID: d.norad[i], EPOCH: new Date(AS_EPOCH_ORIGIN_MS + d.epoch[i] * MS_PER_DAY).toISOString(), MEAN_MOTION: d.mm[i], ECCENTRICITY: d.ecc[i], INCLINATION: d.inc[i], RA_OF_ASC_NODE: d.raan[i], ARG_OF_PERICENTER: d.argp[i], MEAN_ANOMALY: d.ma[i], BSTAR: d.bstar[i], MEAN_MOTION_DOT: 0, MEAN_MOTION_DDOT: 0 }; } function _asEpochMs(d, i) { return AS_EPOCH_ORIGIN_MS + d.epoch[i] * MS_PER_DAY; } // ── The worker: SGP4 for everything, off the main thread ── // Written as a function and sent as its source, so it needs no file of its own (the Almanac ZIM packs only what its // page loads) and no path that differs between Zimi and a ZIM. It knows nothing of this file. function _asWorkerMain() { 'use strict'; var lib = null, N = 0, recs = null, epochMs = null, radius = 6371, EPOCH0 = 0; var D2R = Math.PI / 180, MS_DAY = 86400000; var A_WGS = 6378.137, F_WGS = 1 / 298.257223563, E2 = F_WGS * (2 - F_WGS); var SUN_MAG = 0, ALBEDO = 0; var SKY_SKIP_DEG = 10, SKY_MAX_RATE = 2; // a satellite this far below the horizon cannot be up for this many degrees over the fastest a satellite moves (degrees a second) var skipFrom = null, skipUntil = null; var skipLat = NaN, skipLon = NaN; function init(m) { if (self.location && new URL(m.sgpUrl, self.location.href).origin !== self.location.origin) throw new Error('sgp4 origin'); // only this page's own copy importScripts(m.sgpUrl); lib = self.SatelliteJS; N = m.n; radius = m.radius; EPOCH0 = m.epoch0; SUN_MAG = m.sunMag; ALBEDO = m.albedo; epochMs = new Float64Array(N); recs = new Array(N); skipFrom = new Float64Array(N); skipUntil = new Float64Array(N); var bad = 0; for (var i = 0; i < N; i++) { epochMs[i] = EPOCH0 + m.epoch[i] * MS_DAY; try { var r = lib.json2satrec({ OBJECT_NAME: '', NORAD_CAT_ID: m.norad[i], EPOCH: new Date(epochMs[i]).toISOString(), MEAN_MOTION: m.mm[i], ECCENTRICITY: m.ecc[i], INCLINATION: m.inc[i], RA_OF_ASC_NODE: m.raan[i], ARG_OF_PERICENTER: m.argp[i], MEAN_ANOMALY: m.ma[i], BSTAR: m.bstar[i], MEAN_MOTION_DOT: 0, MEAN_MOTION_DDOT: 0 }); recs[i] = r.error ? null : r; } catch (e) { recs[i] = null; } if (!recs[i]) bad++; } return bad; } // Positions (Earth radii) and velocities (radii a second) in TEME, with a flag for each satellite SGP4 answered for. function tick(ms) { var pos = new Float32Array(N * 3), vel = new Float32Array(N * 3), ok = new Uint8Array(N); for (var i = 0; i < N; i++) { var rec = recs[i]; if (!rec) continue; var pv = lib.sgp4(rec, (ms - epochMs[i]) / 60000); if (!pv || !pv.position || typeof pv.position.x !== 'number' || isNaN(pv.position.x)) continue; var p = pv.position, v = pv.velocity, k = i * 3; pos[k] = p.x / radius; pos[k + 1] = p.y / radius; pos[k + 2] = p.z / radius; vel[k] = v.x / radius; vel[k + 1] = v.y / radius; vel[k + 2] = v.z / radius; ok[i] = 1; } return { pos: pos, vel: vel, ok: ok }; } // The Sun's direction (a unit vector, equatorial) to a few hundredths of a degree: all the dark sky and the shadow need. function sunUnit(ms) { var n = ms / MS_DAY + 2440587.5 - 2451545.0; var L = (280.460 + 0.9856474 * n) * D2R, g = (357.528 + 0.9856003 * n) * D2R; var lam = L + (1.915 * Math.sin(g) + 0.020 * Math.sin(2 * g)) * D2R, eps = (23.439 - 0.0000004 * n) * D2R; return [Math.cos(lam), Math.cos(eps) * Math.sin(lam), Math.sin(eps) * Math.sin(lam)]; } function gmst(ms) { var n = ms / MS_DAY + 2440587.5 - 2451545.0; return (((18.697374558 + 24.06570982441908 * n) % 24 + 24) % 24) * 15 * D2R; } // The place: its frame (up, east, north in the equatorial axes) and position, at a local sidereal angle. function frame(lat, lon, th) { var sl = Math.sin(lat), cl = Math.cos(lat), st = Math.sin(th), ct = Math.cos(th), N0 = A_WGS / Math.sqrt(1 - E2 * sl * sl); return { up: [cl * ct, cl * st, sl], east: [-st, ct, 0], north: [-sl * ct, -sl * st, cl], pos: [N0 * cl * ct, N0 * cl * st, N0 * (1 - E2) * sl] }; } function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } // Magnitude of a diffuse sphere of cross-section area A (m2) lit by the Sun and seen from the place. function magnitude(sat, sun, obs, area) { var rho = [obs[0] - sat[0], obs[1] - sat[1], obs[2] - sat[2]], range = Math.sqrt(dot(rho, rho)); var c = Math.max(-1, Math.min(1, dot(sun, rho) / range)), phi = Math.acos(c); var p = 2 / (3 * Math.PI) * (Math.sin(phi) + (Math.PI - phi) * Math.cos(phi)); var d = range * 1000; return SUN_MAG - 2.5 * Math.log10(Math.max(1e-30, ALBEDO * area * p / (Math.PI * d * d))); } function sunlit(sat, sun) { var along = dot(sat, sun); if (along >= 0) return true; var px = sat[0] - sun[0] * along, py = sat[1] - sun[1] * along, pz = sat[2] - sun[2] * along; return Math.sqrt(px * px + py * py + pz * pz) > A_WGS; } // One satellite seen from the place at ms: {el, az, mag} when it is up and lit, else null. function look(i, ms, lat, lon, area, minEl, info) { var pv = lib.sgp4(recs[i], (ms - epochMs[i]) / 60000); if (!pv || !pv.position || typeof pv.position.x !== 'number' || isNaN(pv.position.x)) return null; var sat = [pv.position.x, pv.position.y, pv.position.z], th = gmst(ms) + lon, f = frame(lat, lon, th); var rho = [sat[0] - f.pos[0], sat[1] - f.pos[1], sat[2] - f.pos[2]], range = Math.sqrt(dot(rho, rho)); var el = Math.asin(dot(rho, f.up) / range) / D2R; if (info) info.el = el; if (el < minEl) return null; var sun = sunUnit(ms); if (!sunlit(sat, sun)) return null; var az = (Math.atan2(dot(rho, f.east), dot(rho, f.north)) / D2R + 360) % 360; return { el: el, az: az, mag: magnitude(sat, sun, f.pos, area) }; } // Every pass over the place in the next hours: runs of steps where the satellite is up, lit and bright enough while // the sky is dark, then each run's edges found to a few seconds. function passes(m) { var lat = m.lat * D2R, lon = m.lon * D2R, steps = Math.floor(m.hours * 3600 / m.step), t0 = m.t0, out = []; var sunAlt = new Float32Array(steps); for (var k = 0; k < steps; k++) { var t = t0 + k * m.step * 1000, f = frame(lat, lon, gmst(t) + lon); sunAlt[k] = Math.asin(dot(sunUnit(t), f.up)) / D2R; } for (var c = 0; c < m.cand.length; c++) { var i = m.cand[c], area = m.area[c]; var altKm = m.altKm[c], dip = Math.acos(radius / (radius + altKm)) / D2R + 3; // below this the satellite is in shadow at any height of the sky var reach = m.inc[c] > 90 ? 180 - m.inc[c] : m.inc[c]; if (Math.abs(m.lat) > reach + dip + 20) continue; var run = null; for (var k2 = 0; k2 < steps; k2++) { if (sunAlt[k2] > m.sunAlt || sunAlt[k2] < -dip - 8) { if (run) { out.push(finish(i, run, lat, lon, area, m)); run = null; } continue; } var tt = t0 + k2 * m.step * 1000, lk = look(i, tt, lat, lon, area, m.minEl); if (lk && lk.mag <= m.magLimit) { if (!run) run = { first: tt }; run.last = tt; } else if (run) { out.push(finish(i, run, lat, lon, area, m)); run = null; } } if (run) out.push(finish(i, run, lat, lon, area, m)); } return out.filter(Boolean); } function finish(i, run, lat, lon, area, m) { var from = run.first - m.step * 1000, to = run.last + m.step * 1000, a = null, best = null, z = null, mag = 99; for (var t = from; t <= to; t += m.refine * 1000) { var lk = look(i, t, lat, lon, area, 0); if (!lk || lk.el < m.minEl || lk.mag > m.magLimit) continue; if (!a) a = { t: t, az: lk.az }; z = { t: t, az: lk.az }; if (!best || lk.el > best.el) best = { t: t, az: lk.az, el: lk.el }; if (lk.mag < mag) mag = lk.mag; } if (!a || !best) return null; return { i: i, start: a.t, peak: best.t, end: z.t, el: best.el, azS: a.az, azP: best.az, azE: z.az, mag: mag }; } // Every satellite up and lit over the place at t, as the sky would show it: where (degrees), how bright, and how fast it // moves (degrees a second, from a second look dt later), brightest first. Nothing while the Sun is above m.sunAlt. function skyNow(m) { var lat = m.lat * D2R, lon = m.lon * D2R, f = frame(lat, lon, gmst(m.t) + lon), sun = sunUnit(m.t); var sunAlt = Math.asin(dot(sun, f.up)) / D2R, out = []; if (sunAlt > m.sunAlt) return { sunAlt: sunAlt, list: out }; if (m.lat !== skipLat || m.lon !== skipLon) { skipFrom.fill(0); skipUntil.fill(0); skipLat = m.lat; skipLon = m.lon; } // what was skipped was for another place for (var c = 0; c < m.cand.length; c++) { var i = m.cand[c] | 0, dip = Math.acos(radius / (radius + m.altKm[c])) / D2R + 3, reach = m.inc[c] > 90 ? 180 - m.inc[c] : m.inc[c]; if (Math.abs(m.lat) > reach + dip + 20 || sunAlt < -dip - 8) continue; if (m.t >= skipFrom[i] && m.t < skipUntil[i]) continue; // far below the horizon at an earlier look, and not yet near it var info = {}, lk = look(i, m.t, lat, lon, m.area[c], m.minEl, info); if (!lk) { if (info.el < -SKY_SKIP_DEG) { skipFrom[i] = m.t; skipUntil[i] = m.t + (-info.el - SKY_SKIP_DEG) / SKY_MAX_RATE * 1000; } continue; } if (lk.mag > m.magLimit) continue; var next = look(i, m.t + m.dt, lat, lon, m.area[c], -90), s = m.dt / 1000; out.push({ i: i, az: lk.az, el: lk.el, mag: lk.mag, azRate: next ? (((next.az - lk.az + 540) % 360) - 180) / s : 0, elRate: next ? (next.el - lk.el) / s : 0 }); } out.sort(function (u, v) { return u.mag - v.mag; }); return { sunAlt: sunAlt, list: out.slice(0, m.max) }; } self.onmessage = function (e) { var m = e.data, out = { id: m.id, cmd: m.cmd }; try { if (m.cmd === 'init') out.bad = init(m); else if (m.cmd === 'tick') { var r = tick(m.ms); out.ms = m.ms; out.pos = r.pos; out.vel = r.vel; out.ok = r.ok; } else if (m.cmd === 'passes') out.list = passes(m); else if (m.cmd === 'sky') { var sk = skyNow(m); out.list = sk.list; out.sunAlt = sk.sunAlt; } } catch (err) { out.error = String(err && err.message || err); } var tr = []; if (out.pos) tr = [out.pos.buffer, out.vel.buffer, out.ok.buffer]; self.postMessage(out, tr); }; } var _asCalls = {}; function _asAsk(msg, transfer) { return new Promise(function (resolve, reject) { if (!_as.worker) { reject(new Error('no worker')); return; } var id = ++_asAsk.n; _asCalls[id] = { resolve: resolve, reject: reject }; msg.id = id; _as.worker.postMessage(msg, transfer || []); }); } _asAsk.n = 0; function _asStartWorker(d) { var blob = new Blob(['(' + _asWorkerMain.toString() + ')()'], { type: 'text/javascript' }); var url = URL.createObjectURL(blob); var w = new Worker(url); URL.revokeObjectURL(url); w.onmessage = function (e) { var c = _asCalls[e.data.id]; if (!c) return; delete _asCalls[e.data.id]; if (e.data.error) c.reject(new Error(e.data.error)); else c.resolve(e.data); }; w.onerror = function () { Object.keys(_asCalls).forEach(function (k) { _asCalls[k].reject(new Error('worker')); delete _asCalls[k]; }); }; _as.worker = w; return _asAsk({ cmd: 'init', sunMag: AE_SATS_REF.sunMag, albedo: AE_SATS_REF.albedo, sgpUrl: new URL(AE_SGP4_URL, document.baseURI).href, n: d.n, radius: AS_EARTH_RE_KM, epoch0: AS_EPOCH_ORIGIN_MS, norad: d.norad, epoch: d.epoch, mm: d.mm, ecc: d.ecc, inc: d.inc, raan: d.raan, argp: d.argp, ma: d.ma, bstar: d.bstar }); } // ── Turning it on and off ── // Called by almanac-earth.js: the button, and the view's open when the choice was kept. function _asSet(on, asked) { _as.on = !!on; _as.barOpen = !!(on && asked); // the filters come up when the toggle is turned on, never by themselves (a kept layer, a reload, a zoom out) if (_as.barOpen && _as.sel >= 0) _asSelect(-1); // the filters, or a satellite's card: one at a time if (_as.barOpen && _ae && _ae.setOpen) _aeShowSettings(false); // and the drawer holds one of the filters or the settings _asPref(_as.on); if (_as.on) _asSatLoad(); if (_as.state === 'ready') _asBuildBar(); if (!_as.on) { _asCloseSheet(); _asSelect(-1); } _asSync(); } var _asGen = 0; // each release makes the loads started before it stale function _asSatLoad() { if (_as.state === 'loading' || _as.state === 'ready') return Promise.resolve(); _as.state = 'loading'; _asSync(); var gen = _asGen, stale = function () { return gen !== _asGen; }; return Promise.all([_aeLoadSgp4(), _aeFetch(AS_URL).then(_aeJson)]).then(function (res) { if (stale()) return 'stale'; // released while loading: no worker, no data _as.lib = res[0]; var d = _asDecode(res[1]); if (!d) throw new Error('catalogue'); d = _asCapData(d); _as.data = d; return _asStartWorker(d); }).then(function (r) { if (r === 'stale' || stale()) return 'stale'; // the release already took the worker and the data _as.state = 'ready'; _asBuildBar(); _asApplyFilters(); _asNeedPasses(); }).catch(function () { if (stale()) return 'stale'; _as.state = 'failed'; if (_as.worker) { _as.worker.terminate(); _as.worker = null; } }).then(function (r) { if (r === 'stale') return; _asSync(); if (typeof _ae !== 'undefined' && _ae) { _ae.dirty = true; _aeKick(); } }); } // The button's look and the strip's visibility follow the state. function _asSync() { var b = _aeById('ae-sats-btn'); if (b) { b.setAttribute('aria-pressed', String(_as.on)); b.setAttribute('aria-busy', String(_as.on && _as.state === 'loading')); b.classList.toggle('as-failed', _as.on && _as.state === 'failed'); } _asSyncBar(); if (typeof _aeBandPaint === 'function') _aeBandPaint(); // (the band's tile says loading and failed) if (_as.cloud) _as.cloud.visible = _as.on && _as.state === 'ready'; _asStandSkySync(); } // Leaving the Almanac: the worker and the catalogue go; what is kept is the choice. function _asRelease() { _asGen++; _asStandSkyOff(); if (_as.worker) { _as.worker.terminate(); _as.worker = null; } _asCalls = {}; _as.state = 'idle'; _as.data = null; _as.cloud = null; _as.scene = null; _as.selLine = null; _as.geoRing = null; _as.sel = -1; _as.passes = null; _as.passPlace = null; _as.passBusy = false; _as.sampleMs = 0; _as.posting = false; _as.alphaAt = -Infinity; if (_as.bar && _as.bar.parentNode) _as.bar.parentNode.removeChild(_as.bar); if (_as.sheetEl && _as.sheetEl.parentNode) _as.sheetEl.parentNode.removeChild(_as.sheetEl); _as.bar = _as.sheetEl = null; _as.sheet = false; } // The GPU scene was freed and will be made again: what hung on it is gone. function _asGlGone() { _as.cloud = null; _as.scene = null; _as.selLine = null; _as.geoRing = null; } // ── The points ── // Each point is sized by its distance (near ones larger), dimmed in the Earth's shadow (it is not sunlit there) and // faded on the far side of the planet, so the shells read as a depth, not a flat sheet. The selected one is never dimmed. var AS_NEAR_SIZE_MIN = 0.7, AS_NEAR_SIZE_MAX = 1.7; // the size scale across the view's depth var AS_SHADOW_ALPHA = 0.3; // what a point in the Earth's shadow keeps var AS_FAR_FADE_RE = 1.2, AS_FAR_ALPHA = 0.55; // the fade past the Earth's centre, over this many Earth radii var AS_VERT = [ 'attribute vec3 aVel; attribute vec3 aColor; attribute float aAlpha; attribute float aSize;', 'uniform float dpr; uniform float dt; uniform vec3 sunDir;', 'varying vec3 vColor; varying float vAlpha;', 'void main() {', ' vec3 p = position + aVel * dt;', ' vec3 w = (modelMatrix * vec4(p, 1.0)).xyz;', ' float dist = length(cameraPosition - w), mid = length(cameraPosition);', ' float along = dot(w, sunDir), perp = length(w - sunDir * along);', ' float dark = step(along, 0.0) * (1.0 - smoothstep(0.97, 1.03, perp));', ' float far = smoothstep(0.0, ' + AS_FAR_FADE_RE.toFixed(2) + ', dist - mid);', ' float plain = step(' + (AS_POINT_SELECTED_PX - 0.5).toFixed(1) + ', aSize);', ' float shade = mix(1.0 - dark * (1.0 - ' + AS_SHADOW_ALPHA.toFixed(2) + '), 1.0, plain) * mix(1.0, ' + AS_FAR_ALPHA.toFixed(2) + ', far * (1.0 - plain));', ' vColor = aColor; vAlpha = aAlpha * shade;', ' gl_PointSize = aSize * dpr * clamp(mid / max(dist, 0.1), ' + AS_NEAR_SIZE_MIN.toFixed(2) + ', ' + AS_NEAR_SIZE_MAX.toFixed(2) + ');', ' gl_Position = aSize > 0.0 && aAlpha > 0.0 ? projectionMatrix * modelViewMatrix * vec4(p, 1.0) : vec4(2.0, 2.0, 2.0, 1.0);', // a hidden point is clipped, not drawn as a 1 px speck '}' ].join('\n'); function _asMakeCloud() { var S = _ae.gl, THREE = S.THREE, n = _as.data.n; var g = new THREE.BufferGeometry(); ['position', 'aVel', 'aColor'].forEach(function (k) { g.setAttribute(k, new THREE.BufferAttribute(new Float32Array(n * 3), 3)); }); ['aAlpha', 'aSize'].forEach(function (k) { g.setAttribute(k, new THREE.BufferAttribute(new Float32Array(n), 1)); }); var u = { dpr: { value: S.dpr }, dt: { value: 0 }, sunDir: { value: new THREE.Vector3(1, 0, 0) }, glow: { value: 0 }, fade: _aeFadeU }; var m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: AS_VERT, fragmentShader: AE_POINTS_FRAG, transparent: true, depthWrite: false, depthTest: true }); var p = new THREE.Points(g, m); p.frustumCulled = false; p.renderOrder = 1; S.scene.add(p); var d = _as.data, col = g.attributes.aColor.array; for (var i = 0; i < n; i++) { var c = AS_GROUP_COLOR[AS_GROUPS[d.group[i]]]; col[i * 3] = c[0]; col[i * 3 + 1] = c[1]; col[i * 3 + 2] = c[2]; } // The selected satellite's orbit. _as.selLine = _aeLine(THREE, THREE.LineLoop, AS_ORBIT_POINTS, AS_ORBIT_COLOR, AS_ORBIT_ALPHA); S.scene.add(_as.selLine); // The geostationary belt as a faint ring, so the high shell reads as one at a glance. _as.geoRing = _aeLine(THREE, THREE.LineLoop, AS_GEO_RING_POINTS, AS_GEO_RING_COLOR, AS_GEO_RING_ALPHA); var ring = _as.geoRing.geometry.attributes.position.array; for (var k = 0; k < AS_GEO_RING_POINTS; k++) { var th = 2 * Math.PI * k / AS_GEO_RING_POINTS; ring[k * 3] = AS_GEO_RE * Math.cos(th); ring[k * 3 + 1] = AS_GEO_RE * Math.sin(th); ring[k * 3 + 2] = 0; } _as.geoRing.geometry.setDrawRange(0, AS_GEO_RING_POINTS); S.scene.add(_as.geoRing); _as.cloud = p; _as.scene = S.scene; _as.sampleMs = 0; _as.alphaAt = -Infinity; _as.hold = null; _asApplyFilters(); } // ── Filters ── function _asVisible(i) { var d = _as.data, f = _as.filter; if (d.norad[i] === AS_ISS_NORAD || _asIsGpsDrawn(i)) return false; var g = AS_GROUPS[d.group[i]], o = AS_ORBITS[d.orbit[i]], ow = d.owners[d.owner[i]]; return (!_asAny(f.group) || f.group[g]) && (!_asAny(f.orbit) || f.orbit[o]) && (!_asAny(f.owner) || f.owner[ow]); } function _asAny(set) { for (var k in set) if (set[k]) return true; return false; } // The GPS satellites the view already draws and names (its own layer) are not drawn twice. function _asIsGpsDrawn(i) { if (!_ae.sats) return false; if (!_as.gpsIds || _as.gpsFor !== _ae.sats) { _as.gpsIds = {}; _as.gpsFor = _ae.sats; _ae.sats.list.forEach(function (s) { _as.gpsIds[s.omm.NORAD_CAT_ID] = 1; }); } return !!_as.gpsIds[_as.data.norad[i]]; } function _asApplyFilters() { if (!_as.cloud || !_as.data) return; var d = _as.data, size = _as.cloud.geometry.attributes.aSize.array, n = d.n, shown = 0; for (var i = 0; i < n; i++) { var on = _asVisible(i); size[i] = !on ? 0 : i === _as.sel ? AS_POINT_SELECTED_PX : d.orbit[i] === 2 ? AS_POINT_GEO_PX : AS_POINT_PX; if (on) shown++; } _as.shown = shown; _as.cloud.geometry.attributes.aSize.needsUpdate = true; _as.alphaAt = -Infinity; _asCount(); if (typeof _ae !== 'undefined' && _ae) { _ae.dirty = true; _aeKick(); } } function _asFiltersClear() { Object.keys(_as.filter).forEach(function (k) { _as.filter[k] = {}; }); if (_as.bar) Array.prototype.forEach.call(_as.bar.querySelectorAll('[data-k]'), function (b) { b.setAttribute('aria-pressed', 'false'); }); _asApplyFilters(); } // Whether the filters are up (the minimap gives them its corner). function _asBarUp() { return !!(_as.bar && !_as.bar.hidden); } var AS_BAR_SIDE_MQ = '(min-width:760px) and (min-height:600px)'; // where the filters stand beside the corner's buttons, not across the foot function _asBarAcross() { return _asBarUp() && !(window.matchMedia && matchMedia(AS_BAR_SIDE_MQ).matches); } function _asCount() { var el = _aeById('as-count'); if (el) el.textContent = _aeT('alm_sats_n', { n: _orrNum(_as.shown, null, 0) }); var all = _aeById('as-all'); if (all) all.setAttribute('aria-pressed', String(!Object.keys(_as.filter).some(function (k) { return _asAny(_as.filter[k]); }))); } // ── Each frame ── // Called by almanac-earth.js after its own satellites. function _asSatFrame(ms, sc) { if (!_as.on || _as.state !== 'ready') return; if (_asStandSkyOff.registered !== _as.data) _asStandSkySync(); // the ground view's file loads on its first use: joined when it is there if (!_as.cloud || _as.scene !== _ae.gl.scene) _asMakeCloud(); var cloud = _as.cloud, fast = typeof _almRate !== 'undefined' && Math.abs(_almRate) > AS_FAST_RATE; cloud.visible = _ae.target === 'earth' && !fast; if (_as.geoRing) _as.geoRing.visible = cloud.visible; if ((_ae.selected || _ae.place || _ae.lm) && _as.sel >= 0) _asSelect(-1); // the view's own cards win _asSyncBar(); if (!cloud.visible) return; cloud.rotation.z = _aeEqEq(sc); var dt = _as.sampleMs ? _aeClamp((ms - _as.sampleMs) / 1000, -AS_EXTRAP_MAX_S, AS_EXTRAP_MAX_S) : 0; cloud.material.uniforms.dt.value = dt; var sl = _aeLen(sc.sun); cloud.material.uniforms.sunDir.value.set(sc.sun[0] / sl, sc.sun[1] / sl, sc.sun[2] / sl); if (!_as.posting && (!_as.sampleMs || Math.abs(ms - _as.sampleMs) >= AS_RESAMPLE_MS)) _asSample(ms); else if (_as.sampleMs && _asNearK() !== _as.nearK) _asAlphas(_as.sampleMs); // a zoom: the swarm thins or fills at once if (_as.sel >= 0) _asUpdateSelOrbit(ms, sc); } function _asSample(ms) { _as.posting = true; _asAsk({ cmd: 'tick', ms: ms }).then(function (r) { _as.posting = false; if (!_as.cloud) return; var a = _as.cloud.geometry.attributes; a.position.array.set(r.pos); a.aVel.array.set(r.vel); a.position.needsUpdate = a.aVel.needsUpdate = true; _as.ok = r.ok; _as.sampleMs = r.ms; _asAlphas(r.ms); _ae.dirty = true; _aeKick(); }).catch(function () { _as.posting = false; }); } // Fade by the age of each satellite's elements: how old they were when the data was read, and then how far the instant // shown is from the present. The present is always drawn as fresh as the data is (the snapshot that ships is the newest // there is offline, and the layer says when it may be out of date); moving the date away from it is what ages the // elements. One SGP4 could not answer for does not draw. function _asAlphas(ms) { var near = _asNearK(); if (ms - _as.alphaAt < AS_ALPHA_REFRESH_MS && ms >= _as.alphaAt && near === _as.nearK) return; _as.nearK = near; var d = _as.data, al = _as.cloud.geometry.attributes.aAlpha.array, ok = _as.ok, n = d.n; var t = (ms - AS_EPOCH_ORIGIN_MS) / MS_PER_DAY, shift = Math.abs(t - (Date.now() - AS_EPOCH_ORIGIN_MS) / MS_PER_DAY); var read = (Date.parse(d.fetched) - AS_EPOCH_ORIGIN_MS) / MS_PER_DAY; for (var i = 0; i < n; i++) { var age = (isNaN(read) ? 0 : Math.max(0, read - d.epoch[i])) + shift, gone = d.orbit[i] === 0 ? AS_LEO_GONE_DAYS : AS_AGE_GONE_DAYS; // drag and manoeuvres age a low orbit's elements sooner al[i] = !ok[i] || age >= gone || (!_asKept(i, near) && i !== _as.sel) ? 0 : (age <= AS_AGE_FRESH_DAYS ? 1 : Math.max(AS_ALPHA_FLOOR, 1 - (age - AS_AGE_FRESH_DAYS) / (gone - AS_AGE_FRESH_DAYS))) * (i === _as.sel ? 1 : near); } _as.cloud.geometry.attributes.aAlpha.needsUpdate = true; _as.alphaAt = ms; } // ── Taps ── // A tap near a dot picks the nearest, unless it is behind the Earth. True when it took the tap. function _asTap(x, y) { if (!_as.on || _as.state !== 'ready' || !_as.cloud || !_as.cloud.visible || !_as.sampleMs) return false; var a = _as.cloud.geometry.attributes, pos = a.position.array, vel = a.aVel.array, size = a.aSize.array, alpha = a.aAlpha.array; var dt = _as.cloud.material.uniforms.dt.value, cz = Math.cos(_as.cloud.rotation.z), sz = Math.sin(_as.cloud.rotation.z), n = _as.data.n; var found = []; for (var i = 0; i < n; i++) { if (!size[i] || alpha[i] <= 0) continue; var k = i * 3, px = pos[k] + vel[k] * dt, py = pos[k + 1] + vel[k + 1] * dt, pz = pos[k + 2] + vel[k + 2] * dt; var p = [px * cz - py * sz, px * sz + py * cz, pz], s = _aeProject(p); if (!s) continue; var dd = Math.hypot(s.x - x, s.y - y); if (dd < AS_TAP_RADIUS_PX) found.push({ i: i, d: dd, p: p }); } found.sort(function (u, v) { return u.d - v.d; }); for (var j = 0; j < found.length; j++) { if (_aeBehindEarth(found[j].p)) continue; _asSelect(found[j].i); return true; } return false; } function _asSelect(i) { if (i === _as.sel) return; var before = _as.sel; _as.sel = i; if (i >= 0) { _ae.selected = null; _ae.place = null; _ae.lm = null; _as.barOpen = false; _asSyncBar(); } // a tapped satellite's card, or the filters: never both at once if (_as.cloud) { var size = _as.cloud.geometry.attributes.aSize.array, d = _as.data; [before, i].forEach(function (k) { if (k >= 0) size[k] = _asVisible(k) || k === i ? (k === i ? AS_POINT_SELECTED_PX : d.orbit[k] === 2 ? AS_POINT_GEO_PX : AS_POINT_PX) : 0; }); _as.cloud.geometry.attributes.aSize.needsUpdate = true; } if (_as.selLine) { _as.selLine.visible = i >= 0; _as.selAt = 0; } _as.alphaAt = -Infinity; // (the chosen one is drawn whatever the thinning) if (_ae && _ae.gl) { _aeRenderCard(); _ae.dirty = true; _aeKick(); } } function _asHasSel() { return _as.sel >= 0 && _as.on && !!_as.data; } // The selected satellite's orbit: one revolution from now, in the scene's frame (the cloud's own turn applied). function _asUpdateSelOrbit(ms, sc) { if (!_as.selLine || Math.abs(ms - _as.selAt) < AS_ORBIT_REFRESH_MS && _as.selAt) return; var rec = _asRec(_as.sel); if (!rec) { _as.selLine.visible = false; return; } var d = _as.data, i = _as.sel, periodMs = 1440 / d.mm[i] * 60000, eqeq = _aeEqEq(sc), arr = _as.selLine.geometry.attributes.position.array, epoch = _asEpochMs(d, i); for (var k = 0; k < AS_ORBIT_POINTS; k++) { var pv = _as.lib.sgp4(rec, (ms + periodMs * k / AS_ORBIT_POINTS - epoch) / 60000); if (!pv || !pv.position || isNaN(pv.position.x)) { _as.selLine.visible = false; return; } var q = _aeTemeToScene(pv.position, eqeq); arr[k * 3] = q[0]; arr[k * 3 + 1] = q[1]; arr[k * 3 + 2] = q[2]; } _as.selLine.geometry.attributes.position.needsUpdate = true; _as.selLine.geometry.setDrawRange(0, AS_ORBIT_POINTS); _as.selLine.visible = true; _as.selAt = ms; } var _asRecs = {}; function _asRec(i) { if (!_as.lib || !_as.data || i < 0) return null; if (!(i in _asRecs)) { try { var r = _as.lib.json2satrec(_asOmm(_as.data, i)); _asRecs[i] = r.error ? null : r; } catch (e) { _asRecs[i] = null; } } return _asRecs[i]; } // Position (km, TEME) and speed (km/s) of one satellite at a time, or null. function _asStateAt(i, ms) { var rec = _asRec(i); if (!rec) return null; var pv = _as.lib.sgp4(rec, (ms - _asEpochMs(_as.data, i)) / 60000); if (!pv || !pv.position || isNaN(pv.position.x)) return null; var v = pv.velocity, p = pv.position; return { pos: p, alt: Math.hypot(p.x, p.y, p.z) - AS_EARTH_RE_KM, speed: Math.hypot(v.x, v.y, v.z) }; } // ── The card ── function _asFlag(code) { var iso = AS_OWNER_ISO[code]; if (!iso || iso.length !== 2) return ''; return String.fromCodePoint(0x1F1E6 + iso.charCodeAt(0) - 65, 0x1F1E6 + iso.charCodeAt(1) - 65); } function _asOwnerLabel(code) { return code === AS_OWNER_TBD ? _aeT('alm_sats_unassigned') : code; } function _asOwnerName(code) { var iso = AS_OWNER_ISO[code]; if (iso && typeof Intl !== 'undefined' && Intl.DisplayNames) { try { var lang = (typeof _lang !== 'undefined' && _lang) || document.documentElement.lang || 'en'; var n = new Intl.DisplayNames([lang], { type: 'region' }).of(iso); if (n && n !== iso) return n; } catch (e) {} } return _asOwnerLabel(code); } function _asGroupLabel(g) { return g === 'other' ? _aeT('alm_sats_other') : { starlink: 'Starlink', oneweb: 'OneWeb', iridium: 'Iridium', gnss: 'GNSS' }[g]; } // Drawn into the Earth view's card by almanac-earth.js _aeRenderCardBody; true when it is its card. function _asRenderCard(card) { if (!_asHasSel()) return false; var d = _as.data, i = _as.sel, g = AS_GROUPS[d.group[i]], o = AS_ORBITS[d.orbit[i]]; var owner = d.owners[d.owner[i]]; var html = '' + '

' + _almEsc(d.name[i]) + '

'; html += '

' + (owner ? _almEsc((_asFlag(owner) + ' ' + _asOwnerName(owner)).trim()) : '') + (d.launch[i] >= 0 ? (owner ? ' · ' : '') + _almEsc(_aeT('alm_sats_launched', { date: _aeFmtDate(AS_LAUNCH_ORIGIN_MS + d.launch[i] * MS_PER_DAY) })) : '') + '

'; html += '

' + _asLearn(AS_GROUP_TERM[g], _almEsc(_asGroupLabel(g))) + ' · ' + _asLearn(AS_ORBIT_TERM[o], o.toUpperCase()) + '

'; html += '

'; card.innerHTML = html; card.hidden = false; _aeById('ae-card-x').onclick = function () { _asSelect(-1); }; _asUpdateCard(_aeDisplayMs()); return true; } function _asLearn(key, html) { return _aeLinked(key) ? _aeLink(key, html) : html; } function _asUpdateCard(ms) { if (!_asHasSel()) return false; var line = _aeById('as-card-line'); if (!line) return true; var st = _asStateAt(_as.sel, ms); if (st) line.textContent = _aeT('alm_sats_line', { alt: _orrNum(st.alt, null, 0), v: _orrNum(st.speed, null, 2) }); var age = _aeById('as-card-age'), days = Math.abs(ms - _asEpochMs(_as.data, _as.sel)) / MS_PER_DAY; if (age) age.textContent = days > AS_AGE_FRESH_DAYS ? _aeT('alm_earth_approx', { date: _aeFmtDate(_asEpochMs(_as.data, _as.sel)) }) : ''; return true; } // ── The strip: filters, the count, the passes ── var AS_BAR_CSS = [ '.ae-standing .as-bar,.ae-standing .as-sheet,.ae-flying .as-bar,.ae-flying .as-sheet{display:none}', // standing, the ground view owns the screen '.as-bar{box-sizing:border-box;width:100%;display:flex;flex-direction:column;gap:3px;pointer-events:auto}', '.as-sheet{position:relative;margin-top:10px;padding-top:8px;border-top:1px solid var(--border);font-size:13px;color:var(--text2)}', '.as-row{display:flex;flex-wrap:wrap;gap:4px 5px;align-items:center}', '@media (pointer:coarse){.as-row{gap:18px 8px}.as-bar{row-gap:18px}}', // a finger's hit area: 26px chips with a 44px box each '.as-lab{flex:none;font-size:10px;letter-spacing:.05em;text-transform:uppercase;color:var(--text2);margin-inline-end:2px}', '.as-bar[hidden],.as-sheet[hidden]{display:none}', '.as-bar .ae-btn{flex:none;font-size:12px;padding:3px 9px;min-height:32px;display:inline-flex;align-items:center;gap:6px}', '.as-bar .ae-round{width:32px;height:32px;padding:0}', '.as-dot{width:8px;height:8px;border-radius:50%;background:currentColor;flex:none}', '.as-head{display:flex;align-items:center;gap:8px}.as-head .as-gap{flex:1}.as-head .as-all{margin-inline-end:6px}.as-head .as-count{align-self:center}', // the count on the line of All (All a little apart: its 44 px reach would take the panel's edge) '.as-bar .as-all[aria-pressed="true"]{color:var(--amber);border-color:var(--amber-border)}', '.as-count{align-self:flex-start;font-size:13px;color:var(--text2);font-variant-numeric:tabular-nums;padding:0 4px}', '.as-flag{font-size:15px;line-height:1}', '.as-failed{opacity:.5}', '.as-sheet h3{margin:0 24px 6px 0;font-size:14px;font-weight:600;color:var(--text)}', '.as-sheet .as-x{position:absolute;top:6px;right:8px;background:none;border:0;color:var(--text2);font-size:20px;cursor:pointer;line-height:1}', '.as-pass{display:grid;grid-template-columns:auto 1fr auto;gap:2px 10px;width:100%;text-align:start;font:inherit;color:inherit;background:none;border:0;border-top:1px solid var(--border);padding:7px 0;cursor:pointer}', '.as-pass:first-of-type{border-top:0}', '.as-pass b{font-weight:600;color:var(--text);font-variant-numeric:tabular-nums}', '.as-pass span{font-variant-numeric:tabular-nums}', '.as-note{margin:6px 0 0;font-size:11.5px;opacity:.8}', '.as-gps{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px}', ].join(''); var AS_PASSES_SVG = ''; function _asChip(kind, key, inner, label) { return ''; } function _asBuildBar() { if (_as.bar && _as.bar.isConnected) return; var host = _aeById('ae-view') || (_ae && _ae.el); if (!host) return; if (!document.getElementById('as-style')) { var st = document.createElement('style'); st.id = 'as-style'; st.textContent = AS_BAR_CSS; document.head.appendChild(st); } var d = _as.data, html = '
'; // (the band's chevron shuts the drawer) var row = function (labelKey, chips) { return '
' + _almEsc(_aeT(labelKey)) + '' + chips + '
'; }; var who = '', orbit = '', owner = ''; AS_GROUPS.forEach(function (g) { var c = AS_GROUP_COLOR[g]; who += _asChip('group', g, '' + _almEsc(_asGroupLabel(g))); }); AS_ORBITS.forEach(function (o) { orbit += _asChip('orbit', o, o.toUpperCase()); }); // SATCAT's "TBD" is an owner not yet assigned: said so, and last. d.topOwners.slice().sort(function (a, b) { return (a === AS_OWNER_TBD) - (b === AS_OWNER_TBD); }).forEach(function (o) { owner += _asChip('owner', o, _asFlag(o) ? '' + _asFlag(o) + '' : _almEsc(_asOwnerLabel(o)), _asOwnerName(o)); }); html += row('alm_sats_f_group', who) + row('alm_sats_f_orbit', orbit + '') + row('alm_sats_f_owner', owner); var bar = document.createElement('div'); bar.className = 'as-bar'; bar.id = 'as-bar'; bar.setAttribute('role', 'group'); bar.setAttribute('aria-label', _aeT('alm_sats_all')); bar.hidden = true; bar.innerHTML = html; bar.addEventListener('click', function (e) { var b = e.target.closest && e.target.closest('button'); if (!b) return; if (b.id === 'as-passes') { _asToggleSheet(); return; } if (b.id === 'as-all') { _asFiltersClear(); return; } // one tap back to every satellite var set = _as.filter[b.getAttribute('data-k')], v = b.getAttribute('data-v'); set[v] = !set[v]; b.setAttribute('aria-pressed', String(!!set[v])); _asApplyFilters(); }); (_aeDrawerHost() || host).insertBefore(bar, (_aeDrawerHost() || host).firstChild); // in the one drawer, the filters above the passes _as.bar = bar; _asCount(); _asSync(); } // The strip is for the Earth: it goes while the view is elsewhere. function _asSyncBar() { if (!_as.bar) return; var hide = !(_as.on && _as.barOpen && _as.state === 'ready' && _ae && _ae.target === 'earth') || !!(_ae.stand && _ae.stand.live); // standing, the ground view owns the screen if (_as.bar.hidden !== hide) _as.bar.hidden = hide; if (_ae && _ae.el && _ae.el.classList.contains('as-bar-up') === hide) { _ae.el.classList.toggle('as-bar-up', !hide); if (typeof _aeRedraw === 'function') _aeRedraw(); } // the corners give the filters their room (the minimap, _aeMiniShown, and the info corner), and take it back at once if (hide && _as.sheet) _asCloseSheet(); else _asDrawerSync(); } // ── Passes ── function _asPlace() { var p = typeof _getLocation === 'function' ? _getLocation() : null; return p && p.lat != null ? { lat: p.lat, lon: p.lon, stored: p.stored } : null; } // The pass list for the place and the next day, asked of the worker when there is none for this place yet. function _asNeedPasses(place) { place = place || _asPlace(); if (!place || _as.state !== 'ready' || _as.passBusy) return; var t = _as.passPlace; if (t && Math.abs(t.lat - place.lat) < 0.05 && Math.abs(t.lon - place.lon) < 0.05 && Date.now() - t.at < AS_PASS_HOURS * 1800 * 1000) return; var c = _asSeenFrom(); _as.passBusy = true; var t0 = Date.now(); _asAsk({ cmd: 'passes', lat: place.lat, lon: place.lon, t0: t0, hours: AS_PASS_HOURS, step: AS_PASS_STEP_S, refine: AS_PASS_REFINE_S, minEl: AS_PASS_MIN_EL, sunAlt: AS_PASS_SUN_ALT, magLimit: AS_PASS_MAG_LIMIT, cand: c.cand, area: c.area, altKm: c.altKm, inc: c.inc }).then(function (r) { _as.passes = _asTrim(_asGroupTrains(r.list.sort(function (u, v) { return u.start - v.start; }))); _as.passPlace = { lat: place.lat, lon: place.lon, at: t0 }; _asRenderSheet(); _skyKickNow(); }).catch(function () { _as.passes = []; _as.passPlace = { lat: place.lat, lon: place.lon, at: t0 }; // not asked again at every paint }).then(function () { _as.passBusy = false; }); } // The satellites that can be seen from the ground at all (a low orbit, with a size to light up), as the columns the worker // takes: index, assumed area, altitude and inclination. Built once for a catalogue. function _asDockedToStation(i) { var d = _as.data, s = d._iss; if (s === undefined) { s = d._iss = d.norad.indexOf(AS_ISS_NORAD); } return s >= 0 && Math.abs(d.inc[i] - d.inc[s]) < AS_ISS_SAME_ORBIT.inc && Math.abs(d.mm[i] - d.mm[s]) < AS_ISS_SAME_ORBIT.mm; } function _asSeenFrom() { var d = _as.data; if (d._seen) return d._seen; var c = { cand: [], area: [], altKm: [], inc: [] }; for (var i = 0; i < d.n; i++) { if (d.mm[i] < AS_PASS_LEO_MM || d.alt[i] > AS_LEO_MAX_KM) continue; if (d.norad[i] !== AS_ISS_NORAD && (AS_ISS_MODULE.test(d.name[i]) || _asDockedToStation(i))) continue; // the station's other catalogue entries are the same pass var a = _asAreaM2(i); if (!a) continue; c.cand.push(i); c.area.push(a); c.altKm.push(d.alt[i]); c.inc.push(d.inc[i]); } return (d._seen = c); } // A satellite's size for the brightness estimate: its radar cross-section, or a stated size for the big constellations. function _asAreaM2(i) { var d = _as.data, g = AS_GROUPS[d.group[i]]; if (d.norad[i] === AS_ISS_NORAD) return AS_PASS_AREA_M2.iss; if (d.rcs[i] >= AS_PASS_MIN_RCS_M2) return d.rcs[i]; return AS_PASS_AREA_M2[g] || 0; } // Starlinks launched together cross the sky in a line: passes close in time and in orbital plane are one train. function _asGroupTrains(list) { var d = _as.data, out = [], open = null; list.forEach(function (p) { var star = AS_GROUPS[d.group[p.i]] === 'starlink'; if (star && open && p.peak - open.last <= AS_TRAIN_GAP_S * 1000 && Math.abs(d.raan[p.i] - d.raan[open.i]) < AS_TRAIN_RAAN_DEG) { open.members.push(p.i); open.last = p.peak; open.end = Math.max(open.end, p.end); open.mag = Math.min(open.mag, p.mag); return; } var q = Object.assign({ members: [p.i], last: p.peak }, p); out.push(q); open = star ? q : null; }); return out; } // A dusk sky has hundreds of Starlinks over a place: single ones are cut to the brightest few, then the list to the passes a // person would notice (bright and high), kept in time order. function _asTrim(list) { var d = _as.data; var lone = list.filter(function (p) { return AS_GROUPS[d.group[p.i]] === 'starlink' && p.members.length < AS_TRAIN_MIN; }) .sort(function (u, v) { return u.mag - v.mag; }).slice(AS_PASS_LONE_STARLINKS); var kept = list.filter(function (p) { return lone.indexOf(p) < 0; }); if (kept.length <= AS_PASS_MAX) return kept; var worth = function (p) { return p.mag - p.el / AS_PASS_EL_WEIGHT_DEG; }; var keep = kept.slice().sort(function (u, v) { return worth(u) - worth(v); }).slice(0, AS_PASS_MAX); return kept.filter(function (p) { return keep.indexOf(p) >= 0; }); } // ── The sky seen from a place, for any scene that draws one ── // _asSkyAsk is asked at the worker's pace (about once a second, off the main thread); _asSkyAt is called every frame on // what it answered and costs a multiply per satellite. Each entry: {i, norad, name, az, el, mag, azRate, elRate} with // az and el in degrees at tMs; every one is above the horizon and sunlit, the ISS included. var AS_SKY_MAG = AE_SATS_REF.skyMag, AS_SKY_MAX = 60, AS_SKY_LOOK_AHEAD_MS = 2000; function _asSkyAsk(lat, lon, tMs) { if (_as.state !== 'ready') return Promise.resolve({ t: tMs, list: [] }); var c = _asSeenFrom(); return _asAsk({ cmd: 'sky', lat: lat, lon: lon, t: tMs, dt: AS_SKY_LOOK_AHEAD_MS, minEl: 0, sunAlt: AS_PASS_SUN_ALT, magLimit: AS_SKY_MAG, max: AS_SKY_MAX, cand: c.cand, area: c.area, altKm: c.altKm, inc: c.inc }).then(function (r) { var d = _as.data; return { t: tMs, sunAlt: r.sunAlt, list: r.list.map(function (e) { return Object.assign({ norad: d.norad[e.i], name: d.name[e.i] }, e); }) }; }); } // ── The same sky in Stand here ── // While the layer is on, the satellites over the stand place are drawn in the ground view's sky (almanac-stand.js // _osSkySource): the station and what a dark sky shows, with a short trail each, and Starlinks of one launch that are // over together as a train. A tap names them. var AS_TRAIN_SKY_MIN = 3, AS_TRAIN_SKY_DEG = 25; var AS_GPS_MAG = 2; // a ring, not a point of light: the number only keeps it past the sky's limit var AS_SKY_TAIL = { steps: 3, stepS: 1.5, fade: 1.6 }; // a satellite's tail: three steps of a second and a half (4.5 s), each dimmer by this many magnitudes var AS_SKY_TAIL_BRIGHT = { mag: 0, steps: 6, stepS: 3, fade: 0.8 }; // the brightest (the station's class, brighter than this) keep a longer, brighter one var AS_SKY_RGB = { iss: [1, 0.95, 0.85] }; function _asStandSkyObjects(answer, tMs) { var d = _as.data, live = _asSkyAt(answer, tMs), launches = {}; live.forEach(function (e) { if (AS_GROUPS[d.group[e.i]] === 'starlink' && d.launch[e.i] >= 0) (launches[d.launch[e.i]] = launches[d.launch[e.i]] || []).push(e); }); var train = {}; Object.keys(launches).forEach(function (k) { var g = launches[k]; // together: every member within a few tens of degrees of the first g = g.filter(function (e) { return Math.abs(e.az - g[0].az) % 360 < AS_TRAIN_SKY_DEG || Math.abs(e.az - g[0].az) % 360 > 360 - AS_TRAIN_SKY_DEG; }); if (g.length >= AS_TRAIN_SKY_MIN) g.forEach(function (e) { train[e.i] = g.length; }); }); var stationDrawn = !!(_ae && _ae.sats && _ae.sats.lib && _ae.sats.list.some(function (q) { return q.iss; })); // the ground view draws the station itself when the Earth's own satellites are loaded var rings = _asGpsOn() ? _asGpsNow(tMs).map(function (g) { return { kind: 'gps', name: g.name, az: g.az, el: g.el, mag: AS_GPS_MAG }; }) : []; return rings.concat(live.map(function (e) { var tail = e.mag < AS_SKY_TAIL_BRIGHT.mag ? AS_SKY_TAIL_BRIGHT : AS_SKY_TAIL, trail = []; for (var k = 1; k <= tail.steps; k++) { var back = -k * tail.stepS, el = e.el + e.elRate * back; if (el < 0) break; trail.push({ az: (((e.az + e.azRate * back) % 360) + 360) % 360, el: el, mag: e.mag + k * tail.fade }); } var inTrain = train[e.i], iss = d.norad[e.i] === AS_ISS_NORAD; return { az: e.az, el: e.el, mag: e.mag, kind: inTrain ? 'train' : 'sat', trail: trail, rgb: iss ? AS_SKY_RGB.iss : undefined, name: iss && stationDrawn ? undefined : inTrain ? _aeT('alm_sats_train', { n: inTrain }) + ' · ' + e.name : e.name // the station's name is the ground view's own }; })); } var _asStandSkyOff = function () {}; function _asStandSkySync() { var want = _as.on && _as.state === 'ready' && typeof _osSkySource === 'function'; if (want && _asStandSkyOff.registered !== _as.data) { _asStandSkyOff(); var off = _osSkySource({ ask: _asSkyAsk, at: _asStandSkyObjects }); _asStandSkyOff = function () { off(); _asStandSkyOff = function () {}; }; _asStandSkyOff.registered = _as.data; } else if (!want) _asStandSkyOff(); } // An answer of _asSkyAsk carried to tMs: positions moved by their rates, those that have set dropped. function _asSkyAt(answer, tMs) { var dt = (tMs - answer.t) / 1000, out = []; answer.list.forEach(function (e) { var el = e.el + e.elRate * dt; if (el < 0) return; out.push(Object.assign({}, e, { az: (((e.az + e.azRate * dt) % 360) + 360) % 360, el: el })); }); return out; } var AS_ARROWS = ['↑', '↗', '→', '↘', '↓', '↙', '←', '↖']; function _asArrow(az) { return AS_ARROWS[Math.round(az / 45) % 8]; } // The zone the Almanac's clock shows (almanac.js _almClockParts): the place's when it is not the device's. var AS_TIME_OPTS = { hour: 'numeric', minute: '2-digit' }, AS_DAY_OPTS = { year: 'numeric', month: 'numeric', day: 'numeric' }, AS_WEEKDAY_OPTS = { weekday: 'short' }; function _asZone(ms) { return _almClockParts(new Date(ms)).tzId; } function _asTimeText(ms, tz) { return _tzFmt(tz, AS_TIME_OPTS).format(new Date(ms)); } function _asDayText(ms, tz) { var a = new Date(ms); if (_tzFmt(tz, AS_DAY_OPTS).format(a) === _tzFmt(tz, AS_DAY_OPTS).format(new Date())) return ''; return _tzFmt(tz, AS_WEEKDAY_OPTS).format(a) + ' '; } function _asRenderSheet() { var el = _as.sheetEl; if (!el || el.hidden) return; var d = _as.data, now = Date.now(), tz = _asZone(now); var html = '

' + _almEsc(_aeT('alm_sats_passes')) + ' · ' + _almEsc(_formatTimezone(null, tz, new Date(now))) + '

'; var gps = _asGpsNow(); html += '
' + _almEsc(_aeT('alm_sats_gps_overhead')) + ' · ' + gps.length + '' + '
'; var list = (_as.passes || []).filter(function (p) { return p.end > now; }); if (!_as.passes) html += '

…

'; else if (!list.length) html += '

' + _almEsc(_aeT('alm_sats_no_passes')) + '

'; list.forEach(function (p) { var name = p.members.length >= AS_TRAIN_MIN ? _aeT('alm_sats_train', { n: p.members.length }) : d.name[p.i]; html += ''; }); html += '

' + _almEsc(_aeT('alm_sats_mag_note')) + '

'; el.innerHTML = html; _aeById('as-x').onclick = _asCloseSheet; _aeById('as-gps-btn').onclick = function () { try { localStorage.setItem(AS_GPS_KEY, _asGpsOn() ? '' : AS_ON); } catch (e) {} if (_asGpsOn() === false) try { localStorage.removeItem(AS_GPS_KEY); } catch (e) {} this.setAttribute('aria-pressed', String(_asGpsOn())); _skyKickNow(); }; Array.prototype.forEach.call(el.querySelectorAll('.as-pass'), function (b) { b.onclick = function () { _asSelect(Number(b.getAttribute('data-i'))); _asCloseSheet(); }; }); } function _asToggleSheet() { if (_as.sheet) _asCloseSheet(); else _asOpenSheet(); } function _asOpenSheet() { var host = _aeDrawerHost() || _aeById('ae-view') || (_ae && _ae.el); if (!host) return; if (typeof _aeDrawerClaim === 'function') _aeDrawerClaim('sats'); if (!_as.sheetEl) { _as.sheetEl = document.createElement('div'); _as.sheetEl.className = 'as-sheet'; _as.sheetEl.setAttribute('role', 'group'); _as.sheetEl.setAttribute('aria-label', _aeT('alm_sats_passes')); host.appendChild(_as.sheetEl); } _as.sheet = true; _as.sheetEl.hidden = false; _asDrawerSync(); var b = _aeById('as-passes'); if (b) b.setAttribute('aria-pressed', 'true'); _asSelect(-1); _asNeedPasses(); _asRenderSheet(); } function _asCloseSheet() { _as.sheet = false; if (_as.sheetEl) _as.sheetEl.hidden = true; var b = _aeById('as-passes'); if (b) b.setAttribute('aria-pressed', 'false'); _asDrawerSync(); } // The filters and the passes live in the one drawer under the band (almanac-earth.js _aeDrawerSync shows it while a child is up). function _asDrawerSync() { if (typeof _aeDrawerSync === 'function') _aeDrawerSync(); } // The filters put away (the drawer opening on the settings, or shutting). function _asShutBar() { if (!_as.barOpen && !_asBarUp()) return; _as.barOpen = false; _asSyncBar(); } // ── Overhead now, and in the live sky ── // The GPS satellites above the horizon of the person's place, from the elements the view already holds. function _asLook(posKm, ms, place) { var th = _asGmst(ms) + place.lon * Math.PI / 180, lat = place.lat * Math.PI / 180; var sl = Math.sin(lat), cl = Math.cos(lat), st = Math.sin(th), ct = Math.cos(th); var A = 6378.137, f = 1 / 298.257223563, e2 = f * (2 - f), n0 = A / Math.sqrt(1 - e2 * sl * sl); var ox = n0 * cl * ct, oy = n0 * cl * st, oz = n0 * (1 - e2) * sl; var rx = posKm.x - ox, ry = posKm.y - oy, rz = posKm.z - oz, range = Math.hypot(rx, ry, rz); var up = rx * cl * ct + ry * cl * st + rz * sl, east = -rx * st + ry * ct, north = -rx * sl * ct - ry * sl * st + rz * cl; return { el: Math.asin(up / range) * 180 / Math.PI, az: (Math.atan2(east, north) * 180 / Math.PI + 360) % 360, range: range }; } function _asGmst(ms) { var n = ms / MS_PER_DAY + 2440587.5 - 2451545.0; return (((18.697374558 + 24.06570982441908 * n) % 24 + 24) % 24) * 15 * Math.PI / 180; } function _asGpsNow(ms, place) { place = place || _asPlace(); ms = ms || Date.now(); if (!place || !_ae || !_ae.sats) return []; var out = []; _ae.sats.list.forEach(function (s) { if (s.iss) return; var st = _aeSatAt(s, ms, 0); if (!st) return; var lk = _asLook(st.posKm, ms, place); if (lk.el >= AS_GPS_MIN_EL) out.push({ name: _aeSatShortName(s), el: lk.el, az: lk.az }); }); return out; } function _skyKickNow() { if (typeof _skyKick === 'function' && typeof _skyState !== 'undefined' && _skyState) _skyKick(); } // The live sky asks for the passes of its place while the layer is on (the sheet lists them); what is in the sky now is drawn by // almanac-onesky.js _osPaintObjects from the registry's objects (_asStandSkyObjects). function _asSkyPrime(s) { if (!_as.on || _as.state !== 'ready') return; _asNeedPasses({ lat: s.lat, lon: s.lon }); }