diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 811e2a1fd6..5a3af0a5b9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1851,6 +1851,19 @@ feed's place, cut to 40 characters (`earthquakeMarkLabel` in `src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon Islands`, or `M6.4` with no place). +Clicking a quake's disc selects it; clicking its magnitude label (what a far +view can hit) also flies the camera there through the world-focus request +(`earthquake` framing in `src/worldFocus.js`). The selected quake shows a card +(`describeEarthquake`): magnitude and USGS class (`M5.5 · Moderate`), a +six-step class meter with the depth band, place, UTC time and source; with a +USGS event id the card opens that event's page. The selection is also the +shared context selection, so "what's selected" answers with it. Its disc is +painted with a gradient fading to the outer circle and wavy contour lines +(shaped by the quake's id, never crossing) under the labels. The package takes +clicks, picking, context, focus, the opener, the painter and the translator by +injection (`src/app/layers/earthquakes.js`); without input and picking it draws +and takes no clicks, and its labels stay non-interactive. + Air quality (`./layers/air-quality`) draws its station discs as one renderer draw set of ground-clamped fills and reads the view through the camera port; it no longer reaches Cesium, so a caller handing it a Cesium viewer, @@ -8165,6 +8178,16 @@ on it. per frame, it holds NO continuous-render hold — the governor stays idle with earthquakes on, and the manager's `layer-tick` / `layer-visibility` requests carry new data to the screen. Pinned in `src/data/earthquakes.test.mjs`. + The one animation is the selected quake's contour lines + (`src/app/layers/earthquakeRipples.js`), painted on the world overlay, not + the ground set: they ask for frames for `RIPPLE_ACTIVE_CYCLES` (3) runs out + to the disc's edge after a selection (about 14 s), only while the disc is on + screen, then rest as still contours and ask for none. A parked camera with a + quake selected therefore returns to idle. A feed refresh updates the + selected quake in place: it neither runs the contours again nor takes back + a shared selection made since; only a click or a label's activation does. + Selecting fades that one disc's flat fill once (an `upsert`, not per frame) + under the painted gradient. - **Geocode framing has an off-centre sanity gate.** A viewport that is both bigger than any city (>300 km diagonal) and not centred on its own geocoded location (anchor >15% of the diagonal from the centroid) is replaced by a diff --git a/scripts/format-scope.json b/scripts/format-scope.json index e474377e12..1069652db2 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -434,6 +434,9 @@ "src/layers/earthquakes/model.js", "src/layers/earthquakes/source.js", "src/layers/earthquakes/ownership.test.mjs", + "src/layers/earthquakes/selection.test.mjs", + "src/app/layers/earthquakeRipples.js", + "src/app/layers/earthquakeRipples.test.mjs", "src/layers/perimeters/index.js", "src/layers/perimeters/records.js", "src/layers/perimeters/source.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 4147d8f6cd..4b4d0e9776 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -4060,6 +4060,7 @@ "src/app/layers/bikeshare.js", "src/app/layers/cctv.js", "src/app/layers/cyclones.js", + "src/app/layers/earthquakeRipples.js", "src/app/layers/earthquakes.js", "src/app/layers/firms.js", "src/app/layers/flights.js", @@ -5466,6 +5467,7 @@ "src/app/layers/bikeshare.js", "src/app/layers/cctv.js", "src/app/layers/cyclones.js", + "src/app/layers/earthquakeRipples.js", "src/app/layers/earthquakes.js", "src/app/layers/firms.js", "src/app/layers/flights.js", diff --git a/src/app/layers/earthquakeRipples.js b/src/app/layers/earthquakeRipples.js new file mode 100644 index 0000000000..31f3557c44 --- /dev/null +++ b/src/app/layers/earthquakeRipples.js @@ -0,0 +1,381 @@ +import { registerWorldOverlayPaintLane } from '../../overlays/worldOverlay.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { + earthquakeContourRings, + earthquakeContourScale, + earthquakeContourShape, + earthquakeRippleRings, + EARTHQUAKE_RIPPLE_PERIOD_MS, +} from '../../layers/earthquakes/model.js'; + +/** Points around each contour line: smooth at the largest disc on screen. */ +export const RIPPLE_RING_SEGMENTS = 96; +/** An index contour's width, and every other line's. */ +const INDEX_WIDTH_PX = 2; +const LINE_WIDTH_PX = 1.1; +/** + * The overlay lane the lines paint in: the magnitude labels' own. A lane's + * custom painters run before its entries, so the lines sit under the labels + * and under the selected quake's card. + */ +export const RIPPLE_PAINT_LANE = 'ambient-label'; +/** + * The selected disc's fill, [offset, alpha] from the epicentre (0) to its + * outer circle (1): strongest in the middle, fading out to nothing at the + * edge. + */ +export const DISC_FADE = Object.freeze([ + [0, 0.42], + [0.35, 0.26], + [0.75, 0.1], + [1, 0], +]); +/** + * Each contour wave's fill, out to its own line: clear inside, tinting + * toward the line; times the wave's own fade. + */ +export const WAVE_FADE = Object.freeze([ + [0, 0], + [0.55, 0], + [1, 0.2], +]); + +/** + * `rgb(r,g,b)` (or `rgba`) as a function of alpha, for gradient stops; any + * other colour keeps its own alpha. + */ +export function cssWithAlpha(color) { + const m = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(color)); + if (!m) return () => color; + const rgb = `${m[1]},${m[2]},${m[3]}`; + return (alpha) => `rgba(${rgb},${Math.max(0, Math.min(1, alpha))})`; +} + +/** + * How many times the lines run out to the edge after a quake is selected + * before they rest as still contours and stop asking for frames: earthquakes + * otherwise hold no render (docs/CURRENT-STATE.md, "Earthquake discs are + * STATIC geometry"), and a quake can stay selected for hours. + */ +export const RIPPLE_ACTIVE_CYCLES = 3; + +let reducedMotionQuery; +/** + * The viewer's reduced-motion setting, live: the media query is kept, so a + * change mid-session is read at the next paint and tick. + */ +const reducedMotion = () => { + try { + reducedMotionQuery ??= + globalThis.matchMedia?.('(prefers-reduced-motion: reduce)') ?? null; + return reducedMotionQuery?.matches === true; + } catch { + return false; + } +}; + +/** + * The selected earthquake's contour lines, painted on the world overlay: + * wavy closed lines, shaped by the quake's id (earthquakeContourShape), run + * from the marker out to the disc's edge and fade there, one after another, + * for RIPPLE_ACTIVE_CYCLES runs after a quake is selected and only while it + * is on screen, then rest as still contours. They never cross, and every third is + * a heavier index contour, as on a topographic map. Nothing is drawn, and no + * frame is asked for, while no quake is selected. With reduced motion the + * lines hold still. + * + * A line is drawn in the tangent plane at the epicentre: at the largest + * disc (M6, 64 km) it sits about 320 m above the curved ground at its edge + * (64² / 2R), about 1.5 px off the drawn disc at the 220 km, -45° framing a + * label click flies to (900 px tall, 35° field of view); less for smaller + * quakes, as the offset grows with the square of the radius. + * @param {object} [deps] + * @param {Function} [deps.registerLane] `registerWorldOverlayPaintLane`. + * @param {() => number} [deps.now] Steady clock, ms. + * @param {(cb: Function) => number} [deps.requestFrame] + * @param {(handle: number) => void} [deps.cancelFrame] + * @param {() => boolean} [deps.prefersReducedMotion] + * @returns {{show: Function, hide: Function, dispose: Function}} + */ +export function createEarthquakeRipples({ + registerLane = registerWorldOverlayPaintLane, + now = () => globalThis.performance?.now?.() ?? Date.now(), + requestFrame = (cb) => globalThis.requestAnimationFrame?.(cb) ?? null, + cancelFrame = (handle) => globalThis.cancelAnimationFrame?.(handle), + prefersReducedMotion = reducedMotion, +} = {}) { + let lane = null; + let target = null; + let frameHandle = null; + // When the running lines settle into still contours (the selection's + // bound), and whether the last paint found the quake on screen. + let startedAt = 0; + let settlesAt = 0; + let onScreen = false; + /** Whether the lines run now: in the window, and motion allowed. */ + const running = () => now() < settlesAt && !prefersReducedMotion(); + // Unit offsets around the line in the epicentre's tangent plane, packed + // x, y, z per point: north·cos + east·sin. + const offsets = new Float64Array((RIPPLE_RING_SEGMENTS + 1) * 3); + const angles = new Float64Array(RIPPLE_RING_SEGMENTS + 1); + for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) + angles[i] = (2 * Math.PI * i) / RIPPLE_RING_SEGMENTS; + + // Screen points, reused every frame. + const at = { x: 0, y: 0 }; + const centerAt = { x: 0, y: 0 }; + const eastAt = { x: 0, y: 0 }; + const northAt = { x: 0, y: 0 }; + + /** Project an ECEF point to CSS pixels; false when it is behind the eye. */ + function project(frame, px, py, pz, out) { + const m = frame.viewProjectionMatrix; + const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; + if (w <= 0) return false; + out.x = + ((m[0] * px + m[4] * py + m[8] * pz + m[12]) / w / 2 + 0.5) * frame.width; + out.y = + (0.5 - (m[1] * px + m[5] * py + m[9] * pz + m[13]) / w / 2) * + frame.height; + return true; + } + + /** + * Trace one closed line at `fraction` of the disc's radius (`shaped`: + * as a contour, else the disc's own circle). True when all of it is in + * front of the eye, so it can be filled. + */ + function trace(frame, fraction, shaped) { + const { ctx } = frame; + const center = target.center; + const reach = fraction * target.radiusM; + ctx.beginPath(); + let pen = false; + let whole = true; + for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) { + // The last point repeats the first angle, so the line closes. + const r = shaped + ? reach * earthquakeContourScale(target.shape, angles[i], fraction) + : reach; + const visible = project( + frame, + center.x + offsets[i * 3] * r, + center.y + offsets[i * 3 + 1] * r, + center.z + offsets[i * 3 + 2] * r, + at, + ); + if (!visible) { + pen = false; + whole = false; + continue; + } + if (pen) ctx.lineTo(at.x, at.y); + else ctx.moveTo(at.x, at.y); + pen = true; + } + return whole; + } + + /** + * Fill the traced path with a radial gradient laid on the ground: the + * canvas places a path when it is traced and a gradient when it fills, so + * under the disc's ground-to-screen transform the gradient's circle + * becomes the disc's ellipse on screen while the path stays exact. + * @param {Array<[number, number]>} stops [offset, alpha], out to `reach`. + */ + function fillGround(ctx, reach, stops) { + ctx.save(); + ctx.transform( + eastAt.x - centerAt.x, + eastAt.y - centerAt.y, + northAt.x - centerAt.x, + northAt.y - centerAt.y, + centerAt.x, + centerAt.y, + ); + const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, reach); + for (const [offset, alpha] of stops) + gradient.addColorStop(offset, target.rgba(alpha)); + ctx.fillStyle = gradient; + ctx.globalAlpha = 1; + ctx.fill(); + ctx.restore(); + } + + /** + * Whether any of the disc is in the viewport: its centre's screen point, + * padded by its larger screen radius (or, seen edge-on, the centre alone). + */ + function discOnScreen(frame, c, e, n) { + if (!Number.isFinite(c.x) || !Number.isFinite(c.y)) return false; + const pad = Math.max( + Math.hypot(e.x - c.x, e.y - c.y) || 0, + Math.hypot(n.x - c.x, n.y - c.y) || 0, + ); + return ( + c.x + pad >= 0 && + c.x - pad <= frame.width && + c.y + pad >= 0 && + c.y - pad <= frame.height + ); + } + + function paint(frame) { + if (!target) return; + const { ctx } = frame; + const center = target.center; + onScreen = false; + if (frame.occluder?.isPointVisible?.(center) === false) return; + const R = target.radiusM; + // The disc's ground frame on screen: its centre, and a radius east and + // north. Seen edge-on (or partly behind the eye) it is not filled. + const centerOk = project(frame, center.x, center.y, center.z, centerAt); + const eastOk = project( + frame, + center.x + target.east.x * R, + center.y + target.east.y * R, + center.z + target.east.z * R, + eastAt, + ); + const northOk = project( + frame, + center.x + target.north.x * R, + center.y + target.north.y * R, + center.z + target.north.z * R, + northAt, + ); + let fills = centerOk && eastOk && northOk; + if (fills) { + const area = + (eastAt.x - centerAt.x) * (northAt.y - centerAt.y) - + (eastAt.y - centerAt.y) * (northAt.x - centerAt.x); + fills = Math.abs(area) > 1; + } + onScreen = + centerOk && + discOnScreen( + frame, + centerAt, + eastOk ? eastAt : centerAt, + northOk ? northAt : centerAt, + ); + // The disc: strongest at the epicentre, fading out to its outer circle. + if (fills && trace(frame, 1, false)) fillGround(ctx, 1, DISC_FADE); + const animate = running(); + const rings = animate + ? earthquakeRippleRings(now() - startedAt) + : earthquakeContourRings(); + // Brought back into view while the window lasts: run again. + if (animate && onScreen && frameHandle === null && lane) + frameHandle = requestFrame(tick); + ctx.strokeStyle = target.color; + ctx.lineJoin = 'round'; + for (const { fraction, alpha, index } of rings) { + if (!(alpha > 0.01)) continue; + const whole = trace(frame, fraction, true); + // Each wave: clear inside, tinting toward its own line, as it fades. + if (fills && whole) + fillGround( + ctx, + fraction, + WAVE_FADE.map(([offset, a]) => [offset, a * alpha]), + ); + ctx.lineWidth = index ? INDEX_WIDTH_PX : LINE_WIDTH_PX; + ctx.globalAlpha = alpha; + ctx.stroke(); + } + ctx.globalAlpha = 1; + } + + /** Ask for one more frame while the lines run (one request at a time). */ + function tick() { + frameHandle = null; + if (!target || !lane) return; + // Settled, or out of sight: one last paint draws the still contours + // (or nothing), and no more frames are asked for. A paint that finds it + // on screen again inside the window starts the frames again. + if (!running() || !onScreen) { + lane.requestPaint(); + return; + } + lane.requestPaint(); + frameHandle = requestFrame(tick); + } + + function stopFrames() { + if (frameHandle !== null) cancelFrame(frameHandle); + frameHandle = null; + } + + /** + * Run the contour lines around one quake, replacing any other. + * @param {{id: string, lon: number, lat: number, radiusM: number, color: string}} next + * @param {{restart?: boolean}} [options] `restart: false` updates the + * same quake in place (a feed refresh) without running it again. + */ + function show(next, { restart = true } = {}) { + if ( + !next || + !Number.isFinite(next.lon) || + !Number.isFinite(next.lat) || + !(next.radiusM > 0) + ) { + hide(); + return; + } + const sameQuake = target?.id === next.id; + const lon = (next.lon * Math.PI) / 180; + const lat = (next.lat * Math.PI) / 180; + const [sinLon, cosLon] = [Math.sin(lon), Math.cos(lon)]; + const [sinLat, cosLat] = [Math.sin(lat), Math.cos(lat)]; + for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) { + const [c, s] = [Math.cos(angles[i]), Math.sin(angles[i])]; + offsets[i * 3] = c * -sinLat * cosLon + s * -sinLon; + offsets[i * 3 + 1] = c * -sinLat * sinLon + s * cosLon; + offsets[i * 3 + 2] = c * cosLat; + } + target = { + id: next.id, + center: fromDegrees(next.lon, next.lat), + radiusM: next.radiusM, + color: next.color || 'rgb(255,165,0)', + shape: earthquakeContourShape(next.id), + rgba: cssWithAlpha(next.color || 'rgb(255,165,0)'), + // Angle 0 is north and a quarter turn is east (see `offsets`). + north: { x: offsets[0], y: offsets[1], z: offsets[2] }, + east: { + x: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3], + y: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 1], + z: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 2], + }, + }; + if (restart || !sameQuake) { + startedAt = now(); + settlesAt = + startedAt + RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS; + // Assume it is in view until a paint says otherwise. + onScreen = true; + } + lane ??= registerLane(RIPPLE_PAINT_LANE, paint, { + id: 'earthquake-ripples', + }); + lane.setActive(true); + lane.requestPaint(); + if (running() && frameHandle === null) frameHandle = requestFrame(tick); + } + + function hide() { + stopFrames(); + if (!target) return; + target = null; + lane?.setActive(false); + } + + function dispose() { + hide(); + lane?.unregister(); + lane = null; + } + + return { show, hide, dispose }; +} diff --git a/src/app/layers/earthquakeRipples.test.mjs b/src/app/layers/earthquakeRipples.test.mjs new file mode 100644 index 0000000000..e97b9f00a8 --- /dev/null +++ b/src/app/layers/earthquakeRipples.test.mjs @@ -0,0 +1,420 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + DISC_FADE, + cssWithAlpha, + RIPPLE_ACTIVE_CYCLES, + RIPPLE_PAINT_LANE, + RIPPLE_RING_SEGMENTS, + createEarthquakeRipples, +} from './earthquakeRipples.js'; +import { + EARTHQUAKE_RIPPLE_PERIOD_MS, + EARTHQUAKE_RIPPLE_RINGS, +} from '../../layers/earthquakes/model.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; + +/** A paint lane, frame clock and canvas the test steps by hand. */ +function harness({ reducedMotion = false } = {}) { + let motionReduced = reducedMotion; + const lanes = []; + const frames = new Map(); + let nextFrame = 1; + let clock = 0; + const ripples = createEarthquakeRipples({ + registerLane(laneId, painter, options) { + const lane = { + laneId, + painter, + options, + active: false, + paints: 0, + unregistered: false, + setActive(next) { + lane.active = next; + }, + requestPaint() { + lane.paints++; + }, + unregister() { + lane.unregistered = true; + }, + }; + lanes.push(lane); + return lane; + }, + now: () => clock, + requestFrame(cb) { + const handle = nextFrame++; + frames.set(handle, cb); + return handle; + }, + cancelFrame: (handle) => frames.delete(handle), + prefersReducedMotion: () => motionReduced, + }); + const strokes = []; + const fills = []; + let path = null; + const ctx = { + globalAlpha: 1, + beginPath() { + path = { moves: 0, lines: 0 }; + }, + moveTo() { + path.moves++; + }, + lineTo() { + path.lines++; + }, + stroke() { + strokes.push({ + ...path, + alpha: ctx.globalAlpha, + color: ctx.strokeStyle, + width: ctx.lineWidth, + }); + }, + // Fills record their path, gradient and the transform they fill under. + saved: 0, + transformed: null, + save() { + ctx.saved++; + }, + restore() { + ctx.saved--; + ctx.transformed = null; + }, + transform(...args) { + ctx.transformed = args; + }, + createRadialGradient(...circles) { + const gradient = { circles, stops: [] }; + gradient.addColorStop = (offset, color) => + gradient.stops.push([offset, color]); + return gradient; + }, + fill() { + fills.push({ + ...path, + gradient: ctx.fillStyle, + transform: ctx.transformed, + }); + }, + }; + // w = 1 everywhere: every point is in front of the eye. + const matrix = new Float64Array(16); + matrix[0] = 1e-7; + matrix[5] = 1e-7; + matrix[15] = 1; + const frame = (visible = true) => ({ + ctx, + width: 800, + height: 600, + viewProjectionMatrix: matrix, + occluder: { isPointVisible: () => visible }, + }); + return { + ripples, + lanes, + frames, + strokes, + fills, + frame, + matrix, + setReducedMotion(next) { + motionReduced = next; + }, + advance(ms) { + clock += ms; + }, + /** Run the pending animation frames once. */ + step() { + const pending = [...frames.entries()]; + frames.clear(); + for (const [, cb] of pending) cb(); + }, + }; +} + +const target = { + id: 'ak1', + lon: -153.3, + lat: 60, + radiusM: 32000, + color: 'rgb(255,0,0)', +}; + +test('nothing is registered or animated until a quake is selected', () => { + const h = harness(); + assert.equal(h.lanes.length, 0); + assert.equal(h.frames.size, 0); + h.ripples.hide(); + assert.equal(h.frames.size, 0); +}); + +test('a selected quake animates one ring set, one frame request at a time', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + assert.equal(lane.laneId, RIPPLE_PAINT_LANE); + assert.equal(RIPPLE_PAINT_LANE, 'ambient-label', 'under the labels'); + assert.equal(lane.active, true); + assert.equal(h.frames.size, 1); + h.ripples.show({ ...target, id: 'ak2' }); + assert.equal(h.lanes.length, 1, 'the lane is reused'); + assert.equal(h.frames.size, 1, 'still one frame loop'); + const before = lane.paints; + h.step(); + h.step(); + assert.equal(lane.paints, before + 2, 'one repaint per frame'); + assert.equal(h.frames.size, 1); + + h.advance(600); + lane.painter(h.frame()); + // At 600 ms every line is between the marker and the edge, so all draw. + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + assert.deepEqual( + h.strokes.map((stroke) => stroke.width), + [2, 1.1, 1.1, 2, 1.1, 1.1], + 'every third line is an index contour', + ); + for (const stroke of h.strokes) { + assert.equal(stroke.moves, 1, 'one unbroken ring'); + assert.equal(stroke.lines, RIPPLE_RING_SEGMENTS); + assert.equal(stroke.color, 'rgb(255,0,0)'); + assert.ok(stroke.alpha > 0 && stroke.alpha <= 1); + } + + h.ripples.hide(); + assert.equal(lane.active, false); + assert.equal(h.frames.size, 0, 'no frames asked for once hidden'); + h.strokes.length = 0; + lane.painter(h.frame()); + assert.equal(h.strokes.length, 0); +}); + +test('rings are skipped behind the globe and broken behind the eye', () => { + const h = harness(); + h.ripples.show(target); + h.advance(600); + const [lane] = h.lanes; + lane.painter(h.frame(false)); + assert.equal(h.strokes.length, 0, 'epicentre over the horizon'); + + // Points with negative x fall behind the eye: each ring breaks there. + const frame = h.frame(); + frame.viewProjectionMatrix[3] = 1e-6; + const center = fromDegrees(target.lon, target.lat); + frame.viewProjectionMatrix[15] = -1e-6 * center.x; + lane.painter(frame); + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + for (const stroke of h.strokes) + assert.ok(stroke.lines < RIPPLE_RING_SEGMENTS, 'part of each ring hidden'); +}); + +test('reduced motion draws still contour rings and asks for no frames', () => { + const h = harness({ reducedMotion: true }); + h.ripples.show(target); + assert.equal(h.frames.size, 0); + assert.equal(h.lanes[0].paints, 1, 'painted once'); + h.lanes[0].painter(h.frame()); + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7)); +}); + +test('an unusable target hides the rings; dispose releases the lane', () => { + const h = harness(); + h.ripples.show(target); + h.ripples.show({ ...target, radiusM: 0 }); + assert.equal(h.lanes[0].active, false); + assert.equal(h.frames.size, 0); + h.ripples.dispose(); + assert.equal(h.lanes[0].unregistered, true); + // Shown again after dispose, it registers a fresh lane. + h.ripples.show(target); + assert.equal(h.lanes.length, 2); + h.ripples.dispose(); +}); + +test('contour lines are wavy, the same for a quake every time, and inside the disc', () => { + const h = harness(); + h.ripples.show(target); + h.advance(600); + // An identity-like projection: screen x, y follow ECEF y, z, so the + // distance from the projected epicentre measures each point's radius. + const frame = h.frame(); + const m = frame.viewProjectionMatrix; + m[0] = 0; + m[5] = 0; + m[4] = 1e-6; + m[9] = 1e-6; + const points = []; + const ctx = frame.ctx; + const record = (x, y) => points.at(-1).push([x, y]); + ctx.beginPath = () => points.push([]); + ctx.moveTo = record; + ctx.lineTo = record; + ctx.stroke = () => {}; + h.lanes[0].painter(frame); + const center = fromDegrees(target.lon, target.lat); + const cx = (center.y * 1e-6 * 0.5 + 0.5) * 800; + const cy = (0.5 - center.z * 1e-6 * 0.5) * 600; + const spread = (line) => { + const radii = line.map(([x, y]) => Math.hypot(x - cx, y - cy)); + return Math.max(...radii) / Math.min(...radii); + }; + // The disc's outer circle first (filled, not stroked), then each line. + assert.equal(points.length, EARTHQUAKE_RIPPLE_RINGS + 1); + points.shift(); + assert.ok( + points.every((line) => spread(line) > 1.05), + 'not circles: each line dents in and out', + ); + for (const line of points) { + const [first, last] = [line[0], line.at(-1)]; + assert.ok( + Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6, + 'closed', + ); + } +}); + +test('the disc fades out to its outer circle; each wave fills with a fade', () => { + const h = harness(); + h.ripples.show(target); + h.advance(600); + // A projection where east and north span the screen: the disc is seen + // from above, so its ground frame can be filled. + const frame = h.frame(); + const m = frame.viewProjectionMatrix; + m[0] = 0; + m[5] = 0; + m[4] = 1e-6; + m[9] = 1e-6; + h.lanes[0].painter(frame); + assert.equal(h.fills.length, 1 + EARTHQUAKE_RIPPLE_RINGS); + const [disc, ...waves] = h.fills; + assert.equal(disc.lines, RIPPLE_RING_SEGMENTS, 'the whole outer circle'); + assert.deepEqual(disc.gradient.circles, [0, 0, 0, 0, 0, 1]); + assert.deepEqual( + disc.gradient.stops, + DISC_FADE.map(([offset, alpha]) => [offset, `rgba(255,0,0,${alpha})`]), + ); + assert.equal(disc.gradient.stops.at(-1)[1], 'rgba(255,0,0,0)', 'fades out'); + assert.ok(disc.transform, 'filled under the ground-to-screen transform'); + assert.equal(h.fills.length, waves.length + 1); + for (const wave of waves) { + const reach = wave.gradient.circles[5]; + assert.ok(reach > 0 && reach < 1, 'out to its own line'); + assert.equal(wave.gradient.stops[0][1], 'rgba(255,0,0,0)', 'clear inside'); + } + // The transforms were undone: nothing leaks into the labels' painting. + assert.equal(frame.ctx.saved, 0); + // Seen edge-on, the ground frame has no area: lines only, no fills. + h.fills.length = 0; + m[9] = 0; + m[5] = 0; + h.lanes[0].painter(frame); + assert.equal(h.fills.length, 0); +}); + +test('cssWithAlpha turns rgb into rgba stops', () => { + assert.equal(cssWithAlpha('rgb(255,165,0)')(0.25), 'rgba(255,165,0,0.25)'); + assert.equal(cssWithAlpha('rgba(1, 2, 3, 0.5)')(2), 'rgba(1,2,3,1)'); + assert.equal(cssWithAlpha('red')(0.3), 'red'); +}); + +test('the lines run a bounded time after a selection, then rest without frames', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + const window = RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS; + assert.ok(window <= 15_000, 'about a quarter of a minute at most'); + let frames = 0; + for (let t = 0; t < window * 3; t += 16) { + if (!h.frames.size) break; + lane.painter(h.frame()); + h.advance(16); + h.step(); + frames++; + } + assert.equal(h.frames.size, 0, 'no frame asked for once settled'); + assert.ok(frames <= Math.ceil(window / 16) + 2, `bounded: ${frames} frames`); + // At rest the lines hold still as readable contours. + h.strokes.length = 0; + lane.painter(h.frame()); + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7)); + // A parked camera repainting the overlay does not start them again. + lane.painter(h.frame()); + assert.equal(h.frames.size, 0); + // A new selection runs again. + h.ripples.show({ ...target, id: 'ak2' }); + assert.equal(h.frames.size, 1); + h.ripples.dispose(); +}); + +test('off screen the frames stop; back in view inside the window they resume', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + // Behind the globe. + lane.painter(h.frame(false)); + const paints = lane.paints; + h.step(); + assert.equal(h.frames.size, 0, 'stopped while out of sight'); + assert.equal(lane.paints, paints + 1, 'one last paint, then none'); + h.step(); + assert.equal(lane.paints, paints + 1); + // Panned away: the disc is far off the viewport. + h.ripples.show(target); + const away = h.frame(); + away.viewProjectionMatrix[12] = 50; + lane.painter(away); + h.step(); + assert.equal(h.frames.size, 0); + // The camera brings it back while the window lasts. + away.viewProjectionMatrix[12] = 0; + lane.painter(h.frame()); + assert.equal(h.frames.size, 1, 'resumed'); + h.ripples.dispose(); +}); + +test('turning reduced motion on mid-run stills the lines and stops the frames', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + lane.painter(h.frame()); + h.setReducedMotion(true); + h.step(); + assert.equal(h.frames.size, 0); + h.strokes.length = 0; + lane.painter(h.frame()); + assert.ok( + h.strokes.every((stroke) => stroke.alpha === 0.7), + 'still', + ); + // Turned off again within the window: the next paint runs them again. + h.setReducedMotion(false); + lane.painter(h.frame()); + assert.equal(h.frames.size, 1); + h.ripples.dispose(); +}); + +test('a refresh of the same quake does not run a settled selection again', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + h.advance(RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS + 1); + lane.painter(h.frame()); + h.step(); + assert.equal(h.frames.size, 0, 'settled'); + h.ripples.show({ ...target, radiusM: 40000 }, { restart: false }); + assert.equal(h.frames.size, 0, 'a refresh keeps it at rest'); + lane.painter(h.frame()); + assert.equal(h.frames.size, 0); + // A different quake, or a user's restart, runs again. + h.ripples.show({ ...target, id: 'other' }, { restart: false }); + assert.equal(h.frames.size, 1); + h.ripples.dispose(); +}); diff --git a/src/app/layers/earthquakes.js b/src/app/layers/earthquakes.js index ae6bc1b63a..dc56448d35 100644 --- a/src/app/layers/earthquakes.js +++ b/src/app/layers/earthquakes.js @@ -1,6 +1,46 @@ import { createEarthquakesLayer } from '../../layers/earthquakes/index.js'; import { overlayHost } from './overlayHost.js'; -/** Wire earthquake observations to the application overlay host. */ +import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js'; +import { inputFor } from '../../input/dispatcher.js'; +import * as picking from '../../data/pickRegistry.js'; +import * as context from '../../data/contextStore.js'; +import { isPointerFree } from '../../data/inputOwnership.js'; +import { requestWorldFocus } from '../../worldFocus.js'; +import { createEarthquakeRipples } from './earthquakeRipples.js'; +import { formatDate, formatNumber, t } from '../../i18n/index.js'; + +const EVENT_TIME = Object.freeze({ + day: 'numeric', + month: 'short', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + timeZone: 'UTC', + timeZoneName: 'short', +}); + +/** The clicked quake's card text, in the page's language. */ +export const earthquakeCardText = Object.freeze({ + t, + formatTime: (time) => formatDate(time, EVENT_TIME), + formatDepth: (km) => formatNumber(km, { maximumFractionDigits: 1 }), +}); + +/** + * Wire earthquake observations to the application overlay host, and its + * discs to the globe's clicks: a clicked quake shows its detail card. + */ export function createApplicationEarthquakes(options) { - return createEarthquakesLayer({ overlayHost, ...options }); + return createEarthquakesLayer({ + overlayHost: { ...overlayHost, hitTest: hitTestWorldOverlay }, + input: (viewer) => inputFor(viewer), + picking, + context, + pointer: { isPointerFree }, + openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), + focus: { requestWorldFocus }, + ripples: createEarthquakeRipples(), + text: earthquakeCardText, + ...options, + }); } diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 15b8414c54..246a9d36fc 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -647,6 +647,16 @@ "UNAVAILABLE": "غير متاح", "Live Flights": "تتبّع الرحلات المباشر", "Earthquakes (24h)": "الزلازل (24 ساعة)", + "earthquake|Minor": "طفيف", + "earthquake|Light": "خفيف", + "earthquake|Moderate": "معتدل", + "earthquake|Strong": "قوي", + "earthquake|Major": "كبير", + "earthquake|Great": "هائل", + "earthquake|Shallow": "ضحل", + "earthquake|Intermediate": "متوسط العمق", + "earthquake|Deep": "عميق", + "{km} km deep": "على عمق {km} كم", "No selected data layers": "لا توجد طبقات بيانات محددة", "Cleared {count} data layers": { "zero": "لم تُمسح أي طبقة بيانات ({count})", @@ -2154,6 +2164,7 @@ "Exit cockpit to fly to a target": "اخرج من القمرة للانتقال إلى هدف", "Exit cockpit to fly to a vessel": "اخرج من القمرة للانتقال إلى سفينة", "Exit cockpit to fly to a fire": "اخرج من القمرة للانتقال إلى حريق", + "Exit cockpit to fly to an earthquake": "اخرج من القمرة للانتقال إلى زلزال", "Exit cockpit to fly to a route": "اخرج من القمرة للانتقال إلى مسار", "Exit cockpit to fly to a file": "اخرج من القمرة للانتقال إلى ملف", "Exit cockpit to fly to a scene": "اخرج من القمرة للانتقال إلى مشهد", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 3d1caeab42..d7900f7789 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -634,6 +634,16 @@ "Live Flights": "Live-Flüge", "Military Flights": "Militärflüge", "Earthquakes (24h)": "Erdbeben (24 h)", + "earthquake|Minor": "Schwach", + "earthquake|Light": "Leicht", + "earthquake|Moderate": "Mittel", + "earthquake|Strong": "Stark", + "earthquake|Major": "Schwer", + "earthquake|Great": "Gewaltig", + "earthquake|Shallow": "Flach", + "earthquake|Intermediate": "Mitteltief", + "earthquake|Deep": "Tief", + "{km} km deep": "{km} km tief", "Satellites": "Satelliten", "Place names": "Ortsnamen", "Space Missions (30d)": "Raummissionen (30 T)", @@ -2058,6 +2068,7 @@ "Exit cockpit to fly to a target": "Cockpit verlassen, um zu einem Ziel zu fliegen", "Exit cockpit to fly to a vessel": "Cockpit verlassen, um zu einem Schiff zu fliegen", "Exit cockpit to fly to a fire": "Cockpit verlassen, um zu einem Brand zu fliegen", + "Exit cockpit to fly to an earthquake": "Cockpit verlassen, um zu einem Erdbeben zu fliegen", "Exit cockpit to fly to a route": "Cockpit verlassen, um zu einer Route zu fliegen", "Exit cockpit to fly to a file": "Cockpit verlassen, um zu einer Datei zu fliegen", "Exit cockpit to fly to a scene": "Cockpit verlassen, um zu einer Szene zu fliegen", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 729e19c280..124e4288cf 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -526,6 +526,16 @@ "UNAVAILABLE": "NO DISPONIBLE", "Live Flights": "Vuelos en vivo", "Earthquakes (24h)": "Terremotos (24 h)", + "earthquake|Minor": "Menor", + "earthquake|Light": "Ligero", + "earthquake|Moderate": "Moderado", + "earthquake|Strong": "Fuerte", + "earthquake|Major": "Mayor", + "earthquake|Great": "Gran", + "earthquake|Shallow": "Superficial", + "earthquake|Intermediate": "Intermedio", + "earthquake|Deep": "Profundo", + "{km} km deep": "{km} km de profundidad", "No selected data layers": "No hay capas de datos seleccionadas", "Cleared {count} data layers": { "one": "Se limpió {count} capa de datos", @@ -2599,6 +2609,7 @@ "Exit cockpit to fly to a target": "Sal de la cabina para volar a un objetivo", "Exit cockpit to fly to a vessel": "Sal de la cabina para volar a un buque", "Exit cockpit to fly to a fire": "Sal de la cabina para volar a un incendio", + "Exit cockpit to fly to an earthquake": "Sal de la cabina para volar a un terremoto", "Exit cockpit to fly to a route": "Sal de la cabina para volar a una ruta", "Exit cockpit to fly to a file": "Sal de la cabina para volar a un archivo", "Exit cockpit to fly to a scene": "Sal de la cabina para volar a una escena", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 8e0ce68982..0edb2993d9 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1479,6 +1479,7 @@ "Exit cockpit to fly to a target": "Quittez le cockpit pour rejoindre une cible", "Exit cockpit to fly to a vessel": "Quittez le cockpit pour rejoindre un navire", "Exit cockpit to fly to a fire": "Quittez le cockpit pour rejoindre un incendie", + "Exit cockpit to fly to an earthquake": "Quittez le cockpit pour rejoindre un séisme", "Exit cockpit to fly to a route": "Quittez le cockpit pour rejoindre un itinéraire", "Exit cockpit to fly to a file": "Quittez le cockpit pour rejoindre un fichier", "Exit cockpit to fly to a scene": "Quittez le cockpit pour rejoindre une scène", @@ -1937,6 +1938,16 @@ "Live Flights": "Vols en direct", "Military Flights": "Vols militaires", "Earthquakes (24h)": "Séismes (24 h)", + "earthquake|Minor": "Mineur", + "earthquake|Light": "Léger", + "earthquake|Moderate": "Modéré", + "earthquake|Strong": "Fort", + "earthquake|Major": "Majeur", + "earthquake|Great": "Exceptionnel", + "earthquake|Shallow": "Superficiel", + "earthquake|Intermediate": "Intermédiaire", + "earthquake|Deep": "Profond", + "{km} km deep": "{km} km de profondeur", "Satellites": "Satellites", "Place names": "Noms de lieux", "Space Missions (30d)": "Missions spatiales (30 j)", diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index a7b5f29e03..3f8afe847f 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -1373,6 +1373,7 @@ "Exit cockpit to fly to a target": "צא מתא הטייס כדי לטוס אל מטרה", "Exit cockpit to fly to a vessel": "צא מתא הטייס כדי לטוס אל אונייה", "Exit cockpit to fly to a fire": "צא מתא הטייס כדי לטוס אל שריפה", + "Exit cockpit to fly to an earthquake": "צא מתא הטייס כדי לטוס אל רעידת אדמה", "Exit cockpit to fly to a sighting": "צא מתא הטייס כדי לטוס אל תצפית", "Exit cockpit to fly to a sighting area": "צא מתא הטייס כדי לטוס אל אזור תצפית", "Exit cockpit to fly to a route": "צא מתא הטייס כדי לטוס אל מסלול", @@ -1789,6 +1790,16 @@ "Live Flights": "טיסות חיות", "Military Flights": "טיסות צבאיות", "Earthquakes (24h)": "רעידות אדמה (24 שע׳)", + "earthquake|Minor": "קל מאוד", + "earthquake|Light": "קל", + "earthquake|Moderate": "בינוני", + "earthquake|Strong": "חזק", + "earthquake|Major": "חזק מאוד", + "earthquake|Great": "עצום", + "earthquake|Shallow": "רדוד", + "earthquake|Intermediate": "עומק בינוני", + "earthquake|Deep": "עמוק", + "{km} km deep": "בעומק {km} ק״מ", "Satellites": "לוויינים", "Space Missions (30d)": "משימות חלל (30 יום)", "Street Traffic": "תנועה ברחובות", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 00338746f1..a94460c494 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1479,6 +1479,7 @@ "Exit cockpit to fly to a target": "Esci dal cockpit per volare a un obiettivo", "Exit cockpit to fly to a vessel": "Esci dal cockpit per volare a una nave", "Exit cockpit to fly to a fire": "Esci dal cockpit per volare a un incendio", + "Exit cockpit to fly to an earthquake": "Esci dal cockpit per volare a un terremoto", "Exit cockpit to fly to a route": "Esci dal cockpit per volare a un percorso", "Exit cockpit to fly to a file": "Esci dal cockpit per volare a un file", "Exit cockpit to fly to a scene": "Esci dal cockpit per volare a una scena", @@ -1937,6 +1938,16 @@ "Live Flights": "Voli live", "Military Flights": "Voli militari", "Earthquakes (24h)": "Terremoti (24 h)", + "earthquake|Minor": "Minore", + "earthquake|Light": "Leggero", + "earthquake|Moderate": "Moderato", + "earthquake|Strong": "Forte", + "earthquake|Major": "Maggiore", + "earthquake|Great": "Grande", + "earthquake|Shallow": "Superficiale", + "earthquake|Intermediate": "Intermedio", + "earthquake|Deep": "Profondo", + "{km} km deep": "{km} km di profondità", "Satellites": "Satelliti", "Place names": "Nomi dei luoghi", "Space Missions (30d)": "Missioni spaziali (30 g)", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 4dfdd5f213..05e31a9414 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -1441,6 +1441,7 @@ "Exit cockpit to fly to a target": "ターゲットへ移動するにはコックピットを終了してください", "Exit cockpit to fly to a vessel": "船舶へ移動するにはコックピットを終了してください", "Exit cockpit to fly to a fire": "火災へ移動するにはコックピットを終了してください", + "Exit cockpit to fly to an earthquake": "地震へ移動するにはコックピットを終了してください", "Exit cockpit to fly to a route": "ルートへ移動するにはコックピットを終了してください", "Exit cockpit to fly to a file": "ファイルの位置へ移動するにはコックピットを終了してください", "Exit cockpit to fly to a scene": "シーンへ移動するにはコックピットを終了してください", @@ -1869,6 +1870,16 @@ "Live Flights": "ライブフライト", "Military Flights": "軍用機", "Earthquakes (24h)": "地震(24時間)", + "earthquake|Minor": "微小", + "earthquake|Light": "軽微", + "earthquake|Moderate": "中規模", + "earthquake|Strong": "強い", + "earthquake|Major": "大規模", + "earthquake|Great": "巨大", + "earthquake|Shallow": "浅発", + "earthquake|Intermediate": "やや深発", + "earthquake|Deep": "深発", + "{km} km deep": "深さ {km} km", "Satellites": "衛星", "Place names": "地名", "Space Missions (30d)": "宇宙ミッション(30日)", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index ae3ec81c4f..79e2b34045 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -1479,6 +1479,7 @@ "Exit cockpit to fly to a target": "Saia da cabine para voar até um alvo", "Exit cockpit to fly to a vessel": "Saia da cabine para voar até uma embarcação", "Exit cockpit to fly to a fire": "Saia da cabine para voar até um incêndio", + "Exit cockpit to fly to an earthquake": "Saia da cabine para voar até um terremoto", "Exit cockpit to fly to a route": "Saia da cabine para voar até uma rota", "Exit cockpit to fly to a file": "Saia da cabine para voar até um arquivo", "Exit cockpit to fly to a scene": "Saia da cabine para voar até uma cena", @@ -1937,6 +1938,16 @@ "Live Flights": "Voos ao vivo", "Military Flights": "Voos militares", "Earthquakes (24h)": "Terremotos (24 h)", + "earthquake|Minor": "Menor", + "earthquake|Light": "Leve", + "earthquake|Moderate": "Moderado", + "earthquake|Strong": "Forte", + "earthquake|Major": "Maior", + "earthquake|Great": "Grande", + "earthquake|Shallow": "Raso", + "earthquake|Intermediate": "Intermediário", + "earthquake|Deep": "Profundo", + "{km} km deep": "{km} km de profundidade", "Satellites": "Satélites", "Place names": "Nomes de lugares", "Space Missions (30d)": "Missões espaciais (30 d)", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 36c3a20571..9261174229 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -631,6 +631,16 @@ "Live Flights": "Рейсы онлайн", "Military Flights": "Военные рейсы", "Earthquakes (24h)": "Землетрясения (24 ч)", + "earthquake|Minor": "Слабое", + "earthquake|Light": "Лёгкое", + "earthquake|Moderate": "Умеренное", + "earthquake|Strong": "Сильное", + "earthquake|Major": "Мощное", + "earthquake|Great": "Катастрофическое", + "earthquake|Shallow": "Мелкофокусное", + "earthquake|Intermediate": "Среднефокусное", + "earthquake|Deep": "Глубокофокусное", + "{km} km deep": "глубина {km} км", "Satellites": "Спутники", "Place names": "Названия мест", "Space Missions (30d)": "Космические миссии (30 дн.)", @@ -2645,6 +2655,7 @@ "Exit cockpit to fly to a target": "Выйдите из кабины, чтобы перелететь к цели", "Exit cockpit to fly to a vessel": "Выйдите из кабины, чтобы перелететь к судну", "Exit cockpit to fly to a fire": "Выйдите из кабины, чтобы перелететь к пожару", + "Exit cockpit to fly to an earthquake": "Выйдите из кабины, чтобы перелететь к землетрясению", "Exit cockpit to fly to a route": "Выйдите из кабины, чтобы перелететь к маршруту", "Exit cockpit to fly to a file": "Выйдите из кабины, чтобы перелететь к файлу", "Exit cockpit to fly to a scene": "Выйдите из кабины, чтобы перелететь к сцене", diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 60ad8724ec..f7d6f81964 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -591,6 +591,16 @@ "Live Flights": "Liveflyg", "Military Flights": "Militärflyg", "Earthquakes (24h)": "Jordbävningar (24 h)", + "earthquake|Minor": "Mindre", + "earthquake|Light": "Lätt", + "earthquake|Moderate": "Måttlig", + "earthquake|Strong": "Kraftig", + "earthquake|Major": "Stor", + "earthquake|Great": "Mycket stor", + "earthquake|Shallow": "Grund", + "earthquake|Intermediate": "Medeldjup", + "earthquake|Deep": "Djup", + "{km} km deep": "{km} km djup", "Satellites": "Satelliter", "Space Missions (30d)": "Rymduppdrag (30 d)", "Street Traffic": "Gatutrafik", @@ -1980,6 +1990,7 @@ "Exit cockpit to fly to a target": "Lämna cockpiten för att flyga till ett mål", "Exit cockpit to fly to a vessel": "Lämna cockpiten för att flyga till ett fartyg", "Exit cockpit to fly to a fire": "Lämna cockpiten för att flyga till en brand", + "Exit cockpit to fly to an earthquake": "Lämna cockpiten för att flyga till en jordbävning", "Exit cockpit to fly to a route": "Lämna cockpiten för att flyga till en rutt", "Exit cockpit to fly to a file": "Lämna cockpiten för att flyga till en fil", "Exit cockpit to fly to a scene": "Lämna cockpiten för att flyga till en scen", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 3231f3322a..8e6d2bfaf3 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -1497,6 +1497,7 @@ "Exit cockpit to fly to a target": "Вийдіть із кабіни, щоб перелетіти до цілі", "Exit cockpit to fly to a vessel": "Вийдіть із кабіни, щоб перелетіти до судна", "Exit cockpit to fly to a fire": "Вийдіть із кабіни, щоб перелетіти до пожежі", + "Exit cockpit to fly to an earthquake": "Вийдіть із кабіни, щоб перелетіти до землетрусу", "Exit cockpit to fly to a route": "Вийдіть із кабіни, щоб перелетіти до маршруту", "Exit cockpit to fly to a file": "Вийдіть із кабіни, щоб перелетіти до файлу", "Exit cockpit to fly to a scene": "Вийдіть із кабіни, щоб перелетіти до сцени", @@ -1970,6 +1971,16 @@ "Live Flights": "Рейси онлайн", "Military Flights": "Військові рейси", "Earthquakes (24h)": "Землетруси (24 год)", + "earthquake|Minor": "Слабкий", + "earthquake|Light": "Легкий", + "earthquake|Moderate": "Помірний", + "earthquake|Strong": "Сильний", + "earthquake|Major": "Потужний", + "earthquake|Great": "Катастрофічний", + "earthquake|Shallow": "Мілкофокусний", + "earthquake|Intermediate": "Середньофокусний", + "earthquake|Deep": "Глибокофокусний", + "{km} km deep": "глибина {km} км", "Satellites": "Супутники", "Place names": "Назви місць", "Space Missions (30d)": "Космічні місії (30 дн)", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 1851c62306..8ea38dc97d 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1415,6 +1415,7 @@ "Exit cockpit to fly to a target": "请先退出座舱,再飞往目标", "Exit cockpit to fly to a vessel": "请先退出座舱,再飞往船舶", "Exit cockpit to fly to a fire": "请先退出座舱,再飞往火点", + "Exit cockpit to fly to an earthquake": "请先退出座舱,再飞往地震", "Exit cockpit to fly to a route": "请先退出座舱,再飞往路线", "Exit cockpit to fly to a file": "请先退出座舱,再飞往文件位置", "Exit cockpit to fly to a scene": "请先退出座舱,再飞往场景", @@ -1844,6 +1845,16 @@ "Live Flights": "实时航班", "Military Flights": "军用航班", "Earthquakes (24h)": "地震(24 小时)", + "earthquake|Minor": "微弱", + "earthquake|Light": "轻微", + "earthquake|Moderate": "中等", + "earthquake|Strong": "强烈", + "earthquake|Major": "重大", + "earthquake|Great": "巨大", + "earthquake|Shallow": "浅源", + "earthquake|Intermediate": "中源", + "earthquake|Deep": "深源", + "{km} km deep": "震源深度 {km} km", "Satellites": "卫星", "Place names": "地名", "Space Missions (30d)": "太空任务(30 天)", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 88e759c66e..81999dbadb 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -1410,6 +1410,7 @@ "Exit cockpit to fly to a target": "請先退出座艙,再飛往目標", "Exit cockpit to fly to a vessel": "請先退出座艙,再飛往船舶", "Exit cockpit to fly to a fire": "請先退出座艙,再飛往火點", + "Exit cockpit to fly to an earthquake": "請先退出座艙,再飛往地震", "Exit cockpit to fly to a route": "請先退出座艙,再飛往路線", "Exit cockpit to fly to a file": "請先退出座艙,再飛往文件位置", "Exit cockpit to fly to a scene": "請先退出座艙,再飛往場景", @@ -1836,6 +1837,16 @@ "Live Flights": "實時航班", "Military Flights": "軍用航班", "Earthquakes (24h)": "地震(24 小時)", + "earthquake|Minor": "微弱", + "earthquake|Light": "輕微", + "earthquake|Moderate": "中等", + "earthquake|Strong": "強烈", + "earthquake|Major": "重大", + "earthquake|Great": "巨大", + "earthquake|Shallow": "淺源", + "earthquake|Intermediate": "中源", + "earthquake|Deep": "深源", + "{km} km deep": "震源深度 {km} km", "Satellites": "衛星", "Place names": "地名", "Space Missions (30d)": "太空任務(30 天)", diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 90d70e9a90..37cd2e8cae 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -11,6 +11,11 @@ import { selectEarthquakeOverlayCohort, mapAnalystRecord, earthquakeCoverage, + earthquakeMarkLabel, + earthquakeMagnitudeTitle, + earthquakeZoomLabel, + earthquakeDiscRadiusM, + describeEarthquake, } from './model.js'; export * from './model.js'; export { createUsgsEarthquakeSource } from './source.js'; @@ -25,6 +30,18 @@ const msg = (text) => text; * as `Hit.set`. */ export const EARTHQUAKE_DISC_SET_ID = 'earthquakes'; +export const EARTHQUAKES_LAYER_ID = 'earthquakes'; +/** The overlay source the clicked quake's detail card is shown in. */ +export const EARTHQUAKE_CARD_SOURCE_ID = 'earthquake-card'; +/** A disc's item id is this prefix and the event's stable id. */ +const PICK_PREFIX = 'earthquake:'; +/** The selected quake's flat fill, faint under the painted gradient. */ +const SELECTED_DISC_ALPHA = 0.04; +const CARD_HOST_OPTIONS = Object.freeze({ + cohortLimit: 1, + collisionCapacity: 1, + moving: false, +}); let instances = 0; /** @@ -33,8 +50,42 @@ let instances = 0; * The discs are one renderer draw set (`drawOf(viewer)`), made at `init`. * Given a Cesium viewer with no renderer bound, the * caller loads the package's `./render/cesium/unbound` export first. + * + * Clicking a disc shows that quake's detail card and selects it in the + * shared context. The application gives the click and selection services; + * without `input` and `picking` the discs are drawn but take no clicks. + * @param {object} options + * @param {object} options.source Snapshot source. + * @param {object} options.overlayHost World-overlay host (`hitTest` lets + * the card be clicked). + * @param {(viewer: object) => {onClick: Function}} [options.input] The + * viewer's click dispatcher. + * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function, + * registerPickOwner: Function, unregisterPickOwner: Function}} [options.picking] + * @param {{registerEntityContext: Function, selectEntityContext: Function, + * clearSelectedEntityContextForLayer: Function, + * getContextStore: Function}} [options.context] Shared selection store. + * @param {{isPointerFree: () => boolean}} [options.pointer] + * @param {(url: string) => void} [options.openExternal] + * @param {{requestWorldFocus: (detail: object) => boolean}} [options.focus] + * The camera transfer a clicked magnitude label asks for. + * @param {{show: (target: {id: string, lon: number, lat: number, + * radiusM: number, color: string}) => void, hide: () => void}} [options.ripples] + * The selected quake's animated contour rings. + * @param {object} [options.text] Card formatters (see describeEarthquake). */ -export function createEarthquakesLayer({ source, overlayHost } = {}) { +export function createEarthquakesLayer({ + source, + overlayHost, + input = null, + picking = null, + context = null, + pointer = null, + openExternal = null, + focus = null, + ripples = null, + text = undefined, +} = {}) { if (typeof source?.getSnapshot !== 'function') throw new TypeError('Earthquakes require a snapshot source'); if (!overlayHost) throw new TypeError('Earthquakes require an overlay host'); @@ -60,6 +111,270 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _marksKey = key; worldClock.coverageChanged(); }; + // The drawn events by stable id, for clicks; the selected one's id, card + // and the context record it was published as. + let _eventById = new Map(); + let _selectedId = null; + let _selectedCardId = null; + let _selectedLink = null; + let _contextId = null; + let _clickHandler = null; + const canSelect = () => Boolean(input && picking); + // The disc whose flat fill is faded while the painter draws its gradient. + let _fadedDiscId = null; + + /** + * A quake's disc: filled on the ground, with static axes (re-tessellating + * clamped ground geometry every frame is what once cost 30 fps). No + * outline: clamped to the ground, Cesium never drew one. A selected + * quake's disc is all but clear: the ripples painter fills it with a + * gradient instead, and the faint fill keeps it pickable. + */ + function discItem(event, faded = false) { + const radius = earthquakeDiscRadiusM(event.mag); + const [r, g, b] = depthColor(event.depthKm || 0); + const fillAlpha = faded + ? SELECTED_DISC_ALPHA + : event.mag >= 5.0 + ? 0.4 + : 0.3; + return { + id: `${PICK_PREFIX}${event.stableId}`, + geometry: { + kind: 'ellipse', + center: { lon: event.lon, lat: event.lat }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [r, g, b, fillAlpha], + height: 'clampGround', + clampTo: 'both', + }; + } + + /** Fade one disc's flat fill (and restore the one faded before). */ + function fadeDisc(stableId) { + if (!ripples || !_discs || _fadedDiscId === stableId) return; + const changed = []; + const before = _eventById.get(_fadedDiscId); + if (before) changed.push(discItem(before, false)); + const next = _eventById.get(stableId); + if (next) changed.push(discItem(next, true)); + _fadedDiscId = next ? stableId : null; + if (changed.length) _discs.upsert(changed); + } + + /** The drawn event a pick id names, or null. */ + function eventOfPickId(pickId) { + if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX)) + return null; + return _eventById.get(pickId.slice(PICK_PREFIX.length)) ?? null; + } + + /** The drawn event a click's draw hit is on: an item of this layer's set. */ + function pickedEvent(hit) { + if (!hit || hit.surface || !_discs || hit.set !== _discs.id) return null; + return eventOfPickId(hit.id); + } + + /** + * Show the selected quake's card, context and contours. `user`: a click or + * a label's activation, which claims the shared selection and runs the + * contours again; a feed refresh only brings them up to date, so it never + * takes back a selection made since, nor restarts the animation. + */ + function publishCard({ user = false } = {}) { + const event = _selectedId ? _eventById.get(_selectedId) : null; + if (!_enabled || !event) { + clearSelection(); + return; + } + const { title, details, link, accessibilityLabel } = describeEarthquake( + event, + text, + ); + _selectedLink = link && openExternal ? link : null; + const card = { + id: `earthquake-card:${event.stableId}`, + selected: true, + // Always hit-testable (the host only hit-tests interactive entries), + // so a click on a card with no link keeps it rather than falling + // through to the ground under it and clearing the selection. + interactive: true, + title, + details, + accent: depthAccent(event.depthKm || 0), + priority: Number.MAX_SAFE_INTEGER, + gapPx: 15, + verticalOnly: true, + placement: 'above', + stateless: true, + horizonCull: true, + position: fromDegrees(event.lon, event.lat), + }; + if (_selectedLink) { + const target = _selectedLink; + card.accessibilityLabel = accessibilityLabel; + card.activate = () => { + openExternal(target); + return true; + }; + } + _selectedCardId = card.id; + overlayHost.setEntries( + EARTHQUAKE_CARD_SOURCE_ID, + [card], + CARD_HOST_OPTIONS, + ); + overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, true); + publishContext(event, user); + fadeDisc(event.stableId); + ripples?.show?.( + { + id: event.stableId, + lon: event.lon, + lat: event.lat, + radiusM: earthquakeDiscRadiusM(event.mag), + color: depthAccent(event.depthKm || 0), + }, + { restart: user }, + ); + } + + /** + * Select the event in the shared context store, so "what's selected" + * (voice, the Cockpit) answers with it, as a clicked fire does. + */ + function publishContext(event, select) { + if (!context) return; + const id = `${PICK_PREFIX}${event.stableId}`; + try { + if (_contextId && _contextId !== id) + context.getContextStore().entities.delete(_contextId); + const carrier = { show: true }; + context.registerEntityContext(carrier, { + id, + layerId: EARTHQUAKES_LAYER_ID, + layerName: layer.name, + source: 'USGS', + // Hidden with the layer: the context store reads its `show`. + dataSource: _discs, + targetPosition: fromDegrees(event.lon, event.lat), + // i18n-ignore: English entity label, as the analyst records are + label: `Earthquake · ${earthquakeMarkLabel(event)}`, + latitude: event.lat, + longitude: event.lon, + properties: { + magnitude: event.mag, + depthKm: event.depthKm ?? null, + place: event.place ?? null, + time: Number.isFinite(event.time) + ? new Date(event.time).toISOString() + : null, + usgsId: event.usgsId ?? null, + }, + }); + _contextId = id; + if (select) context.selectEntityContext(carrier); + } catch { + // No context store (no window): the card still shows. + } + } + + function clearContext() { + if (!context || !_contextId) return; + try { + context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID); + context.getContextStore().entities.delete(_contextId); + } catch { + // store unavailable: nothing to clean + } + _contextId = null; + } + + function clearSelection() { + const had = _selectedId || _selectedCardId; + _selectedId = null; + _selectedCardId = null; + _selectedLink = null; + clearContext(); + ripples?.hide?.(); + fadeDisc(null); + if (had) + overlayHost.setEntries(EARTHQUAKE_CARD_SOURCE_ID, [], CARD_HOST_OPTIONS); + } + + function installClickHandler() { + if (!canSelect() || _clickHandler || !_viewer) return; + picking.registerPickOwner?.( + EARTHQUAKES_LAYER_ID, + (pickedId) => _enabled && eventOfPickId(pickedId) !== null, + ); + // A viewer with no renderer input bound takes no clicks. + let clicks = null; + try { + clicks = input(_viewer) ?? null; + } catch { + clicks = null; + } + if (!clicks) return; + _clickHandler = clicks.onClick((click) => { + if (!_enabled || (pointer && !pointer.isPointerFree())) return; + const at = click.screenPosition; + const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { + sourceId: EARTHQUAKE_CARD_SOURCE_ID, + }); + if (cardHit && cardHit.entryId === _selectedCardId) { + if (_selectedLink) openExternal(_selectedLink); + return; + } + // Another layer's pick (an aircraft, a camera) is not this layer's, + // even under a magnitude label: that layer handles it, and this card + // stays. Checked before the labels, as the fire layer does. + const pickId = click.topHit + ? (picking.resolvePickId(click.topHit) ?? null) + : null; + if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId)) + return; + // A magnitude label is what a far view (the whole globe) can click: + // it selects the quake and flies to it. + const labelHit = overlayHost.hitTest?.(at?.x, at?.y, { + sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID, + }); + if (labelHit && _eventById.has(labelHit.entryId)) { + selectAndFocus(labelHit.entryId); + return; + } + const event = pickedEvent(click.drawHit ?? click.topHit); + if (event) { + _selectedId = event.stableId; + publishCard({ user: true }); + return; + } + clearSelection(); + }); + } + + /** Select a drawn quake, show its card, and ask the camera to go there. */ + function selectAndFocus(stableId) { + const event = _eventById.get(stableId); + if (!_enabled || !event) return false; + _selectedId = stableId; + publishCard({ user: true }); + focus?.requestWorldFocus?.({ + kind: 'earthquake', + id: `${PICK_PREFIX}${stableId}`, + label: earthquakeMagnitudeTitle(event.mag), + position: fromDegrees(event.lon, event.lat), + }); + return true; + } + + function removeClickHandler() { + _clickHandler?.(); + _clickHandler = null; + picking?.unregisterPickOwner?.(EARTHQUAKES_LAYER_ID); + } const layer = { id: 'earthquakes', @@ -93,6 +408,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { // layer has no per-frame animator to keep the render loop alive for. if (_discs) _discs.show = true; overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true); + installClickHandler(); coverageChanged(); }, @@ -101,6 +417,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _request = null; _enabled = false; if (_discs) _discs.show = false; + removeClickHandler(); + clearSelection(); + overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID); + overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false); overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); coverageChanged(); @@ -132,41 +452,52 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { time, } of rows) { count++; - const baseRadius = Math.pow(2, mag) * 1000; - const color = depthColor(depthKm || 0); - const [r, g, b] = color; - const isSignificant = mag >= 5.0; - const fillAlpha = isSignificant ? 0.4 : 0.3; - const position = fromDegrees(lon, lat); - nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat }); - // A filled disc on the ground, with static axes: re-tessellating - // clamped ground geometry every frame is what once cost 30 fps. - // No outline: clamped to the ground, Cesium never drew one. - nextDiscs.push({ - id: `earthquake:${stableId}`, - geometry: { - kind: 'ellipse', - center: { lon, lat }, - semiMajor: baseRadius, - semiMinor: baseRadius, - }, - fill: [r, g, b, fillAlpha], - height: 'clampGround', - clampTo: 'both', - }); - overlayEntries.push( - createEarthquakeOverlayEntry({ - id: String(stableId), - position, - magnitude: mag, - accent: depthAccent(depthKm || 0), - }), + const event = { + stableId: String(stableId), + usgsId, + mag, + place, + time, + depthKm, + lon, + lat, + }; + nextEvents.push(event); + nextDiscs.push( + discItem(event, Boolean(ripples) && event.stableId === _selectedId), ); + const label = createEarthquakeOverlayEntry({ + id: String(stableId), + position, + magnitude: mag, + accent: depthAccent(depthKm || 0), + }); + if (canSelect()) { + const id = String(stableId); + label.interactive = true; + label.accessibilityLabel = earthquakeZoomLabel( + { mag, place }, + text, + ); + label.activate = () => selectAndFocus(id); + } + overlayEntries.push(label); } + // Bigger quakes first, so a small quake inside a big one's disc is + // drawn, and picked, on top of it. + nextDiscs.sort((a, b) => b.geometry.semiMajor - a.geometry.semiMajor); _discs.set(nextDiscs); _events = nextEvents; + _eventById = new Map( + nextEvents.map((event) => [event.stableId, event]), + ); + _fadedDiscId = + ripples && _eventById.has(_selectedId) ? _selectedId : null; + // A selected quake still in the feed keeps its card, refreshed; one + // that left the 24 h window loses it. + if (_selectedId) publishCard(); coverageChanged(); if (_enabled) { overlayHost.setEntries( @@ -199,13 +530,19 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { destroy(viewer = _viewer) { _request?.abort(); _request = null; + removeClickHandler(); + clearSelection(); + ripples?.dispose?.(); _viewer = null; _enabled = false; + overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID); + overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false); overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); _discs?.dispose(); _discs = null; _events = []; + _eventById = new Map(); _uncover?.(); _uncover = null; _marksKey = null; diff --git a/src/layers/earthquakes/model.js b/src/layers/earthquakes/model.js index 25570e7243..228758c011 100644 --- a/src/layers/earthquakes/model.js +++ b/src/layers/earthquakes/model.js @@ -123,6 +123,298 @@ export function createEarthquakeOverlayEntry({ }; } +/** Where USGS publishes one event's page, its event id appended. */ +export const USGS_EVENT_PAGE_URL = + 'https://earthquake.usgs.gov/earthquakes/eventpage/'; + +/** + * The USGS page for an event id, or null when there is no usable id (a + * fallback `event-N` id never names a USGS page, and is never sent). + * @param {unknown} usgsId + * @returns {string|null} + */ +export function earthquakeEventLink(usgsId) { + const id = + typeof usgsId === 'string' || typeof usgsId === 'number' + ? String(usgsId).trim() + : ''; + return /^[A-Za-z0-9_-]{1,64}$/.test(id) + ? `${USGS_EVENT_PAGE_URL}${id}` + : null; +} + +// The package carries no i18n: with no translator given, the card stays +// English, its `{name}` slots filled in. +const english = (text, values) => + String(text).replace(/\{(\w+)\}/g, (all, key) => + values && Object.hasOwn(values, key) ? String(values[key]) : all, + ); +const utcMinute = (time) => + `${new Date(time).toISOString().slice(0, 16).replace('T', ' ')} UTC`; +const oneDecimal = (value) => String(Math.round(value * 10) / 10); + +/** + * The detail card one clicked earthquake shows: its magnitude as the title, + * then where, when and how deep, and the source. With a USGS event id the + * card opens that event's page. + * @param {{mag: number, place?: string|null, time?: number|null, + * depthKm?: number|null, usgsId?: string|null}} event + * @param {object} [text] The application's formatters. + * @param {(text: string, values?: object) => string} [text.t] Translator. + * @param {(time: number) => string} [text.formatTime] An event time. + * @param {(value: number) => string} [text.formatDepth] A depth in km. + * @returns {{title: string, details: string[], link: string|null, + * accessibilityLabel: string}} + */ +export function describeEarthquake( + event, + { t = english, formatTime = utcMinute, formatDepth = oneDecimal } = {}, +) { + const details = []; + // Severity at a glance, right under the title: the class meter, then + // where in the crust it broke. + const glance = [earthquakeSeverityMeter(event?.mag)]; + if (Number.isFinite(event?.depthKm)) { + glance.push( + `${earthquakeDepthBandName(event.depthKm, t)} · ${t('{km} km deep', { + km: formatDepth(event.depthKm), + })}`, + ); + } + details.push(glance.join(' ')); + const place = + typeof event?.place === 'string' + ? event.place.replace(/\s+/g, ' ').trim() + : ''; + if (place) details.push(place); + if (Number.isFinite(event?.time)) details.push(formatTime(event.time)); + details.push(t('Source: {value}', { value: 'USGS' })); + const link = earthquakeEventLink(event?.usgsId); + if (link) details.push(t('Click the card to open the source ↗')); + const title = `${earthquakeMagnitudeTitle(event?.mag)} · ${earthquakeSeverityName( + event?.mag, + t, + )}`; + return { + title, + details, + link, + accessibilityLabel: t('Open the source for {title}', { title }), + }; +} + +/** + * USGS's magnitude classes, weakest first: minor (under 4; the feed starts + * at M2.5), light, moderate, strong, major, great (8 and up). + */ +export const EARTHQUAKE_SEVERITY_LEVELS = 6; + +/** + * A magnitude's USGS class, 0 (minor) to 5 (great). + * @param {number} magnitude + * @returns {number} + */ +export function earthquakeSeverityLevel(magnitude) { + const mag = Number(magnitude); + if (!Number.isFinite(mag) || mag < 4) return 0; + return Math.min(EARTHQUAKE_SEVERITY_LEVELS - 1, Math.floor(mag) - 3); +} + +/** A magnitude's class, as a word in the page's language. */ +export function earthquakeSeverityName(magnitude, t = english) { + switch (earthquakeSeverityLevel(magnitude)) { + case 5: + return t('Great', { context: 'earthquake' }); + case 4: + return t('Major', { context: 'earthquake' }); + case 3: + return t('Strong', { context: 'earthquake' }); + case 2: + return t('Moderate', { context: 'earthquake' }); + case 1: + return t('Light', { context: 'earthquake' }); + default: + return t('Minor', { context: 'earthquake' }); + } +} + +/** + * The class as a six-step meter, one filled block per class up to this one: + * `■■□□□□` for a light quake. Plain text, so the card shows it as it is. + * @param {number} magnitude + * @returns {string} + */ +export function earthquakeSeverityMeter(magnitude) { + const filled = earthquakeSeverityLevel(magnitude) + 1; + return '■'.repeat(filled) + '□'.repeat(EARTHQUAKE_SEVERITY_LEVELS - filled); +} + +/** + * The depth band the disc's colour shows, as a word: shallow (under 70 km, + * red), intermediate (to 300 km, orange), deep (yellow). + */ +export function earthquakeDepthBandName(depthKm, t = english) { + const band = depthBand(depthKm); + if (band === SHALLOW) return t('Shallow', { context: 'earthquake' }); + if (band === INTERMEDIATE) + return t('Intermediate', { context: 'earthquake' }); + return t('Deep', { context: 'earthquake' }); +} + +/** + * A quake's disc radius on the ground, in metres: it doubles with each + * magnitude step (about 5.7 km at M2.5, 32 km at M5, 64 km at M6). + * @param {number} magnitude + * @returns {number} + */ +export const earthquakeDiscRadiusM = (magnitude) => + Math.pow(2, magnitude) * 1000; + +/** How many contour lines run out from a selected quake at once. */ +export const EARTHQUAKE_RIPPLE_RINGS = 6; +/** How long one contour line takes from the marker to the disc's edge. */ +export const EARTHQUAKE_RIPPLE_PERIOD_MS = 4800; +/** Every this many lines one is an index contour, drawn heavier. */ +export const EARTHQUAKE_INDEX_CONTOUR_EVERY = 3; + +/** + * How far a contour line dents in from the circle, as a share of its + * radius. Kept with the drift below so nested lines never cross: a line's + * radius grows with `fraction` faster than its dents move (see + * earthquakeContourScale). + */ +export const EARTHQUAKE_CONTOUR_WOBBLE = 0.24; +const CONTOUR_HARMONICS = Object.freeze([2, 3, 5]); +const CONTOUR_WEIGHTS = Object.freeze([1, 0.6, 0.3]); +const CONTOUR_MAX_DRIFT = 1.5; + +/** A stable 32-bit hash of a string (FNV-1a). */ +function hashString(text) { + let h = 0x811c9dc5; + for (const ch of String(text ?? '')) { + h ^= ch.codePointAt(0); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +/** + * One quake's contour shape: a few harmonics around the circle, each with + * its own phase and a drift that turns it as a line runs outward, seeded by + * the quake's id so the same quake always draws the same contours. + * @param {string} seed The quake's stable id. + * @returns {ReadonlyArray<{harmonic: number, weight: number, phase: number, drift: number}>} + */ +export function earthquakeContourShape(seed) { + let state = hashString(seed) || 1; + // xorshift32: a small, stable stream from the seed. + const next = () => { + state ^= state << 13; + state ^= state >>> 17; + state ^= state << 5; + return (state >>> 0) / 0x100000000; + }; + return Object.freeze( + CONTOUR_HARMONICS.map((harmonic, i) => + Object.freeze({ + harmonic, + weight: CONTOUR_WEIGHTS[i], + phase: next() * 2 * Math.PI, + drift: (next() * 2 - 1) * CONTOUR_MAX_DRIFT, + }), + ), + ); +} + +/** + * Where a contour line runs at `angle` (radians), as a share of a circle of + * the same `fraction`: between 1 - EARTHQUAKE_CONTOUR_WOBBLE and 1, so the + * outermost line never leaves the disc. The dents turn as `fraction` grows, + * and no faster than the line grows, so lines never cross: with wobble A + * and drift D, d(fraction · scale)/d(fraction) ≥ 1 - A - A·D/2 > 0. + * @param {ReturnType} shape + * @param {number} angle + * @param {number} fraction 0 at the marker, 1 at the disc's edge. + * @returns {number} + */ +export function earthquakeContourScale(shape, angle, fraction) { + let sum = 0; + let total = 0; + for (const { harmonic, weight, phase, drift } of shape) { + sum += weight * Math.sin(harmonic * angle + phase + drift * fraction); + total += weight; + } + const n = total > 0 ? sum / total : 0; + return 1 - (EARTHQUAKE_CONTOUR_WOBBLE * (1 - n)) / 2; +} + +/** + * The selected quake's contour lines at a time: each runs from the marker + * (`fraction` 0) out to the disc's edge (1), evenly staggered, fading in + * just after it starts and out as it reaches the edge; every + * EARTHQUAKE_INDEX_CONTOUR_EVERY-th is an index contour. Pure: the painter + * gives the clock. + * @param {number} timeMs Any steady clock, in milliseconds. + * @param {{count?: number, periodMs?: number}} [options] + * @returns {Array<{fraction: number, alpha: number, index: boolean}>} + */ +export function earthquakeRippleRings( + timeMs, + { + count = EARTHQUAKE_RIPPLE_RINGS, + periodMs = EARTHQUAKE_RIPPLE_PERIOD_MS, + } = {}, +) { + const phase = Number.isFinite(timeMs) && periodMs > 0 ? timeMs / periodMs : 0; + const rings = []; + for (let k = 0; k < count; k++) { + const fraction = (((phase + k / count) % 1) + 1) % 1; + rings.push({ + fraction, + alpha: earthquakeRippleAlpha(fraction), + index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0, + }); + } + return rings; +} + +/** + * Still contour lines, for viewers who ask for reduced motion: the same + * lines as the animation, held evenly spaced out to the edge. + * @param {number} [count] + * @returns {Array<{fraction: number, alpha: number, index: boolean}>} + */ +export function earthquakeContourRings(count = EARTHQUAKE_RIPPLE_RINGS) { + const rings = []; + for (let k = 1; k <= count; k++) + rings.push({ + fraction: k / count, + alpha: 0.7, + index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0, + }); + return rings; +} + +const RIPPLE_FADE_IN = 0.12; +/** A ring's opacity where it is: in from 0 near the marker, out to 0 at the edge. */ +function earthquakeRippleAlpha(fraction) { + if (fraction <= 0 || fraction >= 1) return 0; + return fraction < RIPPLE_FADE_IN + ? fraction / RIPPLE_FADE_IN + : (1 - fraction) / (1 - RIPPLE_FADE_IN); +} + +/** + * What a magnitude label says to assistive technology: activating it zooms + * to the quake (`Zoom to M5.0 · 42 km SW of Anchorage, Alaska`). + * @param {{mag: number, place?: string|null}} event + * @param {{t?: (text: string, values?: object) => string}} [text] + * @returns {string} + */ +export function earthquakeZoomLabel(event, { t = english } = {}) { + return t('Zoom to {name}', { name: earthquakeMarkLabel(event) }); +} + /** Keep the largest events, with stable identity as the tie-break. */ export function selectEarthquakeOverlayCohort( entries, diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs new file mode 100644 index 0000000000..568d6cc4e1 --- /dev/null +++ b/src/layers/earthquakes/selection.test.mjs @@ -0,0 +1,610 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import * as picking from '../../data/pickRegistry.js'; +import { + EARTHQUAKE_CARD_SOURCE_ID, + EARTHQUAKE_OVERLAY_SOURCE_ID, + createEarthquakesLayer, + describeEarthquake, + earthquakeEventLink, + earthquakeRippleRings, + earthquakeContourRings, + earthquakeContourShape, + earthquakeContourScale, + EARTHQUAKE_CONTOUR_WOBBLE, + EARTHQUAKE_RIPPLE_PERIOD_MS, + earthquakeSeverityName, + earthquakeSeverityMeter, + earthquakeDepthBandName, +} from './index.js'; + +const quake = (id, extra = {}) => ({ + stableId: id, + usgsId: id, + lon: -153.3, + lat: 60.0, + depthKm: 112.4, + mag: 2.5, + place: '42 km W of Fixture, Alaska', + time: Date.UTC(2026, 10, 13, 15, 37), + ...extra, +}); + +/** A layer whose globe clicks, card hits and context store the test drives. */ +function harness(rows, { context = null, ripples = null } = {}) { + let snapshot = rows; + const handlers = []; + const opened = []; + const cards = []; + const visible = new Map(); + const labels = []; + const focused = []; + // What the overlay hit test finds under the click, per source. + const overlayHits = new Map(); + const viewer = {}; + const { draw } = bindFakeDraw(viewer); + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => snapshot }, + overlayHost: { + setEntries(sourceId, entries) { + if (sourceId === EARTHQUAKE_CARD_SOURCE_ID) cards.push(entries); + if (sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) labels.push(entries); + }, + setVisible: (sourceId, show) => visible.set(sourceId, show), + clearSource() {}, + // As the real host does, only an interactive entry painted now is hit. + hitTest(_x, _y, { sourceId }) { + const hit = overlayHits.get(sourceId); + const painted = + sourceId === EARTHQUAKE_CARD_SOURCE_ID ? cards.at(-1) : labels.at(-1); + const entry = painted?.find((e) => e.id === hit?.entryId); + return hit && entry?.interactive === true ? hit : null; + }, + }, + input: () => ({ + onClick(callback) { + const handler = { callback, destroyed: false }; + handlers.push(handler); + return () => { + handler.destroyed = true; + }; + }, + }), + picking, + context, + ripples, + pointer: { isPointerFree: () => true }, + openExternal: (url) => opened.push(url), + focus: { + requestWorldFocus: (detail) => { + focused.push(detail); + return true; + }, + }, + }); + layer.init(viewer); + const discs = () => draw.find('earthquakes:'); + const live = () => handlers.filter((h) => !h.destroyed); + return { + layer, + viewer, + opened, + cards, + visible, + focused, + handlers, + discs, + setRows(next) { + snapshot = next; + }, + /** Click a quake's disc (by stable id), something else, or the map. */ + click(hit) { + for (const { callback } of live()) + callback({ + screenPosition: { x: 10, y: 10 }, + topHit: hit, + drawHit: hit && !hit.surface ? hit : null, + }); + }, + clickDisc(id) { + this.click({ set: discs().spec.id, id: `earthquake:${id}` }); + }, + clickCard(entryId) { + this.clickOverlay(EARTHQUAKE_CARD_SOURCE_ID, entryId); + }, + /** Click a magnitude label, as the overlay host paints it. */ + clickLabel(id) { + this.clickOverlay(EARTHQUAKE_OVERLAY_SOURCE_ID, id); + }, + clickOverlay(sourceId, entryId) { + this.clickOverlayWith(sourceId, entryId, null); + }, + /** Click an overlay entry with `hit` drawn under the same pixel. */ + clickOverlayWith(sourceId, entryId, hit) { + overlayHits.set(sourceId, { sourceId, entryId }); + this.click(hit); + overlayHits.delete(sourceId); + }, + lastCard: () => cards.at(-1), + lastLabels: () => labels.at(-1), + }; +} + +test('clicking a quake disc shows its detail card; empty map clears it', async () => { + const h = harness([quake('ak1'), quake('ak2', { mag: 4.1 })]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + assert.equal(h.cards.length, 0, 'no card before a click'); + + h.clickDisc('ak2'); + const [card] = h.lastCard(); + assert.equal(card.id, 'earthquake-card:ak2'); + assert.equal(card.title, 'M4.1 · Light'); + assert.deepEqual(card.details, [ + '■■□□□□ Intermediate · 112.4 km deep', + '42 km W of Fixture, Alaska', + '2026-11-13 15:37 UTC', + 'Source: USGS', + 'Click the card to open the source ↗', + ]); + assert.equal(card.interactive, true); + assert.equal(card.accessibilityLabel, 'Open the source for M4.1 · Light'); + assert.equal(h.visible.get(EARTHQUAKE_CARD_SOURCE_ID), true); + + h.click(null); + assert.deepEqual(h.lastCard(), [], 'a click on the map clears the card'); + h.layer.destroy(); +}); + +test('the card opens the USGS event page, from a click or the keyboard', async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.clickCard('earthquake-card:ak1'); + assert.deepEqual(h.opened, [ + 'https://earthquake.usgs.gov/earthquakes/eventpage/ak1', + ]); + assert.equal(h.lastCard()[0].activate(), true); + assert.equal(h.opened.length, 2); + assert.equal(h.lastCard().length, 1, 'opening the source keeps the card'); + h.layer.destroy(); +}); + +test('a quake with no USGS id gets a card with no link', async () => { + const h = harness([quake('event-1', { usgsId: null })]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('event-1'); + const [card] = h.lastCard(); + assert.equal(card.interactive, true, 'hit-testable, so a click keeps it'); + assert.equal(card.activate, undefined); + assert.equal(card.accessibilityLabel, undefined, 'no action to offer'); + assert.ok(!card.details.some((line) => line.includes('Click the card'))); + h.clickCard(card.id); + assert.deepEqual(h.opened, []); + assert.equal(h.lastCard()[0].id, card.id, 'the card stays'); + h.layer.destroy(); +}); + +test("another layer's pick leaves the card; its own pick ids are claimed", async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + assert.equal(picking.findPickOwner('earthquake:ak1'), 'earthquakes'); + assert.equal(picking.findPickOwner('earthquake:gone'), null); + picking.registerPickOwner('test-other', (id) => id === 'plane-1'); + try { + h.clickDisc('ak1'); + const before = h.cards.length; + h.click({ set: 'flights:1', id: 'plane-1' }); + assert.equal(h.cards.length, before, 'the card stays'); + // A pick of the same id from another set is not a quake. + h.click({ set: 'other:1', id: 'earthquake:ak1' }); + assert.deepEqual(h.lastCard(), []); + } finally { + picking.unregisterPickOwner('test-other'); + h.layer.destroy(); + } + assert.equal(picking.findPickOwner('earthquake:ak1'), null); +}); + +test('a refresh keeps the selected quake while it is in the feed', async () => { + const h = harness([quake('ak1'), quake('ak2')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.setRows([quake('ak1', { mag: 2.7 }), quake('ak2')]); + await h.layer.update(h.viewer); + assert.equal( + h.lastCard()[0].title, + 'M2.7 · Minor', + 'the card follows the feed', + ); + h.setRows([quake('ak2')]); + await h.layer.update(h.viewer); + assert.deepEqual(h.lastCard(), [], 'a quake that left the feed loses it'); + h.layer.destroy(); +}); + +test('disable removes the click handler and the card', async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.layer.disable(h.viewer); + assert.deepEqual(h.lastCard(), []); + assert.equal( + h.handlers.every((handler) => handler.destroyed), + true, + ); + assert.equal(picking.findPickOwner('earthquake:ak1'), null); + h.layer.enable(h.viewer); + assert.equal( + h.handlers.filter((handler) => !handler.destroyed).length, + 1, + 'one handler again, not two', + ); + h.layer.destroy(); +}); + +test('a small quake inside a big one is drawn on top of it', async () => { + const h = harness([quake('small', { mag: 2.6 }), quake('big', { mag: 6 })]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + assert.deepEqual( + [...h.discs().items.keys()], + ['earthquake:big', 'earthquake:small'], + ); + h.layer.destroy(); +}); + +test('the clicked quake is the selected context, cleared with the card', async () => { + const entities = new Map(); + const calls = []; + const context = { + getContextStore: () => ({ entities }), + registerEntityContext(carrier, metadata) { + entities.set(metadata.id, { ...metadata, entity: carrier }); + }, + selectEntityContext: (carrier) => calls.push(['select', carrier]), + clearSelectedEntityContextForLayer: (layerId) => + calls.push(['clear', layerId]), + }; + const h = harness([quake('ak1'), quake('ak2')], { context }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const record = entities.get('earthquake:ak1'); + assert.equal(record.layerId, 'earthquakes'); + assert.equal(record.label, 'Earthquake · M2.5 · 42 km W of Fixture, Alaska'); + assert.equal(record.properties.usgsId, 'ak1'); + assert.equal(record.dataSource.show, true, 'hidden with the discs'); + assert.equal(calls.at(-1)[0], 'select'); + h.clickDisc('ak2'); + assert.deepEqual([...entities.keys()], ['earthquake:ak2'], 'one record'); + h.click(null); + assert.equal(entities.size, 0); + assert.deepEqual(calls.at(-1), ['clear', 'earthquakes']); + h.layer.destroy(); +}); + +test('without click services the layer draws and takes no clicks', async () => { + const viewer = {}; + bindFakeDraw(viewer); + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => [quake('ak1')] }, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + layer.init(viewer); + layer.enable(viewer); + assert.equal(await layer.update(viewer), true); + assert.equal(picking.findPickOwner('earthquake:ak1'), null); + layer.destroy(); +}); + +test('describeEarthquake translates through the given formatters', () => { + const card = describeEarthquake(quake('ak1', { place: ' far away ' }), { + t: (text, values) => `<${text}>${JSON.stringify(values ?? {})}`, + formatTime: () => 'TIME', + formatDepth: (km) => `~${km}`, + }); + assert.equal(card.title, 'M2.5 · {"context":"earthquake"}'); + assert.deepEqual(card.details, [ + '■□□□□□ {"context":"earthquake"} · <{km} km deep>{"km":"~112.4"}', + 'far away', + 'TIME', + '{"value":"USGS"}', + '{}', + ]); + const bare = describeEarthquake({ mag: 3, place: null, time: null }); + assert.equal(bare.title, 'M3.0 · Minor'); + assert.deepEqual(bare.details, ['■□□□□□', 'Source: USGS']); + assert.equal(bare.link, null); +}); + +test('severity follows the USGS magnitude classes; depth bands the disc colours', () => { + const cases = [ + [2.5, 'Minor', '■□□□□□'], + [3.99, 'Minor', '■□□□□□'], + [4, 'Light', '■■□□□□'], + [5.4, 'Moderate', '■■■□□□'], + [6.1, 'Strong', '■■■■□□'], + [7.8, 'Major', '■■■■■□'], + [8.2, 'Great', '■■■■■■'], + [9.5, 'Great', '■■■■■■'], + [Number.NaN, 'Minor', '■□□□□□'], + ]; + for (const [mag, name, meter] of cases) { + assert.equal(earthquakeSeverityName(mag), name, String(mag)); + assert.equal(earthquakeSeverityMeter(mag), meter, String(mag)); + } + assert.equal(earthquakeDepthBandName(10), 'Shallow'); + assert.equal(earthquakeDepthBandName(69.9), 'Shallow'); + assert.equal(earthquakeDepthBandName(70), 'Intermediate'); + assert.equal(earthquakeDepthBandName(299), 'Intermediate'); + assert.equal(earthquakeDepthBandName(300), 'Deep'); +}); + +test('earthquakeEventLink accepts only plain USGS ids', () => { + assert.equal( + earthquakeEventLink('us7000abcd'), + 'https://earthquake.usgs.gov/earthquakes/eventpage/us7000abcd', + ); + for (const bad of [null, '', ' ', '../x', 'a/b', 'a?b=1', 'x'.repeat(65)]) + assert.equal(earthquakeEventLink(bad), null, String(bad)); +}); + +test('clicking a magnitude label selects the quake and flies to it', async () => { + const h = harness([ + quake('ak1'), + quake('jp1', { mag: 5, lon: 142, lat: 38 }), + ]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + const label = h.lastLabels().find((entry) => entry.id === 'jp1'); + assert.equal(label.interactive, true, 'labels take clicks'); + assert.equal( + label.accessibilityLabel, + 'Zoom to M5.0 · 42 km W of Fixture, Alaska', + ); + + h.clickLabel('jp1'); + assert.equal(h.lastCard()[0].id, 'earthquake-card:jp1'); + assert.equal(h.focused.length, 1); + const [detail] = h.focused; + assert.equal(detail.kind, 'earthquake'); + assert.equal(detail.id, 'earthquake:jp1'); + assert.equal(detail.label, 'M5.0'); + assert.ok( + Math.hypot(detail.position.x, detail.position.y, detail.position.z) > 6e6, + ); + + // The keyboard path does the same. + assert.equal( + h + .lastLabels() + .find((e) => e.id === 'ak1') + .activate(), + true, + ); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1'); + assert.equal(h.focused.at(-1).id, 'earthquake:ak1'); + + // A disc click only selects: the camera stays where it is. + h.clickDisc('jp1'); + assert.equal(h.focused.length, 2); + assert.equal(h.lastCard()[0].id, 'earthquake-card:jp1'); + + // A label id the layer no longer draws is not a quake. + h.clickLabel('gone'); + assert.deepEqual(h.lastCard(), []); + assert.equal(h.focused.length, 2); + h.layer.destroy(); +}); + +test('without click services the labels stay non-interactive', async () => { + const viewer = {}; + bindFakeDraw(viewer); + const published = []; + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => [quake('ak1')] }, + overlayHost: { + setEntries: (_source, entries) => published.push(entries), + setVisible() {}, + clearSource() {}, + }, + }); + layer.init(viewer); + layer.enable(viewer); + await layer.update(viewer); + const [label] = published.at(-1); + assert.equal(label.interactive, false); + assert.equal(label.activate, undefined); + layer.destroy(); +}); + +test('the selected quake runs contour rings to its disc edge; clearing stops them', async () => { + const calls = []; + const ripples = { + show: (target) => calls.push(['show', target]), + hide: () => calls.push(['hide']), + dispose: () => calls.push(['dispose']), + }; + const h = harness( + [quake('ak1', { mag: 5, depthKm: 10 }), quake('ak2', { mag: 3 })], + { ripples }, + ); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const shown = calls.findLast(([kind]) => kind === 'show')[1]; + assert.deepEqual(shown, { + id: 'ak1', + lon: -153.3, + lat: 60, + radiusM: 32000, + color: 'rgb(255,0,0)', + }); + assert.equal( + h.discs().items.get('earthquake:ak1').geometry.semiMajor, + shown.radiusM, + 'the rings end at the disc edge', + ); + h.clickDisc('ak2'); + assert.equal(calls.findLast(([kind]) => kind === 'show')[1].radiusM, 8000); + h.click(null); + assert.deepEqual(calls.at(-1), ['hide']); + h.clickDisc('ak1'); + h.layer.disable(h.viewer); + assert.deepEqual(calls.at(-1), ['hide']); + h.layer.destroy(); + assert.deepEqual(calls.at(-1), ['dispose']); +}); + +test('ripple rings run from the marker to the edge, staggered, fading at both ends', () => { + const rings = earthquakeRippleRings(0, { count: 3, periodMs: 3000 }); + assert.deepEqual( + rings.map(({ fraction }) => Number(fraction.toFixed(4))), + [0, 0.3333, 0.6667], + ); + assert.equal(rings[0].alpha, 0, 'a ring at the marker is not yet seen'); + // Each ring moves outward with time and wraps back to the marker. + const later = earthquakeRippleRings(1000, { count: 3, periodMs: 3000 }); + assert.ok(later[1].fraction > rings[1].fraction); + assert.ok(later[2].fraction < rings[2].fraction, 'the outer ring wrapped'); + for (let t = 0; t < 6000; t += 37) + for (const { fraction, alpha } of earthquakeRippleRings(t)) { + assert.ok(fraction >= 0 && fraction < 1); + assert.ok(alpha >= 0 && alpha <= 1); + } + const near = (f) => + earthquakeRippleRings(f * EARTHQUAKE_RIPPLE_PERIOD_MS, { count: 1 })[0] + .alpha; + assert.ok(near(0.99) < 0.02, 'fades out at the edge'); + assert.ok(near(0.12) > 0.999, 'fully in just after the start'); + assert.deepEqual( + earthquakeContourRings(3).map(({ fraction }) => fraction), + [1 / 3, 2 / 3, 1], + ); +}); + +test('a quake keeps its own contour shape; nested lines never cross', () => { + const a = earthquakeContourShape('us7000abcd'); + assert.deepEqual( + earthquakeContourShape('us7000abcd'), + a, + 'same id, same shape', + ); + assert.notDeepEqual(earthquakeContourShape('ak2026xyz'), a); + for (const id of ['us7000abcd', 'ak2026xyz', 'event-1', '']) { + const shape = earthquakeContourShape(id); + for (let i = 0; i < 180; i++) { + const angle = (2 * Math.PI * i) / 180; + let previous = 0; + for (let step = 1; step <= 200; step++) { + const fraction = step / 200; + const scale = earthquakeContourScale(shape, angle, fraction); + assert.ok(scale <= 1 + 1e-12, 'never past the disc edge'); + assert.ok(scale >= 1 - EARTHQUAKE_CONTOUR_WOBBLE - 1e-12); + const reach = fraction * scale; + assert.ok(reach > previous, `${id}: lines cross at ${angle}`); + previous = reach; + } + } + } +}); + +test("the selected quake's flat disc fades under its gradient and comes back", async () => { + const ripples = { show() {}, hide() {}, dispose() {} }; + const h = harness([quake('ak1', { mag: 5 }), quake('ak2')], { ripples }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + const alpha = (id) => h.discs().items.get(`earthquake:${id}`).fill[3]; + assert.equal(alpha('ak1'), 0.4); + h.clickDisc('ak1'); + assert.equal(alpha('ak1'), 0.04, 'faint, still pickable'); + h.clickDisc('ak2'); + assert.equal(alpha('ak1'), 0.4, 'restored'); + assert.equal(alpha('ak2'), 0.04); + // A refresh keeps the selected disc faded. + await h.layer.update(h.viewer); + assert.equal(alpha('ak2'), 0.04); + assert.equal(alpha('ak1'), 0.4); + h.click(null); + assert.equal(alpha('ak2'), 0.3); + h.layer.destroy(); +}); + +test('without the ripples painter the selected disc keeps its fill', async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + assert.equal(h.discs().items.get('earthquake:ak1').fill[3], 0.3); + h.layer.destroy(); +}); + +test('a feed refresh neither retakes the selection nor restarts the contours', async () => { + const calls = []; + const shows = []; + const entities = new Map(); + const context = { + getContextStore: () => ({ entities }), + registerEntityContext(carrier, metadata) { + entities.set(metadata.id, { ...metadata, entity: carrier }); + }, + selectEntityContext: () => calls.push('select'), + clearSelectedEntityContextForLayer: () => calls.push('clear'), + }; + const ripples = { + show: (target, options) => shows.push(options), + hide() {}, + dispose() {}, + }; + const h = harness([quake('ak1', { mag: 4 })], { context, ripples }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + assert.deepEqual(calls, ['select']); + assert.deepEqual(shows, [{ restart: true }]); + // Another layer's selection happens here; then the feed refreshes. + h.setRows([quake('ak1', { mag: 4.3 })]); + await h.layer.update(h.viewer); + assert.deepEqual(calls, ['select'], 'not selected again by a refresh'); + assert.deepEqual(shows.at(-1), { restart: false }); + assert.equal( + entities.get('earthquake:ak1').label, + 'Earthquake · M4.3 · 42 km W of Fixture, Alaska', + 'the record is kept up to date', + ); + // Clicking it again is the user's: it selects and runs again. + h.clickDisc('ak1'); + assert.deepEqual(calls, ['select', 'select']); + assert.deepEqual(shows.at(-1), { restart: true }); + h.layer.destroy(); +}); + +test("another layer's object over a magnitude label takes the click", async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); + try { + // The click lands on the label and on a plane drawn there. + h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak1', { + set: 'flights:1', + id: 'plane-9', + }); + assert.equal(h.cards.length, 0, 'the quake is not selected'); + assert.equal(h.focused.length, 0, 'and the camera stays'); + // The label alone still selects and flies. + h.clickLabel('ak1'); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1'); + assert.equal(h.focused.length, 1); + } finally { + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + } +}); diff --git a/src/navigationPolicy.js b/src/navigationPolicy.js index d9e0e1757d..077cfb8d45 100644 --- a/src/navigationPolicy.js +++ b/src/navigationPolicy.js @@ -24,6 +24,7 @@ const COCKPIT_REFUSALS = Object.freeze({ target: msg('Exit cockpit to fly to a target'), vessel: msg('Exit cockpit to fly to a vessel'), fire: msg('Exit cockpit to fly to a fire'), + earthquake: msg('Exit cockpit to fly to an earthquake'), sighting: msg('Exit cockpit to fly to a sighting'), 'sighting-area': msg('Exit cockpit to fly to a sighting area'), train: msg('Exit cockpit to fly to a train'), diff --git a/src/worldFocus.js b/src/worldFocus.js index af50b2f30b..cf9e2fb90f 100644 --- a/src/worldFocus.js +++ b/src/worldFocus.js @@ -18,6 +18,9 @@ export const WORLD_FOCUS_FRAMING = Object.freeze({ // A stopped train's one fly-to, and the frame a moving train is followed // in (src/layers/rail/follow.js): the train and the track either side. train: Object.freeze({ radiusM: 200, rangeM: 2500, pitchDeg: -35 }), + // A clicked quake's magnitude label: its disc (2^M km across, so about + // 11 km at M2.5 and 128 km at M6) and the ground around it. + earthquake: Object.freeze({ radiusM: 20000, rangeM: 220000, pitchDeg: -45 }), 'sighting-area': Object.freeze({ radiusM: 11000, rangeM: 60000, diff --git a/src/worldFocus.test.mjs b/src/worldFocus.test.mjs index 2f90c5b6f9..8512a969d4 100644 --- a/src/worldFocus.test.mjs +++ b/src/worldFocus.test.mjs @@ -209,6 +209,7 @@ test('fires frame wider than vessels — a fire is read by its surroundings', () test('every framing is a real oblique standoff, not a nadir or an inside-out sphere', () => { const kinds = Object.keys(WORLD_FOCUS_FRAMING); assert.deepEqual(kinds.sort(), [ + 'earthquake', 'fire', 'sighting', 'sighting-area', @@ -232,8 +233,10 @@ test('every framing is a real oblique standoff, not a nadir or an inside-out sph framing.rangeM > framing.radiusM, `${kind}: range ${framing.rangeM} must stand off outside radius ${framing.radiusM}`, ); - // An obscured sighting frames its entire 0.2° privacy cell. - const maximumRange = kind === 'sighting-area' ? 60000 : 10000; + // An obscured sighting frames its entire 0.2° privacy cell, and a quake + // its disc, up to 128 km across at M6. + const maximumRange = + { 'sighting-area': 60000, earthquake: 250000 }[kind] ?? 10000; assert.ok( framing.rangeM <= maximumRange, `${kind}: range must fit its surface extent, got ${framing.rangeM}`,