@johnmorrisdotca/chikyu-earth 0.46.5 → 0.47.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,183 @@
1
+ // Where a point is on the Earth: the country, the sea or ocean, the continent, and the nearest city.
2
+ // Pure. A page that never imports this does not pay for it. The country shapes are Natural Earth 1:110m (chizu's world-geo).
3
+ // The seas and continents are the sea-names list. Cities are whoever the caller passes, the same lists here-city uses.
4
+ import { SEA_FEATURES } from "../sea-names/features.js";
5
+ import { HERE_CITY_KM, HERE_CITY_MAX_KM, chooseHereCity, hereCountries } from "../markers/here-city.js";
6
+ import { landAt, PLACE_COAST_KM } from "./land.js";
7
+ import { SEA_REACH_KM, waterAt } from "./water.js";
8
+ export { PLACE_COAST_KM, SEA_REACH_KM };
9
+ const RAD = Math.PI / 180;
10
+ const CONTINENT_ID = {
11
+ Africa: "africa",
12
+ Antarctica: "antarctica",
13
+ Asia: "asia",
14
+ Europe: "europe",
15
+ "North America": "north-america",
16
+ "South America": "south-america",
17
+ };
18
+ const empty = () => ({ country: null, near: null, sea: null, continent: null, nearestCity: null });
19
+ const clean = (lon, lat) => {
20
+ if (!Number.isFinite(lon) || !Number.isFinite(lat) || lat < -90 || lat > 90)
21
+ return null;
22
+ let x = ((lon + 180) % 360 + 360) % 360 - 180;
23
+ if (x === -180 && lon > 0)
24
+ x = 180;
25
+ return { lon: x, lat };
26
+ };
27
+ const countryOf = (hit) => ({ code: hit.code, name: hit.name, nameJa: hit.nameJa });
28
+ const kmTo = (lon, lat, feature) => {
29
+ const φ1 = lat * RAD;
30
+ const φ2 = feature.lat * RAD;
31
+ const Δφ = (feature.lat - lat) * RAD;
32
+ const Δλ = (feature.lon - lon) * RAD;
33
+ const h = Math.sin(Δφ / 2) ** 2 + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) ** 2;
34
+ return 2 * 6371.0088 * Math.asin(Math.min(1, Math.sqrt(h)));
35
+ };
36
+ /** A country chizu puts in one continent can still reach into another (eastern Russia, French Guiana). Use the nearer continent point when it is this much closer. */
37
+ const CONTINENT_SHIFT_KM = 2500;
38
+ const named = (feature) => ({ id: feature.id, name: feature.name.en, nameJa: feature.name.ja });
39
+ const continentOf = (hit, lon, lat) => {
40
+ const continents = SEA_FEATURES.filter((one) => one.kind === "continent");
41
+ if (hit.code === "AU") {
42
+ const australia = continents.find((one) => one.id === "australia");
43
+ return australia ? named(australia) : null;
44
+ }
45
+ if (hit.group === "Oceania")
46
+ return { id: "oceania", name: "Oceania", nameJa: hit.groupJa || "オセアニア" };
47
+ let nearest = continents[0];
48
+ let nearestKm = nearest ? kmTo(lon, lat, nearest) : Number.POSITIVE_INFINITY;
49
+ for (const feature of continents.slice(1)) {
50
+ const km = kmTo(lon, lat, feature);
51
+ if (km < nearestKm) {
52
+ nearest = feature;
53
+ nearestKm = km;
54
+ }
55
+ }
56
+ const grouped = continents.find((one) => one.id === CONTINENT_ID[hit.group]);
57
+ if (!grouped)
58
+ return nearest ? named(nearest) : null;
59
+ const feature = kmTo(lon, lat, grouped) - nearestKm >= CONTINENT_SHIFT_KM && nearest ? nearest : grouped;
60
+ return named(feature);
61
+ };
62
+ const bearingDeg = (fromLon, fromLat, toLon, toLat) => {
63
+ const φ1 = fromLat * RAD;
64
+ const φ2 = toLat * RAD;
65
+ const Δλ = (toLon - fromLon) * RAD;
66
+ const y = Math.sin(Δλ) * Math.cos(φ2);
67
+ const x = Math.cos(φ1) * Math.sin(φ2) - Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ);
68
+ return (Math.atan2(y, x) * (180 / Math.PI) + 360) % 360;
69
+ };
70
+ const cityOf = (lon, lat, options) => {
71
+ const cities = options?.cities;
72
+ if (!cities)
73
+ return null;
74
+ const maxKm = Math.min(HERE_CITY_MAX_KM, options?.maxKm ?? HERE_CITY_KM);
75
+ if (!(maxKm > 0))
76
+ return null;
77
+ const point = { lat, lon };
78
+ const coarse = cities.nearest(point, { maxKm });
79
+ const townsOf = options?.towns;
80
+ const towns = townsOf ? hereCountries(point, cities, maxKm).flatMap((code) => townsOf(code) ?? []) : [];
81
+ const chosen = chooseHereCity(point, coarse, towns, maxKm);
82
+ if (!chosen)
83
+ return null;
84
+ const town = towns.find((one) => one.id === chosen.id);
85
+ const at = town ?? (coarse && coarse.city.id === chosen.id ? coarse.city : undefined);
86
+ const countryCode = (town?.country ?? coarse?.city.country ?? "").trim().toUpperCase() || null;
87
+ const nameJa = chosen.name.jaShort || chosen.name.ja || chosen.name.en;
88
+ const cityLat = at?.lat;
89
+ const cityLon = at?.lon;
90
+ const bearing = cityLat !== undefined && cityLon !== undefined && Number.isFinite(cityLat) && Number.isFinite(cityLon) ? bearingDeg(lon, lat, cityLon, cityLat) : 0;
91
+ return { name: chosen.name.en, nameJa, countryCode, distanceKm: chosen.km, bearingDeg: bearing };
92
+ };
93
+ const headline = (place) => {
94
+ if (place.country)
95
+ return { kind: "country", id: place.country.code ?? place.country.name, name: place.country.name, nameJa: place.country.nameJa };
96
+ if (place.near)
97
+ return { kind: "near", id: place.near.code ?? place.near.name, name: place.near.name, nameJa: place.near.nameJa };
98
+ if (place.sea)
99
+ return { kind: "sea", id: place.sea.id, name: place.sea.name, nameJa: place.sea.nameJa };
100
+ return null;
101
+ };
102
+ const same = (a, b) => a?.kind === b?.kind && a?.id === b?.id;
103
+ /**
104
+ * The country, sea or ocean, continent and nearest city at one point.
105
+ * Countries are the line globe's outlines, Natural Earth at 1:110m. A point inside an outline is `country`.
106
+ * A point outside every outline and within {@link PLACE_COAST_KM} (50 km) of one is `near` instead: the coarse coast is not reported as a country.
107
+ * The sea is the nearest named sea, gulf, bay or ocean within its reach ({@link SEA_REACH_KM}); a smaller water's point is nearer, so it wins over the ocean. It is null while `country` is set, and null when no water is within reach.
108
+ * The continent is the country's group in the outlines, named as in the sea-names list. Australia the country uses that continent, not the Oceania group. A point whose continent point is at least 2,500 km nearer than its country's group (eastern Russia, French Guiana) uses the nearer one. The city lists are the caller's: without `cities`, `nearestCity` is null.
109
+ * Towns under 100,000 are read only when `towns` is passed. The outlines are indexed on a 15° grid so a call is cheap enough to make about once a second.
110
+ *
111
+ * @param lon - Degrees east. A value outside -180 to 180 is wrapped.
112
+ * @param lat - Degrees north, -90 to 90.
113
+ * @param options - City lists and the kilometre limit. Omit them to skip the city.
114
+ * @returns The place. Every field is null when `lat` is not a latitude.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * import { placeOf } from "@johnmorrisdotca/chikyu-earth/place";
119
+ *
120
+ * console.log(placeOf(2.35, 48.86).country?.code);
121
+ * console.log(placeOf(-150, 0).sea?.id);
122
+ * console.log(placeOf(0, 90).country);
123
+ * ```
124
+ */
125
+ export function placeOf(lon, lat, options) {
126
+ const at = clean(lon, lat);
127
+ if (!at)
128
+ return empty();
129
+ const land = landAt(at.lon, at.lat);
130
+ const held = land.country ?? land.near;
131
+ const water = land.country ? null : waterAt(at.lon, at.lat);
132
+ return {
133
+ country: land.country ? countryOf(land.country) : null,
134
+ near: land.near ? { ...countryOf(land.near), distanceKm: land.near.distanceKm } : null,
135
+ sea: water ? { id: water.id, name: water.name.en, nameJa: water.name.ja } : null,
136
+ continent: held ? continentOf(held, at.lon, at.lat) : null,
137
+ nearestCity: cityOf(at.lon, at.lat, options),
138
+ };
139
+ }
140
+ /**
141
+ * The ordered changes of place along a ground track. Each point is `{ lon, lat, t }`.
142
+ * A change is reported at the sample that entered the new place. `near` is how a page says the track is approaching a country; the next sample inside it is the country itself.
143
+ *
144
+ * @param points - The track, in order. A point with no latitude is skipped.
145
+ * @param options - The same city lists as {@link placeOf}. They do not change the country or the sea.
146
+ * @returns One row for the first sample, then one row each time the country, the nearby country or the sea changes.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * import { alongTrack } from "@johnmorrisdotca/chikyu-earth/place";
151
+ *
152
+ * const rows = alongTrack([
153
+ * { lon: -40, lat: 40, t: 0 },
154
+ * { lon: -3.7, lat: 40.4, t: 1 },
155
+ * { lon: 2.35, lat: 48.86, t: 2 },
156
+ * ]);
157
+ * console.log(rows.map((row) => row.entering?.id).join(" "));
158
+ * ```
159
+ */
160
+ export function alongTrack(points, options) {
161
+ const out = [];
162
+ let previous = null;
163
+ let started = false;
164
+ for (const point of points) {
165
+ if (!Number.isFinite(point.t))
166
+ continue;
167
+ const place = placeOf(point.lon, point.lat, options);
168
+ if (!Number.isFinite(point.lon) || !Number.isFinite(point.lat) || point.lat < -90 || point.lat > 90)
169
+ continue;
170
+ const next = headline(place);
171
+ if (!started) {
172
+ out.push({ t: point.t, entering: next, leaving: null });
173
+ previous = next;
174
+ started = true;
175
+ continue;
176
+ }
177
+ if (same(previous, next))
178
+ continue;
179
+ out.push({ t: point.t, entering: next, leaving: previous });
180
+ previous = next;
181
+ }
182
+ return out;
183
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * How close to a 1:110m outline, in kilometres, still counts as that country nearby.
3
+ * The outlines can sit tens of kilometres off a real coast, so a point this close is not reported as inside.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { PLACE_COAST_KM } from "@johnmorrisdotca/chikyu-earth/place";
8
+ *
9
+ * console.log(PLACE_COAST_KM);
10
+ * ```
11
+ */
12
+ export declare const PLACE_COAST_KM = 50;
13
+ /** A country the outlines know, with the continent group chizu gives it. */
14
+ export interface LandHit {
15
+ code: string | null;
16
+ name: string;
17
+ nameJa: string;
18
+ group: string;
19
+ groupJa: string;
20
+ }
21
+ export interface LandAnswer {
22
+ /** Inside one outline, and not merely within {@link PLACE_COAST_KM} of its edge while sitting outside it. */
23
+ country: LandHit | null;
24
+ /** Outside every outline, and within {@link PLACE_COAST_KM} of the nearest one. */
25
+ near: (LandHit & {
26
+ distanceKm: number;
27
+ }) | null;
28
+ }
29
+ /** The country at a longitude and latitude, or the nearest one when the point is just off a coarse outline. The shapes are Natural Earth 1:110m. */
30
+ export declare function landAt(lon: number, lat: number): LandAnswer;
@@ -0,0 +1,177 @@
1
+ // Which country a point is in, from the same Natural Earth 1:110m outlines the line globe draws (chizu's world-geo).
2
+ // The line is coarse, so a point within PLACE_COAST_KM of an outline but outside every shape is `near`, not a country.
3
+ import { geoContains } from "d3-geo";
4
+ import WORLD_GEO from "@johnmorrisdotca/chizu/world-geo";
5
+ /**
6
+ * How close to a 1:110m outline, in kilometres, still counts as that country nearby.
7
+ * The outlines can sit tens of kilometres off a real coast, so a point this close is not reported as inside.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { PLACE_COAST_KM } from "@johnmorrisdotca/chikyu-earth/place";
12
+ *
13
+ * console.log(PLACE_COAST_KM);
14
+ * ```
15
+ */
16
+ export const PLACE_COAST_KM = 50;
17
+ const RAD = Math.PI / 180;
18
+ const MEAN_RADIUS_KM = 6371.0088;
19
+ const CELL = 15;
20
+ const EXPAND = 0.8;
21
+ const toVec = (lon, lat) => {
22
+ const la = lat * RAD;
23
+ const lo = lon * RAD;
24
+ const c = Math.cos(la);
25
+ return [c * Math.cos(lo), c * Math.sin(lo), Math.sin(la)];
26
+ };
27
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
28
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
29
+ const hypot = (a) => Math.hypot(a[0], a[1], a[2]);
30
+ const angle = (a, b) => Math.acos(Math.min(1, Math.max(-1, dot(a, b))));
31
+ /** Kilometres from `p` to the minor arc `a`–`b`. A segment longer than half a turn uses the nearer end. */
32
+ const segmentKm = (p, a, b) => {
33
+ const ab = angle(a, b);
34
+ if (ab < 1e-8 || ab > Math.PI - 1e-4)
35
+ return Math.min(angle(p, a), angle(p, b)) * MEAN_RADIUS_KM;
36
+ const n = cross(a, b);
37
+ const nn = hypot(n);
38
+ if (nn < 1e-12)
39
+ return angle(p, a) * MEAN_RADIUS_KM;
40
+ const scale = dot(p, n) / (nn * nn);
41
+ const raw = [p[0] - n[0] * scale, p[1] - n[1] * scale, p[2] - n[2] * scale];
42
+ const len = hypot(raw);
43
+ if (len < 1e-12)
44
+ return 0;
45
+ const g = [raw[0] / len, raw[1] / len, raw[2] / len];
46
+ const on = dot(cross(a, g), n) >= -1e-7 && dot(cross(g, b), n) >= -1e-7;
47
+ return (on ? angle(p, g) : Math.min(angle(p, a), angle(p, b))) * MEAN_RADIUS_KM;
48
+ };
49
+ const ringsOf = (geometry) => {
50
+ if (geometry.type === "Polygon")
51
+ return geometry.coordinates;
52
+ if (geometry.type === "MultiPolygon")
53
+ return geometry.coordinates.flat();
54
+ return [];
55
+ };
56
+ const boxesOf = (rings) => {
57
+ let south = 90;
58
+ let north = -90;
59
+ let wraps = false;
60
+ const lons = [];
61
+ for (const ring of rings) {
62
+ for (let i = 0; i < ring.length; i += 1) {
63
+ const lon = ring[i][0];
64
+ const lat = ring[i][1];
65
+ lons.push(lon);
66
+ if (lat < south)
67
+ south = lat;
68
+ if (lat > north)
69
+ north = lat;
70
+ if (i > 0 && Math.abs(lon - ring[i - 1][0]) > 180)
71
+ wraps = true;
72
+ }
73
+ }
74
+ if (lons.length === 0)
75
+ return [];
76
+ if (!wraps)
77
+ return [{ west: Math.min(...lons), east: Math.max(...lons), south, north }];
78
+ const east = lons.filter((lon) => lon >= 0);
79
+ const west = lons.filter((lon) => lon < 0);
80
+ const boxes = [];
81
+ if (east.length > 0)
82
+ boxes.push({ west: Math.min(...east), east: 180, south, north });
83
+ if (west.length > 0)
84
+ boxes.push({ west: -180, east: Math.max(...west), south, north });
85
+ return boxes;
86
+ };
87
+ const cellKey = (lon, lat) => {
88
+ const x = Math.max(-180, Math.min(165, Math.floor(lon / CELL) * CELL));
89
+ const y = Math.max(-90, Math.min(75, Math.floor(lat / CELL) * CELL));
90
+ return (x + 180) / CELL + ((y + 90) / CELL) * 24;
91
+ };
92
+ const build = () => {
93
+ const lands = [];
94
+ const grid = new Map();
95
+ for (const feature of WORLD_GEO.features) {
96
+ const geometry = feature.geometry;
97
+ const raw = ringsOf(geometry);
98
+ if (raw.length === 0)
99
+ continue;
100
+ const boxes = boxesOf(raw);
101
+ const rings = raw.map((ring) => ring.map(([lon, lat]) => toVec(lon, lat)));
102
+ const area = boxes.reduce((sum, box) => sum + (box.east - box.west) * (box.north - box.south), 0);
103
+ const index = lands.length;
104
+ const props = feature.properties;
105
+ lands.push({
106
+ code: props.code.length === 2 ? props.code : null,
107
+ name: props.name,
108
+ nameJa: props.nameJa || props.name,
109
+ group: props.group ?? "",
110
+ groupJa: props.groupJa ?? "",
111
+ geometry,
112
+ rings,
113
+ boxes,
114
+ area,
115
+ });
116
+ for (const box of boxes) {
117
+ const west = Math.max(-180, box.west - EXPAND);
118
+ const east = Math.min(180, box.east + EXPAND);
119
+ const south = Math.max(-90, box.south - EXPAND);
120
+ const north = Math.min(90, box.north + EXPAND);
121
+ for (let lat = Math.floor(south / CELL) * CELL; lat <= north; lat += CELL) {
122
+ for (let lon = Math.floor(west / CELL) * CELL; lon <= east; lon += CELL) {
123
+ const key = cellKey(Math.max(-180, Math.min(179.9, lon)), Math.max(-90, Math.min(89.9, lat)));
124
+ const list = grid.get(key);
125
+ if (list)
126
+ list.push(index);
127
+ else
128
+ grid.set(key, [index]);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return { lands, grid };
134
+ };
135
+ let ready = null;
136
+ const index = () => (ready ??= build());
137
+ const nearestKm = (land, point) => {
138
+ let best = Number.POSITIVE_INFINITY;
139
+ for (const ring of land.rings) {
140
+ for (let i = 0; i < ring.length - 1; i += 1) {
141
+ const km = segmentKm(point, ring[i], ring[i + 1]);
142
+ if (km < best)
143
+ best = km;
144
+ if (best === 0)
145
+ return 0;
146
+ }
147
+ }
148
+ return best;
149
+ };
150
+ const asHit = (land) => ({ code: land.code, name: land.name, nameJa: land.nameJa, group: land.group, groupJa: land.groupJa });
151
+ /** The country at a longitude and latitude, or the nearest one when the point is just off a coarse outline. The shapes are Natural Earth 1:110m. */
152
+ export function landAt(lon, lat) {
153
+ const { lands, grid } = index();
154
+ const list = grid.get(cellKey(lon, lat)) ?? [];
155
+ const point = toVec(lon, lat);
156
+ let inside = null;
157
+ for (const id of list) {
158
+ const land = lands[id];
159
+ const feature = { type: "Feature", geometry: land.geometry, properties: {} };
160
+ if (!geoContains(feature, [lon, lat]))
161
+ continue;
162
+ if (!inside || land.area < inside.area)
163
+ inside = land;
164
+ }
165
+ if (inside)
166
+ return { country: asHit(inside), near: null };
167
+ let best = null;
168
+ for (const id of list) {
169
+ const land = lands[id];
170
+ const km = nearestKm(land, point);
171
+ if (km <= PLACE_COAST_KM && (!best || km < best.km))
172
+ best = { land, km };
173
+ }
174
+ if (!best)
175
+ return { country: null, near: null };
176
+ return { country: null, near: { ...asHit(best.land), distanceKm: best.km } };
177
+ }
@@ -0,0 +1,15 @@
1
+ import type { SeaFeature } from "../sea-names/geometry.ts";
2
+ /**
3
+ * How far from a sea, gulf or bay's own point, in kilometres, a point still counts as that water.
4
+ * Each reach is wide enough to cover that water and short of the next named water's point.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { SEA_REACH_KM } from "@johnmorrisdotca/chikyu-earth/place";
9
+ *
10
+ * console.log(SEA_REACH_KM["sea-of-japan"] > 0);
11
+ * ```
12
+ */
13
+ export declare const SEA_REACH_KM: Readonly<Record<string, number>>;
14
+ /** The named sea, gulf, bay or ocean a point is over, or null when none is within its reach. A smaller water's point is nearer, so it wins over an ocean. */
15
+ export declare function waterAt(lon: number, lat: number): SeaFeature | null;
@@ -0,0 +1,63 @@
1
+ import { SEA_FEATURES } from "../sea-names/features.js";
2
+ const RAD = Math.PI / 180;
3
+ const MEAN_RADIUS_KM = 6371.0088;
4
+ /**
5
+ * How far from a sea, gulf or bay's own point, in kilometres, a point still counts as that water.
6
+ * Each reach is wide enough to cover that water and short of the next named water's point.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { SEA_REACH_KM } from "@johnmorrisdotca/chikyu-earth/place";
11
+ *
12
+ * console.log(SEA_REACH_KM["sea-of-japan"] > 0);
13
+ * ```
14
+ */
15
+ export const SEA_REACH_KM = {
16
+ "arctic-ocean": 3500,
17
+ "southern-ocean": 5500,
18
+ "atlantic-ocean": 10000,
19
+ "pacific-ocean": 12000,
20
+ "indian-ocean": 7000,
21
+ "black-sea": 650,
22
+ "philippine-sea": 1600,
23
+ "tasman-sea": 1100,
24
+ "bay-of-bengal": 1300,
25
+ "south-china-sea": 1400,
26
+ "arabian-sea": 1400,
27
+ "beaufort-sea": 800,
28
+ "caribbean-sea": 1200,
29
+ "gulf-of-mexico": 900,
30
+ "labrador-sea": 800,
31
+ "hudson-bay": 700,
32
+ "caspian-sea": 650,
33
+ "baffin-bay": 800,
34
+ "gulf-of-alaska": 800,
35
+ "red-sea": 1100,
36
+ "sea-of-okhotsk": 900,
37
+ "weddell-sea": 1400,
38
+ "persian-gulf": 450,
39
+ "mediterranean-sea": 1800,
40
+ "ross-sea": 900,
41
+ "coral-sea": 1200,
42
+ "sea-of-japan": 800,
43
+ };
44
+ const waters = SEA_FEATURES.filter((one) => one.kind !== "continent");
45
+ const kmBetween = (lon, lat, feature) => {
46
+ const φ1 = lat * RAD;
47
+ const φ2 = feature.lat * RAD;
48
+ const Δφ = (feature.lat - lat) * RAD;
49
+ const Δλ = (feature.lon - lon) * RAD;
50
+ const h = Math.sin(Δφ / 2) ** 2 + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) ** 2;
51
+ return 2 * MEAN_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
52
+ };
53
+ /** The named sea, gulf, bay or ocean a point is over, or null when none is within its reach. A smaller water's point is nearer, so it wins over an ocean. */
54
+ export function waterAt(lon, lat) {
55
+ let best = null;
56
+ for (const feature of waters) {
57
+ const reach = SEA_REACH_KM[feature.id] ?? 0;
58
+ const km = kmBetween(lon, lat, feature);
59
+ if (km <= reach && (!best || km < best.km))
60
+ best = { feature, km };
61
+ }
62
+ return best?.feature ?? null;
63
+ }
@@ -3,7 +3,7 @@ import type { AssetCache, Item3D } from "@johnmorrisdotca/kazoku-ui/renderer";
3
3
  import type { GeoPoint, GlobeView } from "../types.ts";
4
4
  import type { SatelliteRef } from "../satellites/types.ts";
5
5
  import { lookAt } from "../view.ts";
6
- import { type SatelliteState } from "../space/satellite-layer.ts";
6
+ import { type SatelliteScreen, type SatelliteState } from "../space/satellite-layer.ts";
7
7
  import type { Layer } from "./tiers.ts";
8
8
  import { type ThreeParts } from "./textures.ts";
9
9
  import { type TileSet, type TileSources } from "./tile-set.ts";
@@ -87,6 +87,8 @@ export interface EarthModel {
87
87
  tiles: TileSet | null;
88
88
  /** The satellite at a point of the view (CSS pixels), within a radius, once a draw has been made and one is there. */
89
89
  pick: ((x: number, y: number, radius: number) => SatelliteRef | null) | null;
90
+ /** Where a satellite of a shown group is on the screen as of the last draw, or `null`. */
91
+ placeSatellite: ((ref: SatelliteRef) => SatelliteScreen | null) | null;
90
92
  /** The pixel ratio the textures are chosen for. */
91
93
  ratio(): number;
92
94
  /** Meteors seen from space (src/meteors/layer.ts): off unless the element switches them on. */
@@ -135,6 +137,12 @@ export interface EarthDeps {
135
137
  width: number;
136
138
  height: number;
137
139
  }) => void;
140
+ /** Where the satellite under the pointer is, or null. Called at each draw while one is under the pointer (and once when it is let go). */
141
+ onHover?: (place: {
142
+ x: number;
143
+ y: number;
144
+ visible: boolean;
145
+ } | null) => void;
138
146
  /** The rings the places' layer wants drawn in one draw call, read right after `onPose`. */
139
147
  placeSprites?: () => PlaceSpriteData | null;
140
148
  /** Told once, when the rings of the places that are not markers of their own were first wanted: whether the picture can draw them (false when the three.js parts handed over lack `Points`). */
@@ -44,6 +44,7 @@ export const newModel = () => ({
44
44
  drawn: null,
45
45
  tiles: null,
46
46
  pick: null,
47
+ placeSatellite: null,
47
48
  ratio: () => Math.min(globalThis.devicePixelRatio || 1, 2),
48
49
  meteors: newMeteorState(),
49
50
  bodyLabel: newBodyLabelState(),
@@ -191,6 +192,7 @@ export function createEarthItem(model, deps) {
191
192
  inertial.add(spun);
192
193
  scene.add(inertial);
193
194
  let layer;
195
+ let hoverShown = false;
194
196
  // far enough in front that a geostationary satellite (6.6 radii out) is never behind the camera: an orthographic picture is the same from anywhere on the line
195
197
  const camera = new three.OrthographicCamera(-1, 1, 1, -1, 1, 120);
196
198
  camera.position.set(0, 0, 50);
@@ -242,6 +244,16 @@ export function createEarthItem(model, deps) {
242
244
  }
243
245
  layer?.update(model.time, model.speed, radius);
244
246
  model.pick = layer ? (x, y, radius) => layer.pick(x, y, camera, size, radius) : null;
247
+ model.placeSatellite = layer ? (ref) => layer.placeOf(ref, camera, size) : null;
248
+ if (layer && deps.onHover) {
249
+ const hover = model.satellites.hover;
250
+ const ref = hover.enabled && hover.ref && hover.fade > 0 ? hover.ref : null;
251
+ const at = ref ? layer.placeOf(ref, camera, size) : null;
252
+ const place = at ? { x: at.x, y: at.y, visible: at.visible } : null;
253
+ if (place || hoverShown)
254
+ deps.onHover(place);
255
+ hoverShown = place !== null;
256
+ }
245
257
  model.drawn = { view: { ...view }, time: model.time, radius, centre: { ...centre } };
246
258
  textures.sync(radius * model.ratio());
247
259
  tiles.sync({ lon: look.lon, lat: look.lat, width: size.width, height: size.height, panX: view.panX, panY: view.panY, radius }, [sunDir.value.x, sunDir.value.y, sunDir.value.z], true, model.ratio());
@@ -344,6 +356,7 @@ export function createEarthItem(model, deps) {
344
356
  dispose() {
345
357
  layer?.dispose();
346
358
  model.pick = null;
359
+ model.placeSatellite = null;
347
360
  clearTimeout(meteorTimer);
348
361
  meteors?.dispose();
349
362
  nameOn?.dispose();
@@ -56,6 +56,9 @@ type SatelliteStats = {
56
56
  averageUpdateMs: number;
57
57
  updates: number;
58
58
  selectedRing: boolean;
59
+ hoverPath: boolean;
60
+ hoverOpacity: number;
61
+ selectedOpacity: number;
59
62
  };
60
63
  /**
61
64
  * A `speed` attribute: how many seconds pass for each real second.
@@ -537,8 +540,26 @@ export declare class ChikyuEarthRealistic extends HTMLElement {
537
540
  ok: false;
538
541
  reason: "not-set";
539
542
  };
543
+ /**
544
+ * Draw a faint orbit while the pointer rests on a satellite. On unless `hover-path="off"`. Left unset, it is on when `names-on-hover` is on.
545
+ * The colour and the opacity are the custom properties `--chikyu-hover-path` and `--chikyu-hover-path-opacity`.
546
+ */
547
+ get hoverPath(): boolean;
548
+ set hoverPath(value: boolean);
549
+ /** Show a satellite's name while the pointer rests on it. On unless `names-on-hover="off"`. A touch does not rest, so it shows nothing. */
550
+ get namesOnHover(): boolean;
551
+ set namesOnHover(value: boolean);
540
552
  /** Mark one satellite: a larger ring round it and its orbit drawn. `null` lets it go. */
541
553
  selectSatellite(ref: SatelliteRef | null): void;
554
+ /**
555
+ * Where a satellite is on the screen as of the last draw: `{ x, y, visible, heightKm }` in CSS pixels from the view's top left, `visible` meaning it is inside the box and not behind the Earth. `null` when its group is not set or not shown, it cannot be placed, or it is behind the camera.
556
+ */
557
+ placeSatellite(ref: SatelliteRef): {
558
+ x: number;
559
+ y: number;
560
+ visible: boolean;
561
+ heightKm: number;
562
+ } | null;
542
563
  /** The satellite marked by `selectSatellite` or by a press on it, if any. */
543
564
  get selectedSatellite(): SatelliteRef | null;
544
565
  /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period, and `ownerCountry` when the owner is one country); undefined if it cannot be placed then. */