mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 00:43:15 +00:00
14443a17be
A traveller who visited only Alberta saw all of Canada colored on the zoomed-out globe. A new layer switch, Regions instead of countries, keeps the coarse regions of every country with a visited region on screen at every zoom: the engine loads and holds them (setPinnedRegions), the renderer draws them at full strength with faint inner borders, and the country itself only tints faintly beneath them once they are drawn. The switch is remembered per device, on the desktop layers dialog and the phone sheet, in all 28 languages. Also without the switch, a country with visited regions now steps far back once its regions fade in (to about a fifth instead of two thirds), so the regions really visited stand out from the rest of the country.
864 lines
30 KiB
TypeScript
864 lines
30 KiB
TypeScript
/**
|
|
* Drives the Atlas globe: camera with inertia and a zoom spring, gestures,
|
|
* loading the right level of detail and the regions in view, picking, and one
|
|
* animation loop that only runs while something moves.
|
|
*
|
|
* Framework free. AtlasGlobe.tsx mounts it and feeds it data; it reports back
|
|
* through the callbacks in GlobeEngineOptions.
|
|
*/
|
|
import type { Topology } from 'topojson-specification';
|
|
import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type GlobeTheme } from './GlobeRenderer';
|
|
import {
|
|
frameParams,
|
|
latLimits,
|
|
MAX_ZOOM,
|
|
MIN_ZOOM,
|
|
morphOf,
|
|
projectPoint,
|
|
RAD,
|
|
sunVector,
|
|
xSqueeze,
|
|
type FrameParams,
|
|
type GlobeCamera,
|
|
type GlobeViewport,
|
|
} from './globeMath';
|
|
import { buildOcean, type BuiltLayer, type LineMesh } from './globeMesh';
|
|
import type { MeshRequest, MeshResponse } from './globeMesh.worker';
|
|
|
|
export interface AtlasMeshManifest {
|
|
version: number;
|
|
lods: string[];
|
|
regionLods: string[];
|
|
world: Record<string, string>;
|
|
countries: Array<{
|
|
a2: string | null;
|
|
a3: string;
|
|
name: string;
|
|
anchor: [number, number] | null;
|
|
bbox: number[];
|
|
area: number;
|
|
}>;
|
|
regions: Record<string, { bbox: number[]; counted: number; total: number; index: string }>;
|
|
/** [a2, code, name, nameEn, lon, lat] per region */
|
|
regionSearch?: string;
|
|
attribution: string[];
|
|
}
|
|
|
|
export interface RegionIndex {
|
|
bbox: number[];
|
|
counted: number;
|
|
features: Array<{
|
|
code: string | null;
|
|
name: string | null;
|
|
nameEn: string | null;
|
|
anchor: [number, number] | null;
|
|
counted: boolean;
|
|
}>;
|
|
files: Record<string, string>;
|
|
}
|
|
|
|
export interface GlobeEngineOptions {
|
|
canvas: HTMLCanvasElement;
|
|
/** Fetches a JSON file below /api/addons/atlas/mesh/ (auth and API base are the caller's). */
|
|
fetchJson: (path: string) => Promise<unknown>;
|
|
theme: GlobeTheme;
|
|
initial?: Partial<GlobeCamera>;
|
|
onFrame?: (engine: GlobeEngine) => void;
|
|
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
|
|
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
|
|
onReady?: () => void;
|
|
onError?: (err: unknown) => void;
|
|
}
|
|
|
|
export type GlobeHit =
|
|
| { kind: 'country'; index: number; a2: string | null }
|
|
| { kind: 'region'; a2: string; code: string | null; name: string | null };
|
|
|
|
/** Zoom from which regions crossfade in, and from which the finer region files load. */
|
|
const REGION_FADE_START = 5;
|
|
const REGION_FADE_END = 6;
|
|
/**
|
|
* From here on the regions in view are fetched ahead, while the zoom is still
|
|
* on its way, so they are drawn by the time they fade in instead of a beat later.
|
|
*/
|
|
const REGION_PREFETCH_ZOOM = 3;
|
|
/** How often the view is checked for regions to fetch, in seconds. */
|
|
const REGION_SCAN_EVERY = 0.2;
|
|
/** A region file that failed is asked for again after this long, not every frame. */
|
|
const REGION_RETRY_AFTER = 20;
|
|
const REGION_FINE_ZOOM = 8;
|
|
const WORLD_LOD_ZOOM: Array<[string, number]> = [
|
|
['l2', 4.2],
|
|
['l1', 2.0],
|
|
['l0', 0],
|
|
];
|
|
const MAX_EDGE: Record<string, number> = { l0: 8, l1: 4, l2: 2, r0: 3, r1: 1.5 };
|
|
|
|
/**
|
|
* What one visit to the Atlas loaded and built, kept for the next one in this
|
|
* tab: the manifest and the built world meshes, by file name (the name carries
|
|
* the content hash). Coming back then puts the globe up at once, instead of
|
|
* reading and triangulating the world again behind a loading notice. A new
|
|
* page load starts empty, so a deploy's new geometry is read as before.
|
|
*/
|
|
let keptManifest: Promise<AtlasMeshManifest> | null = null;
|
|
const keptWorlds = new Map<string, BuiltLayer>();
|
|
const FIRST_REGION_ID = 512;
|
|
|
|
export class GlobeEngine {
|
|
readonly renderer: GlobeRenderer;
|
|
readonly cam: GlobeCamera = { lon: 10, lat: 30, zoom: 1 };
|
|
manifest: AtlasMeshManifest | null = null;
|
|
readonly regionIndex = new Map<string, RegionIndex>();
|
|
/** Status-texture id of each country's first region. */
|
|
readonly regionBase = new Map<string, number>();
|
|
vp: GlobeViewport = { width: 1, height: 1, baseRadius: 1, globeY: 0, flatY: 0 };
|
|
frame: FrameParams;
|
|
theme: GlobeTheme;
|
|
hover = -1;
|
|
selected = -1;
|
|
selectedOutline: LineMesh | null = null;
|
|
arcs: ArcLayer[] = [];
|
|
arcStart = 0;
|
|
revealStart = 0;
|
|
/** Set while something orbits the globe and needs every frame. */
|
|
ambient = false;
|
|
private reducedMotion =
|
|
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
private idleTimer = 0;
|
|
/** Extra px at the bottom the map should keep clear (sheets, docks). */
|
|
insetBottom = 0;
|
|
|
|
private opts: GlobeEngineOptions;
|
|
private dpr = 1;
|
|
private targetZoom = 1;
|
|
private vx = 0;
|
|
private vy = 0;
|
|
private dragging = false;
|
|
private pointers = new Map<number, { x: number; y: number }>();
|
|
private pinch: { d: number; z: number } | null = null;
|
|
private down: { x: number; y: number; t: number } | null = null;
|
|
private fly: { from: GlobeCamera; to: GlobeCamera; t0: number; dur: number } | null = null;
|
|
private raf = 0;
|
|
private idleFrames = 0;
|
|
private alive = true;
|
|
private worker: Worker;
|
|
private job = 0;
|
|
private pending = new Map<number, { resolve: (l: BuiltLayer) => void; reject: (err: Error) => void }>();
|
|
private worldLoading = new Set<string>();
|
|
private regionLoading = new Set<string>();
|
|
private regionFailedAt = new Map<string, number>();
|
|
private regionScanAt = -1;
|
|
private inViewRegionKeys: ReadonlySet<string> = new Set();
|
|
/** Countries whose regions show at every zoom, not only once zoomed in (the regions view). */
|
|
private pinned: ReadonlySet<string> = new Set();
|
|
private prefetchQueue: string[] = [];
|
|
private prefetchTimer = 0;
|
|
private nextRegionId = FIRST_REGION_ID;
|
|
private ink: { id: number; lon: number; lat: number; t0: number } | null = null;
|
|
private t0 = performance.now();
|
|
private lastHoverAt = 0;
|
|
private resizeObs: ResizeObserver;
|
|
private regionKeys: string[] = [];
|
|
private zoomAnchor: { x: number; y: number; lon: number; lat: number } | null = null;
|
|
private sun: [number, number, number] = sunVector(new Date());
|
|
private sunAt = 0;
|
|
|
|
constructor(opts: GlobeEngineOptions) {
|
|
this.opts = opts;
|
|
this.theme = opts.theme;
|
|
Object.assign(this.cam, opts.initial ?? {});
|
|
this.targetZoom = this.cam.zoom;
|
|
this.renderer = new GlobeRenderer(opts.canvas);
|
|
this.renderer.setOcean(buildOcean());
|
|
this.frame = frameParams(this.cam, this.vp);
|
|
this.worker = new Worker(new URL('./globeMesh.worker.ts', import.meta.url), { type: 'module' });
|
|
// A build that fails rejects its own job only: the caller decides what that
|
|
// means (a region stays plain, a missing world level keeps the coarser one).
|
|
this.worker.onmessage = (e: MessageEvent<MeshResponse>) => {
|
|
const job = this.pending.get(e.data.job);
|
|
this.pending.delete(e.data.job);
|
|
if (!job) return;
|
|
if (e.data.layer) job.resolve(e.data.layer);
|
|
else job.reject(new Error(e.data.error ?? 'Atlas mesh build failed'));
|
|
};
|
|
this.bindInput(opts.canvas);
|
|
this.resizeObs = new ResizeObserver(() => this.resize());
|
|
this.resizeObs.observe(opts.canvas);
|
|
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
|
|
this.resize();
|
|
void this.boot();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- loading
|
|
|
|
private build(topo: Topology, object: string, maxEdge: number, idBase: number): Promise<BuiltLayer> {
|
|
const job = ++this.job;
|
|
return new Promise((resolve, reject) => {
|
|
this.pending.set(job, { resolve, reject });
|
|
this.worker.postMessage({ job, topo, object, maxEdge, idBase } satisfies MeshRequest);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* A fetch tried again with growing pauses (1, 2, 4, 8 s): a server that is
|
|
* restarting or a connection that drops for a moment must not leave the
|
|
* globe empty for good.
|
|
*/
|
|
private async fetchRetrying(path: string): Promise<unknown> {
|
|
for (let n = 0; ; n++) {
|
|
try {
|
|
return await this.opts.fetchJson(path);
|
|
} catch (err) {
|
|
if (n >= 4 || !this.alive) throw err;
|
|
await new Promise((r) => window.setTimeout(r, 1000 * 2 ** n));
|
|
}
|
|
}
|
|
}
|
|
|
|
private async boot(): Promise<void> {
|
|
try {
|
|
keptManifest ??= this.fetchRetrying('manifest') as Promise<AtlasMeshManifest>;
|
|
try {
|
|
this.manifest = await keptManifest;
|
|
} catch (err) {
|
|
// A failed read is not kept: the next visit asks again.
|
|
keptManifest = null;
|
|
throw err;
|
|
}
|
|
await this.loadWorld('l0');
|
|
this.revealStart = this.now();
|
|
this.opts.onReady?.();
|
|
this.kick();
|
|
} catch (err) {
|
|
this.opts.onError?.(err);
|
|
}
|
|
}
|
|
|
|
private async loadWorld(lod: string): Promise<void> {
|
|
if (!this.manifest || this.renderer.hasWorld(lod) || this.worldLoading.has(lod)) return;
|
|
this.worldLoading.add(lod);
|
|
try {
|
|
const file = this.manifest.world[lod];
|
|
let layer = keptWorlds.get(file);
|
|
if (!layer) {
|
|
const topo = (await this.fetchRetrying(`world/${file}`)) as Topology;
|
|
layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0);
|
|
keptWorlds.set(file, layer);
|
|
}
|
|
if (!this.alive) return;
|
|
this.renderer.setWorld(lod, layer);
|
|
this.kick();
|
|
} finally {
|
|
this.worldLoading.delete(lod);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Shows these countries' regions at every zoom instead of only once zoomed
|
|
* in, so a country with a few visited regions reads as those regions rather
|
|
* than as a whole visited country. An empty list goes back to the usual fade.
|
|
*/
|
|
setPinnedRegions(a2s: readonly string[]): void {
|
|
this.pinned = new Set(a2s);
|
|
this.kick();
|
|
}
|
|
|
|
/** The region layers that must stay on the GPU: those in view and the pinned countries' coarse ones. */
|
|
private regionsInUse(): ReadonlySet<string> {
|
|
if (!this.pinned.size) return this.inViewRegionKeys;
|
|
return new Set([...this.inViewRegionKeys, ...[...this.pinned].map((a2) => `${a2}:r0`)]);
|
|
}
|
|
|
|
async loadRegionIndex(a2: string): Promise<RegionIndex | null> {
|
|
const have = this.regionIndex.get(a2);
|
|
if (have) return have;
|
|
const entry = this.manifest?.regions[a2];
|
|
if (!entry) return null;
|
|
const idx = (await this.opts.fetchJson(entry.index)) as RegionIndex;
|
|
if (!this.regionIndex.has(a2)) {
|
|
this.regionIndex.set(a2, idx);
|
|
if (this.nextRegionId + idx.features.length < MAX_FEATURES) {
|
|
this.regionBase.set(a2, this.nextRegionId);
|
|
this.nextRegionId += idx.features.length;
|
|
}
|
|
}
|
|
return this.regionIndex.get(a2) ?? null;
|
|
}
|
|
|
|
private async loadRegion(a2: string, lod: string): Promise<void> {
|
|
const key = `${a2}:${lod}`;
|
|
if (this.renderer.hasRegion(key) || this.regionLoading.has(key)) return;
|
|
const failedAt = this.regionFailedAt.get(key);
|
|
if (failedAt !== undefined && this.now() - failedAt < REGION_RETRY_AFTER) return;
|
|
this.regionLoading.add(key);
|
|
try {
|
|
const idx = await this.loadRegionIndex(a2);
|
|
const base = this.regionBase.get(a2);
|
|
if (!idx || base === undefined) return;
|
|
const topo = (await this.opts.fetchJson(idx.files[lod])) as Topology;
|
|
const layer = await this.build(topo, 'regions', MAX_EDGE[lod], base);
|
|
if (!this.alive) return;
|
|
this.renderer.setRegion(key, layer, this.regionsInUse());
|
|
this.onRegionLoaded?.(a2);
|
|
this.kick();
|
|
} catch {
|
|
// A country's regions are detail on top of a working globe: one that does
|
|
// not load leaves the country plain and is asked for again later, it does
|
|
// not turn the whole Atlas into an error.
|
|
this.regionFailedAt.set(key, this.now());
|
|
} finally {
|
|
this.regionLoading.delete(key);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fetches the coarse regions of these countries in the background, one at a
|
|
* time while the browser is idle (the owner passes the countries the user is
|
|
* most likely to zoom into), so their first zoom finds them ready.
|
|
*/
|
|
prefetchRegions(codes: string[]): void {
|
|
const known = new Set(this.prefetchQueue);
|
|
for (const a2 of codes) if (this.manifest?.regions[a2] && !known.has(a2)) this.prefetchQueue.push(a2);
|
|
this.schedulePrefetch();
|
|
}
|
|
|
|
private schedulePrefetch(): void {
|
|
if (this.prefetchTimer || !this.prefetchQueue.length || !this.alive) return;
|
|
const next = () => {
|
|
this.prefetchTimer = 0;
|
|
const a2 = this.prefetchQueue.shift();
|
|
if (!a2 || !this.alive) return;
|
|
void this.loadRegion(a2, 'r0').finally(() => this.schedulePrefetch());
|
|
};
|
|
const idle = (window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number })
|
|
.requestIdleCallback;
|
|
this.prefetchTimer = idle ? idle(next, { timeout: 1500 }) : window.setTimeout(next, 120);
|
|
}
|
|
|
|
/** Called after a country's regions arrived, so the owner can colour them. */
|
|
onRegionLoaded: ((a2: string) => void) | null = null;
|
|
|
|
private worldKey(): string {
|
|
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z && this.renderer.hasWorld(lod)) return lod;
|
|
for (const [lod] of WORLD_LOD_ZOOM.slice().reverse()) if (this.renderer.hasWorld(lod)) return lod;
|
|
return 'l0';
|
|
}
|
|
|
|
private wantedWorld(): string {
|
|
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z) return lod;
|
|
return 'l0';
|
|
}
|
|
|
|
/** Countries with regions whose box overlaps the view, nearest first. */
|
|
private countriesInView(): string[] {
|
|
const m = this.manifest;
|
|
if (!m) return [];
|
|
const out: Array<[string, number]> = [];
|
|
const { width, height } = this.vp;
|
|
for (const c of m.countries) {
|
|
if (!c.a2 || !m.regions[c.a2]) continue;
|
|
const [w, s, e, n] = c.bbox;
|
|
let best = Infinity;
|
|
let inView = false;
|
|
for (const [lon, lat] of [
|
|
[(w + e) / 2, (s + n) / 2],
|
|
[w, s],
|
|
[e, n],
|
|
[w, n],
|
|
[e, s],
|
|
c.anchor ?? [(w + e) / 2, (s + n) / 2],
|
|
]) {
|
|
const p = projectPoint(lon, lat, this.frame);
|
|
if (p.visible < 0) continue;
|
|
if (p.x > -200 && p.x < width + 200 && p.y > -200 && p.y < height + 200) inView = true;
|
|
best = Math.min(best, Math.hypot(p.x - width / 2, p.y - height / 2));
|
|
}
|
|
if (inView) out.push([c.a2, best]);
|
|
}
|
|
return out
|
|
.sort((a, b) => a[1] - b[1])
|
|
.slice(0, 10)
|
|
.map((x) => x[0]);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- camera
|
|
|
|
private now(): number {
|
|
return (performance.now() - this.t0) / 1000;
|
|
}
|
|
|
|
resize(): void {
|
|
const c = this.opts.canvas;
|
|
const r = c.getBoundingClientRect();
|
|
this.dpr = Math.min(2, window.devicePixelRatio || 1);
|
|
c.width = Math.max(1, Math.round(r.width * this.dpr));
|
|
c.height = Math.max(1, Math.round(r.height * this.dpr));
|
|
const narrow = r.width < 640;
|
|
const usable = r.height - this.insetBottom;
|
|
this.vp = {
|
|
width: r.width,
|
|
height: r.height,
|
|
baseRadius: narrow ? r.width * 0.42 : Math.min(r.width, usable) * 0.31,
|
|
// On a phone the globe sits a little lower, clear of the search and buttons on top.
|
|
globeY: narrow ? usable * 0.54 : usable * 0.5,
|
|
flatY: usable * 0.5,
|
|
};
|
|
this.kick();
|
|
}
|
|
|
|
setInsetBottom(px: number): void {
|
|
if (Math.abs(px - this.insetBottom) < 1) return;
|
|
this.insetBottom = px;
|
|
this.resize();
|
|
}
|
|
|
|
setTheme(theme: GlobeTheme): void {
|
|
this.theme = theme;
|
|
this.kick();
|
|
}
|
|
|
|
flyTo(lon: number, lat: number, zoom = Math.max(this.cam.zoom, 1), dur = 1100): void {
|
|
let dl = lon - this.cam.lon;
|
|
dl = ((dl + 540) % 360) - 180;
|
|
this.fly = {
|
|
from: { ...this.cam },
|
|
to: { lon: this.cam.lon + dl, lat: Math.max(-70, Math.min(70, lat)), zoom },
|
|
t0: performance.now(),
|
|
dur,
|
|
};
|
|
this.vx = this.vy = 0;
|
|
this.kick();
|
|
}
|
|
|
|
/** Flies so a country's box fills the view. */
|
|
flyToBox(bbox: number[], minZoom = 1, maxZoom = 7): void {
|
|
const [w, s, e, n] = bbox;
|
|
const span = Math.max(e - w, (n - s) * 1.6, 0.5);
|
|
const zoom = Math.max(minZoom, Math.min(maxZoom, (110 / span) ** 0.85));
|
|
this.flyTo((w + e) / 2, (s + n) / 2, zoom);
|
|
}
|
|
|
|
zoomBy(f: number): void {
|
|
this.targetZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, this.targetZoom * f));
|
|
this.kick();
|
|
}
|
|
|
|
startInk(id: number, lon: number, lat: number): void {
|
|
this.ink = { id, lon, lat, t0: this.now() };
|
|
this.kick();
|
|
}
|
|
|
|
setSelected(id: number, outline: LineMesh | null): void {
|
|
this.selected = id;
|
|
this.selectedOutline = outline;
|
|
this.kick();
|
|
}
|
|
|
|
setArcs(arcs: ArcLayer[]): void {
|
|
this.arcs = arcs;
|
|
this.arcStart = this.now();
|
|
this.kick();
|
|
}
|
|
|
|
project(lon: number, lat: number): ReturnType<typeof projectPoint> {
|
|
return projectPoint(lon, lat, this.frame);
|
|
}
|
|
|
|
get morph(): number {
|
|
return this.frame.t;
|
|
}
|
|
|
|
get regionAlpha(): number {
|
|
const z = this.cam.zoom;
|
|
return Math.max(0, Math.min(1, (z - REGION_FADE_START) / (REGION_FADE_END - REGION_FADE_START)));
|
|
}
|
|
|
|
// ---------------------------------------------------------------- input
|
|
|
|
private bindInput(c: HTMLCanvasElement): void {
|
|
c.addEventListener('pointerdown', this.onDown);
|
|
c.addEventListener('pointermove', this.onMove);
|
|
c.addEventListener('pointerup', this.onUp);
|
|
c.addEventListener('pointercancel', this.onUp);
|
|
c.addEventListener('pointerleave', this.onLeave);
|
|
c.addEventListener('wheel', this.onWheel, { passive: false });
|
|
c.addEventListener('dblclick', this.onDbl);
|
|
}
|
|
|
|
private local(e: PointerEvent | WheelEvent | MouseEvent): { x: number; y: number } {
|
|
const r = this.opts.canvas.getBoundingClientRect();
|
|
return { x: e.clientX - r.left, y: e.clientY - r.top };
|
|
}
|
|
|
|
private onDown = (e: PointerEvent): void => {
|
|
this.opts.canvas.setPointerCapture(e.pointerId);
|
|
const p = this.local(e);
|
|
this.pointers.set(e.pointerId, p);
|
|
this.down = { ...p, t: performance.now() };
|
|
this.vx = this.vy = 0;
|
|
this.fly = null;
|
|
this.zoomAnchor = null;
|
|
this.dragging = true;
|
|
this.clearHover();
|
|
if (this.pointers.size === 2) {
|
|
const [a, b] = [...this.pointers.values()];
|
|
this.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), z: this.targetZoom };
|
|
}
|
|
this.kick();
|
|
};
|
|
|
|
private onMove = (e: PointerEvent): void => {
|
|
const p = this.local(e);
|
|
const prev = this.pointers.get(e.pointerId);
|
|
if (prev) {
|
|
this.pointers.set(e.pointerId, p);
|
|
if (this.pointers.size === 2 && this.pinch) {
|
|
const [a, b] = [...this.pointers.values()];
|
|
const d = Math.hypot(a.x - b.x, a.y - b.y);
|
|
this.targetZoom = Math.max(MIN_ZOOM * 0.85, Math.min(MAX_ZOOM * 1.1, (this.pinch.z * d) / this.pinch.d));
|
|
this.cam.zoom = this.targetZoom;
|
|
this.kick();
|
|
return;
|
|
}
|
|
if (this.pointers.size > 1) return;
|
|
const k = 1 / (this.frame.scale * RAD);
|
|
const kx = k / xSqueeze(this.frame);
|
|
const dx = p.x - prev.x;
|
|
const dy = p.y - prev.y;
|
|
this.cam.lon -= dx * kx;
|
|
this.cam.lat = this.clampLat(this.cam.lat + dy * k);
|
|
this.vx = dx * kx * 0.85 + this.vx * 0.15;
|
|
this.vy = dy * k * 0.85 + this.vy * 0.15;
|
|
this.kick();
|
|
return;
|
|
}
|
|
const now = performance.now();
|
|
if (now - this.lastHoverAt < 45) return;
|
|
this.lastHoverAt = now;
|
|
const hit = this.hitAt(p.x, p.y);
|
|
const id = hit ? this.idOf(hit) : -1;
|
|
if (id !== this.hover) {
|
|
this.hover = id;
|
|
this.kick();
|
|
}
|
|
this.opts.onHover?.(hit, p.x, p.y);
|
|
};
|
|
|
|
private onUp = (e: PointerEvent): void => {
|
|
if (!this.pointers.has(e.pointerId)) return;
|
|
this.pointers.delete(e.pointerId);
|
|
if (this.pointers.size < 2) this.pinch = null;
|
|
if (this.pointers.size > 0) return;
|
|
this.dragging = false;
|
|
const p = this.local(e);
|
|
if (this.down && Math.hypot(p.x - this.down.x, p.y - this.down.y) < 6 && performance.now() - this.down.t < 400) {
|
|
this.vx = this.vy = 0;
|
|
this.opts.onSelect?.(this.hitAt(p.x, p.y), p.x, p.y);
|
|
}
|
|
this.down = null;
|
|
this.kick();
|
|
};
|
|
|
|
private onLeave = (): void => {
|
|
if (this.dragging) return;
|
|
this.hover = -1;
|
|
this.opts.onHover?.(null, 0, 0);
|
|
this.kick();
|
|
};
|
|
|
|
/** Drops the hover while the camera moves; the next pointer move picks again. */
|
|
private clearHover(): void {
|
|
if (this.hover === -1) return;
|
|
this.hover = -1;
|
|
this.opts.onHover?.(null, 0, 0);
|
|
}
|
|
|
|
private onWheel = (e: WheelEvent): void => {
|
|
e.preventDefault();
|
|
this.clearHover();
|
|
const before = this.targetZoom;
|
|
const f = Math.exp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0016));
|
|
this.targetZoom = Math.max(MIN_ZOOM * 0.9, Math.min(MAX_ZOOM, before * f));
|
|
// On the flat map the place under the cursor stays under the cursor while the
|
|
// zoom glides; tick() moves the centre to keep it there, frame by frame.
|
|
if (this.frame.t > 0.5 && this.targetZoom !== before) {
|
|
const p = this.local(e);
|
|
const geo = this.unprojectFlat(p.x, p.y);
|
|
this.zoomAnchor = { x: p.x, y: p.y, lon: geo[0], lat: geo[1] };
|
|
}
|
|
this.fly = null;
|
|
this.kick();
|
|
};
|
|
|
|
/** Screen point to lon/lat on the flat map (t = 1); close enough while t > 0.5. */
|
|
private unprojectFlat(x: number, y: number): [number, number] {
|
|
const f = this.frame;
|
|
const k = 1 / (f.scale * RAD);
|
|
return [this.cam.lon + ((x - f.originX) * k) / xSqueeze(f), this.cam.lat - (y - f.originY) * k];
|
|
}
|
|
|
|
/** Moves the centre so the anchored place sits under its screen point again. */
|
|
private holdAnchor(): void {
|
|
const a = this.zoomAnchor;
|
|
if (!a) return;
|
|
for (let i = 0; i < 2; i++) {
|
|
const f = frameParams(this.cam, this.vp);
|
|
const k = 1 / (f.scale * RAD);
|
|
this.cam.lat = this.clampLat(a.lat + (a.y - f.originY) * k);
|
|
this.cam.lon = a.lon - ((a.x - f.originX) * k) / xSqueeze(f);
|
|
}
|
|
}
|
|
|
|
private onDbl = (e: MouseEvent): void => {
|
|
const p = this.local(e);
|
|
const hit = this.hitAt(p.x, p.y);
|
|
if (!hit) this.zoomBy(1.8);
|
|
};
|
|
|
|
private onContextLost = (e: Event): void => {
|
|
e.preventDefault();
|
|
this.opts.onError?.(new Error('WebGL context lost'));
|
|
};
|
|
|
|
// ---------------------------------------------------------------- picking
|
|
|
|
idOf(hit: GlobeHit): number {
|
|
if (hit.kind === 'country') return hit.index;
|
|
const idx = this.regionIndex.get(hit.a2);
|
|
const base = this.regionBase.get(hit.a2);
|
|
if (!idx || base === undefined) return -1;
|
|
const i = idx.features.findIndex((f) => f.code === hit.code);
|
|
return i < 0 ? -1 : base + i;
|
|
}
|
|
|
|
/**
|
|
* The country under the middle of the view, the one whose regions get their
|
|
* names. Read from the pick buffer, so it is the country really there and not
|
|
* the first whose bounding box holds the point (France's box spans half the
|
|
* world with its overseas parts). The read-back is not free, so it is only
|
|
* redone when the camera moved, at most every 150 ms.
|
|
*/
|
|
focusCountry(): string | null {
|
|
const now = this.now();
|
|
const cam = `${this.cam.lon.toFixed(3)},${this.cam.lat.toFixed(3)},${this.cam.zoom.toFixed(2)}`;
|
|
if (cam === this.focusCam || now - this.focusAt < 0.15) return this.focus;
|
|
this.focusAt = now;
|
|
this.focusCam = cam;
|
|
const hit = this.hitAt(this.vp.width / 2, this.vp.height / 2);
|
|
this.focus = hit?.a2 ?? null;
|
|
return this.focus;
|
|
}
|
|
|
|
private focus: string | null = null;
|
|
private focusAt = -1;
|
|
private focusCam = '';
|
|
|
|
hitAt(x: number, y: number): GlobeHit | null {
|
|
const id = this.renderer.pick(x, y, this.regionAlpha > 0.5);
|
|
if (id < 0) return null;
|
|
if (id < FIRST_REGION_ID) {
|
|
const c = this.manifest?.countries[id];
|
|
return c ? { kind: 'country', index: id, a2: c.a2 } : null;
|
|
}
|
|
for (const [a2, base] of this.regionBase) {
|
|
const idx = this.regionIndex.get(a2);
|
|
if (idx && id >= base && id < base + idx.features.length) {
|
|
const f = idx.features[id - base];
|
|
return { kind: 'region', a2, code: f.code, name: f.nameEn ?? f.name };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- loop
|
|
|
|
/** Starts the loop if it sleeps. */
|
|
kick(): void {
|
|
this.idleFrames = 0;
|
|
if (this.idleTimer) {
|
|
window.clearTimeout(this.idleTimer);
|
|
this.idleTimer = 0;
|
|
}
|
|
if (!this.raf && this.alive) this.raf = requestAnimationFrame(this.tick);
|
|
}
|
|
|
|
/** A latitude for the view's centre, held where the map's edges stay off screen. */
|
|
private clampLat(lat: number): number {
|
|
const [south, north] = latLimits(this.cam.zoom, this.vp);
|
|
return Math.max(south, Math.min(north, lat));
|
|
}
|
|
|
|
private tick = (): void => {
|
|
this.raf = 0;
|
|
if (!this.alive) return;
|
|
let moving = false;
|
|
const now = performance.now();
|
|
if (this.fly) {
|
|
const p = Math.min(1, (now - this.fly.t0) / this.fly.dur);
|
|
const e = p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
|
|
const { from, to } = this.fly;
|
|
this.cam.lon = from.lon + (to.lon - from.lon) * e;
|
|
this.cam.lat = from.lat + (to.lat - from.lat) * e;
|
|
// Pull back a little mid-flight, so long hops read as travel.
|
|
const hop = Math.min(1, Math.abs(to.lon - from.lon) / 120) * Math.sin(Math.PI * e) * 0.35;
|
|
this.cam.zoom = Math.max(MIN_ZOOM, from.zoom + (to.zoom - from.zoom) * e - hop * from.zoom);
|
|
this.targetZoom = this.cam.zoom;
|
|
if (p >= 1) {
|
|
this.fly = null;
|
|
this.targetZoom = to.zoom;
|
|
}
|
|
moving = true;
|
|
}
|
|
if (!this.dragging && !this.fly && (Math.abs(this.vx) > 1e-3 || Math.abs(this.vy) > 1e-3)) {
|
|
this.cam.lon -= this.vx;
|
|
this.cam.lat = this.clampLat(this.cam.lat + this.vy);
|
|
this.vx *= 0.93;
|
|
this.vy *= 0.93;
|
|
moving = true;
|
|
}
|
|
if (!this.pinch) {
|
|
if (this.targetZoom < MIN_ZOOM) this.targetZoom += (MIN_ZOOM - this.targetZoom) * 0.18;
|
|
if (this.targetZoom > MAX_ZOOM) this.targetZoom += (MAX_ZOOM - this.targetZoom) * 0.18;
|
|
}
|
|
const dz = (this.targetZoom - this.cam.zoom) * 0.2;
|
|
if (Math.abs(dz) > 1e-4) {
|
|
this.cam.zoom += dz;
|
|
moving = true;
|
|
if (this.zoomAnchor && morphOf(this.cam.zoom) > 0.5) this.holdAnchor();
|
|
} else {
|
|
this.zoomAnchor = null;
|
|
}
|
|
this.cam.lon = ((this.cam.lon + 540) % 360) - 180;
|
|
// Zooming into the flat map narrows how far north and south it may look.
|
|
this.cam.lat = this.clampLat(this.cam.lat);
|
|
|
|
this.frame = frameParams(this.cam, this.vp);
|
|
const want = this.wantedWorld();
|
|
// A finer level that cannot load leaves the coarser one on screen.
|
|
if (!this.renderer.hasWorld(want)) this.loadWorld(want).catch(() => undefined);
|
|
// Fetch ahead, by where the zoom is heading and not only where it is, and
|
|
// during the motion too: the coarse regions well before they fade in, the
|
|
// fine ones a step before they are drawn.
|
|
const heading = Math.max(this.cam.zoom, this.targetZoom);
|
|
const scanNow = this.now();
|
|
if (heading >= REGION_PREFETCH_ZOOM && scanNow - this.regionScanAt >= REGION_SCAN_EVERY) {
|
|
this.regionScanAt = scanNow;
|
|
const fine = heading >= REGION_FINE_ZOOM - 1;
|
|
const inView = this.countriesInView();
|
|
// What is in view now is what must not be dropped, and the last to go.
|
|
this.inViewRegionKeys = new Set(inView.flatMap((a2) => [`${a2}:r0`, `${a2}:r1`]));
|
|
for (const k of this.inViewRegionKeys) this.renderer.touchRegion(k);
|
|
for (const a2 of inView) {
|
|
void this.loadRegion(a2, 'r0');
|
|
if (fine) void this.loadRegion(a2, 'r1');
|
|
}
|
|
}
|
|
// The pinned countries' coarse regions, wherever the camera is.
|
|
for (const a2 of this.pinned) {
|
|
if (!this.manifest?.regions[a2]) continue;
|
|
this.renderer.touchRegion(`${a2}:r0`);
|
|
void this.loadRegion(a2, 'r0');
|
|
}
|
|
this.regionKeys = this.collectRegionKeys();
|
|
|
|
const time = this.now();
|
|
if (time - this.sunAt > 30) {
|
|
this.sun = sunVector(new Date());
|
|
this.sunAt = time;
|
|
}
|
|
let inkActive = false;
|
|
let ink: { id: number; lon: number; lat: number; radius: number } | null = null;
|
|
if (this.ink) {
|
|
const p = (time - this.ink.t0) / 0.75;
|
|
inkActive = p < 1;
|
|
ink = {
|
|
id: this.ink.id,
|
|
lon: this.ink.lon,
|
|
lat: this.ink.lat,
|
|
radius: (1 - Math.pow(1 - Math.min(1, p), 3)) * Math.PI,
|
|
};
|
|
if (!inkActive) this.ink = null;
|
|
}
|
|
const arcProgress = Math.min(1.001, (time - this.arcStart) / 1.6);
|
|
this.renderer.draw({
|
|
frame: this.frame,
|
|
dpr: this.dpr,
|
|
width: this.vp.width,
|
|
height: this.vp.height,
|
|
time,
|
|
revealStart: this.revealStart,
|
|
hover: this.hover,
|
|
selected: this.selected,
|
|
ink,
|
|
regionAlpha: this.regionAlpha,
|
|
pinnedRegions: this.pinned,
|
|
theme: this.theme,
|
|
arcs: this.arcs,
|
|
arcProgress,
|
|
regionKeys: this.regionKeys,
|
|
worldKey: this.worldKey(),
|
|
selectedOutline: this.selectedOutline,
|
|
sun: this.sun,
|
|
night: this.theme.dark ? 0.34 : 0.1,
|
|
});
|
|
this.opts.onFrame?.(this);
|
|
|
|
const revealing = time - this.revealStart < 3.2;
|
|
const twinkle = this.theme.dark && this.frame.t < 0.9;
|
|
if (moving || inkActive || revealing || arcProgress < 1 || this.dragging) this.idleFrames = 0;
|
|
else this.idleFrames++;
|
|
// Things that orbit (moon, satellites) need every frame while the globe shows;
|
|
// otherwise keep only the stars alive at a low rate once everything rests.
|
|
const ambient = this.ambient && this.frame.t < 0.6 && !document.hidden && !this.reducedMotion;
|
|
if (this.idleFrames < 3 || ambient) this.raf = requestAnimationFrame(this.tick);
|
|
else if (twinkle) this.idleTimer = window.setTimeout(() => this.kick(), 90);
|
|
};
|
|
|
|
private collectRegionKeys(): string[] {
|
|
const out: string[] = [];
|
|
// Pinned countries draw their regions before the zoom brings the rest in.
|
|
for (const a2 of this.pinned) {
|
|
if (this.regionAlpha <= 0 && this.renderer.hasRegion(`${a2}:r0`)) out.push(`${a2}:r0`);
|
|
}
|
|
if (this.regionAlpha <= 0) return out;
|
|
const fine = this.cam.zoom >= REGION_FINE_ZOOM;
|
|
for (const a2 of this.regionIndex.keys()) {
|
|
const k1 = `${a2}:r1`;
|
|
const k0 = `${a2}:r0`;
|
|
if (fine && this.renderer.hasRegion(k1)) out.push(k1);
|
|
else if (this.renderer.hasRegion(k0)) out.push(k0);
|
|
else if (this.renderer.hasRegion(k1)) out.push(k1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
get zoom(): number {
|
|
return this.cam.zoom;
|
|
}
|
|
|
|
isMorphing(): boolean {
|
|
const t = morphOf(this.cam.zoom);
|
|
return t > 0 && t < 1;
|
|
}
|
|
|
|
dispose(): void {
|
|
this.alive = false;
|
|
this.prefetchQueue = [];
|
|
window.clearTimeout(this.idleTimer);
|
|
cancelAnimationFrame(this.raf);
|
|
this.resizeObs.disconnect();
|
|
this.worker.terminate();
|
|
const c = this.opts.canvas;
|
|
c.removeEventListener('pointerdown', this.onDown);
|
|
c.removeEventListener('pointermove', this.onMove);
|
|
c.removeEventListener('pointerup', this.onUp);
|
|
c.removeEventListener('pointercancel', this.onUp);
|
|
c.removeEventListener('pointerleave', this.onLeave);
|
|
c.removeEventListener('wheel', this.onWheel);
|
|
c.removeEventListener('dblclick', this.onDbl);
|
|
c.removeEventListener('webglcontextlost', this.onContextLost);
|
|
this.renderer.dispose();
|
|
}
|
|
}
|