From c7cb0bc067369467b0de6c77d96e853e4fcb50fc Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 28 Nov 2026 22:34:41 +0100 Subject: [PATCH] feat(atlas): a WebGL globe engine One shader morphs an orthographic globe into a flat map as the zoom grows. Country and region meshes are built in a worker from the TopoJSON, picked on the GPU and coloured from a status texture; borders, coasts and flight arcs are instanced screen-space lines. Regions are fetched ahead of the zoom and kept to a bounded set; labels avoid each other. Includes the day and night line, the moon in its phase and the badge medals. --- .../src/components/AtlasGlobe/AtlasGlobe.tsx | 118 +++ .../src/components/AtlasGlobe/BadgeMedal.tsx | 179 ++++ .../src/components/AtlasGlobe/GlobeEngine.ts | 803 ++++++++++++++++++ .../src/components/AtlasGlobe/GlobePins.tsx | 68 ++ .../components/AtlasGlobe/GlobeRenderer.ts | 592 +++++++++++++ client/src/components/AtlasGlobe/GlobeSky.tsx | 92 ++ .../components/AtlasGlobe/GlobeStatsBar.tsx | 55 ++ .../src/components/AtlasGlobe/atlasGlobe.css | 311 +++++++ .../src/components/AtlasGlobe/globeLabels.ts | 165 ++++ .../components/AtlasGlobe/globeMath.test.ts | 111 +++ client/src/components/AtlasGlobe/globeMath.ts | 235 +++++ .../components/AtlasGlobe/globeMesh.test.ts | 85 ++ client/src/components/AtlasGlobe/globeMesh.ts | 220 +++++ .../components/AtlasGlobe/globeMesh.worker.ts | 43 + .../src/components/AtlasGlobe/globeShaders.ts | 308 +++++++ .../src/components/AtlasGlobe/globeTheme.ts | 65 ++ 16 files changed, 3450 insertions(+) create mode 100644 client/src/components/AtlasGlobe/AtlasGlobe.tsx create mode 100644 client/src/components/AtlasGlobe/BadgeMedal.tsx create mode 100644 client/src/components/AtlasGlobe/GlobeEngine.ts create mode 100644 client/src/components/AtlasGlobe/GlobePins.tsx create mode 100644 client/src/components/AtlasGlobe/GlobeRenderer.ts create mode 100644 client/src/components/AtlasGlobe/GlobeSky.tsx create mode 100644 client/src/components/AtlasGlobe/GlobeStatsBar.tsx create mode 100644 client/src/components/AtlasGlobe/atlasGlobe.css create mode 100644 client/src/components/AtlasGlobe/globeLabels.ts create mode 100644 client/src/components/AtlasGlobe/globeMath.test.ts create mode 100644 client/src/components/AtlasGlobe/globeMath.ts create mode 100644 client/src/components/AtlasGlobe/globeMesh.test.ts create mode 100644 client/src/components/AtlasGlobe/globeMesh.ts create mode 100644 client/src/components/AtlasGlobe/globeMesh.worker.ts create mode 100644 client/src/components/AtlasGlobe/globeShaders.ts create mode 100644 client/src/components/AtlasGlobe/globeTheme.ts diff --git a/client/src/components/AtlasGlobe/AtlasGlobe.tsx b/client/src/components/AtlasGlobe/AtlasGlobe.tsx new file mode 100644 index 000000000..ccd26249e --- /dev/null +++ b/client/src/components/AtlasGlobe/AtlasGlobe.tsx @@ -0,0 +1,118 @@ +import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'; +import { GlobeEngine, type AtlasMeshManifest, type GlobeHit } from './GlobeEngine'; +import { placeLabels, type GlobeLabel } from './globeLabels'; +import { globeTheme } from './globeTheme'; + +export interface AtlasGlobeHandle { + engine: GlobeEngine | null; +} + +export interface AtlasGlobeProps { + fetchJson: (path: string) => Promise; + dark: boolean; + /** Country name for a label, by ISO A2 (localised by the caller). */ + labelFor: (a2: string) => string | null; + /** Whether a country's region names are drawn when zoomed in. */ + labelRegionsOf?: (a2: string) => boolean; + /** Paints statuses once the geometry is in (and again whenever this changes). */ + paint: (engine: GlobeEngine) => void; + paintKey: unknown; + onHover?: (hit: GlobeHit | null, x: number, y: number) => void; + onSelect?: (hit: GlobeHit | null, x: number, y: number) => void; + onReady?: (manifest: AtlasMeshManifest) => void; + onFrame?: (engine: GlobeEngine) => void; + onError?: (err: unknown) => void; + insetBottom?: number; + className?: string; +} + +/** + * The Atlas globe: a WebGL2 canvas driven by GlobeEngine, with country names + * as HTML labels on top so every script, the user's text size and screen + * readers work without a glyph atlas. + */ +const AtlasGlobe = forwardRef(function AtlasGlobe(props, ref) { + const canvasRef = useRef(null); + const labelsRef = useRef(null); + const engineRef = useRef(null); + const propsRef = useRef(props); + propsRef.current = props; + const [ready, setReady] = useState(false); + + useImperativeHandle( + ref, + () => ({ + get engine() { + return engineRef.current; + }, + }), + [] + ); + + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + let engine: GlobeEngine; + try { + engine = new GlobeEngine({ + canvas, + fetchJson: (p) => propsRef.current.fetchJson(p), + theme: globeTheme(propsRef.current.dark), + onHover: (h, x, y) => propsRef.current.onHover?.(h, x, y), + onSelect: (h, x, y) => propsRef.current.onSelect?.(h, x, y), + onError: (e) => propsRef.current.onError?.(e), + onReady: () => { + if (engine.manifest) propsRef.current.onReady?.(engine.manifest); + propsRef.current.paint(engine); + setReady(true); + }, + onFrame: (e) => { + if (labelsRef.current) + placeLabels(labelsRef.current, labelPool, e, propsRef.current.labelFor, propsRef.current.labelRegionsOf); + propsRef.current.onFrame?.(e); + }, + }); + } catch (err) { + propsRef.current.onError?.(err); + return; + } + const labelPool: GlobeLabel[] = []; + engine.onRegionLoaded = () => propsRef.current.paint(engine); + engineRef.current = engine; + return () => { + engine.dispose(); + engineRef.current = null; + }; + }, []); + + useEffect(() => { + engineRef.current?.setTheme(globeTheme(props.dark)); + }, [props.dark]); + + useEffect(() => { + const e = engineRef.current; + if (e && ready) { + props.paint(e); + e.kick(); + } + // paintKey stands for everything paint() reads. + }, [props.paintKey, ready]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + engineRef.current?.setInsetBottom(props.insetBottom ?? 0); + }, [props.insetBottom]); + + return ( +
+ + + ); +}); + +export default AtlasGlobe; diff --git a/client/src/components/AtlasGlobe/BadgeMedal.tsx b/client/src/components/AtlasGlobe/BadgeMedal.tsx new file mode 100644 index 000000000..a23c3590b --- /dev/null +++ b/client/src/components/AtlasGlobe/BadgeMedal.tsx @@ -0,0 +1,179 @@ +import type { BadgeMotif, BadgeTier } from '@trek/shared'; +import { + CalendarClock, + Compass, + Earth, + Flag, + Flame, + Footprints, + Globe, + Map as MapIcon, + Moon, + Orbit, + Plane, + PlaneTakeoff, + Sailboat, + Snowflake, + Sparkles, + Star, + TowerControl, + TreePalm, + type LucideIcon, +} from 'lucide-react'; +import React from 'react'; + +/** + * A badge as a hexagonal glass medal: a tinted glass body, a ring in the tier's + * metal, and a motif drawn for this badge alone. The shine is a CSS layer that + * follows the pointer (see .ag-medal in atlasGlobe.css). Map/medal paint, not UI + * surfaces, so the colours are literal here. + */ + +export const TIERS: Record = { + bronze: ['#f5b06b', '#a55a1e'], // theme-lint-disable: medal metal + silver: ['#eef2f7', '#8a97ab'], // theme-lint-disable: medal metal + gold: ['#fde68a', '#c98a0e'], // theme-lint-disable: medal metal + aurora: ['#5eead4', '#a78bfa'], // theme-lint-disable: medal metal +}; + +const HEX = '46,3 89,27 89,77 46,101 3,77 3,27'; +const INNER = '46,12 80,31 80,73 46,92 12,73 12,31'; +const INK = '#e0f2fe'; // theme-lint-disable: medal line art +const ACCENT = '#7dd3fc'; // theme-lint-disable: medal line art + +/** + * One drawn symbol per motif, from the same icon set as the rest of TREK so every + * medal reads at a glance and shares one stroke weight. Badges that come in steps + * (5, 10, 25 countries) carry their number under the symbol. + */ +const ICONS: Record = { + first: Footprints, + countries: Flag, + continents: Earth, + seven: Earth, + region: MapIcon, + earth: Orbit, + moon: Moon, + flights: Plane, + longhaul: PlaneTakeoff, + airports: TowerControl, + dateline: CalendarClock, + equator: Globe, + hemispheres: Compass, + tropics: TreePalm, + polar: Snowflake, + streak: Flame, + burst: Sparkles, + wish: Star, + islands: Sailboat, +}; + +function Motif({ motif, label }: { motif: BadgeMotif; label?: string }): React.ReactElement { + const Icon = ICONS[motif]; + if (motif === 'seven') { + // All seven continents: the globe with seven lit points around it. + return ( + <> + + {Array.from({ length: 7 }, (_, i) => { + const a = (i / 7) * Math.PI * 2 - Math.PI / 2; + return ; + })} + + ); + } + if (!label) return ; + const long = label.length >= 4; + return ( + <> + + + {label} + + + ); +} + +export interface BadgeMedalProps { + motif: BadgeMotif; + tier: BadgeTier; + earned: boolean; + /** 0..1 progress ring for a badge not yet earned. */ + progress?: number; + /** Short text some motifs carry (a number, a country code). */ + label?: string; + /** Back side: shown instead of the motif. */ + back?: React.ReactNode; + size?: number; + id: string; +} + +export default function BadgeMedal({ + motif, + tier, + earned, + progress = 0, + label, + back, + size = 92, + id, +}: BadgeMedalProps): React.ReactElement { + const [c1, c2] = TIERS[tier]; + const g = `bm-${id}`; + return ( + + ); +} diff --git a/client/src/components/AtlasGlobe/GlobeEngine.ts b/client/src/components/AtlasGlobe/GlobeEngine.ts new file mode 100644 index 000000000..409e7809b --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeEngine.ts @@ -0,0 +1,803 @@ +/** + * 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, + 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; + countries: Array<{ + a2: string | null; + a3: string; + name: string; + anchor: [number, number] | null; + bbox: number[]; + area: number; + }>; + regions: Record; + /** [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; +} + +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; + theme: GlobeTheme; + initial?: Partial; + 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. */ +export const REGION_FADE_START = 5; +export 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 = { l0: 8, l1: 4, l2: 2, r0: 3, r1: 1.5 }; +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(); + /** Status-texture id of each country's first region. */ + readonly regionBase = new Map(); + 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(); + 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 void; reject: (err: Error) => void }>(); + private worldLoading = new Set(); + private regionLoading = new Set(); + private regionFailedAt = new Map(); + private regionScanAt = -1; + private inViewRegionKeys: ReadonlySet = 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) => { + 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 { + 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 { + 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 { + try { + this.manifest = (await this.fetchRetrying('manifest')) as AtlasMeshManifest; + 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 { + if (!this.manifest || this.renderer.hasWorld(lod) || this.worldLoading.has(lod)) return; + this.worldLoading.add(lod); + try { + const topo = (await this.fetchRetrying(`world/${this.manifest.world[lod]}`)) as Topology; + const layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0); + if (!this.alive) return; + this.renderer.setWorld(lod, layer); + this.kick(); + } finally { + this.worldLoading.delete(lod); + } + } + + async loadRegionIndex(a2: string): Promise { + 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 { + 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.inViewRegionKeys); + 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 { + 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 = Math.max(-80, Math.min(80, 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 = Math.max(-80, Math.min(80, 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); + } + + 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 = Math.max(-80, Math.min(80, 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; + + 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'); + } + } + 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, + 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[] { + if (this.regionAlpha <= 0) return []; + const fine = this.cam.zoom >= REGION_FINE_ZOOM; + const out: string[] = []; + 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(); + } +} diff --git a/client/src/components/AtlasGlobe/GlobePins.tsx b/client/src/components/AtlasGlobe/GlobePins.tsx new file mode 100644 index 000000000..1e89313f6 --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobePins.tsx @@ -0,0 +1,68 @@ +import { Star } from 'lucide-react'; +import { forwardRef, useImperativeHandle, useRef } from 'react'; +import type { GlobeEngine } from './GlobeEngine'; + +export interface GlobePin { + key: string; + lon: number; + lat: number; + title: string; + /** A wish that was reached (ticked off by hand or by a recording). */ + reached?: boolean; + onClick?: () => void; +} + +export interface GlobePinsHandle { + layout: (engine: GlobeEngine) => void; +} + +/** + * Places pinned on the globe, the bucket list's wishes with coordinates. Small + * star buttons moved per frame with transform; hidden behind the horizon. + */ +const GlobePins = forwardRef(function GlobePins({ pins }, ref) { + const refs = useRef>([]); + useImperativeHandle( + ref, + () => ({ + layout(engine: GlobeEngine) { + const { width, height } = engine.vp; + pins.forEach((p, i) => { + const el = refs.current[i]; + if (!el) return; + const s = engine.project(p.lon, p.lat); + const show = s.visible > 0.02 && s.x > -20 && s.x < width + 20 && s.y > -20 && s.y < height + 20; + el.style.transform = `translate3d(${s.x.toFixed(1)}px, ${s.y.toFixed(1)}px, 0) translate(-50%, -50%)`; + el.style.opacity = show ? String(Math.min(1, s.visible * 6)) : '0'; + el.style.pointerEvents = show ? 'auto' : 'none'; + }); + }, + }), + [pins] + ); + return ( + <> + {pins.map((p, i) => ( + + ))} + + ); +}); + +export default GlobePins; diff --git a/client/src/components/AtlasGlobe/GlobeRenderer.ts b/client/src/components/AtlasGlobe/GlobeRenderer.ts new file mode 100644 index 000000000..d62474c29 --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeRenderer.ts @@ -0,0 +1,592 @@ +/** + * WebGL2 renderer of the Atlas globe. Owns the GPU state only: programs, + * layer buffers, the status textures and the picking target. What to show + * comes in through setStatus()/setLayer() and one draw() per frame. + * + * Colours live in two small textures indexed by feature id, so marking a + * country rewrites four bytes instead of rebuilding geometry. + */ +import type { FrameParams } from './globeMath'; +import type { BuiltLayer, FillMesh, LineMesh } from './globeMesh'; +import { FILL_FS, FILL_VS, LINE_FS, LINE_VS, PICK_FS, RIM_FS, SKY_FS, SKY_VS } from './globeShaders'; + +export const STATUS_TEX_W = 256; +export const STATUS_TEX_H = 64; +export const MAX_FEATURES = STATUS_TEX_W * STATUS_TEX_H; + +export type Rgb = [number, number, number]; + +export interface GlobeTheme { + land: Rgb; + ocean: Rgb; + oceanDeep: Rgb; + space0: Rgb; + space1: Rgb; + glow: Rgb; + border: [number, number, number, number]; + coast: [number, number, number, number]; + regionBorder: [number, number, number, number]; + selection: [number, number, number, number]; + arc: [number, number, number, number]; + dark: boolean; +} + +export interface ArcLayer { + /** per segment: a.lon, a.lat, b.lon, b.lat, hA, hB, sA, sB */ + data: Float32Array; + count: number; + width: number; +} + +export interface DrawState { + frame: FrameParams; + dpr: number; + width: number; + height: number; + time: number; + revealStart: number; + hover: number; + selected: number; + ink: { id: number; lon: number; lat: number; radius: number } | null; + regionAlpha: number; + theme: GlobeTheme; + arcs: ArcLayer[]; + arcProgress: number; + /** Region layers to draw, by key. */ + regionKeys: string[]; + worldKey: string; + selectedOutline: LineMesh | null; + /** Unit vector to the sun in earth-fixed coordinates. */ + sun: [number, number, number]; + night: number; +} + +interface Program { + prog: WebGLProgram; + u: Record; + a: Record; +} + +interface GpuFill { + vao: WebGLVertexArrayObject; + pickVao: WebGLVertexArrayObject; + count: number; + buffers: WebGLBuffer[]; +} + +interface GpuLines { + vao: WebGLVertexArrayObject; + count: number; + buffers: WebGLBuffer[]; +} + +interface GpuLayer { + fill: GpuFill; + coast: GpuLines; + borders: GpuLines; +} + +function compile(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader { + const s = gl.createShader(type) as WebGLShader; + gl.shaderSource(s, src); + gl.compileShader(s); + if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { + const log = gl.getShaderInfoLog(s); + gl.deleteShader(s); + throw new Error(`Atlas globe shader failed: ${log ?? 'unknown'}`); + } + return s; +} + +function link(gl: WebGL2RenderingContext, vs: string, fs: string): Program { + const prog = gl.createProgram() as WebGLProgram; + gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, vs)); + gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, fs)); + gl.linkProgram(prog); + if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { + throw new Error(`Atlas globe program failed: ${gl.getProgramInfoLog(prog) ?? 'unknown'}`); + } + const u: Program['u'] = {}; + const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number; + for (let i = 0; i < n; i++) { + const info = gl.getActiveUniform(prog, i); + if (info) u[info.name] = gl.getUniformLocation(prog, info.name); + } + const a: Program['a'] = {}; + const m = gl.getProgramParameter(prog, gl.ACTIVE_ATTRIBUTES) as number; + for (let i = 0; i < m; i++) { + const info = gl.getActiveAttrib(prog, i); + if (info) a[info.name] = gl.getAttribLocation(prog, info.name); + } + return { prog, u, a }; +} + +/** How many region layers (a country at one detail) stay on the GPU at most. */ +const MAX_REGION_LAYERS = 64; + +export class GlobeRenderer { + readonly gl: WebGL2RenderingContext; + private fillP: Program; + private pickP: Program; + private lineP: Program; + private skyP: Program; + private rimP: Program; + private quad: WebGLVertexArrayObject; + private cornerBuf: WebGLBuffer; + private statusTex: WebGLTexture; + private fxTex: WebGLTexture; + private status = new Uint8Array(MAX_FEATURES * 4); + private fx = new Uint8Array(MAX_FEATURES * 4); + private statusDirty = true; + private ocean: GpuFill | null = null; + private worlds = new Map(); + private regions = new Map(); + private arcs = new Map(); + private outline: { src: LineMesh; gpu: GpuLines } | null = null; + private pickFbo: WebGLFramebuffer | null = null; + private pickTex: WebGLTexture | null = null; + private pickSize = [0, 0]; + private last: DrawState | null = null; + + constructor(canvas: HTMLCanvasElement) { + const gl = canvas.getContext('webgl2', { + antialias: true, + alpha: false, + premultipliedAlpha: false, + preserveDrawingBuffer: false, + }); + if (!gl) throw new Error('WebGL2 unavailable'); + this.gl = gl; + this.fillP = link(gl, FILL_VS, FILL_FS); + this.pickP = link(gl, FILL_VS, PICK_FS); + this.lineP = link(gl, LINE_VS, LINE_FS); + this.skyP = link(gl, SKY_VS, SKY_FS); + this.rimP = link(gl, SKY_VS, RIM_FS); + this.quad = this.makeQuad(); + this.cornerBuf = gl.createBuffer() as WebGLBuffer; + gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, -1, 1, -1, 0, 1, 0, 1, 1, -1, 1, 1]), gl.STATIC_DRAW); + this.statusTex = this.makeTex(); + this.fxTex = this.makeTex(); + } + + private makeTex(): WebGLTexture { + const gl = this.gl; + const t = gl.createTexture() as WebGLTexture; + gl.bindTexture(gl.TEXTURE_2D, t); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, STATUS_TEX_W, STATUS_TEX_H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + return t; + } + + private makeQuad(): WebGLVertexArrayObject { + const gl = this.gl; + const vao = gl.createVertexArray() as WebGLVertexArrayObject; + gl.bindVertexArray(vao); + const b = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); + for (const p of [this.skyP, this.rimP]) { + const loc = p.a.a_pos; + if (loc === undefined) continue; + gl.enableVertexAttribArray(loc); + gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); + } + gl.bindVertexArray(null); + return vao; + } + + /** rgba: colour + fill strength. fx: hatch, reveal order (0..255), outline, spare. */ + setStatus( + id: number, + rgba: [number, number, number, number], + fx: [number, number, number, number] = [0, 0, 0, 0] + ): void { + if (id < 0 || id >= MAX_FEATURES) return; + this.status.set(rgba, id * 4); + this.fx.set(fx, id * 4); + this.statusDirty = true; + } + + clearStatus(from: number, to: number): void { + this.status.fill(0, from * 4, to * 4); + this.fx.fill(0, from * 4, to * 4); + this.statusDirty = true; + } + + private uploadFill(m: FillMesh): GpuFill { + const gl = this.gl; + const buffers: WebGLBuffer[] = []; + const make = (data: Float32Array | Uint32Array, target: number): WebGLBuffer => { + const b = gl.createBuffer() as WebGLBuffer; + gl.bindBuffer(target, b); + gl.bufferData(target, data, gl.STATIC_DRAW); + buffers.push(b); + return b; + }; + const llB = make(m.ll, gl.ARRAY_BUFFER); + const refB = make(m.ref, gl.ARRAY_BUFFER); + const fidB = make(m.fid, gl.ARRAY_BUFFER); + const idxB = make(m.index, gl.ELEMENT_ARRAY_BUFFER); + const vaoFor = (p: Program): WebGLVertexArrayObject => { + const vao = gl.createVertexArray() as WebGLVertexArrayObject; + gl.bindVertexArray(vao); + const bind = (name: string, buf: WebGLBuffer, size: number): void => { + const loc = p.a[name]; + if (loc === undefined || loc < 0) return; + gl.bindBuffer(gl.ARRAY_BUFFER, buf); + gl.enableVertexAttribArray(loc); + gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0); + }; + bind('a_ll', llB, 2); + bind('a_ref', refB, 2); + bind('a_fid', fidB, 1); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxB); + gl.bindVertexArray(null); + return vao; + }; + return { vao: vaoFor(this.fillP), pickVao: vaoFor(this.pickP), count: m.index.length, buffers }; + } + + private uploadLines(seg: Float32Array, count: number, stride: 4 | 8): GpuLines { + const gl = this.gl; + const p = this.lineP; + const vao = gl.createVertexArray() as WebGLVertexArrayObject; + gl.bindVertexArray(vao); + gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf); + gl.enableVertexAttribArray(p.a.a_corner); + gl.vertexAttribPointer(p.a.a_corner, 2, gl.FLOAT, false, 0, 0); + const b = gl.createBuffer() as WebGLBuffer; + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, seg, gl.STATIC_DRAW); + const bytes = stride * 4; + const attr = (name: string, offset: number): void => { + const loc = p.a[name]; + if (loc === undefined || loc < 0) return; + gl.enableVertexAttribArray(loc); + gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, bytes, offset); + gl.vertexAttribDivisor(loc, 1); + }; + attr('a_a', 0); + attr('a_b', 8); + if (stride === 8) { + attr('a_h', 16); + attr('a_s', 24); + } + gl.bindVertexArray(null); + return { vao, count, buffers: [b] }; + } + + private uploadLayer(l: BuiltLayer): GpuLayer { + return { + fill: this.uploadFill(l.fill), + coast: this.uploadLines(l.coast.seg, l.coast.count, 4), + borders: this.uploadLines(l.borders.seg, l.borders.count, 4), + }; + } + + private freeLayer(g: GpuLayer | null): void { + if (!g) return; + const gl = this.gl; + for (const part of [g.fill, g.coast, g.borders]) { + for (const b of part.buffers) gl.deleteBuffer(b); + gl.deleteVertexArray(part.vao); + } + gl.deleteVertexArray(g.fill.pickVao); + } + + setOcean(m: FillMesh): void { + this.ocean = this.uploadFill(m); + } + + setWorld(key: string, l: BuiltLayer): void { + const next = this.uploadLayer(l); + this.freeLayer(this.worlds.get(key) ?? null); + this.worlds.set(key, next); + } + + hasWorld(key: string): boolean { + return this.worlds.has(key); + } + + /** + * Keeps a country's regions on the GPU. Past MAX_REGION_LAYERS the ones held + * longest go (never one of `inUse`, the layers drawn now): a long session + * over many countries would otherwise keep every region it ever touched. + * Gone ones come back from the browser cache when they are wanted again. + */ + setRegion(key: string, l: BuiltLayer, inUse: ReadonlySet = new Set()): void { + const next = this.uploadLayer(l); + this.freeLayer(this.regions.get(key) ?? null); + this.regions.delete(key); + this.regions.set(key, next); + for (const old of [...this.regions.keys()]) { + if (this.regions.size <= MAX_REGION_LAYERS) break; + if (old === key || inUse.has(old)) continue; + this.freeLayer(this.regions.get(old) ?? null); + this.regions.delete(old); + } + } + + /** Marks a region layer as just used, so it is the last to go. */ + touchRegion(key: string): void { + const layer = this.regions.get(key); + if (!layer) return; + this.regions.delete(key); + this.regions.set(key, layer); + } + + hasRegion(key: string): boolean { + return this.regions.has(key); + } + + private arcGpu(a: ArcLayer): GpuLines { + let g = this.arcs.get(a); + if (!g) { + g = this.uploadLines(a.data, a.count, 8); + this.arcs.set(a, g); + } + return g; + } + + /** Frees the arc buffers of layers no longer drawn. */ + private pruneArcs(keep: ArcLayer[]): void { + for (const [k, v] of this.arcs) { + if (keep.includes(k)) continue; + for (const b of v.buffers) this.gl.deleteBuffer(b); + this.gl.deleteVertexArray(v.vao); + this.arcs.delete(k); + } + } + + private outlineGpu(m: LineMesh): GpuLines { + if (this.outline?.src === m) return this.outline.gpu; + if (this.outline) { + for (const b of this.outline.gpu.buffers) this.gl.deleteBuffer(b); + this.gl.deleteVertexArray(this.outline.gpu.vao); + } + const gpu = this.uploadLines(m.seg, m.count, 4); + this.outline = { src: m, gpu }; + return gpu; + } + + private setProjection(p: Program, s: DrawState): void { + const gl = this.gl; + const f = s.frame; + gl.uniform2f(p.u.u_center, f.centerLon, f.centerLat); + gl.uniform1f(p.u.u_t, f.t); + gl.uniform1f(p.u.u_scale, f.scale * s.dpr); + gl.uniform2f(p.u.u_origin, f.originX * s.dpr, f.originY * s.dpr); + gl.uniform2f(p.u.u_viewport, s.width * s.dpr, s.height * s.dpr); + } + + private get world(): GpuLayer | null { + return this.last ? (this.worlds.get(this.last.worldKey) ?? null) : null; + } + + draw(s: DrawState): void { + const gl = this.gl; + this.last = s; + const W = Math.round(s.width * s.dpr); + const H = Math.round(s.height * s.dpr); + gl.viewport(0, 0, W, H); + gl.disable(gl.DEPTH_TEST); + gl.enable(gl.BLEND); + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + const th = s.theme; + const f = s.frame; + + // Sky + gl.useProgram(this.skyP.prog); + gl.uniform2f(this.skyP.u.u_viewport, W, H); + gl.uniform2f(this.skyP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr); + gl.uniform1f(this.skyP.u.u_radius, f.scale * s.dpr); + gl.uniform1f(this.skyP.u.u_t, f.t); + gl.uniform1f(this.skyP.u.u_time, s.time); + gl.uniform2f(this.skyP.u.u_drift, f.centerLon, f.centerLat); + gl.uniform3fv(this.skyP.u.u_space0, th.space0); + gl.uniform3fv(this.skyP.u.u_space1, th.space1); + gl.uniform3fv(this.skyP.u.u_glow, th.glow); + gl.uniform1f(this.skyP.u.u_dark, th.dark ? 1 : 0); + gl.bindVertexArray(this.quad); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + + if (this.statusDirty) { + gl.bindTexture(gl.TEXTURE_2D, this.statusTex); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.status); + gl.bindTexture(gl.TEXTURE_2D, this.fxTex); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.fx); + this.statusDirty = false; + } + + // Fills + const p = this.fillP; + gl.useProgram(p.prog); + this.setProjection(p, s); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, this.statusTex); + gl.uniform1i(p.u.u_status, 0); + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, this.fxTex); + gl.uniform1i(p.u.u_fx, 1); + gl.uniform3fv(p.u.u_land, th.land); + gl.uniform3fv(p.u.u_ocean, th.ocean); + gl.uniform3fv(p.u.u_oceanDeep, th.oceanDeep); + gl.uniform1f(p.u.u_time, s.time); + gl.uniform1f(p.u.u_revealStart, s.revealStart); + gl.uniform1i(p.u.u_hover, s.hover); + gl.uniform1i(p.u.u_selected, s.selected); + gl.uniform1i(p.u.u_inkId, s.ink ? s.ink.id : -1); + gl.uniform2f(p.u.u_inkLL, s.ink ? (s.ink.lon * Math.PI) / 180 : 0, s.ink ? (s.ink.lat * Math.PI) / 180 : 0); + gl.uniform1f(p.u.u_inkR, s.ink ? s.ink.radius : 0); + gl.uniform1f(p.u.u_dpr, s.dpr); + gl.uniform1f(p.u.u_layerAlpha, 1); + gl.uniform3fv(p.u.u_sun, s.sun); + gl.uniform1f(p.u.u_night, s.night); + gl.uniform1f(p.u.u_shadeMin, th.dark ? 0.42 : 0.82); + // Dark mode lights a hovered country up; on near-white land in light mode it tints it blue. + if (th.dark) gl.uniform4f(p.u.u_hoverTint, 1, 1, 1, 0.09); + else gl.uniform4f(p.u.u_hoverTint, 0.42, 0.56, 0.82, 0.16); + if (this.ocean) { + gl.uniform1i(p.u.u_mode, 1); + gl.bindVertexArray(this.ocean.vao); + gl.drawElements(gl.TRIANGLES, this.ocean.count, gl.UNSIGNED_INT, 0); + } + const regionsOn = s.regionAlpha > 0.001 && s.regionKeys.some((k) => this.regions.has(k)); + if (this.world) { + gl.uniform1i(p.u.u_mode, 0); + gl.uniform1f(p.u.u_dimBase, 1); + gl.uniform1f(p.u.u_regionFade, s.regionAlpha); + gl.bindVertexArray(this.world.fill.vao); + gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0); + } + if (regionsOn) { + gl.uniform1i(p.u.u_mode, 2); + gl.uniform1f(p.u.u_layerAlpha, s.regionAlpha); + for (const k of s.regionKeys) { + const r = this.regions.get(k); + if (!r) continue; + gl.bindVertexArray(r.fill.vao); + gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0); + } + } + + // Lines + const lp = this.lineP; + gl.useProgram(lp.prog); + this.setProjection(lp, s); + gl.uniform1f(lp.u.u_lift, 0); + gl.uniform1f(lp.u.u_progress, 2); + gl.uniform1f(lp.u.u_glow, 0); + const lines = (g: GpuLines, color: number[], width: number): void => { + if (!g.count) return; + gl.uniform4fv(lp.u.u_color, color); + gl.uniform1f(lp.u.u_width, width * s.dpr); + gl.bindVertexArray(g.vao); + gl.vertexAttrib2f(lp.a.a_h, 0, 0); + gl.vertexAttrib2f(lp.a.a_s, 0, 0); + gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count); + }; + if (regionsOn) { + const c = [...th.regionBorder]; + c[3] *= s.regionAlpha; + for (const k of s.regionKeys) { + const r = this.regions.get(k); + if (r) lines(r.borders, c, 0.7); + } + } + if (this.world) { + lines(this.world.borders, th.border, 0.8); + lines(this.world.coast, th.coast, 0.9); + } + if (s.selectedOutline) { + gl.uniform1f(lp.u.u_glow, 0.55); + lines(this.outlineGpu(s.selectedOutline), th.selection, 1.8); + gl.uniform1f(lp.u.u_glow, 0); + } + if (this.arcs.size > s.arcs.length) this.pruneArcs(s.arcs); + if (s.arcs.length) { + gl.uniform1f(lp.u.u_lift, 1); + gl.uniform1f(lp.u.u_progress, s.arcProgress); + for (const a of s.arcs) { + const g = this.arcGpu(a); + gl.uniform4fv(lp.u.u_color, th.arc); + gl.uniform1f(lp.u.u_width, a.width * s.dpr); + gl.uniform1f(lp.u.u_glow, 0.35); + gl.bindVertexArray(g.vao); + gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count); + } + gl.uniform1f(lp.u.u_lift, 0); + } + + // Rim light over the limb + gl.useProgram(this.rimP.prog); + gl.uniform2f(this.rimP.u.u_viewport, W, H); + gl.uniform2f(this.rimP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr); + gl.uniform1f(this.rimP.u.u_radius, f.scale * s.dpr); + gl.uniform1f(this.rimP.u.u_t, f.t); + gl.uniform3fv(this.rimP.u.u_glow, th.glow); + gl.bindVertexArray(this.quad); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + gl.bindVertexArray(null); + } + + /** Feature id under a CSS-pixel position, or -1. Renders an id pass of the last frame. */ + pick(x: number, y: number, includeRegions: boolean): number { + const s = this.last; + if (!s) return -1; + const gl = this.gl; + const W = Math.round(s.width * s.dpr); + const H = Math.round(s.height * s.dpr); + if (!this.pickFbo || this.pickSize[0] !== W || this.pickSize[1] !== H) { + if (this.pickTex) gl.deleteTexture(this.pickTex); + if (this.pickFbo) gl.deleteFramebuffer(this.pickFbo); + this.pickTex = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this.pickTex); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, W, H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + this.pickFbo = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.pickTex, 0); + this.pickSize = [W, H]; + } + gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo); + gl.viewport(0, 0, W, H); + gl.disable(gl.BLEND); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + const p = this.pickP; + gl.useProgram(p.prog); + this.setProjection(p, s); + if (this.world) { + gl.bindVertexArray(this.world.fill.pickVao); + gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0); + } + if (includeRegions) { + for (const k of s.regionKeys) { + const r = this.regions.get(k); + if (!r) continue; + gl.bindVertexArray(r.fill.pickVao); + gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0); + } + } + const px = new Uint8Array(4); + gl.readPixels(Math.round(x * s.dpr), H - Math.round(y * s.dpr) - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindVertexArray(null); + gl.enable(gl.BLEND); + const id = px[0] + (px[1] << 8) + (px[2] << 16); + return id - 1; + } + + dispose(): void { + const gl = this.gl; + for (const w of this.worlds.values()) this.freeLayer(w); + this.worlds.clear(); + for (const r of this.regions.values()) this.freeLayer(r); + this.regions.clear(); + // The context is left alive: React mounts twice in development and the + // second engine takes over the same canvas. + void gl; + } +} diff --git a/client/src/components/AtlasGlobe/GlobeSky.tsx b/client/src/components/AtlasGlobe/GlobeSky.tsx new file mode 100644 index 000000000..e1be424df --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeSky.tsx @@ -0,0 +1,92 @@ +import { forwardRef, useImperativeHandle, useMemo, useRef } from 'react'; +import type { GlobeEngine } from './GlobeEngine'; +import { moonPhase, smoothstep } from './globeMath'; + +export interface GlobeSkyHandle { + layout: (engine: GlobeEngine) => void; + /** A shooting star across the sky, for the moment something is marked. */ + shootingStar: () => void; +} + +/** + * What hangs in the sky around the globe: the moon in its real phase, and the + * shooting star that crosses when a country is marked. The moon is placed per + * frame without React rendering. + */ +const GlobeSky = forwardRef(function GlobeSky({ dark }, ref) { + const moonRef = useRef(null); + const starHost = useRef(null); + const phase = useMemo(() => moonPhase(new Date()), []); + + useImperativeHandle( + ref, + () => ({ + layout(engine: GlobeEngine) { + const f = engine.frame; + const { width, height } = engine.vp; + const fade = 1 - smoothstep(0.05, 0.6, f.t); + if (!moonRef.current) return; + if (!dark) { + moonRef.current.style.opacity = '0'; + return; + } + const d = Math.max(f.scale * 1.75, Math.min(width, height) * 0.42); + const x = f.originX + Math.cos(-0.65) * d * 1.25; + const y = f.originY + Math.sin(-0.65) * d * 0.62; + moonRef.current.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`; + moonRef.current.style.opacity = String(fade * 0.95); + }, + shootingStar() { + const host = starHost.current; + if (!host || !dark || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; + const el = document.createElement('div'); + el.className = 'ag-shooting-star'; + el.style.left = `${host.clientWidth * (0.55 + Math.random() * 0.35)}px`; + el.style.top = `${host.clientHeight * (0.05 + Math.random() * 0.25)}px`; + host.appendChild(el); + el.animate( + [ + { transform: 'rotate(-28deg) translateX(0) scaleX(0.2)', opacity: 0 }, + { transform: 'rotate(-28deg) translateX(-90px) scaleX(1)', opacity: 1, offset: 0.25 }, + { transform: 'rotate(-28deg) translateX(-420px) scaleX(0.6)', opacity: 0 }, + ], + { duration: 1100, easing: 'cubic-bezier(.2,.6,.3,1)' } + ).onfinish = () => el.remove(); + }, + }), + [dark] + ); + + // The lit part of the moon: the disc with an ellipse carving the shadow. + const lit = phase.lit; + const waxing = phase.phase < 0.5; + const k = Math.abs(1 - 2 * lit); + const shadowPath = `M 14 1 A 13 13 0 0 ${waxing ? 0 : 1} 14 27 A ${(13 * k).toFixed(2)} 13 0 0 ${lit > 0.5 === waxing ? 1 : 0} 14 1 Z`; + + return ( + <> +