@johnmorrisdotca/chikyu-earth 0.17.0 → 0.19.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.
@@ -0,0 +1,257 @@
1
+ // The land as the printable sheets need it, worked out from the package's own outlines (chizu's Natural Earth 1:110m): the coast of each continent as lines (the borders inside a continent are left out, so a child colours a whole continent),
2
+ // how much of the Earth is land, and which countries touch each other. Pure.
3
+ import WORLD_GEO from "@johnmorrisdotca/chizu/world-geo";
4
+ import { geoArea, geoCentroid, geoDistance } from "d3-geo";
5
+ /** The continents, by the name chizu gives each country's group. */
6
+ const GROUP_IDS = {
7
+ Africa: "africa",
8
+ Asia: "asia",
9
+ Europe: "europe",
10
+ "North America": "north-america",
11
+ "South America": "south-america",
12
+ Oceania: "oceania",
13
+ Antarctica: "antarctica",
14
+ };
15
+ const LANDS = WORLD_GEO.features.map((feature) => {
16
+ const geometry = feature.geometry;
17
+ return {
18
+ name: feature.properties.name,
19
+ ja: feature.properties.nameJa || feature.properties.name,
20
+ alpha2: feature.properties.code.length === 2 ? feature.properties.code : null,
21
+ continent: GROUP_IDS[feature.properties.group] ?? "asia",
22
+ polygons: (geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates),
23
+ };
24
+ });
25
+ /** The area of a polygon in steradians (the whole sphere is 4π), whichever way its ring is wound. */
26
+ const areaOf = (rings) => {
27
+ const a = geoArea({ type: "Polygon", coordinates: rings });
28
+ return a > 2 * Math.PI ? 4 * Math.PI - a : a;
29
+ };
30
+ /** Russia is in both Europe and Asia: the line between them is taken as the meridian 60 degrees east (the Urals are close to it), and everything east of it, with Chukotka past the antimeridian, is Asia. */
31
+ const URALS = 60;
32
+ const isEast = (lon) => lon >= URALS || lon <= -150;
33
+ /** The part of a ring on the east side of the Urals meridian (one half-plane, so a plain clip). */
34
+ function eastOf(ring) {
35
+ const out = [];
36
+ for (let i = 0; i < ring.length - 1; i += 1) {
37
+ const a = ring[i];
38
+ const b = ring[i + 1];
39
+ const ain = a[0] >= URALS;
40
+ const bin = b[0] >= URALS;
41
+ if (ain)
42
+ out.push(a);
43
+ if (ain !== bin)
44
+ out.push([URALS, a[1] + ((URALS - a[0]) / (b[0] - a[0])) * (b[1] - a[1])]);
45
+ }
46
+ if (out.length > 0)
47
+ out.push(out[0]);
48
+ return out;
49
+ }
50
+ /** The point a vertex is known by: the antimeridian is one line, so 180 and -180 are the same. */
51
+ const keyOf = (p) => `${p[0] === 180 ? -180 : p[0]},${p[1]}`;
52
+ /** Every edge of every outline, and who it is shared with. Built on first use. */
53
+ let table;
54
+ function edgesOf() {
55
+ if (table !== undefined)
56
+ return table;
57
+ const edges = new Map();
58
+ const areas = new Map();
59
+ let total = 0;
60
+ LANDS.forEach((land, index) => {
61
+ land.polygons.forEach((polygon, which) => {
62
+ const size = areaOf(polygon);
63
+ if (land.alpha2 === "RU") {
64
+ const ring = polygon[0];
65
+ const lons = ring.map((p) => p[0]);
66
+ const east = Math.min(...lons) >= URALS || Math.max(...lons) <= URALS ? (isEast(lons[0]) ? size : 0) : areaOf([eastOf(ring)]);
67
+ areas.set("asia", (areas.get("asia") ?? 0) + east);
68
+ areas.set("europe", (areas.get("europe") ?? 0) + size - east);
69
+ }
70
+ else
71
+ areas.set(land.continent, (areas.get(land.continent) ?? 0) + size);
72
+ total += size;
73
+ // a hole is another country's land (Lesotho in South Africa), never a line of its own
74
+ const ring = polygon[0];
75
+ for (let i = 0; i < ring.length - 1; i += 1) {
76
+ const a = ring[i];
77
+ const b = ring[i + 1];
78
+ const ka = keyOf(a);
79
+ const kb = keyOf(b);
80
+ if (ka === kb)
81
+ continue;
82
+ const key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
83
+ let edge = edges.get(key);
84
+ if (edge === undefined) {
85
+ edge = { a, b, continents: new Set(), lands: new Set(), polygons: new Set(), count: 0, biggest: 0 };
86
+ edges.set(key, edge);
87
+ }
88
+ edge.continents.add(land.alpha2 === "RU" ? (isEast((a[0] + b[0]) / 2) ? "asia" : "europe") : land.continent);
89
+ edge.lands.add(index);
90
+ edge.polygons.add(`${index}:${which}`);
91
+ edge.count += 1;
92
+ edge.biggest = Math.max(edge.biggest, size);
93
+ }
94
+ });
95
+ });
96
+ table = { edges: [...edges.values()], areas, total };
97
+ return table;
98
+ }
99
+ /** The line between Europe and Asia through Russia: the meridian from where the main land is crossed by it in the south to where it is crossed in the north. */
100
+ function uralsLine() {
101
+ const russia = LANDS.find((land) => land.alpha2 === "RU");
102
+ if (russia === undefined)
103
+ return undefined;
104
+ const ring = russia.polygons.reduce((a, b) => (b[0].length > a[0].length ? b : a))[0];
105
+ const crossings = [];
106
+ for (let i = 0; i < ring.length - 1; i += 1) {
107
+ const a = ring[i];
108
+ const b = ring[i + 1];
109
+ if ((a[0] - URALS) * (b[0] - URALS) < 0)
110
+ crossings.push(a[1] + ((URALS - a[0]) / (b[0] - a[0])) * (b[1] - a[1]));
111
+ }
112
+ if (crossings.length < 2)
113
+ return undefined;
114
+ return [[URALS, Math.min(...crossings)], [URALS, Math.max(...crossings)]];
115
+ }
116
+ /**
117
+ * The coasts of the continents as lines in longitude and latitude, for a child to colour a whole continent: the line round each continent and between two continents (Europe and Asia), and none between two countries of one continent. Islands under `minAreaSr` steradians are left out
118
+ * (about 80,000 square kilometres at the default, so Great Britain, Japan, Madagascar and New Zealand stay and small islands go, which at a thick line would only be blobs).
119
+ * @param minAreaSr - The smallest island kept, in steradians (the whole sphere is 4 pi).
120
+ * @returns Lines of `[longitude, latitude]` points.
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * import { continentLines } from "@johnmorrisdotca/chikyu-earth/sheets";
125
+ *
126
+ * const lines = continentLines();
127
+ * console.log(lines.length > 5, lines[0]?.length);
128
+ * ```
129
+ */
130
+ export function continentLines(minAreaSr = 0.002) {
131
+ const edges = edgesOf().edges.filter((edge) => (edge.count === 1 || edge.continents.size > 1) && edge.biggest >= minAreaSr);
132
+ const ends = new Map();
133
+ const add = (point, at) => {
134
+ const key = keyOf(point);
135
+ const list = ends.get(key);
136
+ if (list === undefined)
137
+ ends.set(key, [at]);
138
+ else
139
+ list.push(at);
140
+ };
141
+ edges.forEach((edge, i) => {
142
+ add(edge.a, i);
143
+ add(edge.b, i);
144
+ });
145
+ const used = new Set();
146
+ const lines = [];
147
+ const other = (edge, from) => (keyOf(edge.a) === from ? edge.b : edge.a);
148
+ const walk = (start, first) => {
149
+ const points = [start];
150
+ let at = first;
151
+ let from = keyOf(start);
152
+ for (;;) {
153
+ used.add(at);
154
+ const next = other(edges[at], from);
155
+ points.push(next);
156
+ from = keyOf(next);
157
+ const here = ends.get(from);
158
+ if (here.length !== 2)
159
+ break;
160
+ const following = here.find((i) => !used.has(i));
161
+ if (following === undefined)
162
+ break;
163
+ at = following;
164
+ }
165
+ return points;
166
+ };
167
+ // lines start at a point where three lines meet or one ends, then whatever loops are left
168
+ for (const [key, list] of ends) {
169
+ if (list.length === 2)
170
+ continue;
171
+ for (const first of list) {
172
+ if (used.has(first))
173
+ continue;
174
+ const edge = edges[first];
175
+ const start = keyOf(edge.a) === key ? edge.a : edge.b;
176
+ lines.push(walk(start, first));
177
+ }
178
+ }
179
+ edges.forEach((edge, i) => {
180
+ if (!used.has(i))
181
+ lines.push(walk(edge.a, i));
182
+ });
183
+ const urals = uralsLine();
184
+ if (urals !== undefined)
185
+ lines.push(urals);
186
+ return lines;
187
+ }
188
+ /**
189
+ * How much of the Earth is land, by the package's outlines, in percent, and the share of all the land each continent has.
190
+ * @returns The land's percent of the whole sphere, and each continent's percent of the land.
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * import { landShares } from "@johnmorrisdotca/chikyu-earth/sheets";
195
+ *
196
+ * const shares = landShares();
197
+ * console.log(Math.round(shares.landPercent), shares.continents.asia > shares.continents.africa);
198
+ * ```
199
+ */
200
+ export function landShares() {
201
+ const { areas, total } = edgesOf();
202
+ const continents = {};
203
+ for (const id of Object.values(GROUP_IDS))
204
+ continents[id] = ((areas.get(id) ?? 0) / total) * 100;
205
+ return { landPercent: (total / (4 * Math.PI)) * 100, continents };
206
+ }
207
+ /** The farthest an island may be from the main land and still be drawn with it (France's Guiana and Hawaii are too far; Japan's and Indonesia's islands are not). */
208
+ const NEAR = 0.52;
209
+ /**
210
+ * One country by its ISO alpha-2 code, for a "my country" sheet: its main land and the islands near it (a far territory such as French Guiana is left out), the continent it is in and the countries it touches.
211
+ * @param alpha2 - The two-letter code, such as `JP`.
212
+ * @returns The shape, or `undefined` when the package has no outline for the code.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * import { countryShape } from "@johnmorrisdotca/chikyu-earth/sheets";
217
+ *
218
+ * const france = countryShape("FR");
219
+ * console.log(france?.continent, france?.neighbours.length);
220
+ * ```
221
+ */
222
+ export function countryShape(alpha2) {
223
+ const index = LANDS.findIndex((land) => land.alpha2 === alpha2.toUpperCase());
224
+ if (index < 0)
225
+ return undefined;
226
+ const land = LANDS[index];
227
+ const sized = land.polygons.map((rings, which) => ({ rings, which, size: areaOf(rings), centre: geoCentroid({ type: "Polygon", coordinates: rings }) }));
228
+ const main = sized.reduce((a, b) => (b.size > a.size ? b : a));
229
+ const kept = sized.filter((p) => p === main || (geoDistance(p.centre, main.centre) <= NEAR && p.size >= main.size * 0.003));
230
+ // only the land that is drawn: French Guiana's neighbours are not France's on this sheet
231
+ const touching = new Set();
232
+ for (const edge of edgesOf().edges)
233
+ if (kept.some((p) => edge.polygons.has(`${index}:${p.which}`)) && edge.lands.size > 1)
234
+ for (const other of edge.lands)
235
+ if (other !== index)
236
+ touching.add(other);
237
+ return {
238
+ name: land.name,
239
+ ja: land.ja,
240
+ alpha2: land.alpha2,
241
+ continent: land.continent,
242
+ feature: { type: "Feature", properties: {}, geometry: { type: "MultiPolygon", coordinates: kept.map((p) => p.rings) } },
243
+ neighbours: [...touching].map((i) => ({ name: LANDS[i].name, ja: LANDS[i].ja })).sort((a, b) => a.name.localeCompare(b.name)),
244
+ };
245
+ }
246
+ /**
247
+ * The two-letter codes of the countries that have an outline.
248
+ * @returns The codes, in the order of the outlines.
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * import { countryCodes } from "@johnmorrisdotca/chikyu-earth/sheets";
253
+ *
254
+ * console.log(countryCodes().includes("JP"));
255
+ * ```
256
+ */
257
+ export const countryCodes = () => LANDS.flatMap((land) => (land.alpha2 === null ? [] : [land.alpha2]));
@@ -0,0 +1,15 @@
1
+ /**
2
+ * A d3-geo path made fit for a thick line: simpler to within `toleranceMm`, loops whose longest side is under `minLoopMm` left out, corners rounded.
3
+ * @param d - The path as d3-geo's `geoPath` writes it, in millimetres.
4
+ * @param toleranceMm - How far the simpler line may stray from the real one.
5
+ * @param minLoopMm - The smallest island, by its longest side, that is kept.
6
+ * @returns The path.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { thickPath } from "@johnmorrisdotca/chikyu-earth/sheets";
11
+ *
12
+ * console.log(thickPath("M0,0L5,0.1L10,0L20,0", 0.5, 0));
13
+ * ```
14
+ */
15
+ export declare function thickPath(d: string, toleranceMm: number, minLoopMm: number): string;
@@ -0,0 +1,116 @@
1
+ // Thick lines hide fine detail, so a coast is made simpler before it is drawn: a path from d3-geo is read back as points in millimetres, the points that matter at the line's thickness are kept (Douglas-Peucker), loops too small to colour
2
+ // are dropped, and the corners are rounded. Pure.
3
+ /** The runs of a path written by d3-geo: `M x,y L x,y ... Z` or without the `Z`. */
4
+ function runsOf(d) {
5
+ const runs = [];
6
+ for (const part of d.split("M").slice(1)) {
7
+ const closed = part.endsWith("Z");
8
+ const points = part
9
+ .replace(/Z$/, "")
10
+ .split("L")
11
+ .map((pair) => {
12
+ const [x, y] = pair.split(",");
13
+ return [Number(x), Number(y)];
14
+ });
15
+ const first = points[0];
16
+ const last = points.at(-1);
17
+ const loops = closed || (points.length > 3 && Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6);
18
+ if (loops && Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6)
19
+ points.pop();
20
+ runs.push({ points, closed: loops });
21
+ }
22
+ return runs;
23
+ }
24
+ const distance = (p, a, b) => {
25
+ const dx = b[0] - a[0];
26
+ const dy = b[1] - a[1];
27
+ const length = dx * dx + dy * dy;
28
+ if (length === 0)
29
+ return Math.hypot(p[0] - a[0], p[1] - a[1]);
30
+ const t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length));
31
+ return Math.hypot(p[0] - (a[0] + t * dx), p[1] - (a[1] + t * dy));
32
+ };
33
+ /** Douglas-Peucker: the points of a line that leave it within `tolerance` of the simpler line through them. */
34
+ function simplify(points, tolerance) {
35
+ if (points.length < 3)
36
+ return points;
37
+ const keep = new Array(points.length).fill(false);
38
+ keep[0] = true;
39
+ keep[points.length - 1] = true;
40
+ const stack = [[0, points.length - 1]];
41
+ while (stack.length > 0) {
42
+ const [from, to] = stack.pop();
43
+ let far = -1;
44
+ let most = tolerance;
45
+ for (let i = from + 1; i < to; i += 1) {
46
+ const d = distance(points[i], points[from], points[to]);
47
+ if (d > most) {
48
+ most = d;
49
+ far = i;
50
+ }
51
+ }
52
+ if (far >= 0) {
53
+ keep[far] = true;
54
+ stack.push([from, far], [far, to]);
55
+ }
56
+ }
57
+ return points.filter((_, i) => keep[i]);
58
+ }
59
+ const r = (v) => (Math.round(v * 100) / 100).toString();
60
+ const mid = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
61
+ /** A run as a path with rounded corners: straight to the middle of the first side, then a curve through each corner. */
62
+ function rounded(run) {
63
+ const p = run.points;
64
+ if (p.length < 3)
65
+ return `M${r(p[0][0])} ${r(p[0][1])}L${r(p.at(-1)[0])} ${r(p.at(-1)[1])}`;
66
+ if (run.closed) {
67
+ const start = mid(p[0], p[1]);
68
+ let d = `M${r(start[0])} ${r(start[1])}`;
69
+ for (let i = 1; i <= p.length; i += 1) {
70
+ const corner = p[i % p.length];
71
+ const next = mid(corner, p[(i + 1) % p.length]);
72
+ d += `Q${r(corner[0])} ${r(corner[1])} ${r(next[0])} ${r(next[1])}`;
73
+ }
74
+ return `${d}Z`;
75
+ }
76
+ let d = `M${r(p[0][0])} ${r(p[0][1])}`;
77
+ const first = mid(p[0], p[1]);
78
+ d += `L${r(first[0])} ${r(first[1])}`;
79
+ for (let i = 1; i < p.length - 1; i += 1) {
80
+ const next = mid(p[i], p[i + 1]);
81
+ d += `Q${r(p[i][0])} ${r(p[i][1])} ${r(next[0])} ${r(next[1])}`;
82
+ }
83
+ return `${d}L${r(p.at(-1)[0])} ${r(p.at(-1)[1])}`;
84
+ }
85
+ /**
86
+ * A d3-geo path made fit for a thick line: simpler to within `toleranceMm`, loops whose longest side is under `minLoopMm` left out, corners rounded.
87
+ * @param d - The path as d3-geo's `geoPath` writes it, in millimetres.
88
+ * @param toleranceMm - How far the simpler line may stray from the real one.
89
+ * @param minLoopMm - The smallest island, by its longest side, that is kept.
90
+ * @returns The path.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * import { thickPath } from "@johnmorrisdotca/chikyu-earth/sheets";
95
+ *
96
+ * console.log(thickPath("M0,0L5,0.1L10,0L20,0", 0.5, 0));
97
+ * ```
98
+ */
99
+ export function thickPath(d, toleranceMm, minLoopMm) {
100
+ const out = [];
101
+ for (const run of runsOf(d)) {
102
+ if (run.points.length < 2)
103
+ continue;
104
+ if (run.closed) {
105
+ const xs = run.points.map((p) => p[0]);
106
+ const ys = run.points.map((p) => p[1]);
107
+ if (Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)) < minLoopMm)
108
+ continue;
109
+ }
110
+ const points = simplify(run.points, toleranceMm);
111
+ if (run.closed ? points.length < 3 : points.length < 2)
112
+ continue;
113
+ out.push(rounded({ points, closed: run.closed }));
114
+ }
115
+ return out.join("");
116
+ }
@@ -0,0 +1,68 @@
1
+ import type { SheetOptions } from "./earth.ts";
2
+ /** How far the view of the day and night globe is tipped to show the north (degrees): the line between day and night is then a curve. */
3
+ export declare const DAY_NIGHT_TIP = 20;
4
+ /**
5
+ * The turn of the globe on the day and night sheet for a moment: the Sun's longitude less 90 degrees at the middle, so the lit half is on the right, tipped to show the north.
6
+ * @param ms - The moment, in milliseconds since the Unix epoch.
7
+ * @returns The place at the middle of the globe, the place where the Sun is straight overhead and the roll of the globe about the line of sight, in degrees.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { dayNightView } from "@johnmorrisdotca/chikyu-earth/sheets";
12
+ *
13
+ * const view = dayNightView(Date.UTC(2026, 5, 21, 12));
14
+ * console.log(view.sun.lat.toFixed(1));
15
+ * ```
16
+ */
17
+ export declare function dayNightView(ms: number): {
18
+ centre: [number, number];
19
+ sun: {
20
+ lon: number;
21
+ lat: number;
22
+ };
23
+ roll: number;
24
+ };
25
+ /**
26
+ * The line between day and night at a moment: the points 90 degrees from where the Sun is straight overhead, as longitude and latitude.
27
+ * @param ms - The moment, in milliseconds since the Unix epoch.
28
+ * @param points - How many points (at least 3, default 72).
29
+ * @returns The points in order round the Earth.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { terminator } from "@johnmorrisdotca/chikyu-earth/sheets";
34
+ *
35
+ * console.log(terminator(Date.UTC(2026, 2, 20, 12), 8).length);
36
+ * ```
37
+ */
38
+ export declare function terminator(ms: number, points?: number): [number, number][];
39
+ /**
40
+ * The day and night sheet: the Earth with the Sun's light coming from the right, the lit half left white (day) and the dark half hatched (night), the line between them thick, and three facts, for the date and time you give. The line is worked out from the package's own sun position.
41
+ * @param ms - The moment, in milliseconds since the Unix epoch.
42
+ * @param options - The room, the language and the type.
43
+ * @returns The `<svg>` markup, carrying the place of the Sun as `data-sun`.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { dayNightSvg } from "@johnmorrisdotca/chikyu-earth/sheets";
48
+ *
49
+ * const svg = dayNightSvg(Date.UTC(2026, 5, 21, 12), { widthMm: 184.6, heightMm: 180 });
50
+ * console.log(svg.includes("data-sun="), svg.includes("Night"));
51
+ * ```
52
+ */
53
+ export declare function dayNightSvg(ms: number, options: SheetOptions): string;
54
+ /**
55
+ * The seasons sheet: the Sun in the middle, the Earth's orbit as a ring, and the Earth at four points of it (March, June, September and December), each with its tilt, the dark half hatched, the season of the northern half named, and three facts.
56
+ * The axis leans the same way at all four, so in June the north leans toward the Sun and in December away from it.
57
+ * @param options - The room, the language and the type.
58
+ * @returns The `<svg>` markup.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { seasonsSvg } from "@johnmorrisdotca/chikyu-earth/sheets";
63
+ *
64
+ * const svg = seasonsSvg({ widthMm: 184.6, heightMm: 180, lang: "en" });
65
+ * console.log(svg.includes("Summer"), svg.includes("Winter"));
66
+ * ```
67
+ */
68
+ export declare function seasonsSvg(options: SheetOptions): string;
@@ -0,0 +1,216 @@
1
+ // The day and night sheet and the seasons sheet: the Earth with the Sun's light on one half (hatched where it is night), and the Earth at four points round the Sun with its tilt. Pure: a string of SVG measured in millimetres.
2
+ import { geoCircle, geoDistance, geoOrthographic, geoPath } from "d3-geo";
3
+ import { subsolarPoint } from "../realistic/sun.js";
4
+ import { hatchPath } from "./hatch.js";
5
+ import { continentLines } from "./land.js";
6
+ import { thickPath } from "./outline.js";
7
+ import { SAY, TILT_DEGREES, TITLES, dayNightFacts, seasonsFacts } from "./text.js";
8
+ import { TYPES, factsBlock, haloText, innerMm, labelMm, nameBlock, outlineMm, svgOpen, textWidth } from "./common.js";
9
+ const GAP = 5;
10
+ const RAD = Math.PI / 180;
11
+ /** How far the view of the day and night globe is tipped to show the north (degrees): the line between day and night is then a curve. */
12
+ export const DAY_NIGHT_TIP = 20;
13
+ /**
14
+ * The turn of the globe on the day and night sheet for a moment: the Sun's longitude less 90 degrees at the middle, so the lit half is on the right, tipped to show the north.
15
+ * @param ms - The moment, in milliseconds since the Unix epoch.
16
+ * @returns The place at the middle of the globe, the place where the Sun is straight overhead and the roll of the globe about the line of sight, in degrees.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { dayNightView } from "@johnmorrisdotca/chikyu-earth/sheets";
21
+ *
22
+ * const view = dayNightView(Date.UTC(2026, 5, 21, 12));
23
+ * console.log(view.sun.lat.toFixed(1));
24
+ * ```
25
+ */
26
+ export function dayNightView(ms) {
27
+ const sun = subsolarPoint(ms);
28
+ const centre = [sun.lon - 90, DAY_NIGHT_TIP];
29
+ // the globe is rolled a little about the line of sight so the Sun is straight to the right of it (the Earth's axis then leans, as it does)
30
+ const flat = geoOrthographic().rotate([-centre[0], -centre[1]]).translate([0, 0]).scale(1);
31
+ const at = flat([sun.lon, sun.lat]) ?? [1, 0];
32
+ const roll = (Math.atan2(-at[1], at[0]) * 180) / Math.PI;
33
+ const side = (g) => Math.abs(geoOrthographic().rotate([-centre[0], -centre[1], g]).translate([0, 0]).scale(1)([sun.lon, sun.lat])?.[1] ?? 1);
34
+ return { centre, sun, roll: side(roll) <= side(-roll) ? roll : -roll };
35
+ }
36
+ /**
37
+ * The line between day and night at a moment: the points 90 degrees from where the Sun is straight overhead, as longitude and latitude.
38
+ * @param ms - The moment, in milliseconds since the Unix epoch.
39
+ * @param points - How many points (at least 3, default 72).
40
+ * @returns The points in order round the Earth.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { terminator } from "@johnmorrisdotca/chikyu-earth/sheets";
45
+ *
46
+ * console.log(terminator(Date.UTC(2026, 2, 20, 12), 8).length);
47
+ * ```
48
+ */
49
+ export function terminator(ms, points = 72) {
50
+ const sun = subsolarPoint(ms);
51
+ const ring = geoCircle().center([sun.lon + 180, -sun.lat]).radius(90).precision(360 / Math.max(3, points))();
52
+ return ring.coordinates[0].slice(0, -1);
53
+ }
54
+ /** The Sun as a drawing: a disc with rays. */
55
+ function sunIcon(x, y, radius, thick) {
56
+ const rays = [];
57
+ for (let i = 0; i < 8; i += 1) {
58
+ const a = (Math.PI / 4) * i;
59
+ rays.push(`M${(x + Math.cos(a) * (radius + thick * 1.6)).toFixed(2)} ${(y + Math.sin(a) * (radius + thick * 1.6)).toFixed(2)}L${(x + Math.cos(a) * (radius + thick * 1.6 + 3)).toFixed(2)} ${(y + Math.sin(a) * (radius + thick * 1.6 + 3)).toFixed(2)}`);
60
+ }
61
+ return `<circle cx="${x}" cy="${y}" r="${radius}" fill="none" stroke="#000" stroke-width="${thick}" data-sun-icon=""/><path d="${rays.join("")}" fill="none" stroke="#000" stroke-width="${thick}" stroke-linecap="round"/>`;
62
+ }
63
+ /** An arrow from (x0, y0) to (x1, y1) with a head. */
64
+ function arrow(x0, y0, x1, y1, thick) {
65
+ const a = Math.atan2(y1 - y0, x1 - x0);
66
+ const head = thick * 2;
67
+ const hx = (k) => (x1 - Math.cos(a + k) * head).toFixed(2);
68
+ const hy = (k) => (y1 - Math.sin(a + k) * head).toFixed(2);
69
+ return `<path d="M${x0.toFixed(2)} ${y0.toFixed(2)}L${x1.toFixed(2)} ${y1.toFixed(2)}M${hx(0.55)} ${hy(0.55)}L${x1.toFixed(2)} ${y1.toFixed(2)}L${hx(-0.55)} ${hy(-0.55)}" fill="none" stroke="#000" stroke-width="${thick}" stroke-linecap="round" stroke-linejoin="round"/>`;
70
+ }
71
+ /**
72
+ * The day and night sheet: the Earth with the Sun's light coming from the right, the lit half left white (day) and the dark half hatched (night), the line between them thick, and three facts, for the date and time you give. The line is worked out from the package's own sun position.
73
+ * @param ms - The moment, in milliseconds since the Unix epoch.
74
+ * @param options - The room, the language and the type.
75
+ * @returns The `<svg>` markup, carrying the place of the Sun as `data-sun`.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * import { dayNightSvg } from "@johnmorrisdotca/chikyu-earth/sheets";
80
+ *
81
+ * const svg = dayNightSvg(Date.UTC(2026, 5, 21, 12), { widthMm: 184.6, heightMm: 180 });
82
+ * console.log(svg.includes("data-sun="), svg.includes("Night"));
83
+ * ```
84
+ */
85
+ export function dayNightSvg(ms, options) {
86
+ const { widthMm: w, heightMm: h } = options;
87
+ const lang = options.lang ?? "en";
88
+ const type = options.type ?? "kid";
89
+ const outline = outlineMm(type);
90
+ const inner = innerMm(type);
91
+ const facts = factsBlock(dayNightFacts(ms, lang), w, 0, type);
92
+ const free = h - facts.height - GAP;
93
+ const zone = type === "kid" ? 40 : 28;
94
+ const reachOut = type === "kid" ? 22 : 14;
95
+ const diameter = Math.min(w - zone - reachOut, free);
96
+ const radius = diameter / 2 - outline / 2;
97
+ const left = (w - (diameter + zone + reachOut)) / 2;
98
+ const cx = left + diameter / 2;
99
+ const cy = free / 2;
100
+ const { centre, sun, roll } = dayNightView(ms);
101
+ const projection = geoOrthographic().rotate([-centre[0], -centre[1], roll]).translate([cx, cy]).scale(radius).clipAngle(90).precision(0.3);
102
+ const path = geoPath(projection);
103
+ const sunAt = [sun.lon, sun.lat];
104
+ const night = (x, y) => {
105
+ if (Math.hypot(x - cx, y - cy) > radius)
106
+ return false;
107
+ const place = projection.invert?.([x, y]);
108
+ return place !== null && place !== undefined && Number.isFinite(place[0]) && geoDistance(place, sunAt) > Math.PI / 2;
109
+ };
110
+ const shade = hatchPath({ x0: cx - radius, y0: cy - radius, x1: cx + radius, y1: cy + radius }, type === "kid" ? 3.2 : 1.6, 45, night);
111
+ const coast = thickPath(path({ type: "MultiLineString", coordinates: continentLines(0.0006) }) ?? "", outline * 0.4, outline * 3.5);
112
+ const line = path(geoCircle().center([sun.lon + 180, -sun.lat]).radius(90).precision(1)()) ?? "";
113
+ const size = labelMm(type);
114
+ const dayWord = nameBlock([SAY[lang].day], cx + radius * 0.5, cy - radius * 0.12, size, ' data-say="day"');
115
+ const nightWord = nameBlock([SAY[lang].night], cx - radius * 0.5, cy - radius * 0.12, size, ' data-say="night"');
116
+ const sx = left + diameter + reachOut + zone / 2;
117
+ const sunRadius = type === "kid" ? 11 : 7;
118
+ const arrows = [-0.5, 0, 0.5].map((k) => arrow(sx - zone / 2 - 1, cy + k * radius * 0.7, cx + Math.sqrt(Math.max(0, 1 - (k * 0.7) ** 2)) * radius + 4, cy + k * radius * 0.7, inner)).join("");
119
+ const sunWord = nameBlock([SAY[lang].sun], sx, cy + sunRadius + 20, size);
120
+ const picture = `<path d="${shade}" fill="none" stroke="#000" stroke-width="${type === "kid" ? 0.9 : 0.35}" stroke-linecap="round" data-night=""/>` +
121
+ `<path d="${line}" fill="none" stroke="#000" stroke-width="${inner}" data-terminator=""/>` +
122
+ `<path d="${coast}" fill="none" stroke="#000" stroke-width="${outline}" stroke-linecap="round" stroke-linejoin="round" data-coast=""/>` +
123
+ `<circle cx="${cx}" cy="${cy}" r="${radius}" fill="none" stroke="#000" stroke-width="${outline}" data-rim=""/>` +
124
+ `${dayWord.markup}${nightWord.markup}${arrows}${sunIcon(sx, cy, sunRadius, inner)}${sunWord.markup}`;
125
+ return `${svgOpen(w, h, TITLES.daynight(lang), "daynight").replace("<svg ", `<svg data-sun="${sun.lon.toFixed(3)} ${sun.lat.toFixed(3)}" data-view="${centre[0].toFixed(3)} ${centre[1]} ${roll.toFixed(3)}" data-disc="${cx.toFixed(3)} ${cy.toFixed(3)} ${radius.toFixed(3)}" `)}${picture}<g transform="translate(0 ${h - facts.height})">${facts.markup}</g></svg>`;
126
+ }
127
+ /** One Earth of the seasons sheet: a disc with the night half hatched, the equator and the tilted axis with a dot at the north. */
128
+ function earth(x, y, radius, towardSun, type) {
129
+ const outline = outlineMm(type);
130
+ const inner = innerMm(type);
131
+ const tilt = TILT_DEGREES;
132
+ const dark = (px, py) => Math.hypot(px - x, py - y) <= radius && (px - x) * towardSun[0] + (py - y) * towardSun[1] < 0;
133
+ const shade = hatchPath({ x0: x - radius, y0: y - radius, x1: x + radius, y1: y + radius }, type === "kid" ? 2.8 : 1.4, 45, dark);
134
+ const sin = Math.sin(tilt * RAD);
135
+ const cos = Math.cos(tilt * RAD);
136
+ const reach = radius * 1.4;
137
+ const north = [x + sin * reach, y - cos * reach];
138
+ const south = [x - sin * reach, y + cos * reach];
139
+ const dot = type === "kid" ? 2.6 : 1.4;
140
+ return (`<path d="${shade}" fill="none" stroke="#000" stroke-width="${type === "kid" ? 0.8 : 0.3}" stroke-linecap="round" data-night=""/>` +
141
+ `<path d="M${south[0].toFixed(2)} ${south[1].toFixed(2)}L${north[0].toFixed(2)} ${north[1].toFixed(2)}" fill="none" stroke="#000" stroke-width="${inner}" stroke-linecap="round" data-axis=""/>` +
142
+ `<circle cx="${north[0].toFixed(2)}" cy="${north[1].toFixed(2)}" r="${dot}" fill="#000"/>` +
143
+ `<circle cx="${x}" cy="${y}" r="${radius}" fill="none" stroke="#000" stroke-width="${outline}" data-earth=""/>`);
144
+ }
145
+ /**
146
+ * The seasons sheet: the Sun in the middle, the Earth's orbit as a ring, and the Earth at four points of it (March, June, September and December), each with its tilt, the dark half hatched, the season of the northern half named, and three facts.
147
+ * The axis leans the same way at all four, so in June the north leans toward the Sun and in December away from it.
148
+ * @param options - The room, the language and the type.
149
+ * @returns The `<svg>` markup.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * import { seasonsSvg } from "@johnmorrisdotca/chikyu-earth/sheets";
154
+ *
155
+ * const svg = seasonsSvg({ widthMm: 184.6, heightMm: 180, lang: "en" });
156
+ * console.log(svg.includes("Summer"), svg.includes("Winter"));
157
+ * ```
158
+ */
159
+ export function seasonsSvg(options) {
160
+ const { widthMm: w, heightMm: h } = options;
161
+ const lang = options.lang ?? "en";
162
+ const type = options.type ?? "kid";
163
+ const inner = innerMm(type);
164
+ const facts = factsBlock(seasonsFacts(lang), w, 0, type);
165
+ const free = h - facts.height - GAP;
166
+ const size = labelMm(type);
167
+ const month = TYPES[type].bodyMm;
168
+ const radius = Math.max(6, Math.min(type === "kid" ? 13 : 8, free * 0.1));
169
+ const cx = w / 2;
170
+ const cy = free / 2;
171
+ const ry = Math.max(radius * 2, free / 2 - radius - 4 - size * 1.15 - 2);
172
+ const rx = Math.min(cx - radius - (type === "kid" ? 22 : 14), ry * 2.8);
173
+ const sunRadius = Math.max(4, Math.min(type === "kid" ? 10 : 6, ry - radius - inner * 1.6 - 6));
174
+ const say = SAY[lang];
175
+ // the Earth at the right is December, at the top March, at the left June, at the bottom September, one way round
176
+ const stops = [
177
+ { angle: 0, season: say.winter, month: say.months[3] },
178
+ { angle: 90, season: say.spring, month: say.months[0] },
179
+ { angle: 180, season: say.summer, month: say.months[1] },
180
+ { angle: 270, season: say.autumn, month: say.months[2] },
181
+ ];
182
+ const at = (angle) => [cx + rx * Math.cos(angle * RAD), cy - ry * Math.sin(angle * RAD)];
183
+ const parts = [];
184
+ parts.push(`<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="none" stroke="#000" stroke-width="${inner}" stroke-dasharray="${inner * 2.4} ${inner * 1.6}" data-orbit=""/>`);
185
+ for (const angle of [60, 120, 240, 300]) {
186
+ const [px, py] = at(angle);
187
+ const tx = -rx * Math.sin(angle * RAD);
188
+ const ty = -ry * Math.cos(angle * RAD);
189
+ const length = Math.hypot(tx, ty);
190
+ const ux = tx / length;
191
+ const uy = ty / length;
192
+ const head = inner * 1.8;
193
+ parts.push(`<polygon points="${(px + ux * head).toFixed(2)},${(py + uy * head).toFixed(2)} ${(px - ux * head - uy * head * 0.8).toFixed(2)},${(py - uy * head + ux * head * 0.8).toFixed(2)} ${(px - ux * head + uy * head * 0.8).toFixed(2)},${(py - uy * head - ux * head * 0.8).toFixed(2)}" fill="#000" data-way=""/>`);
194
+ }
195
+ parts.push(sunIcon(cx, cy, sunRadius, inner));
196
+ for (const stop of stops) {
197
+ const [px, py] = at(stop.angle);
198
+ const toSun = [(cx - px) / Math.hypot(cx - px, cy - py), (cy - py) / Math.hypot(cx - px, cy - py)];
199
+ parts.push(`<g data-season="${stop.angle}">${earth(px, py, radius, toSun, type)}</g>`);
200
+ if (stop.angle === 90 || stop.angle === 270) {
201
+ // above the top Earth and below the bottom one the season and the month are one line
202
+ const seasonW = textWidth(stop.season, size);
203
+ const monthW = textWidth(stop.month, month);
204
+ const left = px - (seasonW + 3 + monthW) / 2;
205
+ const base = stop.angle === 90 ? py - radius - 4 : py + radius + 4 + size * 0.8;
206
+ parts.push(haloText(left + seasonW / 2, base, size, stop.season, ' data-say="season"'));
207
+ parts.push(haloText(left + seasonW + 3 + monthW / 2, base, month, stop.month, ' data-say="month"'));
208
+ }
209
+ else {
210
+ const first = py + radius + 4 + size * 0.8;
211
+ parts.push(haloText(px, first, size, stop.season, ' data-say="season"'));
212
+ parts.push(haloText(px, first + month * 1.3, month, stop.month, ' data-say="month"'));
213
+ }
214
+ }
215
+ return `${svgOpen(w, h, TITLES.seasons(lang), "seasons")}${parts.join("")}<g transform="translate(0 ${h - facts.height})">${facts.markup}</g></svg>`;
216
+ }