import { followShellLift, globeImageryHost, WEATHER_SHELL_HEIGHTS, } from '../weather/shellRendering.js'; import { createWindRelief } from './relief.js'; import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js'; import { canvasOf, findCamera, findDraw, findFrame, findGlobe, findQuery, } from '../../render/rendererOf.js'; import { fromDegreesInto } from '../../geo/ellipsoid.js'; import { NO_IMAGERY_HOST } from '../weather/imageryHost.js'; import { msg } from '../../i18n/index.js'; import { createWindGpuRendering } from './gpuRendering.js'; import { advectParticle, sampleWind } from './model.js'; import { createFieldRaster, SCALAR_UNAVAILABLE, trailEraseAlpha, windTrailColor, } from './fields.js'; // English for diagnostics; the row status shows it translated (index.js). The // scalar texts are the source's own; setOptions accepts only these overlays. const FIELD_UNAVAILABLE = Object.freeze({ speed: msg('Wind speed field unavailable'), ...SCALAR_UNAVAILABLE, }); /** English status for a scalar overlay with no drawable field. */ export function fieldUnavailableText(overlay) { return Object.hasOwn(FIELD_UNAVAILABLE, overlay) ? FIELD_UNAVAILABLE[overlay] : null; } const WIND_FIELD_FADE_HIGH_METERS = 1_200_000; const WIND_FIELD_FADE_LOW_METERS = 200_000; const WIND_FIELD_LOG_RANGE = Math.log( WIND_FIELD_FADE_HIGH_METERS / WIND_FIELD_FADE_LOW_METERS, ); // Snapshots own immutable decoded arrays. Compare their contents, not grid URLs // (which include the scalar overlay) or only cycle IDs (which can be revised). // This bounded scan runs on acquisition, never in the animation loop. function sameWind(previous, next, previousField, nextField) { if (!previous || !next || !previousField || !nextField) return false; for (const key of ['model', 'level', 'units']) if (previous[key] !== next[key]) return false; for (const key of ['runIso', 'validIso', 'forecastHour', 'date', 'hour']) if (previous.cycle?.[key] !== next.cycle?.[key]) return false; for (const key of ['nx', 'ny', 'lo1', 'la1', 'dx', 'dy']) if (previousField[key] !== nextField[key]) return false; for (const key of ['u', 'v']) { const before = previousField[key]; const after = nextField[key]; if (!before || !after || before.length !== after.length) return false; if (before === after) continue; for (let i = 0; i < before.length; i++) if (before[i] !== after[i]) return false; } return true; } let windShells = 0; /** The colour field as a raised shell over the whole globe, through the * draw port's raster-shell field; it rises with the camera. */ function createWindShell(viewer, draw, texture, alpha, ports) { const seq = (windShells += 1); const height = WEATHER_SHELL_HEIGHTS.wind; const field = draw.field({ kind: 'rasterShell', id: `wind-shell:${seq}`, image: { canvas: texture, key: `wind-shell:${seq}` }, rectangle: { west: -180, south: -90, east: 180, north: 90 }, heightM: height, alpha, }); let shownAlpha = alpha; let drawn = false; let owed = true; field.on('drawn', () => { drawn = true; owed = false; }); const offLift = followShellLift( viewer, (liftM) => { owed = true; field.update({ liftM }); }, ports, ); return { setAlpha(value) { if (value === shownAlpha) return; shownAlpha = value; owed = true; field.update({ alpha: value }); }, setShow(value) { field.show = Boolean(value); }, destroy() { offLift(); field.dispose(); }, getDiagnostics: () => ({ height, ready: drawn, uploaded: drawn, show: field.show, alpha: shownAlpha, rendering: owed && field.show, detail: { uploaded: false, window: null }, }), }; } /** Globe-projected surface flow plus one owned, static colour field: globe * imagery on the globe host, a raised shell on the 3D Tiles host. */ export function createWindRendering({ container, getViewer, getHost: hostOf, eventTarget = globalThis.window, createGpuRendering = createWindGpuRendering, globeOf = findGlobe, drawOf = findDraw, cameraOf = findCamera, frameOf = findFrame, queryOf = findQuery, onStatusChange, } = {}) { // The host the shell names, else the viewer's globe imagery. const getHost = () => hostOf?.() ?? globeImageryHost(getViewer?.()); let canvas = null; let context = null; let snapshot = null; let field = null; let particles = []; let frame = null; let running = false; let lastTime = null; let cssWidth = 1; let cssHeight = 1; let warned = false; let overlay = 'none'; let paused = false; let reducedMotion = false; let imagery = null; let shell = null; let imageryKind = null; let imageryError = null; let imageryErrorRemove = null; let media = null; let removers = []; let bounds = null; let cameraChanged = true; let painted = 0; const gpu = createGpuRendering({ getViewer, drawOf }); let gpuActive = false; let reportedGpuReady = null; let gpuNarrow = false; const relief = createWindRelief({ getViewer, globeOf }); const signature = Array(8).fill(null); const wind = { u: 0, v: 0 }; const before = { lon: 0, lat: 0 }; const world = { x: 0, y: 0, z: 0 }; const degree = Math.PI / 180; const hidden = () => globalThis.document?.hidden === true; const still = () => paused || reducedMotion; const budget = () => Math.max( 200, Math.min( cssWidth < 600 ? 1000 : 3000, Math.floor((cssWidth * cssHeight) / 420), ), ); const viewerReady = () => { const viewer = getViewer?.(); return viewer && !viewer.isDestroyed?.() ? viewer : null; }; const poseOf = (viewer) => cameraOf(viewer)?.pose?.() ?? null; // The camera's height, or undefined where there is none (or the eye sits // at the earth's centre and it is not a number). const heightOf = (viewer) => { const height = viewer ? poseOf(viewer)?.height : undefined; return Number.isFinite(height) ? height : undefined; }; const requestRender = (viewer) => frameOf(viewer)?.requestRender?.('wind'); // What a paint projects with: the query port and the eye's position. const viewOf = (viewer) => ({ query: queryOf(viewer), eye: poseOf(viewer)?.position ?? null, }); function cancel() { if (frame !== null) globalThis.cancelAnimationFrame(frame); frame = null; } function schedule() { if ( running && field && canvas && !hidden() && !still() && !gpuActive && frame === null ) frame = globalThis.requestAnimationFrame(draw); } function clearPixels() { context?.clearRect(0, 0, cssWidth, cssHeight); } function resize(viewer) { const ratio = Math.min(2, globalThis.devicePixelRatio || 1); const surface = canvasOf(viewer); cssWidth = surface?.clientWidth || container?.clientWidth || 1; cssHeight = surface?.clientHeight || container?.clientHeight || 1; const width = Math.max(1, Math.floor(cssWidth * ratio)); const height = Math.max(1, Math.floor(cssHeight * ratio)); // Assigning even unchanged dimensions erases a real canvas. if (canvas.width === width && canvas.height === height) return false; canvas.width = width; canvas.height = height; canvas.style.width = `${cssWidth}px`; canvas.style.height = `${cssHeight}px`; context.setTransform?.(ratio, 0, 0, ratio, 0, 0); return true; } function checkCamera(viewer) { const pose = poseOf(viewer); const position = pose?.position; const values = [ position?.x, position?.y, position?.z, pose?.heading, pose?.pitch, pose?.roll, cssWidth, cssHeight, ]; let changed = false; for (let i = 0; i < values.length; i++) { if (values[i] !== signature[i]) changed = true; signature[i] = values[i]; } return changed; } function updateBounds(viewer) { bounds = null; const camera = cameraOf(viewer); if (!camera?.viewRectangle) return; try { const rect = camera.viewRectangle(); if (!rect) return; const west = rect.west; let east = rect.east; const south = Math.max(-89, rect.south); const north = Math.min(89, rect.north); if (east < west) east += 360; if ( [west, east, south, north].every(Number.isFinite) && east > west && north > south ) bounds = { west, east, sinSouth: Math.sin(south * degree), sinNorth: Math.sin(north * degree), }; } catch { /* A sky-facing camera can have no earth rectangle. */ } } function project(view, lon, lat) { if (!Number.isFinite(lon) || !Number.isFinite(lat) || !view.query) return null; const point = fromDegreesInto(lon, lat, 0, world); if (view.eye && view.query.isOccluded?.(point)) return null; const projected = view.query.project(point); if ( !projected || !Number.isFinite(projected.x) || !Number.isFinite(projected.y) ) return null; // A perspective surface normal dims the limb instead of accumulating a bright rim. const camera = view.eye; const dx = camera?.x - point.x; const dy = camera?.y - point.y; const dz = camera?.z - point.z; const denominator = Math.hypot(point.x, point.y, point.z) * Math.hypot(dx, dy, dz); const cosine = denominator > 0 ? (point.x * dx + point.y * dy + point.z * dz) / denominator : 1; projected.visibility = Number.isFinite(cosine) ? Math.max(0, Math.min(1, cosine / 0.3)) : 1; return projected; } const inView = (point) => point && point.x >= 0 && point.y >= 0 && point.x <= cssWidth && point.y <= cssHeight; function spawn(particle, view) { for (let attempt = 0; attempt < 6; attempt++) { const west = bounds?.west ?? -180; const east = bounds?.east ?? 180; const low = bounds?.sinSouth ?? -0.9998; const high = bounds?.sinNorth ?? 0.9998; particle.lon = ((west + Math.random() * (east - west) + 540) % 360) - 180; particle.lat = Math.asin(low + Math.random() * (high - low)) / degree; particle.age = 1 + Math.random() * 7; particle.life = 8 + Math.random() * 4; if (inView(project(view, particle.lon, particle.lat))) return; } } function seed(viewer, view = viewOf(viewer)) { const count = budget(); if (particles.length > count) particles.length = count; while (particles.length < count) particles.push({ lon: 0, lat: 0, age: 0, life: 10 }); updateBounds(viewer); for (const particle of particles) spawn(particle, view); } function removeImagery() { imageryErrorRemove?.(); imageryErrorRemove = null; imagery?.remove(); imagery = null; shell?.destroy(); shell = null; imageryKind = null; } function updateImageryFade(height, settled = false) { // The tileset shell keeps the quantised move-end fade; globe imagery keeps // its smooth per-frame fade. if ( (!imagery && !shell) || !Number.isFinite(height) || (imageryKind === 'tileset' && !settled) ) return; const fade = !gpuActive ? 1 : height <= WIND_FIELD_FADE_LOW_METERS ? 0 : height >= WIND_FIELD_FADE_HIGH_METERS ? 1 : Math.log(height / WIND_FIELD_FADE_LOW_METERS) / WIND_FIELD_LOG_RANGE; const baseAlpha = overlay === 'temperature' ? 1 : 0.85; const smoothAlpha = baseAlpha * fade; const alpha = gpuActive && imageryKind === 'tileset' ? Math.round(smoothAlpha * 10) / 10 : smoothAlpha; if (shell) { shell.setAlpha(alpha); shell.setShow(alpha > 0 && getHost().kind !== 'none'); return; } if (Math.abs(imagery.alpha - alpha) > 0.005) imagery.alpha = alpha; const show = alpha > 0 && getHost().kind !== 'none'; if (imagery.show !== show) imagery.show = show; } function installImagery() { removeImagery(); imageryError = null; const viewer = viewerReady(); if (!snapshot || overlay === 'none' || !viewer) return; const { kind } = getHost(); if (kind === 'none') { imageryError = NO_IMAGERY_HOST; return; } const globe = kind === 'tileset' ? null : globeOf(viewer); const raster = createFieldRaster(snapshot, overlay); if (!raster) { imageryError = fieldUnavailableText(overlay); return; } const draw = kind === 'tileset' ? drawOf(viewer) : null; if (kind === 'tileset' ? !draw?.field : !globe) { imageryError = msg('Globe imagery unavailable'); return; } try { const texture = document.createElement('canvas'); texture.width = raster.width; texture.height = raster.height; const ctx = texture.getContext('2d'); const pixels = ctx.createImageData(raster.width, raster.height); pixels.data.set(raster.rgba); ctx.putImageData(pixels, 0, 0); if (kind === 'tileset') { shell = createWindShell( viewer, draw, texture, overlay === 'temperature' ? 1 : 0.85, { cameraOf, frameOf }, ); imageryKind = kind; updateImageryFade(heightOf(viewer), true); requestRender(viewer); return; } imagery = globe.imagery.add({ kind: 'single-image', url: texture.toDataURL('image/png'), rectangle: { west: -180, south: -90, east: 180, north: 90 }, zOrder: WEATHER_IMAGERY_Z.wind, }); imagery.drapeOn = 'surface'; imageryKind = kind; // Temperature colors carry quantitative meaning; double transparency // blends orange heat into blue ocean and obscures useful gradients. imagery.alpha = overlay === 'temperature' ? 1 : 0.85; if (gpuActive) updateImageryFade(heightOf(viewer), true); imageryErrorRemove = imagery.on('tileError', () => { imageryError = msg('Globe field image unavailable'); }); requestRender(viewer); } catch { removeImagery(); imageryError = msg('Globe field image unavailable'); } } function rehome() { if (!snapshot || overlay === 'none') return; const { kind } = getHost(); const wasHidden = imageryError === NO_IMAGERY_HOST; if ((imagery || shell) && kind !== 'none' && kind !== imageryKind) { installImagery(); onStatusChange?.(); return; } // A host without imagery hides the retained shell until a host returns. if (shell && kind === 'none') shell.setShow(false); // Globe imagery stays on the globe, which draws nothing while hidden; // it is hidden too until a host returns. const show = kind !== 'none' && imagery?.alpha > 0; if (imagery && imagery.show !== show) { imagery.show = show; requestRender(viewerReady()); } if ((gpuActive || kind === 'tileset') && kind !== 'none') updateImageryFade(heightOf(viewerReady()), true); if (kind === 'none') imageryError = NO_IMAGERY_HOST; else if (wasHidden) { imageryError = null; if (!imagery && !shell) installImagery(); } if (wasHidden !== (imageryError === NO_IMAGERY_HOST)) onStatusChange?.(); } /** No idle animation for pause/reduced motion; scene events repaint only changed views. */ function viewChanged() { if (gpuActive) { const viewer = viewerReady(); if (viewer) updateImageryFade(heightOf(viewer)); const narrow = (canvasOf(viewer)?.clientWidth || 800) < 700; let visibilityUpdated = false; if (running && field && !hidden() && narrow !== gpuNarrow) { gpuNarrow = narrow; gpuActive = gpu.setField(field); if (!gpuActive && viewer) { resize(viewer); seed(viewer); } motionChanged(); visibilityUpdated = true; } // The renderer culls and animates the streamlines; this fades them. if (gpuActive && viewer && !visibilityUpdated) gpu.updateVisibility(); const ready = gpuActive ? gpu.getDiagnostics().ready : null; if (ready !== reportedGpuReady) { reportedGpuReady = ready; onStatusChange?.(); } return; // The renderer projects persistent curves; only a responsive budget change rebuilds them. } if (!running || !field || hidden() || !canvas) return; const viewer = viewerReady(); if (!viewer) return; const resized = resize(viewer); if (resized || checkCamera(viewer)) { cameraChanged = true; if (still()) paint(viewer, 0, true); else schedule(); } } function motionChanged() { reducedMotion = media?.matches === true; cancel(); lastTime = null; cameraChanged = true; gpu.setOptions({ overlay, paused: still() }); if (!running || !field || hidden()) return; const viewer = viewerReady(); if (gpuActive) { if (viewer) updateImageryFade(heightOf(viewer)); if (viewer) gpu.updateVisibility(); return; } if (still() && viewer) paint(viewer, 0, true); else schedule(); } function listen(target, event, callback) { if (!target?.addEventListener) return; target.addEventListener(event, callback); removers.push(() => target.removeEventListener(event, callback)); } function cameraSettled() { if (gpuActive || imageryKind === 'tileset') updateImageryFade(heightOf(viewerReady()), true); cameraMoved(); } function cameraMoved() { viewChanged(); // A parked request-render scene may never run preRender until we wake it. if (gpuActive && running && field && !hidden()) requestRender(viewerReady()); } function listenPort(port, event, callback) { const off = port?.on?.(event, () => callback()); if (typeof off === 'function') removers.push(off); } function attachListeners() { if (removers.length) return; media = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)') ?? null; reducedMotion = media?.matches === true; listen(media, 'change', motionChanged); listen(globalThis.document, 'visibilitychange', motionChanged); listen(globalThis, 'resize', cameraMoved); listen(eventTarget, 'gev:map-stack-changed', rehome); const viewer = viewerReady(); if (!viewer) return; listenPort(frameOf(viewer), 'preRender', viewChanged); listenPort(cameraOf(viewer), 'moveEnd', cameraSettled); } function detachListeners() { for (const remove of removers) remove(); removers = []; media = null; } function paint(viewer, dt, staticFrame, fadeSeconds = dt) { const resized = resize(viewer); const changed = checkCamera(viewer) || cameraChanged || resized; const view = viewOf(viewer); if (changed) { clearPixels(); updateBounds(viewer); cameraChanged = false; } if (particles.length !== budget()) seed(viewer, view); if (staticFrame) clearPixels(); context.globalAlpha = 1; context.globalCompositeOperation = 'destination-out'; context.fillStyle = `rgba(0,0,0,${trailEraseAlpha(fadeSeconds)})`; context.fillRect(0, 0, cssWidth, cssHeight); context.globalCompositeOperation = 'source-over'; context.lineCap = 'round'; const cameraHeight = heightOf(viewer) ?? 1e6; const speedScale = Math.max(0.002, Math.min(4000, cameraHeight / 400)); const advection = { speedScale }; // Stroke length is a display sample of the local field, not frame travel. // At low FPS capped advection still moves the head by dt, but a readable // world-anchored tail survives without extra projections or screen stretching. const strokeSeconds = staticFrame ? 3 : 2; painted = 0; for (const particle of particles) { sampleWind(field, particle.lon, particle.lat, wind); if (!staticFrame) { advectParticle(particle, wind, dt, advection); particle.age += dt; } let point = project(view, particle.lon, particle.lat); if (changed && !inView(point)) { // Refill newly exposed regions while retaining world anchors still in view. spawn(particle, view); sampleWind(field, particle.lon, particle.lat, wind); point = project(view, particle.lon, particle.lat); } if (particle.age > particle.life || !inView(point)) { spawn(particle, view); continue; } before.lon = particle.lon; before.lat = particle.lat; advectParticle(before, wind, -strokeSeconds, advection); const previous = project(view, before.lon, before.lat); if (!inView(previous)) continue; const startX = previous.x; const startY = previous.y; const visibility = previous.visibility; const distance = Math.hypot(point.x - startX, point.y - startY); // Perspective/frustum jumps and antimeridian discontinuities never become strokes. if ( Math.abs(before.lon - particle.lon) > 180 || distance > Math.min(80, cssWidth * 0.08) ) continue; const alpha = Math.min(visibility, point.visibility) * Math.min(1, particle.age / 0.8, (particle.life - particle.age) / 1.2); if (alpha <= 0) continue; const speed = Math.hypot(wind.u, wind.v); context.globalAlpha = alpha * 0.55; context.lineWidth = 1.0; context.strokeStyle = overlay === 'none' ? windTrailColor(speed) : '#9ddce4'; context.beginPath(); context.moveTo(startX, startY); context.lineTo(point.x, point.y); context.stroke(); if (distance > 0.6) { context.globalAlpha = alpha * 0.9; context.strokeStyle = '#d6f4f5'; context.lineWidth = 1.35; context.beginPath(); context.moveTo( startX + (point.x - startX) * 0.72, startY + (point.y - startY) * 0.72, ); context.lineTo(point.x, point.y); context.stroke(); } if (staticFrame) { // Preserve direction at rest with a small arrowhead, without moving the field. if (distance > 2) { const ux = (point.x - startX) / distance; const uy = (point.y - startY) / distance; context.beginPath(); context.moveTo(point.x - ux * 3 - uy * 2, point.y - uy * 3 + ux * 2); context.lineTo(point.x, point.y); context.lineTo(point.x - ux * 3 + uy * 2, point.y - uy * 3 - ux * 2); context.stroke(); } } painted++; } context.globalAlpha = 1; } function draw(time) { frame = null; if (!running || !field || hidden() || still() || gpuActive) return; const viewer = viewerReady(); if (!viewer) return; try { const resized = resize(viewer); if (resized) cameraChanged = true; const elapsed = lastTime === null ? 1 / 60 : Math.max(0, (time - lastTime) / 1000); // Limit full particle paints to 30 Hz while preserving elapsed-time motion/fading. if (lastTime === null || elapsed >= 0.032 || cameraChanged) { paint(viewer, Math.min(0.1, elapsed), false, elapsed); lastTime = time; } } catch (error) { if (!warned) { console.warn('[Data:Wind] frame failed:', error?.message || error); warned = true; } } schedule(); } return { rehome, attach() { if (canvas) return; canvas = document.createElement('canvas'); canvas.dataset.gevWind = '1'; Object.assign(canvas.style, { position: 'absolute', inset: '0', pointerEvents: 'none', zIndex: '1', }); canvas.setAttribute?.('aria-hidden', 'true'); context = canvas.getContext('2d'); container.appendChild(canvas); }, setField(next) { const nextField = next?.grid ? { ...next.grid, u: next.u, v: next.v } : next; const viewer = viewerReady(); const nextNarrow = (canvasOf(viewer)?.clientWidth || 800) < 700; const reuseGeometry = gpuActive && gpuNarrow === nextNarrow && gpu.supported() && sameWind(snapshot, next, field, nextField); snapshot = next; field = nextField; cameraChanged = true; lastTime = null; cancel(); if (canvas && field) { gpuNarrow = nextNarrow; if (!reuseGeometry) { gpuActive = gpu.supported() && gpu.setField(field); reportedGpuReady = gpuActive ? gpu.getDiagnostics().ready : null; } clearPixels(); particles = []; if (viewer && !gpuActive) { resize(viewer); seed(viewer); } installImagery(); relief.attach(); motionChanged(); } }, setOptions(options = {}) { const nextOverlay = ['none', 'speed', 'temperature', 'pressure'].includes( options.overlay, ) ? options.overlay : overlay; const newPaused = typeof options.paused === 'boolean' ? options.paused : paused; const changedOverlay = nextOverlay !== overlay; const changedPause = newPaused !== paused; overlay = nextOverlay; paused = newPaused; if (changedOverlay) { installImagery(); clearPixels(); } if (changedOverlay || changedPause) motionChanged(); }, start() { if (running || !canvas) return; running = true; attachListeners(); rehome(); motionChanged(); }, stop() { running = false; cancel(); lastTime = null; detachListeners(); gpu.setOptions({ overlay, paused: true }); }, clear() { cancel(); snapshot = null; field = null; particles = []; painted = 0; gpu.clear(); relief.clear(); gpuActive = false; reportedGpuReady = null; removeImagery(); imageryError = null; clearPixels(); }, destroy() { this.stop(); this.clear(); gpu.destroy(); relief.destroy(); canvas?.remove(); canvas = null; context = null; }, getParticleCount() { return gpuActive ? gpu.getParticleCount() : particles.length; }, getDiagnostics() { return { overlay, paused, reducedMotion, hidden: hidden(), particleCount: gpuActive ? gpu.getParticleCount() : particles.length, renderMode: gpuActive ? 'gpu-streamlines' : 'canvas-fallback', gpu: gpu.getDiagnostics(), relief: relief.getDiagnostics(), painted, framePending: frame !== null, imageryActive: imagery !== null || shell !== null, host: shell ? 'shell' : imagery ? 'globe' : null, shell: shell?.getDiagnostics() ?? null, imageryError, }; }, }; }