@johnmorrisdotca/chikyu-earth 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0 - 2026-11-03
4
+
5
+ The demo's elements refresh by themselves, every satellite shows its age, and you can bring your own source (MODULES-261, steps 3 and 4).
6
+
7
+ - **A scheduled build refreshes the demo's element files every six hours** (`.github/workflows/pages.yml`, `scripts/elements.ts fetch`): one download of each of CelesTrak's 13 lists and 5 single satellites, a six-second pause between asks, a user agent that names the repository and a contact, a list not asked for again within 110 minutes, and a stop at the first answer that is not 200 (CelesTrak's rules for software, read 2026-11-03), keeping every other group's last file. A push carries over the files already on the live site and asks CelesTrak for nothing. A check refuses to publish a set with an empty or missing group or one older than 30 days. No server runs per view: the browser reads files on Pages. The embed page reads the same files, and takes any group (`&satellites=gps,weather`).
8
+ - **Age and dimming.** The page says how long ago the files were downloaded and each satellite's age. A satellite whose elements are more than 14 days from the time shown is placed but drawn dimmer (`createSatellites` option `dimAfterDays`, `Satellites.dimmed` and `dimVersion`, `DEFAULT_DIM_AFTER_DAYS`), and the page says why (its place is less exact); one more than 30 days away is left out. **`DEFAULT_MAX_AGE_DAYS` is now 30** (it was 14, where the satellite was left out): the 14 days is the dimming now. Still one instanced draw for a group, and the dimming costs one number a satellite, copied to the graphics card only when one changes.
9
+ - **Tests on recorded and made-up elements, never a live request.** The browser tests are served the recorded stations and Starlink of 2026-11-02 (`test/recorded/`, `e2e/recorded.ts`) so no position moves as the demo's files are refreshed; the file maker, the polite downloader (a made-up CelesTrak that answers 200, then 403), the age check and the dimming are unit-tested (`test/elements.test.ts`, `test/satellites.test.ts`), and the demo's dimming and notes in `e2e/groups.gl.ts`.
10
+ - **`fetchElements(url, options)`** (`@johnmorrisdotca/chikyu-earth/satellites`) asks an address you choose, in the visitor's browser, for OMM JSON, OMM CSV or TLE text and returns element sets for `createSatellites`, with `skipped` (what it left out, and why), `retrievedAt` and `fromCache`. It has no address of its own, and it is polite by design: https only (http on localhost), no cookies or referrer, no redirects; the same address is not asked again within two hours (the answer already read is returned from the page or from `localStorage`); any answer that is not 200, or none, leaves the address alone for an hour and throws an **`ElementSourceError`** (`status`, `retryAt`), using the answer already read meanwhile; at most 20 million bytes and 50,000 sets. `forgetElements()` is for tests.
11
+ - **`parseElements(text)`** reads the three formats with no request (so it runs on a server): OMM JSON (an array or one object, numbers as numbers or text), OMM CSV (quoted names) and TLE (two lines or three, checksums checked, the epoch, the implied decimals and the designator turned into OMM's fields); a TLE read this way flies to within half a kilometre of the OMM it was written from.
12
+ - **The demo has "Your own source"**: paste an address, press Load; the satellites become a "Yours" group you can show, find by name and ride. Nothing is asked until the visitor presses the button (an address in the page's own address only fills the box). It says how many were read and from where, what was left out and why, whether the answer was just asked for or kept (and for how long it will not be asked again), or why it could not be used. English and Japanese.
13
+ - Tests: made-up fetch and made-up TLE with real checksums (`test/source.test.ts`); in the browser a made-up address that the test serves, a refusal, something that is not elements and an http address, with a check that the page asked nothing else (`e2e/groups.gl.ts`).
14
+
3
15
  ## 0.12.0 - 2026-11-03
4
16
 
5
17
  More satellites to follow and ride (MODULES-261, steps 1 and 2): where the data may come from, a curated catalogue, and fourteen groups in the demo.
@@ -8,7 +20,7 @@ More satellites to follow and ride (MODULES-261, steps 1 and 2): where the data
8
20
  - **A curated catalogue** in `@johnmorrisdotca/chikyu-earth/satellites`: `SATELLITE_GROUPS` (fourteen groups: stations, famous, science, Earth observation, weather, geostationary, GPS, GLONASS, Galileo, BeiDou, amateur radio, OneWeb, Iridium, Starlink, each with its CelesTrak list or catalogue numbers, an orbit kind, whether it sits still, and a line in English and Japanese), `CATALOGUE` (about forty satellites by NORAD number, from the ISS and Tiangong to Hubble and Vanguard 1, the oldest satellite still in orbit, each with a line in English and Japanese), `findInCatalogue` and `catalogueEntry`. JWST is left out on purpose: it is not in Earth orbit. No elements in it.
9
21
  - **The demo's groups are buttons** (a coloured dot each; a group switched on says what it is, and the demo zooms out to a group that goes far from the Earth), with **Find** (a search box over the catalogue and the names of every satellite in the demo's files, plus ISS and Tiangong) and two new rides, **The chosen satellite** and **One from the last group**. The address keeps the groups (`sats=gps,weather`), the chosen satellite (`sat=<NORAD number>`) and the ride (`ride=chosen`). A chosen satellite shows its catalogue line beside its height, speed and age.
10
22
  - **`demo/elements/`** (demo site only): one file for each group, made from one download of each CelesTrak list on 2026-11-03, `manifest.json` and `index.json`; `scripts/elements.ts` makes them from downloaded lists and fetches nothing. Starlink stays at every fifth satellite (about 2,200 dots in one draw call); the others are whole (the geostationary list has 569).
11
- - **Moons that have left the view are let go even when nothing else is drawn.** The space view let go of a moon four seconds after it left the view, but only when the next draw happened; a view at rest draws nothing, so the moons of Jupiter and Saturn were kept (their shaders and pictures) until someone touched the view. It now asks for one more draw when the first of them is due. Test: `e2e/space.gl.ts`. This is why the space soak failed in CI on "programs" since 0.11.0 (the count was never growing: the moons kept after leaving the view made it differ from one moment to the next); the soak now also looks at the Earth, not at whichever body the walk left it on, before it counts.
23
+ - **Moons that have left the view are let go even when nothing else is drawn.** The space view let go of a moon four seconds after it left the view, but only when the next draw happened; a view at rest draws nothing, so the moons of Jupiter and Saturn were kept (their shaders and pictures) until someone touched the view. It now asks for one more draw when the first of them is due. Test: `e2e/space.gl.ts`. This is why the space soak failed in CI on "programs" since 0.11.0 (the count was never growing: the moons kept after leaving the view made it differ from one moment to the next); the soak now also looks at the Earth, on the day the view opened on (which moons of Saturn and Jupiter are in the view depends on the day), in sight and drawing, before it counts; the count came back to what it was in three of three local runs and the one-minute soak in CI.
12
24
  - Tests: the catalogue and the file maker (`test/catalogue.test.ts`, `test/elements.test.ts`) and the demo's groups, Find and Ride on **made-up** element files served in place of the demo's own, with a check that nothing is asked of any other site (`e2e/groups.gl.ts`).
13
25
 
14
26
  ## 0.11.0 - 2026-11-03
package/NOTICE.md CHANGED
@@ -50,7 +50,7 @@ bundle or ship it. The planets are drawn as plain colours, from no picture.
50
50
  Shashwat Kandadai and contributors), the page's own optional peer dependency: this package does not bundle or ship it.
51
51
 
52
52
  The demo's files `demo/elements/*.json` (the demo site only, not the npm package) hold element sets, one file for each of fourteen groups, from one download of each of CelesTrak's lists on 2026-11-03 (about 16:00 UTC), with every fifth
53
- Starlink satellite kept (2,231 of 11,155), within the same usage policy, credited the same way and with the same grey tier. `demo/celestrak-snapshot.json` below is the older snapshot of 2026-11-02 that the embed page and some tests still read. It holds element sets from **CelesTrak** (https://celestrak.org, T.S. Kelso), which serves the U.S. Space Force's
53
+ Starlink satellite kept (2,231 of 11,155), within the same usage policy, credited the same way and with the same grey tier. The files are refreshed by a scheduled build every six hours (`.github/workflows/pages.yml`, `scripts/elements.ts`), one download of each list each time, within the same policy; `test/recorded/celestrak-snapshot-2026-11-02.json` below is the older snapshot of 2026-11-02, kept only for the tests. It holds element sets from **CelesTrak** (https://celestrak.org, T.S. Kelso), which serves the U.S. Space Force's
54
54
  18th Space Defense Squadron's general-perturbation (GP) data and, for Starlink, SpaceX's own supplemental elements. It is one download of the `stations` list and one of the `starlink` list on 2026-11-02
55
55
  (about 17:07 UTC), within CelesTrak's usage policy (https://celestrak.org/usage-policy.php, read 2026-11-02: one download per update per list, nothing fetched at a visitor's request), with every fifth Starlink satellite
56
56
  kept (2,232 of 11,156), as numbers only. CelesTrak states no licence or credit rule for the data; it is credited on the demo page, and the demo shows the age of the elements. The tier is "grey" in John's
package/README.md CHANGED
@@ -157,7 +157,7 @@ computed in the browser by astronomy-engine (MIT), nothing is fetched. [docs/spa
157
157
 
158
158
  ## Satellites
159
159
 
160
- The ISS, a space station or thousands of Starlink satellites at the places SGP4 puts them for the date and time shown, on `<chikyu-space>`: a group is one draw call however many it holds, press one to get its name, height and speed, and its orbit is drawn. Chikyu fetches nothing: your page passes in orbital elements (CelesTrak's JSON, within its usage policy), and satellite.js (MIT, an optional peer) does the maths about once a second, with every frame between interpolated. A group is hidden while the clock runs faster than 60 times real time. A small catalogue (`SATELLITE_GROUPS`, `CATALOGUE`, `findInCatalogue`) names fourteen groups (stations, weather, GPS, Galileo, OneWeb and more) and about forty satellites worth following, with no elements in it. The guide has the rules for getting elements and the budget, each line tested: [satellites guide](docs/guides/satellites.md), [docs/satellites.md](docs/satellites.md).
160
+ The ISS, a space station or thousands of Starlink satellites at the places SGP4 puts them for the date and time shown, on `<chikyu-space>`: a group is one draw call however many it holds, press one to get its name, height and speed, and its orbit is drawn. Chikyu fetches nothing: your page passes in orbital elements (CelesTrak's JSON, within its usage policy), and satellite.js (MIT, an optional peer) does the maths about once a second, with every frame between interpolated. `fetchElements(url)` reads OMM JSON, CSV or TLE from an address you choose, politely (https, not again within two hours, stop on any answer that is not 200). A satellite whose elements are more than 14 days from the time shown is drawn dimmer, and one more than 30 days away is left out. A group is hidden while the clock runs faster than 60 times real time. A small catalogue (`SATELLITE_GROUPS`, `CATALOGUE`, `findInCatalogue`) names fourteen groups (stations, weather, GPS, Galileo, OneWeb and more) and about forty satellites worth following, with no elements in it. The guide has the rules for getting elements and the budget, each line tested: [satellites guide](docs/guides/satellites.md), [docs/satellites.md](docs/satellites.md).
161
161
 
162
162
  <p align="center"><img alt="The ISS, ringed, over South Africa on 3 November 2026, with its orbit and the stations' orbits" src="docs/images/space-sat-iss.png" width="420"></p>
163
163
 
@@ -1,4 +1,5 @@
1
1
  export { createSatellites, type SatellitesOptions } from "./track.ts";
2
- export { DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.ts";
2
+ export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.ts";
3
3
  export type { ElementSet, RefusedElementSet, SatelliteInfo, SatelliteRef, Satellites } from "./types.ts";
4
4
  export { CATALOGUE, SATELLITE_GROUPS, catalogueEntry, findInCatalogue, type CatalogueEntry, type OrbitKind, type SatelliteGroupInfo } from "./catalogue.ts";
5
+ export { ElementSourceError, fetchElements, forgetElements, parseElements, type ElementFormat, type ElementSource, type FetchElementsOptions, type ParsedElements } from "./source.ts";
@@ -1,4 +1,5 @@
1
1
  // The satellites' pure parts: orbital elements in, positions out (SGP4 by satellite.js, an optional peer). They import on a server. The space view takes a group with `setSatellites`.
2
2
  export { createSatellites } from "./track.js";
3
- export { DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.js";
3
+ export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.js";
4
4
  export { CATALOGUE, SATELLITE_GROUPS, catalogueEntry, findInCatalogue } from "./catalogue.js";
5
+ export { ElementSourceError, fetchElements, forgetElements, parseElements } from "./source.js";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * How old, in days, an element set may be at the moment shown before the satellite is left out: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust.
2
+ * How old, in days, an element set may be at the moment shown before the satellite is left out altogether (30 by default). Between `DEFAULT_DIM_AFTER_DAYS` and this the satellite is still placed, but drawn dimmer, because SGP4's error grows by a few kilometres a day.
3
3
  *
4
4
  * @example
5
5
  * ```ts
@@ -8,7 +8,18 @@
8
8
  * console.log(DEFAULT_MAX_AGE_DAYS);
9
9
  * ```
10
10
  */
11
- export declare const DEFAULT_MAX_AGE_DAYS = 14;
11
+ export declare const DEFAULT_MAX_AGE_DAYS = 30;
12
+ /**
13
+ * How old, in days, an element set may be at the moment shown before the satellite is drawn dimmer to say its place is less exact: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust it fully.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { DEFAULT_DIM_AFTER_DAYS } from "@johnmorrisdotca/chikyu-earth/satellites";
18
+ *
19
+ * console.log(DEFAULT_DIM_AFTER_DAYS);
20
+ * ```
21
+ */
22
+ export declare const DEFAULT_DIM_AFTER_DAYS = 14;
12
23
  /**
13
24
  * The fastest clock, in game seconds a second, at which the space view still places a group of satellites: above it the two moments SGP4 is run at would be too far apart to interpolate, so the group is hidden rather than drawn wrongly. A satellite that was chosen with `selectSatellite` or ridden along is still placed exactly, one SGP4 call a frame.
14
25
  *
@@ -1,6 +1,6 @@
1
1
  // The satellites' two limits, apart from the SGP4 code so the space view can read them without needing satellite.js.
2
2
  /**
3
- * How old, in days, an element set may be at the moment shown before the satellite is left out: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust.
3
+ * How old, in days, an element set may be at the moment shown before the satellite is left out altogether (30 by default). Between `DEFAULT_DIM_AFTER_DAYS` and this the satellite is still placed, but drawn dimmer, because SGP4's error grows by a few kilometres a day.
4
4
  *
5
5
  * @example
6
6
  * ```ts
@@ -9,7 +9,18 @@
9
9
  * console.log(DEFAULT_MAX_AGE_DAYS);
10
10
  * ```
11
11
  */
12
- export const DEFAULT_MAX_AGE_DAYS = 14;
12
+ export const DEFAULT_MAX_AGE_DAYS = 30;
13
+ /**
14
+ * How old, in days, an element set may be at the moment shown before the satellite is drawn dimmer to say its place is less exact: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust it fully.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { DEFAULT_DIM_AFTER_DAYS } from "@johnmorrisdotca/chikyu-earth/satellites";
19
+ *
20
+ * console.log(DEFAULT_DIM_AFTER_DAYS);
21
+ * ```
22
+ */
23
+ export const DEFAULT_DIM_AFTER_DAYS = 14;
13
24
  /**
14
25
  * The fastest clock, in game seconds a second, at which the space view still places a group of satellites: above it the two moments SGP4 is run at would be too far apart to interpolate, so the group is hidden rather than drawn wrongly. A satellite that was chosen with `selectSatellite` or ridden along is still placed exactly, one SGP4 call a frame.
15
26
  *
@@ -0,0 +1,155 @@
1
+ import type { ElementSet } from "./types.ts";
2
+ /**
3
+ * The text formats `parseElements` reads: CCSDS OMM as JSON (what CelesTrak's `FORMAT=json` and Space-Track's JSON serve), the same as CSV (CelesTrak's default), and two- or three-line TLE text.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { ElementFormat } from "@johnmorrisdotca/chikyu-earth/satellites";
8
+ *
9
+ * const format: ElementFormat = "tle";
10
+ * console.log(format);
11
+ * ```
12
+ */
13
+ export type ElementFormat = "omm-json" | "omm-csv" | "tle";
14
+ /**
15
+ * What `parseElements` found: the element sets that can be used, and the ones it left out with the reason.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import type { ParsedElements } from "@johnmorrisdotca/chikyu-earth/satellites";
20
+ *
21
+ * const count = (parsed: ParsedElements): number => parsed.sets.length;
22
+ * console.log(typeof count);
23
+ * ```
24
+ */
25
+ export interface ParsedElements {
26
+ format: ElementFormat;
27
+ sets: ElementSet[];
28
+ skipped: {
29
+ name: string;
30
+ reason: string;
31
+ }[];
32
+ }
33
+ /**
34
+ * Read element sets from text: OMM as JSON (an array or a single object), OMM as CSV (a header row, then one satellite a row) or TLE (two lines, or three with the name first). The format is found from the text.
35
+ * An element set that is missing a number, has a wrong TLE checksum or is not a possible orbit is left out, with the reason, in `skipped`. It throws if the text is none of the three.
36
+ *
37
+ * @param text - What the source answered.
38
+ * @returns The element sets that can be used and the ones that cannot.
39
+ * @example
40
+ * ```js
41
+ * import { parseElements } from "@johnmorrisdotca/chikyu-earth/satellites";
42
+ *
43
+ * const csv = [
44
+ * "OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,NORAD_CAT_ID,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT",
45
+ * "MADE-UP 1,2026-001A,2026-11-03T12:00:00,15.2,0.0002,53,10,90,20,900001,0.0001,0.00001,0",
46
+ * ].join("\n");
47
+ * const { sets, format } = parseElements(csv);
48
+ * console.log(format, sets.length, sets[0].OBJECT_NAME);
49
+ * ```
50
+ */
51
+ export declare function parseElements(text: string): ParsedElements;
52
+ /**
53
+ * Why a source could not be used: the address was refused before any request, the source answered something other than 200 (and will not be asked again for a while), the answer was too big, or it could not be read.
54
+ *
55
+ * @param message - What went wrong, in a sentence.
56
+ * @param details - The HTTP status the source answered and when it may be asked again, when they are known.
57
+ * @example
58
+ * ```ts
59
+ * import { ElementSourceError } from "@johnmorrisdotca/chikyu-earth/satellites";
60
+ *
61
+ * const error = new ElementSourceError("refused", { status: 403 });
62
+ * console.log(error.status);
63
+ * ```
64
+ */
65
+ export declare class ElementSourceError extends Error {
66
+ /** The HTTP status the source answered, when it answered. */
67
+ readonly status: number | undefined;
68
+ /** When, in milliseconds since the Unix epoch, the source may be asked again (it is not asked before). */
69
+ readonly retryAt: number | undefined;
70
+ constructor(message: string, details?: {
71
+ status?: number;
72
+ retryAt?: number;
73
+ });
74
+ }
75
+ /**
76
+ * What `fetchElements` can be told. Every one has a safe default.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * import type { FetchElementsOptions } from "@johnmorrisdotca/chikyu-earth/satellites";
81
+ *
82
+ * const options: FetchElementsOptions = { minIntervalMs: 3 * 3_600_000 };
83
+ * console.log(options.minIntervalMs);
84
+ * ```
85
+ */
86
+ export interface FetchElementsOptions {
87
+ /** The shortest time between two requests to the same address; within it the answer already read is returned (2 hours by default: CelesTrak's elements change every 2 hours and it asks for one download an update). */
88
+ minIntervalMs?: number;
89
+ /** How long a source that answered anything but 200 (or did not answer) is left alone (1 hour by default). */
90
+ blockedMs?: number;
91
+ /** The most bytes of answer read (20 million by default). */
92
+ maxBytes?: number;
93
+ /** The most element sets kept (50,000 by default). */
94
+ maxSets?: number;
95
+ /** Where answers and refusals are kept between page loads: `localStorage` by default where there is one; `null` keeps them for this page only. */
96
+ store?: Pick<Storage, "getItem" | "setItem" | "removeItem"> | null;
97
+ /** The fetch function (the browser's by default). */
98
+ fetch?: typeof fetch;
99
+ /** The time, in milliseconds since the Unix epoch (`Date.now` by default). */
100
+ now?: () => number;
101
+ signal?: AbortSignal;
102
+ }
103
+ /**
104
+ * Element sets read from a source: where from, when, and whether this answer was kept from earlier rather than asked for now.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * import type { ElementSource } from "@johnmorrisdotca/chikyu-earth/satellites";
109
+ *
110
+ * const describe = (source: ElementSource): string => `${source.sets.length} from ${source.url}, ${source.fromCache ? "kept" : "new"}`;
111
+ * console.log(typeof describe);
112
+ * ```
113
+ */
114
+ export interface ElementSource extends ParsedElements {
115
+ url: string;
116
+ /** When the source was asked, in milliseconds since the Unix epoch. */
117
+ retrievedAt: number;
118
+ fromCache: boolean;
119
+ }
120
+ /**
121
+ * Forget what `fetchElements` kept in this page and which sources it is leaving alone: for a test. It does not clear `localStorage`, and a page that asks again at once is asking against the source's rules.
122
+ *
123
+ * @returns Nothing.
124
+ * @example
125
+ * ```ts
126
+ * import { forgetElements } from "@johnmorrisdotca/chikyu-earth/satellites";
127
+ *
128
+ * forgetElements();
129
+ * console.log("forgotten");
130
+ * ```
131
+ */
132
+ export declare function forgetElements(): void;
133
+ /**
134
+ * Ask a source of your own choosing for element sets, in the visitor's browser, and read them. The package has no address of its own: you pass one, and you are the one to read that source's terms
135
+ * (docs/satellite-sources.md has what CelesTrak, Space-Track and others say). It is polite by design:
136
+ * - only `https` (or `http` on `localhost`), with no cookies and no referrer sent;
137
+ * - the same address is not asked again within `minIntervalMs` (2 hours): the answer already read is returned, from this page or from `localStorage`;
138
+ * - any answer that is not 200, or no answer, stops the asking: the address is left alone for `blockedMs` (1 hour) and a `ElementSourceError` with the status says so (the answer already read, if there is one, is returned instead);
139
+ * - an answer over `maxBytes` or `maxSets` is refused.
140
+ * The source must send the headers a browser needs to let a page read it (CORS); one that does not cannot be read from a page, and no workaround is made here.
141
+ *
142
+ * @param url - The address of OMM JSON, OMM CSV or TLE text.
143
+ * @param options - See `FetchElementsOptions`.
144
+ * @returns The element sets, ready for `createSatellites`, with where and when they came from.
145
+ * @example
146
+ * ```ts no-run
147
+ * import { createSatellites, fetchElements } from "@johnmorrisdotca/chikyu-earth/satellites";
148
+ *
149
+ * // An address you chose, whose terms you have read. This one answers made-up elements.
150
+ * const source = await fetchElements("https://example.org/my-elements.json");
151
+ * const group = createSatellites(source.sets);
152
+ * console.log(group.count, source.skipped.length, source.fromCache);
153
+ * ```
154
+ */
155
+ export declare function fetchElements(url: string, options?: FetchElementsOptions): Promise<ElementSource>;
@@ -0,0 +1,383 @@
1
+ const NUMBERS = ["MEAN_MOTION", "ECCENTRICITY", "INCLINATION", "RA_OF_ASC_NODE", "ARG_OF_PERICENTER", "MEAN_ANOMALY", "NORAD_CAT_ID", "BSTAR", "MEAN_MOTION_DOT", "MEAN_MOTION_DDOT"];
2
+ const OPTIONAL_NUMBERS = ["EPHEMERIS_TYPE", "ELEMENT_SET_NO", "REV_AT_EPOCH"];
3
+ /** A record with the fields of an OMM, from text or numbers, or the reason it is not one. */
4
+ function toElementSet(record) {
5
+ const out = {};
6
+ const name = typeof record["OBJECT_NAME"] === "string" ? record["OBJECT_NAME"].trim() : "";
7
+ out["OBJECT_NAME"] = name || `NORAD ${String(record["NORAD_CAT_ID"] ?? "?")}`;
8
+ if (typeof record["OBJECT_ID"] === "string" && record["OBJECT_ID"])
9
+ out["OBJECT_ID"] = record["OBJECT_ID"];
10
+ if (typeof record["CLASSIFICATION_TYPE"] === "string" && record["CLASSIFICATION_TYPE"])
11
+ out["CLASSIFICATION_TYPE"] = record["CLASSIFICATION_TYPE"];
12
+ const epoch = record["EPOCH"];
13
+ if (typeof epoch !== "string" || !Number.isFinite(Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(epoch) ? epoch : `${epoch}Z`)))
14
+ return "the epoch is missing or is not a date";
15
+ out["EPOCH"] = epoch;
16
+ for (const key of NUMBERS) {
17
+ const value = typeof record[key] === "string" && record[key].trim() !== "" ? Number(record[key]) : record[key];
18
+ if (typeof value !== "number" || !Number.isFinite(value))
19
+ return `${key} is missing or is not a number`;
20
+ out[key] = value;
21
+ }
22
+ for (const key of OPTIONAL_NUMBERS) {
23
+ const value = typeof record[key] === "string" && record[key].trim() !== "" ? Number(record[key]) : record[key];
24
+ if (typeof value === "number" && Number.isFinite(value))
25
+ out[key] = value;
26
+ }
27
+ if (out["MEAN_MOTION"] <= 0)
28
+ return "MEAN_MOTION must be above zero";
29
+ if (out["ECCENTRICITY"] < 0 || out["ECCENTRICITY"] >= 1)
30
+ return "ECCENTRICITY must be from 0 up to (not including) 1";
31
+ return out;
32
+ }
33
+ function fromRecords(records, format) {
34
+ const sets = [];
35
+ const skipped = [];
36
+ for (const record of records) {
37
+ if (record === null || typeof record !== "object" || Array.isArray(record)) {
38
+ skipped.push({ name: "?", reason: "not an object" });
39
+ continue;
40
+ }
41
+ const made = toElementSet(record);
42
+ if (typeof made === "string")
43
+ skipped.push({ name: String(record["OBJECT_NAME"] ?? "?"), reason: made });
44
+ else
45
+ sets.push(made);
46
+ }
47
+ return { format, sets, skipped };
48
+ }
49
+ /** The cells of one CSV line (a cell may be in double quotes, with `""` for a quote). */
50
+ function cellsOf(line) {
51
+ const cells = [];
52
+ let at = 0;
53
+ while (at <= line.length) {
54
+ if (line[at] === '"') {
55
+ let text = "";
56
+ at += 1;
57
+ while (at < line.length) {
58
+ if (line[at] === '"' && line[at + 1] === '"') {
59
+ text += '"';
60
+ at += 2;
61
+ }
62
+ else if (line[at] === '"') {
63
+ at += 1;
64
+ break;
65
+ }
66
+ else
67
+ text += line[at++];
68
+ }
69
+ cells.push(text);
70
+ at += 1;
71
+ }
72
+ else {
73
+ const next = line.indexOf(",", at);
74
+ const end = next < 0 ? line.length : next;
75
+ cells.push(line.slice(at, end));
76
+ at = end + 1;
77
+ }
78
+ }
79
+ return cells;
80
+ }
81
+ /** The checksum of a TLE line: the digits added, each minus sign counting one, modulo 10. */
82
+ const tleChecksum = (line) => {
83
+ let sum = 0;
84
+ for (const ch of line.slice(0, 68))
85
+ sum += ch >= "0" && ch <= "9" ? Number(ch) : ch === "-" ? 1 : 0;
86
+ return sum % 10;
87
+ };
88
+ /** `00000-0` style: a sign, five digits with the point before them, and an exponent. */
89
+ const implied = (text) => {
90
+ const t = text.trim();
91
+ const m = /^([+-]?)(\d+)([+-]\d)$/.exec(t.replace(/^ +/, ""));
92
+ if (!m)
93
+ return Number.NaN;
94
+ return (m[1] === "-" ? -1 : 1) * Number(`0.${m[2]}`) * 10 ** Number(m[3]);
95
+ };
96
+ function fromTle(text) {
97
+ const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, "")).filter((line) => line.trim() !== "");
98
+ const sets = [];
99
+ const skipped = [];
100
+ for (let i = 0; i < lines.length; i += 1) {
101
+ const one = lines[i];
102
+ if (!one.startsWith("1 "))
103
+ continue;
104
+ const two = lines[i + 1];
105
+ const named = i > 0 && !lines[i - 1].startsWith("1 ") && !lines[i - 1].startsWith("2 ") ? lines[i - 1].replace(/^0 /, "").trim() : "";
106
+ const id = Number(one.slice(2, 7));
107
+ const label = named || `NORAD ${id}`;
108
+ if (!two || !two.startsWith("2 ")) {
109
+ skipped.push({ name: label, reason: "the second line is missing" });
110
+ continue;
111
+ }
112
+ i += 1;
113
+ if (one.length < 69 || two.length < 69) {
114
+ skipped.push({ name: label, reason: "a line is shorter than 69 characters" });
115
+ continue;
116
+ }
117
+ if (tleChecksum(one) !== Number(one[68]) || tleChecksum(two) !== Number(two[68])) {
118
+ skipped.push({ name: label, reason: "a line's checksum is wrong" });
119
+ continue;
120
+ }
121
+ if (Number(two.slice(2, 7)) !== id) {
122
+ skipped.push({ name: label, reason: "the two lines are for different satellites" });
123
+ continue;
124
+ }
125
+ const yy = Number(one.slice(18, 20));
126
+ const year = yy < 57 ? 2000 + yy : 1900 + yy;
127
+ const day = Number(one.slice(20, 32));
128
+ const epoch = new Date(Date.UTC(year, 0, 1) + (day - 1) * 86_400_000).toISOString().replace("Z", "");
129
+ const designator = one.slice(9, 17).trim();
130
+ const dy = Number(designator.slice(0, 2));
131
+ const record = {
132
+ OBJECT_NAME: label,
133
+ OBJECT_ID: designator.length >= 5 && Number.isFinite(dy) ? `${dy < 57 ? 2000 + dy : 1900 + dy}-${designator.slice(2)}` : undefined,
134
+ EPOCH: epoch,
135
+ MEAN_MOTION: Number(two.slice(52, 63)),
136
+ ECCENTRICITY: Number(`0.${two.slice(26, 33).trim()}`),
137
+ INCLINATION: Number(two.slice(8, 16)),
138
+ RA_OF_ASC_NODE: Number(two.slice(17, 25)),
139
+ ARG_OF_PERICENTER: Number(two.slice(34, 42)),
140
+ MEAN_ANOMALY: Number(two.slice(43, 51)),
141
+ NORAD_CAT_ID: id,
142
+ BSTAR: implied(one.slice(53, 61)),
143
+ MEAN_MOTION_DOT: Number(one.slice(33, 43)),
144
+ MEAN_MOTION_DDOT: implied(one.slice(44, 52)),
145
+ CLASSIFICATION_TYPE: one[7],
146
+ EPHEMERIS_TYPE: Number(one[62]),
147
+ ELEMENT_SET_NO: Number(one.slice(64, 68)),
148
+ REV_AT_EPOCH: Number(two.slice(63, 68)),
149
+ };
150
+ const made = toElementSet(record);
151
+ if (typeof made === "string")
152
+ skipped.push({ name: label, reason: made });
153
+ else
154
+ sets.push(made);
155
+ }
156
+ return { format: "tle", sets, skipped };
157
+ }
158
+ /**
159
+ * Read element sets from text: OMM as JSON (an array or a single object), OMM as CSV (a header row, then one satellite a row) or TLE (two lines, or three with the name first). The format is found from the text.
160
+ * An element set that is missing a number, has a wrong TLE checksum or is not a possible orbit is left out, with the reason, in `skipped`. It throws if the text is none of the three.
161
+ *
162
+ * @param text - What the source answered.
163
+ * @returns The element sets that can be used and the ones that cannot.
164
+ * @example
165
+ * ```js
166
+ * import { parseElements } from "@johnmorrisdotca/chikyu-earth/satellites";
167
+ *
168
+ * const csv = [
169
+ * "OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,NORAD_CAT_ID,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT",
170
+ * "MADE-UP 1,2026-001A,2026-11-03T12:00:00,15.2,0.0002,53,10,90,20,900001,0.0001,0.00001,0",
171
+ * ].join("\n");
172
+ * const { sets, format } = parseElements(csv);
173
+ * console.log(format, sets.length, sets[0].OBJECT_NAME);
174
+ * ```
175
+ */
176
+ export function parseElements(text) {
177
+ const body = text.replace(/^\uFEFF/, "").trim();
178
+ if (body.startsWith("[") || body.startsWith("{")) {
179
+ let json;
180
+ try {
181
+ json = JSON.parse(body);
182
+ }
183
+ catch {
184
+ throw new Error("the text looks like JSON but is not");
185
+ }
186
+ return fromRecords(Array.isArray(json) ? json : [json], "omm-json");
187
+ }
188
+ const first = body.split(/\r?\n/, 1)[0] ?? "";
189
+ if (/OBJECT_NAME|NORAD_CAT_ID/.test(first) && first.includes(",")) {
190
+ const lines = body.split(/\r?\n/).filter((line) => line.trim() !== "");
191
+ const header = cellsOf(lines[0]).map((cell) => cell.trim());
192
+ return fromRecords(lines.slice(1).map((line) => Object.fromEntries(cellsOf(line).map((cell, index) => [header[index] ?? `#${index}`, cell]))), "omm-csv");
193
+ }
194
+ if (/^\s*(0 .*\n)?1 \d{5}/m.test(body) || /^1 \d{5}/m.test(body))
195
+ return fromTle(body);
196
+ throw new Error("the text is not OMM JSON, OMM CSV or TLE");
197
+ }
198
+ /**
199
+ * Why a source could not be used: the address was refused before any request, the source answered something other than 200 (and will not be asked again for a while), the answer was too big, or it could not be read.
200
+ *
201
+ * @param message - What went wrong, in a sentence.
202
+ * @param details - The HTTP status the source answered and when it may be asked again, when they are known.
203
+ * @example
204
+ * ```ts
205
+ * import { ElementSourceError } from "@johnmorrisdotca/chikyu-earth/satellites";
206
+ *
207
+ * const error = new ElementSourceError("refused", { status: 403 });
208
+ * console.log(error.status);
209
+ * ```
210
+ */
211
+ export class ElementSourceError extends Error {
212
+ /** The HTTP status the source answered, when it answered. */
213
+ status;
214
+ /** When, in milliseconds since the Unix epoch, the source may be asked again (it is not asked before). */
215
+ retryAt;
216
+ constructor(message, details = {}) {
217
+ super(message);
218
+ this.name = "ElementSourceError";
219
+ this.status = details.status;
220
+ this.retryAt = details.retryAt;
221
+ }
222
+ }
223
+ const memory = new Map();
224
+ const blocked = new Map();
225
+ const KEY = "chikyu-earth.elements.";
226
+ const MAX_STORED = 2_000_000;
227
+ const defaultStore = () => {
228
+ try {
229
+ return globalThis.localStorage ?? null;
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ };
235
+ /**
236
+ * Forget what `fetchElements` kept in this page and which sources it is leaving alone: for a test. It does not clear `localStorage`, and a page that asks again at once is asking against the source's rules.
237
+ *
238
+ * @returns Nothing.
239
+ * @example
240
+ * ```ts
241
+ * import { forgetElements } from "@johnmorrisdotca/chikyu-earth/satellites";
242
+ *
243
+ * forgetElements();
244
+ * console.log("forgotten");
245
+ * ```
246
+ */
247
+ export function forgetElements() {
248
+ memory.clear();
249
+ blocked.clear();
250
+ }
251
+ /**
252
+ * Ask a source of your own choosing for element sets, in the visitor's browser, and read them. The package has no address of its own: you pass one, and you are the one to read that source's terms
253
+ * (docs/satellite-sources.md has what CelesTrak, Space-Track and others say). It is polite by design:
254
+ * - only `https` (or `http` on `localhost`), with no cookies and no referrer sent;
255
+ * - the same address is not asked again within `minIntervalMs` (2 hours): the answer already read is returned, from this page or from `localStorage`;
256
+ * - any answer that is not 200, or no answer, stops the asking: the address is left alone for `blockedMs` (1 hour) and a `ElementSourceError` with the status says so (the answer already read, if there is one, is returned instead);
257
+ * - an answer over `maxBytes` or `maxSets` is refused.
258
+ * The source must send the headers a browser needs to let a page read it (CORS); one that does not cannot be read from a page, and no workaround is made here.
259
+ *
260
+ * @param url - The address of OMM JSON, OMM CSV or TLE text.
261
+ * @param options - See `FetchElementsOptions`.
262
+ * @returns The element sets, ready for `createSatellites`, with where and when they came from.
263
+ * @example
264
+ * ```ts no-run
265
+ * import { createSatellites, fetchElements } from "@johnmorrisdotca/chikyu-earth/satellites";
266
+ *
267
+ * // An address you chose, whose terms you have read. This one answers made-up elements.
268
+ * const source = await fetchElements("https://example.org/my-elements.json");
269
+ * const group = createSatellites(source.sets);
270
+ * console.log(group.count, source.skipped.length, source.fromCache);
271
+ * ```
272
+ */
273
+ export async function fetchElements(url, options = {}) {
274
+ const now = options.now ?? Date.now;
275
+ const minInterval = options.minIntervalMs ?? 2 * 3_600_000;
276
+ const blockedMs = options.blockedMs ?? 3_600_000;
277
+ const maxBytes = options.maxBytes ?? 20_000_000;
278
+ const maxSets = options.maxSets ?? 50_000;
279
+ const store = options.store === undefined ? defaultStore() : options.store;
280
+ let address;
281
+ try {
282
+ address = new URL(url);
283
+ }
284
+ catch {
285
+ throw new ElementSourceError("that is not an address");
286
+ }
287
+ const local = address.hostname === "localhost" || address.hostname === "127.0.0.1" || address.hostname === "[::1]";
288
+ if (address.protocol !== "https:" && !(address.protocol === "http:" && local))
289
+ throw new ElementSourceError("only https addresses are used (http only on localhost)");
290
+ const key = address.href;
291
+ const kept = () => {
292
+ const found = memory.get(key);
293
+ if (found)
294
+ return found;
295
+ try {
296
+ const text = store?.getItem(`${KEY}${key}`);
297
+ const at = Number(store?.getItem(`${KEY}${key}.at`));
298
+ if (text && Number.isFinite(at))
299
+ return { at, text };
300
+ }
301
+ catch {
302
+ // storage is not available: this page only
303
+ }
304
+ return undefined;
305
+ };
306
+ const useKept = (found) => {
307
+ const parsed = parseElements(found.text);
308
+ return { ...parsed, url: key, retrievedAt: found.at, fromCache: true };
309
+ };
310
+ const have = kept();
311
+ if (have && now() - have.at < minInterval)
312
+ return useKept(have);
313
+ let until = blocked.get(key) ?? 0;
314
+ try {
315
+ until = Math.max(until, Number(store?.getItem(`${KEY}${key}.until`)) || 0);
316
+ }
317
+ catch {
318
+ // storage is not available
319
+ }
320
+ if (until > now()) {
321
+ if (have)
322
+ return useKept(have);
323
+ throw new ElementSourceError("that source did not answer 200 a short while ago and is being left alone", { retryAt: until });
324
+ }
325
+ const stop = (message, status) => {
326
+ const retryAt = now() + blockedMs;
327
+ blocked.set(key, retryAt);
328
+ try {
329
+ store?.setItem(`${KEY}${key}.until`, String(retryAt));
330
+ }
331
+ catch {
332
+ // storage is full or not available
333
+ }
334
+ return new ElementSourceError(message, { status, retryAt });
335
+ };
336
+ const ask = options.fetch ?? globalThis.fetch;
337
+ let response;
338
+ try {
339
+ response = await ask(key, { method: "GET", credentials: "omit", referrerPolicy: "no-referrer", redirect: "error", signal: options.signal ?? null, headers: { accept: "application/json, text/csv, text/plain" } });
340
+ }
341
+ catch (error) {
342
+ if (options.signal?.aborted)
343
+ throw error;
344
+ if (have)
345
+ return useKept(have);
346
+ throw stop(`the source could not be reached: ${error instanceof Error ? error.message : "no answer"}`);
347
+ }
348
+ if (response.status !== 200) {
349
+ const blockedError = stop(`the source answered ${response.status}, so it is left alone for a while`, response.status);
350
+ if (have)
351
+ return useKept(have);
352
+ throw blockedError;
353
+ }
354
+ const declared = Number(response.headers.get("content-length"));
355
+ if (Number.isFinite(declared) && declared > maxBytes)
356
+ throw new ElementSourceError(`the answer is ${declared} bytes, over the ${maxBytes} allowed`, { status: 200 });
357
+ const text = await response.text();
358
+ if (text.length > maxBytes)
359
+ throw new ElementSourceError(`the answer is over the ${maxBytes} bytes allowed`, { status: 200 });
360
+ let parsed;
361
+ try {
362
+ parsed = parseElements(text);
363
+ }
364
+ catch (error) {
365
+ throw new ElementSourceError(error instanceof Error ? error.message : "the answer could not be read", { status: 200 });
366
+ }
367
+ if (parsed.sets.length > maxSets)
368
+ throw new ElementSourceError(`the answer has ${parsed.sets.length} element sets, over the ${maxSets} allowed`, { status: 200 });
369
+ const at = now();
370
+ memory.set(key, { at, text });
371
+ blocked.delete(key);
372
+ try {
373
+ if (text.length <= MAX_STORED) {
374
+ store?.setItem(`${KEY}${key}`, text);
375
+ store?.setItem(`${KEY}${key}.at`, String(at));
376
+ }
377
+ store?.removeItem(`${KEY}${key}.until`);
378
+ }
379
+ catch {
380
+ // storage is full or not available: this page only
381
+ }
382
+ return { ...parsed, url: key, retrievedAt: at, fromCache: false };
383
+ }
@@ -6,20 +6,22 @@ import type { ElementSet, Satellites } from "./types.ts";
6
6
  * ```ts
7
7
  * import type { SatellitesOptions } from "@johnmorrisdotca/chikyu-earth/satellites";
8
8
  *
9
- * const options: SatellitesOptions = { maxAgeDays: 7 };
9
+ * const options: SatellitesOptions = { dimAfterDays: 7, maxAgeDays: 21 };
10
10
  * console.log(options.maxAgeDays);
11
11
  * ```
12
12
  */
13
13
  export interface SatellitesOptions {
14
- /** The oldest an element set may be at the moment shown, in days (14 by default). */
14
+ /** The oldest an element set may be at the moment shown, in days, before the satellite is left out (30 by default). */
15
15
  maxAgeDays?: number;
16
+ /** The age, in days, past which a satellite is drawn dimmer because its place is less exact (14 by default). */
17
+ dimAfterDays?: number;
16
18
  }
17
19
  /**
18
20
  * Make a group of satellites from their element sets. Each starts SGP4 once here; one that does not (bad numbers, decayed at its own epoch) is listed in `refused` and left out.
19
21
  * It needs satellite.js (MIT, an optional peer dependency) and imports in a browser or on a server.
20
22
  *
21
23
  * @param sets - Element sets in CelesTrak's JSON format (`ElementSet`), fetched by your page.
22
- * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown.
24
+ * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown; `dimAfterDays`: the age past which it is drawn dimmer.
23
25
  * @returns The group: `at(ms, out)` for positions, `exact`, `orbit`, `info`, and counters.
24
26
  *
25
27
  * @example
@@ -1,7 +1,7 @@
1
1
  // SGP4 for a group of satellites, kept cheap: the whole group is run at two moments a step apart and every position in between is an interpolation, so the cost is one batch a step
2
2
  // (about once a second), never one a frame. satellite.js (MIT) does the SGP4 itself; this file never touches the screen and imports on a server.
3
3
  import { json2satrec, sgp4 } from "satellite.js";
4
- import { DEFAULT_MAX_AGE_DAYS } from "./limits.js";
4
+ import { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS } from "./limits.js";
5
5
  /** The Earth's mean radius in kilometres: the unit of every position here (the same as the space view's). */
6
6
  const EARTH_RADIUS_KM = 6371;
7
7
  const DAY_MS = 86_400_000;
@@ -13,7 +13,7 @@ const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text :
13
13
  * It needs satellite.js (MIT, an optional peer dependency) and imports in a browser or on a server.
14
14
  *
15
15
  * @param sets - Element sets in CelesTrak's JSON format (`ElementSet`), fetched by your page.
16
- * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown.
16
+ * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown; `dimAfterDays`: the age past which it is drawn dimmer.
17
17
  * @returns The group: `at(ms, out)` for positions, `exact`, `orbit`, `info`, and counters.
18
18
  *
19
19
  * @example
@@ -44,6 +44,8 @@ const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text :
44
44
  export function createSatellites(sets, options = {}) {
45
45
  const maxAgeDays = options.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS;
46
46
  const maxAgeMs = maxAgeDays * DAY_MS;
47
+ const dimAfterDays = options.dimAfterDays ?? DEFAULT_DIM_AFTER_DAYS;
48
+ const dimAfterMs = dimAfterDays * DAY_MS;
47
49
  const recs = [];
48
50
  const usable = [];
49
51
  const epochs = [];
@@ -76,6 +78,8 @@ export function createSatellites(sets, options = {}) {
76
78
  let okA = new Uint8Array(n);
77
79
  let okB = new Uint8Array(n);
78
80
  const shown = new Uint8Array(n);
81
+ const dimmed = new Float32Array(n);
82
+ let dimVersion = 0;
79
83
  let aMs = 0;
80
84
  let bMs = 0;
81
85
  let ready = false;
@@ -129,6 +133,11 @@ export function createSatellites(sets, options = {}) {
129
133
  sets: usable,
130
134
  refused,
131
135
  maxAgeDays,
136
+ dimAfterDays,
137
+ dimmed,
138
+ get dimVersion() {
139
+ return dimVersion;
140
+ },
132
141
  get propagations() {
133
142
  return propagations;
134
143
  },
@@ -173,6 +182,11 @@ export function createSatellites(sets, options = {}) {
173
182
  let count = 0;
174
183
  for (let i = 0; i < n; i += 1) {
175
184
  const k = i * 3;
185
+ const dim = Math.abs(ms - epochs[i]) > dimAfterMs ? 1 : 0;
186
+ if (dim !== dimmed[i]) {
187
+ dimmed[i] = dim;
188
+ dimVersion += 1;
189
+ }
176
190
  if (okA[i] === 1 && okB[i] === 1) {
177
191
  out[k] = a[k] + (b[k] - a[k]) * t;
178
192
  out[k + 1] = a[k + 1] + (b[k + 1] - a[k + 1]) * t;
@@ -115,7 +115,7 @@ export interface RefusedElementSet {
115
115
  /**
116
116
  * A group of satellites, ready to give positions for any moment: what `createSatellites` returns, and what `<chikyu-space>` takes in `setSatellites`.
117
117
  * Positions are in Earth radii (6371 km) from the Earth's centre, in the space view's axes (x to the vernal equinox, y north); a satellite whose elements
118
- * are older than `maxAgeDays` at the moment asked about is not placed (its place stays at the centre and `visible(index)` is false).
118
+ * are older than `maxAgeDays` at the moment asked about is not placed (its place stays at the centre and `visible(index)` is false); one older than `dimAfterDays` is placed and flagged in `dimmed`.
119
119
  *
120
120
  * @example
121
121
  * ```ts
@@ -134,6 +134,12 @@ export interface Satellites {
134
134
  readonly refused: readonly RefusedElementSet[];
135
135
  /** The oldest an element set may be at the moment shown, in days. */
136
136
  readonly maxAgeDays: number;
137
+ /** The age, in days, past which a satellite is drawn dimmer. */
138
+ readonly dimAfterDays: number;
139
+ /** One number for each satellite, set by `at`: 1 when its elements are more than `dimAfterDays` from the moment shown (draw it dimmer), 0 when not. */
140
+ readonly dimmed: Float32Array;
141
+ /** Goes up each time `at` changes any of `dimmed`, so a drawing can copy the numbers only when they changed. */
142
+ readonly dimVersion: number;
137
143
  /** SGP4 calls made so far, for a page or a test to count. */
138
144
  readonly propagations: number;
139
145
  /** Milliseconds the last batch of SGP4 took, and the longest so far. */
@@ -7,18 +7,22 @@ const ORBIT_REFRESH_GAME_MS = 30 * 60_000;
7
7
  const ORBIT_REFRESH_WALL_MS = 1000;
8
8
  const POINT_VERT = /* glsl */ `
9
9
  uniform float size;
10
+ attribute float dim;
11
+ varying float vDim;
10
12
  void main() {
13
+ vDim = dim;
11
14
  gl_PointSize = size;
12
15
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
13
16
  }`;
14
17
  const POINT_FRAG = /* glsl */ `
15
18
  uniform vec3 tint;
16
19
  uniform float ring;
20
+ varying float vDim;
17
21
  void main() {
18
22
  float d = length(gl_PointCoord - vec2(0.5));
19
23
  if (d > 0.5) discard;
20
24
  float a = ring > 0.5 ? smoothstep(0.30, 0.38, d) * (1.0 - smoothstep(0.44, 0.5, d)) : smoothstep(0.5, 0.2, d);
21
- gl_FragColor = vec4(tint, a);
25
+ gl_FragColor = vec4(tint, a * (1.0 - 0.7 * vDim));
22
26
  }`;
23
27
  export function createSatelliteLayer(three, scene, state, ratio) {
24
28
  if (!three.Points)
@@ -31,6 +35,7 @@ export function createSatelliteLayer(three, scene, state, ratio) {
31
35
  const selectedPosition = new Float32Array(3);
32
36
  const selectedGeometry = new three.BufferGeometry();
33
37
  selectedGeometry.setAttribute("position", new three.BufferAttribute(selectedPosition, 3));
38
+ selectedGeometry.setAttribute("dim", new three.BufferAttribute(new Float32Array(1), 1));
34
39
  const selectedPoints = new Points(selectedGeometry, selectedMaterial);
35
40
  selectedPoints.frustumCulled = false;
36
41
  selectedPoints.renderOrder = 6;
@@ -109,12 +114,14 @@ export function createSatelliteLayer(three, scene, state, ratio) {
109
114
  const geometry = new three.BufferGeometry();
110
115
  const attribute = new three.BufferAttribute(positions, 3);
111
116
  geometry.setAttribute("position", attribute);
117
+ const dim = new three.BufferAttribute(group.satellites.dimmed, 1);
118
+ geometry.setAttribute("dim", dim);
112
119
  const material = new three.ShaderMaterial({ vertexShader: POINT_VERT, fragmentShader: POINT_FRAG, uniforms: { size: { value: group.size * ratio() }, tint: { value: new three.Color(group.color) }, ring: { value: 0 } }, transparent: true, depthWrite: false });
113
120
  const points = new Points(geometry, material);
114
121
  points.frustumCulled = false;
115
122
  points.renderOrder = 5;
116
123
  scene.add(points);
117
- entry = { source: group.satellites, points, geometry, material, positions, attribute, lines: [], linesAt: Number.NaN, linesWall: 0, style: "" };
124
+ entry = { source: group.satellites, points, geometry, material, positions, attribute, dim, dimVersion: -1, lines: [], linesAt: Number.NaN, linesWall: 0, style: "" };
118
125
  drawn.set(name, entry);
119
126
  }
120
127
  const style = `${group.color}|${group.size}|${ratio()}`;
@@ -133,6 +140,10 @@ export function createSatelliteLayer(three, scene, state, ratio) {
133
140
  group.satellites.setStep(step);
134
141
  group.satellites.at(time, entry.positions);
135
142
  entry.attribute.needsUpdate = true;
143
+ if (entry.dimVersion !== group.satellites.dimVersion) {
144
+ entry.dimVersion = group.satellites.dimVersion;
145
+ entry.dim.needsUpdate = true;
146
+ }
136
147
  placed += group.satellites.placed;
137
148
  orbitsOf(entry, group, time, started);
138
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/chikyu-earth",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Chikyu Earth 地球 — A line-drawn globe for the web: country outlines that turn at the Earth's own rate, centred on where you are, with an optional realistic Earth from space (three.js), the Sun, Moon and planets, satellites on their orbits, and markers for any place. A web component and an SVG string.",
5
5
  "keywords": [
6
6
  "earth",