diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index a4a117c3b..a3318089b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5798,7 +5798,7 @@ silently demoting every later lookup for the session. - On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification. - A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated. - Contacts rows and the Cockpit Contact counts name each cohort's provider: the source of the last snapshot, marked `FALLBACK` or `STALE` as its layer row would be. A poll in flight keeps the mark, where the layer row shows `LOADING`. A flight snapshot from the adsb.lol regional fallback reads `adsb.lol · FALLBACK`, not `OpenSky`. -- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is a polyline because WebGL draws ellipse outlines at 1 px whatever width is asked for, drawn as an unpickable primitive rather than an entity so a click or tap on its edge reaches the contact underneath (headless viewers without a primitive collection get a static entity instead); it is rebuilt when the subject moves. Three dim sonar pulses (3 px with a 1 px dark outline, same colours, at most 60% opacity) grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius. One unpickable 250 km disc draws both the pulse lines and the gradient, its shader reading the pulse radii and opacities each frame, so a click or tap near a pulse still reaches the contact underneath; the disc follows the subject by a model-matrix rotation and is rebuilt only after the subject moves 20 km, and not at all while the pulses rest. While the camera is below the disc's 2.5 km height, where it would sweep across the sky, the pulses rest: the disc is hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the disc and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one render request 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`), so they repaint at about 12.5 fps and never beat the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or in a scene without primitives or preRender and postRender hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. +- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is one outlined line in an unpickable draw-port line set (`src/layers/awareness/rangeRing.js`), so a click or tap on its edge reaches the contact underneath; the halo is the line's own outline, so the translucent core and halo never darken where they meet; it moves when the subject moves. Three dim sonar pulses (3 px with a dark edge half a pixel wide on each side, same colours, at most 60% opacity), each an outlined line in the same set, grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius: one unpickable flat ellipse 2.5 km up with 270 km semi-axes, filled with a 256-pixel canvas painted with the band (two canvases in turn, each under a new key). The ellipse stands until the subject has moved 20 km from where it was built, the canvas keeping the band concentric with the subject meanwhile, and not at all while the pulses rest. The fronts move on every frame the camera moves in (and every frame while something holds continuous rendering); the soft band is repainted at most every 80 ms. While the camera is below the band's 2.5 km height, where it would sweep across the sky, the pulses rest: the band and fronts are hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the band and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one step 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`) whose changes ask for the frame that draws them, so a parked view repaints at about 12.5 fps, one frame a step, and never beats the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or on a renderer without frame hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. - For a selected live aircraft or vessel, the context window refreshes from the existing tracker/feed position every 750 ms, so nearest distances and cohort counts follow the subject without introducing a duplicate poll loop. - Aircraft cohort membership uses every locally loaded, selectable contact inside the 250 km window, including a plane hidden only by horizon culling or because its 3D model owns the visual. Counts and navigation therefore do not change with the current camera angle or billboard/model handoff. - Nearby examples in the context panel are focus controls: they use their owning layer's existing selection/tracking path, then frame that contact. Static-installation distances use ellipsoidal surface distance so the count matches the ground-projected context disk. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index f84b3fc96..f4f8b9059 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -154,14 +154,8 @@ back to Cesium. Both lists only ever shrink. - `src/render/cesiumAllowList.json` lists the files outside the Cesium adapter (`src/render/cesium/`) that may still import or be handed Cesium (`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list - when it no longer drives Cesium at all; nothing is added. The list holds - one file, `src/layers/awareness/rangeRingCesium.js`: the Global Context - range ring and its sonar pulses, a disc whose fill is computed per pixel - from values set each frame and an outlined line whose opacity changes - without a rebuild, neither of which the draw port can draw yet. It draws - only on a viewer with a Cesium primitive collection; on any other - renderer the layer draws the ring without pulses through the draw port. - It leaves the list when the draw port can draw both. Two files name + when it no longer drives Cesium at all; nothing is added. The list is + empty: no file outside the adapter reaches Cesium. Two files name the adapter by design and are not on it: the application scene (`src/app/scene.js`), the composition root that picks the Cesium renderer, may import `src/render/cesium/application.js` and nothing else of the diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 338c7ac5a..901bae6b3 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2530,7 +2530,7 @@ "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", "src/data/entityRecords.js", - "src/layers/awareness/rangeRingCesium.js", + "src/layers/awareness/rangeRing.js", "src/data/feedState.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", @@ -4494,7 +4494,7 @@ "src/app/layers/osmPlaces.js", "src/voice/areaActions.js", "src/render/cesium/zoomOutGuard.js", - "src/layers/awareness/rangeRingCesium.js", + "src/layers/awareness/rangeRing.js", "src/data/firmsIntensity.js", "src/data/firmsHeatRaster.js", "src/layers/firms/heatImagery.js", @@ -5255,7 +5255,7 @@ "src/layers/osmPlaces/model.js", "src/layers/osmPlaces/index.js", "src/app/layers/osmPlaces.js", - "src/layers/awareness/rangeRingCesium.js", + "src/layers/awareness/rangeRing.js", "src/data/feedState.js", "src/loadingFeedback.js", "src/data/firmsIntensity.js", diff --git a/src/data/militaryAwareness.test.mjs b/src/data/militaryAwareness.test.mjs index 7e42a7c5b..18baed26f 100644 --- a/src/data/militaryAwareness.test.mjs +++ b/src/data/militaryAwareness.test.mjs @@ -110,7 +110,9 @@ function installAwarenessRuntime({ const originalDocument = globalThis.document; const listeners = new Map(); let nextTimer = 1; - let preRenderListener = null; + // Every preRender listener, as a scene keeps them: the lifecycle's and + // the range ring's pulses both listen. + const preRenderListeners = new Set(); class FakeElement { constructor() { @@ -173,9 +175,9 @@ function installAwarenessRuntime({ }, preRender: { addEventListener(listener) { - preRenderListener = listener; + preRenderListeners.add(listener); return () => { - preRenderListener = null; + preRenderListeners.delete(listener); }; }, }, @@ -239,7 +241,7 @@ function installAwarenessRuntime({ return { dispatch: fakeWindow.dispatch.bind(fakeWindow), tick() { - preRenderListener?.(); + for (const listener of [...preRenderListeners]) listener(); }, viewer, renderRequests, diff --git a/src/layers/awareness/policy.js b/src/layers/awareness/policy.js index 2e973a473..575fb87aa 100644 --- a/src/layers/awareness/policy.js +++ b/src/layers/awareness/policy.js @@ -74,30 +74,31 @@ export const AWARENESS_RANGE_RING_STYLE = Object.freeze({ * over `fadeInFraction` of its travel, then fades as (1 - travel) to the * `fadeOutPower` down to `endOpacityFraction` of `peakOpacity`, so a pulse * is dim but still visible when it reaches the ring and the ring flashes. - * Each line is `width` CSS pixels wide, its outer `outlineWidth` a dark - * halo, in the ring's colours, as Cesium's polyline outline material draws. + * Each front is a line `width` CSS pixels wide whose outer `outlineWidth`, + * half on each side, is a dark halo, in the ring's colours. * Behind each line a radial gradient in the same blue fades inward over - * `gradientDepthFraction` of the radius, at most - * `gradientOpacity` strong. One unpickable disc draws the lines and the - * gradient, so pulses never catch a click meant for a contact; its shader - * takes at most four pulses. The disc follows the subject by a model-matrix - * rotation, so it stays concentric with the ring, and is rebuilt only after - * the subject moves `gradientRebuildM` from where it was built; while the - * pulses rest the hidden disc is left alone and catches up when they wake. The - * disc is hidden while the camera is below its height, where it would sweep - * the sky. + * `gradientDepthFraction` of the radius, at most `gradientOpacity` strong, + * painted on a canvas that fills one flat ellipse at the rim. Lines and + * ellipse are unpickable, so pulses never catch a click meant for a + * contact. The ellipse is `gradientRebuildM` wider than the ring and moves + * only after the subject moves that far from where it was built, the + * canvas keeping the band concentric meanwhile; while the pulses rest the + * hidden band is left alone and catches up when they wake. The band is + * hidden while the camera is below its height, where it would sweep the + * sky. * The pulses run for `activeMs` (three ring flashes) after a selection or * a camera move, fading in and out over `settleMs`, then rest: the ring * stays on screen, static, and nothing asks for frames, so a parked view * goes quiet again. Only a camera move within `inputWakeMs` of the user * handling the map (pointer, wheel or touch on the canvas, which covers a * drag's inertia, while the camera controls take input) wakes them; a moving subject and the app's own camera moves - * (tracking, cockpit, orbit, a fly-to) do not. Below the disc's height they + * (tracking, cockpit, orbit, a fly-to) do not. Below the band's height they * rest too. While they run they never hold - * continuous rendering; each drawn frame arms one more request after the - * Cyber sonar's 80 ms cadence, so the two never beat. When something else - * already renders continuously they update every frame. Skipped under - * prefers-reduced-motion. */ + * continuous rendering; each drawn frame arms one more step after the + * Cyber sonar's 80 ms cadence, so the two never beat. The fronts move on + * every frame the camera moves in, or while something else holds + * continuous rendering; the band is repainted at most every 80 ms. + * Skipped under prefers-reduced-motion. */ export const AWARENESS_RANGE_PULSE = Object.freeze({ count: 3, periodMs: 9000, diff --git a/src/layers/awareness/rangeRing.js b/src/layers/awareness/rangeRing.js new file mode 100644 index 000000000..cdb88e65d --- /dev/null +++ b/src/layers/awareness/rangeRing.js @@ -0,0 +1,677 @@ +/** + * @module layers/awareness/rangeRing + * @description The Global Context range ring and its sonar pulses, drawn + * through the renderer's draw port. The ring is a haloed line (a solid line + * with an outline) 2.5 km above the ellipsoid. While pulses run, each pulse + * front is a haloed line whose positions move each step: every + * `CYBER_SONAR_RENDER_INTERVAL_MS` on a parked view, every frame the camera + * moves in. The band behind the fronts is one flat ellipse at the same + * height filled with a canvas painted anew at most every interval (a new + * key for new content). Nothing here is + * pickable, so a click or tap near the ring reaches the contact underneath. + * Under reduced motion, or where the renderer has no frame hooks, the ring + * alone is drawn and stays. + */ +import { CYBER_SONAR_RENDER_INTERVAL_MS } from '../../cyberSonar.js'; +import { AWARENESS_RADIUS_M } from '../../data/militaryAwarenessEngine.js'; +import { + AWARENESS_RANGE_ECHO, + AWARENESS_RANGE_PULSE, + AWARENESS_RANGE_RING_STYLE, + CONTEXT_RIM_HEIGHT_M, +} from './policy.js'; +import { + awarenessEchoStrength, + clearAwarenessEchoField, + setAwarenessEchoField, +} from '../../awarenessEcho.js'; +import { WGS84, fromRadians, toLonLatH } from '../../geo/ellipsoid.js'; +import { distance, sub } from '../../geo/vector.js'; +import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js'; + +/** + * A closed ring of positions `radiusM` along the surface from `groundCenter`, + * raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's + * radius of curvature in that direction (Euler's formula), which keeps the + * ring within ~50 m of the true geodesic radius at 250 km. + * @param {{x: number, y: number, z: number}} groundCenter Ring centre on the ellipsoid. + * @param {number} radiusM Surface radius in metres. + * @param {number} heightM Height of the ring above the ellipsoid. + * @param {number} [segments] Chords around the ring. + * @returns {{x: number, y: number, z: number}[]} `segments + 1` positions; + * the last repeats the first. + */ +export function awarenessRangeRingPositions( + groundCenter, + radiusM, + heightM, + segments = AWARENESS_RANGE_RING_STYLE.segments, +) { + const { lon, lat } = toLonLatH(groundCenter); + const latitude = (lat * Math.PI) / 180; + const longitude = (lon * Math.PI) / 180; + const { x: a, z: b } = WGS84.radii; + const e2 = 1 - (b * b) / (a * a); + const sinLat = Math.sin(latitude); + const cosLat = Math.cos(latitude); + const sinLon = Math.sin(longitude); + const cosLon = Math.cos(longitude); + const w = 1 - e2 * sinLat * sinLat; + const meridional = (a * (1 - e2)) / (w * Math.sqrt(w)); + const primeVertical = a / Math.sqrt(w); + // Step along the great circle in 3D from the centre's up, north and east + // unit vectors. Unlike the latitude/longitude destination formula, this + // stays well conditioned at and next to the poles. + const up = [cosLat * cosLon, cosLat * sinLon, sinLat]; + const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat]; + const east = [-sinLon, cosLon, 0]; + const positions = []; + for (let i = 0; i <= segments; i++) { + const bearing = ((i % segments) / segments) * 2 * Math.PI; + const cosB = Math.cos(bearing); + const sinB = Math.sin(bearing); + const angular = + radiusM * ((cosB * cosB) / meridional + (sinB * sinB) / primeVertical); + const cosA = Math.cos(angular); + const sinA = Math.sin(angular); + const [x, y, z] = up.map( + (u, k) => u * cosA + (north[k] * cosB + east[k] * sinB) * sinA, + ); + positions.push( + fromRadians(Math.atan2(y, x), Math.atan2(z, Math.hypot(x, y)), heightM), + ); + } + return positions; +} + +/** + * Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at + * constant speed from `startFraction` of the range to the full range, fade in + * over `fadeInFraction` of the way, then fade as (1 - travel) to the + * `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim + * but still visible when it reaches the range ring. The opacity already + * includes `peakOpacity`. + * @param {number} nowMs Monotonic clock in milliseconds. + * @param {number} index Pulse number, 0 to `count - 1`. + * @param {number} [radiusM] Range the pulses grow to. + * @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`. + * @returns {{radiusM: number, alpha: number}} + */ +export function awarenessPulseState( + nowMs, + index, + radiusM = AWARENESS_RADIUS_M, + pulse = AWARENESS_RANGE_PULSE, +) { + const cycle = nowMs / pulse.periodMs + index / pulse.count; + const phase = cycle - Math.floor(cycle); + return { + radiusM: + radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase), + alpha: + pulse.peakOpacity * + Math.min(1, phase / pulse.fadeInFraction) * + (pulse.endOpacityFraction + + (1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower), + }; +} + +const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)'; + +/** Whether the viewer asked the system for less motion. */ +function prefersReducedMotion() { + return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false; +} + +/** + * How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over + * `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to + * `wake.untilMs`. + * @param {number} nowMs Monotonic clock in milliseconds. + * @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`. + * @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`. + * @returns {number} 0 to 1. + */ +export function awarenessPulseLevel( + nowMs, + wake, + pulse = AWARENESS_RANGE_PULSE, +) { + const level = Math.min( + (nowMs - wake.startMs) / pulse.settleMs, + (wake.untilMs - nowMs) / pulse.settleMs, + ); + return Math.max(0, Math.min(1, level)); +} + +/** + * Run the pulses for `activeMs` from `nowMs`. A wake while they already run + * keeps their current level, so they never jump back to full mid-fade. + * @param {{startMs: number, untilMs: number}} wake Updated in place. + * @param {number} nowMs Monotonic clock in milliseconds. + * @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`. + * @returns {{startMs: number, untilMs: number}} `wake`. + */ +export function wakeAwarenessPulses( + wake, + nowMs, + pulse = AWARENESS_RANGE_PULSE, +) { + wake.startMs = + nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs; + wake.untilMs = nowMs + pulse.activeMs; + return wake; +} + +/** + * How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a + * pulse front reaches it, fading over `flashMs`, so the ring appears once + * per arriving pulse instead of standing on screen. + * @param {number} nowMs Monotonic clock in milliseconds. + * @returns {number} 0 to 1. + */ +export function awarenessRingFlash(nowMs) { + return awarenessEchoStrength( + nowMs, + AWARENESS_RADIUS_M, + AWARENESS_RADIUS_M, + AWARENESS_RANGE_PULSE, + { fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs }, + ); +} + +/** `rgba(r, g, b, a)` as a draw-port colour, channels 0 to 1. */ +function rgba(css) { + const [r, g, b, a = 1] = css.match(/[\d.]+/g).map(Number); + return [r / 255, g / 255, b / 255, a]; +} + +/** A colour with its alpha scaled by `alpha`. */ +const faded = ([r, g, b, a], alpha) => [r, g, b, a * alpha]; + +/** + * A haloed line as the draw port draws it: `widthPx` wide, its outer + * `haloPx` on each side in the halo's colour, the rest in the core's. + * @returns {object} The line item. + */ +const haloedLine = (id, positions, { core, halo, widthPx, haloPx, show }) => ({ + id, + positions, + widthPx, + mode: '3d', + style: { + kind: 'solid', + color: core, + outline: { color: halo, widthPx: haloPx }, + }, + show, +}); + +/** Side of the band's canvas, pixels: the band is soft, 2 km a pixel. */ +export const AWARENESS_BAND_PIXELS = 256; + +/** + * The band behind the pulse fronts into `image` (an `ImageData` of + * `size × size`): at each pixel, a fraction `r` of `rangeM` from the + * subject, the sum over pulses of `alpha × t²` where the pulse's front is + * within `gradientDepthFraction` of the range outside it (`t` is 1 at the + * front, 0 that far inward), times `gradientOpacity`, in `rgb`. The canvas + * spans `spanM` either side of its centre; the subject is `offset` metres + * east and north of that centre. + * @param {{data: Uint8ClampedArray, width: number}} image + * @param {{radii: number[], alphas: number[], rgb: number[], spanM: number, + * rangeM: number, offset: {east: number, north: number}, pulse?: object}} band + */ +export function paintAwarenessBand(image, band) { + const { radii, alphas, rgb, spanM, rangeM, offset } = band; + const pulse = band.pulse ?? AWARENESS_RANGE_PULSE; + const size = image.width; + const data = image.data; + const depth = pulse.gradientDepthFraction; + const [r, g, b] = rgb.map((c) => Math.round(c * 255)); + const perPixel = (2 * spanM) / size / rangeM; + const cx = size / 2 + offset.east / ((2 * spanM) / size); + // Canvas rows run north to south. + const cy = size / 2 - offset.north / ((2 * spanM) / size); + const count = radii.length; + const opacity = pulse.gradientOpacity; + for (let y = 0; y < size; y++) { + const dy = (y + 0.5 - cy) * perPixel; + const dy2 = dy * dy; + for (let x = 0; x < size; x++) { + const dx = (x + 0.5 - cx) * perPixel; + // Not `Math.hypot`, many times slower: this runs on every frame the + // camera moves while the pulses run. + const at = Math.sqrt(dx * dx + dy2); + let sum = 0; + for (let i = 0; i < count; i++) { + const inside = radii[i] - at; + if (inside >= 0 && inside <= depth) { + const t = 1 - inside / depth; + sum += alphas[i] * t * t; + } + } + const k = (y * size + x) * 4; + data[k] = r; + data[k + 1] = g; + data[k + 2] = b; + // `Math.round` of a non-negative value. + data[k + 3] = (Math.min(1, sum * opacity) * 255 + 0.5) | 0; + } + } +} + +/** `p` in metres east and north of `origin`, in `origin`'s surface frame. */ +function eastNorth(origin, p) { + const { lon, lat } = toLonLatH(origin); + const l = (lon * Math.PI) / 180; + const f = (lat * Math.PI) / 180; + const d = sub(p, origin); + return { + east: -Math.sin(l) * d.x + Math.cos(l) * d.y, + north: + -Math.sin(f) * Math.cos(l) * d.x - + Math.sin(f) * Math.sin(l) * d.y + + Math.cos(f) * d.z, + }; +} + +/** Camera height above the ellipsoid, or NaN when the renderer cannot say. */ +function cameraHeightM(viewer) { + return findCamera(viewer)?.pose()?.height ?? Number.NaN; +} + +/** Each instance's set ids are its own. */ +let instances = 0; + +/** + * The range ring and pulses of one awareness layer. + * `layerState.visual` is what is drawn now, or null. + * @param {object} options + * @param {object} options.state + * @param {(reason: string) => void} options.governorRequestRender + * @param {(subject: object) => void} options.redraw Draws the subject's + * ring again (a reduced-motion change). + */ +export function createRangeRing({ + state: layerState, + governorRequestRender, + redraw, +}) { + const instance = ++instances; + /** The lines (ring and fronts) and the band's sets, on the viewer they draw on. */ + let sets = null; + + function setsOn(viewer) { + if (sets?.viewer === viewer) return sets; + disposeSets(); + const draw = drawOf(viewer); + sets = { + viewer, + lines: draw.lines({ + id: `awareness:${instance}:rim`, + pickable: false, + }), + band: draw.shapes({ + id: `awareness:${instance}:band`, + pickable: false, + }), + }; + return sets; + } + + function disposeSets() { + sets?.lines.dispose(); + sets?.band.dispose(); + sets = null; + } + + /** + * Run the range pulses again for `activeMs`, after a camera move. Call it + * during a frame (lifecycle's preRender): that frame's postRender arms the + * next request, so waking asks for no extra frame of its own. + */ + function wakePulses() { + const visual = layerState.visual; + if (!visual?.wake) return; + wakeAwarenessPulses(visual.wake, performance.now()); + visual.step(performance.now()); + } + + function clearVisual() { + const visual = layerState.visual; + if (!visual) return; + visual.stopPulses?.(); + visual.removeMotionListener?.(); + if (sets) { + sets.lines.clear(); + sets.band.clear(); + } + // Idle mode renders only on request; a removed ring must not linger. + governorRequestRender('awareness-visual'); + clearAwarenessEchoField(); + layerState.visual = null; + } + + /** Let go of the sets too, as the layer goes. */ + function disposeVisual() { + clearVisual(); + disposeSets(); + } + + function renderVisual(subject) { + const viewer = layerState.viewer; + if (!viewer || !subject?.position) return; + const location = toLonLatH(subject.position); + if (!location) return; + const groundCenter = fromRadians( + (location.lon * Math.PI) / 180, + (location.lat * Math.PI) / 180, + 0, + ); + const key = `${subject.layerId}:${subject.id}`; + const reducedMotion = prefersReducedMotion(); + const visual = layerState.visual; + // A reduced-motion change rebuilds the visual, with or without pulses; + // so does a ring drawn on another viewer (the layer re-initialized). + if ( + visual?.key === key && + visual.viewer === viewer && + visual.reducedMotion === reducedMotion + ) { + // Move the ring only after a meaningful displacement so live tracking + // does not redraw it for sub-pixel motion every 750 ms. + if (distance(visual.center, groundCenter) >= 250) { + // The echo field reads `visual.center` in place and follows on its + // own. + Object.assign(visual.center, groundCenter); + visual.ringPositions = awarenessRangeRingPositions( + groundCenter, + AWARENESS_RADIUS_M, + CONTEXT_RIM_HEIGHT_M, + ); + visual.step(performance.now()); + // Content actually changed — buy exactly one frame instead of holding. + governorRequestRender('awareness-visual'); + } + return; + } + clearVisual(); + const { lines, band } = setsOn(viewer); + const frame = findFrame(viewer); + // A renderer without frame hooks gets the static ring only, as the + // Cyber sonar scene does. So does a viewer who prefers reduced motion. + const animate = Boolean(!reducedMotion && frame?.on); + // Pulses run from now until `wake.untilMs`, then rest. + const wake = animate + ? wakeAwarenessPulses( + { startMs: -Infinity, untilMs: -Infinity }, + performance.now(), + ) + : null; + // From a camera below the rim height the band would sweep across the + // sky, so the pulses are hidden there and rest with it: no flash, no + // echoes, no frames. + const belowRim = () => cameraHeightM(viewer) < CONTEXT_RIM_HEIGHT_M; + const levelAt = (nowMs) => + wake && !belowRim() ? awarenessPulseLevel(nowMs, wake) : 0; + + const ring = AWARENESS_RANGE_RING_STYLE; + const pulse = AWARENESS_RANGE_PULSE; + const core = rgba(ring.color); + const halo = rgba(ring.outlineColor); + // While pulses run, the ring flashes as each one arrives and otherwise + // dims to `restOpacity`; as they settle it returns to full and stays. + const ringAlpha = (nowMs) => { + const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs)); + return 1 - levelAt(nowMs) * (1 - pulsed); + }; + const center = { ...groundCenter }; + const next = { + key, + viewer, + center, + ringPositions: awarenessRangeRingPositions( + groundCenter, + AWARENESS_RADIUS_M, + CONTEXT_RIM_HEIGHT_M, + ), + reducedMotion, + wake, + stopPulses: null, + removeMotionListener: null, + step: () => {}, + /** When the pulses were last drawn as they were then. */ + lastStepMs: Number.NEGATIVE_INFINITY, + }; + + /** The ring at `alpha` of its colours. */ + const ringItems = (alpha) => [ + haloedLine('ring', next.ringPositions, { + core: faded(core, alpha), + halo: faded(halo, alpha), + widthPx: ring.width, + haloPx: ring.outlineWidth, + show: true, + }), + ]; + + if (!animate) { + lines.set(ringItems(1)); + next.step = () => lines.upsert(ringItems(1)); + } else { + const count = pulse.count; + // The band's ellipse is built around `bandCenter` and stands until + // the subject has moved `gradientRebuildM` from it; meanwhile the + // canvas draws the band about the subject, inside a margin as wide. + const spanM = AWARENESS_RADIUS_M + pulse.gradientRebuildM; + let bandCenter = null; + let bandShown = null; + // Two canvases in turn: a new key draws new content, and a renderer + // that holds a canvas until its next frame never sees it rewritten. + const doc = globalThis.document; + const canvases = [0, 1].map(() => { + const canvas = doc?.createElement?.('canvas'); + if (!canvas?.getContext) return null; + canvas.width = canvas.height = AWARENESS_BAND_PIXELS; + const context = canvas.getContext('2d'); + if (!context) return null; + return { + canvas, + context, + image: context.createImageData( + AWARENESS_BAND_PIXELS, + AWARENESS_BAND_PIXELS, + ), + }; + }); + const paints = canvases.every(Boolean); + let painted = 0; + let paintedMs = Number.NEGATIVE_INFINITY; + + // The image last drawn: a resting band keeps it, hidden, so showing + // it again changes it in place. + let image = null; + const bandItem = (show) => { + const { lon, lat } = toLonLatH(bandCenter); + return { + id: 'band', + geometry: { + kind: 'ellipse', + center: { lon, lat, height: CONTEXT_RIM_HEIGHT_M }, + semiMajor: spanM, + semiMinor: spanM, + }, + height: 'absolute', + fill: { image }, + show, + }; + }; + + /** + * Draw the pulses as they are at `nowMs`, and the ring where it now + * is: the fronts, the band and the ring's flash. + */ + next.step = (nowMs) => { + const level = levelAt(nowMs); + const items = ringItems(ringAlpha(nowMs)); + const radii = []; + const alphas = []; + for (let index = 0; index < count; index++) { + const state = awarenessPulseState(nowMs, index); + radii.push(state.radiusM / AWARENESS_RADIUS_M); + alphas.push(state.alpha * level); + const front = + level > 0 + ? awarenessRangeRingPositions( + center, + state.radiusM, + CONTEXT_RIM_HEIGHT_M, + ) + : next.ringPositions; + items.push( + haloedLine(`pulse:${index}`, front, { + core: faded(core, state.alpha * level), + halo: faded(halo, state.alpha * level), + widthPx: pulse.width, + // The fronts' `outlineWidth` is both sides together. + haloPx: pulse.outlineWidth / 2, + show: level > 0, + }), + ); + } + lines.upsert(items); + if (!paints) return; + const show = level > 0; + // A resting band stays where it was built, and catches up on wake. + const rebuilt = + show && + (!bandCenter || + distance(bandCenter, center) >= pulse.gradientRebuildM); + if (rebuilt) bandCenter = { ...center }; + if (!bandCenter) return; + if (!show) { + if (bandShown) band.upsert([bandItem(false)]); + bandShown = false; + return; + } + // The soft band is painted at most once a Cyber sonar interval; + // the fronts, crisp lines, move on every step. + if ( + bandShown && + !rebuilt && + nowMs - paintedMs < CYBER_SONAR_RENDER_INTERVAL_MS + ) + return; + paintedMs = nowMs; + const target = canvases[painted % 2]; + paintAwarenessBand(target.image, { + radii, + alphas, + rgb: core, + spanM, + rangeM: AWARENESS_RADIUS_M, + offset: eastNorth(bandCenter, center), + }); + target.context.putImageData(target.image, 0, 0); + painted += 1; + image = { + canvas: target.canvas, + key: `awareness-band:${instance}:${painted}`, + }; + band.upsert([bandItem(true)]); + bandShown = true; + }; + + lines.set(ringItems(1)); + /** Draw the pulses at `nowMs` while they run or settle. */ + const stepRunning = (nowMs) => { + if (levelAt(nowMs) > 0 || bandShown || ringAlpha(nowMs) < 1) { + next.lastStepMs = nowMs; + next.step(nowMs); + } + }; + // The eye as the pulses were last drawn under it, to tell frames the + // camera moved in from frames the pulses themselves asked for. + const camera = findCamera(viewer); + let lastEye = ''; + const eyeMoved = () => { + const pose = camera?.pose(); + if (!pose) return false; + const { position: p, direction: d } = pose; + const eye = `${p.x},${p.y},${p.z},${d.x},${d.y},${d.z}`; + if (eye === lastEye) return false; + lastEye = eye; + return true; + }; + next.lastStepMs = performance.now(); + next.step(next.lastStepMs); + // Each frame drawn while the camera moves, or held drawing, or at + // least a Cyber sonar interval after the last step, steps them. A + // step asks for the frame that draws it, which is no reason to step + // again: a parked view, held by nothing, draws one frame each + // interval, as the timer below asks. + const offPreRender = frame.on('preRender', () => { + const nowMs = performance.now(); + const moved = eyeMoved(); + if ( + moved || + frame.diagnostics?.()?.holds?.length > 0 || + nowMs - next.lastStepMs >= CYBER_SONAR_RENDER_INTERVAL_MS + ) + stepRunning(nowMs); + }); + // Each drawn frame, whoever asked for it, arms one step a Cyber + // sonar interval later, as the Cyber sonar scene does, whose changes + // ask for the frame that draws them. Requests never land within + // 80 ms of a frame, so they cannot beat the detection lane's 80 ms + // gate, and they stop once the pulses rest. + let timer = null; + const offPostRender = frame.on('postRender', () => { + globalThis.clearTimeout(timer); + timer = null; + const nowMs = performance.now(); + if ((nowMs < wake.untilMs || bandShown) && !belowRim()) + timer = globalThis.setTimeout(() => { + timer = null; + stepRunning(performance.now()); + governorRequestRender('awareness-pulse'); + }, CYBER_SONAR_RENDER_INTERVAL_MS); + }); + next.stopPulses = () => { + offPreRender(); + offPostRender(); + globalThis.clearTimeout(timer); + timer = null; + }; + // The detection overlay pulses the brackets of flights and vessels a + // front crosses; it reads the centre in place, so it follows too. + setAwarenessEchoField({ + center, + radiusM: AWARENESS_RADIUS_M, + pulse, + echo: AWARENESS_RANGE_ECHO, + level: levelAt, + }); + } + + // Turning reduced motion on or off mid-session rebuilds the visual. + const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY); + const onMotionChange = () => { + if (layerState.subject) redraw(layerState.subject); + }; + // Safari before 14 has only the older addListener / removeListener. + if (motionQuery?.addEventListener) + motionQuery.addEventListener('change', onMotionChange); + else motionQuery?.addListener?.(onMotionChange); + next.removeMotionListener = () => { + if (motionQuery?.removeEventListener) + motionQuery.removeEventListener('change', onMotionChange); + else motionQuery?.removeListener?.(onMotionChange); + }; + + layerState.visual = next; + governorRequestRender('awareness-visual'); + } + return { renderVisual, clearVisual, disposeVisual, wakePulses }; +} diff --git a/src/layers/awareness/rangeRing.test.mjs b/src/layers/awareness/rangeRing.test.mjs index 06f116f54..a4dbe7e74 100644 --- a/src/layers/awareness/rangeRing.test.mjs +++ b/src/layers/awareness/rangeRing.test.mjs @@ -1,12 +1,12 @@ // src/layers/awareness/rangeRing.test.mjs — the 250 km Global Context range -// ring is a haloed polyline that stays legible on light and dark ground, -// sits where the old ellipse outline did, and follows the subject. -// Dim sonar pulses grow slowly from the subject to the ring, each with an -// inward-fading gradient behind it, drawn on one unpickable disc; the ring -// dims and flashes as each one arrives and the overlay's echo field follows -// the subject. The pulses run for a bounded time after a selection or camera -// move, then rest with the ring steady. Under reduced motion the ring simply -// stays on screen. +// ring is a haloed line that stays legible on light and dark ground, sits +// where the old ellipse outline did, and follows the subject. Dim sonar +// pulses grow slowly from the subject to the ring, each a haloed line with +// an inward-fading band behind it drawn on one flat canvas-filled ellipse; +// the ring dims and flashes as each one arrives and the overlay's echo field +// follows the subject. All of it goes through the draw port, unpickable. The +// pulses run for a bounded time after a selection or camera move, then rest +// with the ring steady. Under reduced motion the ring simply stays on screen. import '../../testSupport/registerDom.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; @@ -20,13 +20,13 @@ import { } from './policy.js'; import { CYBER_SONAR_RENDER_INTERVAL_MS } from '../../cyberSonar.js'; import { - AWARENESS_PULSE_GRADIENT_MAX, + AWARENESS_BAND_PIXELS, awarenessPulseLevel, awarenessPulseState, awarenessRangeRingPositions, awarenessRingFlash, - awarenessRingGeometryOptions, createRendering, + paintAwarenessBand, wakeAwarenessPulses, } from './rendering.js'; import { getAwarenessEchoField } from '../../awarenessEcho.js'; @@ -47,11 +47,67 @@ function luminance(color) { ); } +/** A CSS colour as the ring's draw-port colour: channels 0 to 1. */ +function rgba(css) { + const c = Cesium.Color.fromCssColorString(css); + return [c.red, c.green, c.blue, c.alpha]; +} + +const close = (a, b, eps = 1e-9) => + a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) < eps); + /** - * The rendering part over a bare entity collection, counting render asks and - * by reason. `reducedMotion` stubs the media query for the length of the - * test; `motion.set(on)` flips it later and tells its listeners, as the - * browser does. + * A 2D canvas double: its context makes image data and keeps the last one + * put, so a test can read what the band painted. + */ +function fakeCanvas() { + const canvas = { width: 0, height: 0, painted: null }; + const context = { + createImageData: (width, height) => ({ + width, + height, + data: new Uint8ClampedArray(width * height * 4), + }), + putImageData(image) { + canvas.painted = image; + }, + }; + canvas.getContext = (kind) => (kind === '2d' ? context : null); + return canvas; +} + +/** A Cesium scene double with the frame events the frame port listens to. */ +const sceneDouble = () => ({ + preRender: new Cesium.Event(), + postRender: new Cesium.Event(), + screenSpaceCameraController: { enableInputs: true }, + requestRender() {}, +}); + +/** A viewer double bound to fake camera, frame, query and draw ports. */ +function viewerDouble(entities) { + const viewer = { + entities, + scene: sceneDouble(), + canvas: new EventTarget(), + camera: { + positionWC: Cesium.Cartesian3.fromDegrees(3, 20, 800_000), + positionCartographic: { height: 800_000 }, + heading: 0, + pitch: -1, + roll: 0, + }, + }; + const ports = fakeScenePorts(viewer); + bindFakeCesiumCamera(viewer, ports); + return { viewer, draw: ports.draw }; +} + +/** + * The rendering part over a viewer double, counting render asks and by + * reason. `reducedMotion` stubs the media query for the length of the test; + * `motion.set(on)` flips it later and tells its listeners, as the browser + * does. Canvases are doubles that keep what is painted on them. */ function ringRendering(t, { reducedMotion = false, legacyQuery = false } = {}) { const previous = globalThis.matchMedia; @@ -84,6 +140,10 @@ function ringRendering(t, { reducedMotion = false, legacyQuery = false } = {}) { t.after(() => { globalThis.matchMedia = previous; }); + const createElement = document.createElement.bind(document); + t.mock.method(document, 'createElement', (tag, ...rest) => + tag === 'canvas' ? fakeCanvas() : createElement(tag, ...rest), + ); const motion = { set(on) { reducedMotion = on; @@ -97,12 +157,8 @@ function ringRendering(t, { reducedMotion = false, legacyQuery = false } = {}) { }; const state = createState({ services: {} }); const entities = new Cesium.EntityCollection(); - const scene = { - primitives: new Cesium.PrimitiveCollection(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - }; - state.viewer = { entities, scene }; + const { viewer, draw } = viewerDouble(entities); + state.viewer = viewer; const reasons = []; const rendering = createRendering({ state, @@ -121,7 +177,8 @@ function ringRendering(t, { reducedMotion = false, legacyQuery = false } = {}) { return { state, entities, - scene, + scene: viewer.scene, + draw, rendering, motion, reasons, @@ -148,8 +205,8 @@ function frameLoop(t, ring, { date = false } = {}) { let drawn = 0; const draw = () => { drawn = ring.reasons.length; - ring.scene.preRender.raiseEvent(ring.scene); - ring.scene.postRender.raiseEvent(ring.scene); + ring.state.viewer.scene.preRender.raiseEvent(ring.state.viewer.scene); + ring.state.viewer.scene.postRender.raiseEvent(ring.state.viewer.scene); }; return { now: () => clock, @@ -164,31 +221,41 @@ function frameLoop(t, ring, { date = false } = {}) { }; } -/** The ring and the pulse disc among scene primitives. */ -function pulsePrimitives(scene) { - const all = Array.from({ length: scene.primitives.length }, (_, i) => - scene.primitives.get(i), +/** The ring's live draw sets on `draw`: its lines and its band. */ +function ringSets(draw) { + const live = [...draw.sets.values()].filter( + (record) => !record.disposed && record.spec.id.startsWith('awareness:'), ); - const ring = all.find( - (p) => p.appearance instanceof Cesium.PolylineMaterialAppearance, - ); - const discs = all.filter((p) => p instanceof Cesium.Primitive && p !== ring); - return { ring, disc: discs[0], count: discs.length }; + return { + lines: live.find((record) => record.kind === 'lines'), + band: live.find((record) => record.kind === 'shapes'), + count: live.length, + }; } -/** Where a disc built around `built` sits after its model matrix. */ -function discCenter(disc, built) { - return Cesium.Matrix4.multiplyByPoint( - disc.modelMatrix, - built, - new Cesium.Cartesian3(), +/** The ring's lines and band items as drawn now. */ +function drawn(ring) { + const { lines, band } = ringSets(ring.draw); + const item = (id) => lines?.items.get(id); + // A haloed line is one item; its halo is the style's outline. + const haloOf = (line) => + line && { + ...line, + style: { kind: 'solid', color: line.style.outline.color }, + }; + const pulses = [...(lines?.items.keys() ?? [])].filter((id) => + id.startsWith('pulse:'), ); -} - -/** The ring's material uniforms as the next drawn frame sets them. */ -function ringColors(scene) { - scene.preRender.raiseEvent(scene); - return pulsePrimitives(scene).ring.appearance.material.uniforms; + return { + core: item('ring'), + halo: haloOf(item('ring')), + pulse: (index, part = 'core') => + part === 'halo' ? haloOf(item(`pulse:${index}`)) : item(`pulse:${index}`), + pulses, + band: band?.items.get('band'), + lines, + bandSet: band, + }; } const flight = (lon) => ({ @@ -201,7 +268,9 @@ const flight = (lon) => ({ function surfaceDistances(center, positions) { const from = Cesium.Cartographic.fromCartesian(center); return positions.map((position) => { - const to = Cesium.Cartographic.fromCartesian(position); + const to = Cesium.Cartographic.fromCartesian( + Cesium.Cartesian3.clone(position), + ); return new Cesium.EllipsoidGeodesic(from, to).surfaceDistance; }); } @@ -290,88 +359,62 @@ test('the ring core and halo contrast on light and dark ground', () => { assert.ok(width - 2 * outlineWidth >= 2); }); -test('renderVisual draws one haloed polyline ring, not an ellipse outline', (t) => { +test('renderVisual draws the ring as a haloed line in an unpickable set, never an entity', (t) => { const ring = ringRendering(t); - const { entities, scene, state, rendering } = ring; + const { entities, state, rendering } = ring; frameLoop(t, ring); // freeze the clock: the pulses have not faded in yet rendering.renderVisual(flight(3)); - // A polyline primitive, never an entity or an ellipse outline. assert.equal(entities.values.length, 0); - const ringPrimitive = pulsePrimitives(scene).ring; - assert.ok(ringPrimitive); - const geometry = ringPrimitive.geometryInstances.geometry; - assert.ok(geometry instanceof Cesium.PolylineGeometry); - // 4 px wide, straight chords between surface-following positions, as the - // entity ring was drawn. - const options = awarenessRingGeometryOptions(state.visual.ringPositions); - assert.equal(options.width, 4); - assert.equal(options.width, AWARENESS_RANGE_RING_STYLE.width); - assert.equal(options.arcType, Cesium.ArcType.NONE); - assert.equal(options.positions, state.visual.ringPositions); + const { core, halo, lines } = drawn(ring); + assert.equal(lines.spec.pickable, false); + // 4 px wide in all, a 1 px halo on each side of a 2 px core, in one + // line, straight 3D chords between surface-following positions. + assert.equal(core.widthPx, AWARENESS_RANGE_RING_STYLE.width); assert.equal( - options.vertexFormat, - Cesium.PolylineMaterialAppearance.VERTEX_FORMAT, + core.style.outline.widthPx, + AWARENESS_RANGE_RING_STYLE.outlineWidth, ); - const { material } = ringPrimitive.appearance; - assert.equal(material.type, 'PolylineOutline'); - // The ring's hue is fixed; its opacity flashes with arriving pulses, and - // at the moment it appears, before the pulses fade in, it is at full. - const core = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.color, + assert.equal(core.mode, '3d'); + assert.equal(core.positions, state.visual.ringPositions); + assert.equal(halo.positions, core.positions); + // At the moment it appears, before the pulses fade in, it is at full. + assert.equal(core.style.kind, 'solid'); + assert.ok(close(core.style.color, rgba(AWARENESS_RANGE_RING_STYLE.color))); + assert.ok( + close(halo.style.color, rgba(AWARENESS_RANGE_RING_STYLE.outlineColor)), ); - const { color, outlineWidth } = ringColors(scene); - assert.equal(color.red, core.red); - assert.equal(color.blue, core.blue); - assert.ok(Math.abs(color.alpha - core.alpha) < 1e-9, `${color.alpha}`); - assert.equal(outlineWidth, AWARENESS_RANGE_RING_STYLE.outlineWidth); const ground = Cesium.Cartesian3.fromDegrees(3, 27, 0); for (const distance of surfaceDistances(ground, state.visual.ringPositions)) assert.ok(Math.abs(distance - AWARENESS_RADIUS_M) < 100); }); -test('the ring and pulses follow the subject past 250 m and ignore smaller drift', (t) => { - const { scene, state, rendering, renders } = ringRendering(t); - const subject = flight; - rendering.renderVisual(subject(3)); - const ringBefore = pulsePrimitives(scene).ring; +test('the ring follows the subject past 250 m and ignores smaller drift', (t) => { + const ring = ringRendering(t); + const { state, rendering, renders } = ring; + rendering.renderVisual(flight(3)); + const sets = ringSets(ring.draw); const first = state.visual.ringPositions; - const discBefore = pulsePrimitives(scene).disc; const rendersAfterAdd = renders(); - - // ~100 m east: under the threshold, nothing is rebuilt or rendered. - rendering.renderVisual(subject(3.001)); - assert.equal(pulsePrimitives(scene).ring, ringBefore); + // ~100 m east: under the threshold, nothing is redrawn or rendered. + rendering.renderVisual(flight(3.001)); assert.equal(state.visual.ringPositions, first); + assert.equal(drawn(ring).core.positions, first); assert.equal(renders(), rendersAfterAdd); - - // ~1 km east: the ring is rebuilt around the new centre, keeping its - // material, so a flash carries on. - rendering.renderVisual(subject(3.01)); - const ringAfter = pulsePrimitives(scene).ring; - assert.notEqual(ringAfter, ringBefore); - assert.ok(ringBefore.isDestroyed()); - assert.equal(ringAfter.appearance.material, ringBefore.appearance.material); - assert.equal(ringAfter.allowPicking, false); + // ~1 km east: the ring is drawn around the new centre, in the same sets. + rendering.renderVisual(flight(3.01)); const moved = state.visual.ringPositions; assert.notEqual(moved, first); + assert.equal(drawn(ring).core.positions, moved); + assert.equal(ringSets(ring.draw).lines, sets.lines); for (const distance of surfaceDistances( Cesium.Cartesian3.fromDegrees(3.01, 27, 0), moved, )) assert.ok(Math.abs(distance - AWARENESS_RADIUS_M) < 100); assert.equal(renders(), rendersAfterAdd + 1); - // The pulses are drawn on a disc that follows to the NEW centre by its - // model matrix, so they stay concentric with the ring without a rebuild. - assert.equal(pulsePrimitives(scene).disc, discBefore); - assert.ok( - Cesium.Cartesian3.distance( - discCenter(discBefore, Cesium.Cartesian3.fromDegrees(3, 27, 0)), - Cesium.Cartesian3.fromDegrees(3.01, 27, 0), - ) < 1, - ); - rendering.clearVisual(); - assert.equal(scene.primitives.length, 0); + assert.equal(sets.lines.items.size, 0); + assert.equal(sets.band.items.size, 0); }); test('a pulse grows slowly from the subject and arrives dim at the ring', () => { @@ -443,15 +486,61 @@ test('pulses ask for a frame 80 ms after each drawn frame instead of holding con assert.ok(Math.abs(pulseFrames() - 10) <= 1, `${pulseFrames()} frames`); const frames = pulseFrames(); rendering.clearVisual(); - assert.equal(ring.scene.primitives.length, 0); + assert.equal(ringSets(ring.draw).lines.items.size, 0); assert.equal(ring.scene.postRender.numberOfListeners, 0); loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS * 10); assert.equal(pulseFrames(), frames, 'no frames once the ring is gone'); }); +test('a pulse frame draws the step made before it was asked for; only a moving camera steps every frame', (t) => { + const ring = ringRendering(t); + const { rendering, state } = ring; + const loop = frameLoop(t, ring); + rendering.renderVisual(flight(3)); + loop.advance(1); + // Each pulse request comes with its step already made, so the frame it + // asks for steps nothing more and asks for no other. + const asked = []; + const push = ring.reasons.push; + ring.reasons.push = function (reason) { + asked.push([reason, state.visual.lastStepMs, performance.now()]); + return push.call(this, reason); + }; + let steps = 0; + const step = state.visual.step; + state.visual.step = (nowMs) => { + steps += 1; + step(nowMs); + }; + loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS * 10); + const pulses = asked.filter(([reason]) => reason === 'awareness-pulse'); + assert.ok(pulses.length >= 9, `${pulses.length} pulse frames`); + for (const [, stepMs, nowMs] of pulses) assert.equal(stepMs, nowMs); + assert.equal(steps, pulses.length, 'one step a pulse frame'); + // Frames the camera moves in step each one: the fronts move, and the + // soft band is painted again only a Cyber sonar interval on. + steps = 0; + const bandKey = drawn(ring).band.fill.image.key; + for (let i = 0; i < 5; i++) { + state.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees( + 3, + 20 + (i + 1) * 0.01, + 800_000, + ); + loop.draw(); + } + assert.equal(steps, 5); + assert.equal(drawn(ring).band.fill.image.key, bandKey); + // A frame asked for by something else within the interval, the camera + // parked, steps nothing. + steps = 0; + loop.draw(); + assert.equal(steps, 0); +}); + test('a parked view stops asking for frames once the pulses rest', (t) => { const ring = ringRendering(t); - const { scene, rendering, pulseFrames } = ring; + const { rendering, pulseFrames } = ring; const loop = frameLoop(t, ring); const { activeMs, count, periodMs } = AWARENESS_RANGE_PULSE; // Long enough for three ring flashes, then quiet, and short: a burst is @@ -471,11 +560,13 @@ test('a parked view stops asking for frames once the pulses rest', (t) => { assert.equal(pulseFrames(), frames, 'render requests stop after the bound'); // At rest the ring stands on screen at full, as without pulses, and the // pulses, gradient and echoes are hidden. - const core = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.color, + const now = drawn(ring); + assert.ok( + close(now.core.style.color, rgba(AWARENESS_RANGE_RING_STYLE.color)), ); - assert.ok(Math.abs(ringColors(scene).color.alpha - core.alpha) < 1e-9); - assert.equal(pulsePrimitives(scene).disc.show, false); + for (let index = 0; index < AWARENESS_RANGE_PULSE.count; index++) + assert.equal(now.pulse(index).show, false); + assert.equal(now.band.show, false); assert.equal(getAwarenessEchoField().level(loop.now()), 0); }); @@ -510,17 +601,8 @@ test('a camera move seen by the lifecycle wakes resting pulses; a parked camera const loop = frameLoop(t, ring, { date: true }); const { activeMs, inputWakeMs } = AWARENESS_RANGE_PULSE; state.enabled = true; - state.viewer.canvas = new EventTarget(); const touch = () => state.viewer.canvas.dispatchEvent(new Event('pointerdown')); - state.viewer.camera = { - positionWC: Cesium.Cartesian3.fromDegrees(3, 20, 800_000), - heading: 0, - pitch: -1, - roll: 0, - }; - // The lifecycle reads frames, the camera and its canvas through the ports. - bindFakeCesiumCamera(state.viewer, fakeScenePorts(state.viewer)); const lifecycle = createLifecycle({ state, services: { @@ -623,16 +705,6 @@ function inputLifecycle(t, ring) { const { state, rendering } = ring; const loop = frameLoop(t, ring, { date: true }); state.enabled = true; - state.viewer.canvas = new EventTarget(); - state.viewer.scene.screenSpaceCameraController = { enableInputs: true }; - state.viewer.camera = { - positionWC: Cesium.Cartesian3.fromDegrees(3, 20, 800_000), - heading: 0, - pitch: -1, - roll: 0, - }; - // The lifecycle reads frames, the camera and its canvas through the ports. - bindFakeCesiumCamera(state.viewer, fakeScenePorts(state.viewer)); const lifecycle = createLifecycle({ state, services: { @@ -835,14 +907,6 @@ test('disabling the layer tears the pulses down completely', (t) => { const ring = ringRendering(t); const { state, scene, rendering, motion, pulseFrames } = ring; const loop = frameLoop(t, ring); - state.viewer.camera = { - positionWC: Cesium.Cartesian3.fromDegrees(3, 20, 800_000), - heading: 0, - pitch: -1, - roll: 0, - }; - // The lifecycle reads frames, the camera and its canvas through the ports. - bindFakeCesiumCamera(state.viewer, fakeScenePorts(state.viewer)); const lifecycle = createLifecycle({ state, services: { @@ -872,9 +936,11 @@ test('disabling the layer tears the pulses down completely', (t) => { rendering.renderVisual(state.subject); loop.advance(1000); assert.ok(pulseFrames() > 0); - assert.equal(scene.primitives.length, 2); + const sets = ringSets(ring.draw); + assert.ok(sets.lines.items.size > 0 && sets.band.items.size === 1); lifecycle.methods.disable(); - assert.equal(scene.primitives.length, 0, 'ring and disc removed'); + assert.equal(sets.lines.items.size, 0, 'ring and pulses removed'); + assert.equal(sets.band.items.size, 0, 'band removed'); assert.equal(scene.preRender.numberOfListeners, 0); assert.equal(scene.postRender.numberOfListeners, 0); assert.equal(motion.listeners(), 0, 'no media-query listener'); @@ -927,244 +993,235 @@ test('the pulse level fades in, holds, fades out and keeps its level when woken' assert.equal(awarenessPulseLevel(at + activeMs, wake), 0); }); -test('a viewer without a Cesium primitive collection gets the static ring only, through the draw port', (t) => { - const { state, entities, rendering, pulseFrames } = ringRendering(t); - for (const scene of [ - {}, - { primitives: { add() {} } }, - { primitives: { add() {} }, preRender: new Cesium.Event() }, - undefined, - ]) { +test('a renderer without frame hooks gets the static ring only', (t) => { + const ring = ringRendering(t); + const { state, entities, rendering, pulseFrames } = ring; + for (const scene of [{}, undefined]) { state.viewer = { entities, scene }; const { draw } = bindFakeDraw(state.viewer); rendering.clearVisual(); rendering.renderVisual(flight(3)); - // No primitive collection: the ring is two lines in an unpickable draw - // set, a bright core over a dark halo, and nothing animates. + // The ring is one line in an unpickable draw set, a bright core inside + // a dark halo, and nothing animates. assert.equal(entities.values.length, 0); - const [set] = [...draw.sets.values()].filter((record) => !record.disposed); - assert.equal(set.kind, 'lines'); - assert.equal(set.spec.pickable, false); - const { halo, core } = Object.fromEntries(set.items); - assert.equal(halo.widthPx, AWARENESS_RANGE_RING_STYLE.width); - assert.equal( - core.widthPx, - AWARENESS_RANGE_RING_STYLE.width - - AWARENESS_RANGE_RING_STYLE.outlineWidth, - ); - assert.deepEqual(core.style, { - kind: 'solid', - color: AWARENESS_RANGE_RING_STYLE.color, - }); - assert.deepEqual(halo.style, { - kind: 'solid', - color: AWARENESS_RANGE_RING_STYLE.outlineColor, - }); - assert.equal(core.positions, halo.positions); - const ground = Cesium.Cartesian3.fromDegrees(3, 27, 0); - for (const distance of surfaceDistances(ground, core.positions)) - assert.ok(Math.abs(distance - AWARENESS_RADIUS_M) < 100); + const { lines, band } = ringSets(draw); + assert.equal(lines.spec.pickable, false); + assert.deepEqual([...lines.items.keys()], ['ring']); + assert.equal(band.items.size, 0, 'no band'); + const core = lines.items.get('ring'); + assert.ok(close(core.style.color, rgba(AWARENESS_RANGE_RING_STYLE.color))); rendering.clearVisual(); - assert.equal(set.items.size, 0, 'clearing takes the ring away'); + assert.equal(lines.items.size, 0, 'clearing takes the ring away'); assert.equal(state.visual, null); } assert.equal(pulseFrames(), 0); }); -test('a gradient disc behind the pulses fades inward and follows the subject', (t) => { +test('the band fades inward from each front, in the ring blue, about the subject', () => { + const size = 64; + const image = { width: size, data: new Uint8ClampedArray(size * size * 4) }; + const { gradientDepthFraction: depth, gradientOpacity } = + AWARENESS_RANGE_PULSE; + const rangeM = 100; + const spanM = 100; + const band = (offset = { east: 0, north: 0 }) => + paintAwarenessBand(image, { + radii: [0.8, 0], + alphas: [0.5, 0], + rgb: [0.25, 0.5, 1], + spanM, + rangeM, + offset, + }); + // Alpha at a pixel `fraction` of the range east of the canvas centre. + const alphaEast = (fraction) => { + const x = Math.floor(size / 2 + (fraction * size) / 2); + const k = ((size / 2) * size + x) * 4; + return image.data[k + 3] / 255; + }; + band(); + const k = ((size / 2) * size + size / 2) * 4; + assert.deepEqual([...image.data.slice(k, k + 3)], [64, 128, 255]); + // Strongest just inside the front, nothing beyond it or `depth` inside. + const peak = 0.5 * gradientOpacity; + assert.ok(Math.abs(alphaEast(0.79) - peak) < 0.02, `${alphaEast(0.79)}`); + assert.equal(alphaEast(0.85), 0); + assert.equal(alphaEast(0.8 - depth - 0.1), 0); + // Quadratic: half way in, a quarter as strong. + assert.ok( + Math.abs(alphaEast(0.8 - depth / 2) - peak / 4) < 0.02, + `${alphaEast(0.8 - depth / 2)}`, + ); + // The subject 20 m east of the canvas centre: the band moves with it. + band({ east: 20, north: 0 }); + assert.ok(Math.abs(alphaEast(0.79 + 0.2) - peak) < 0.02); + // 0.3 of the range from the subject: deeper than the band reaches. + assert.equal(alphaEast(0.5), 0); +}); + +test('the band is one flat unpickable ellipse at the rim, drawn anew each step about the subject', (t) => { const ring = ringRendering(t); - const { scene, rendering } = ring; + const { state, rendering } = ring; const loop = frameLoop(t, ring); rendering.renderVisual(flight(3)); - assert.ok(AWARENESS_RANGE_PULSE.count <= AWARENESS_PULSE_GRADIENT_MAX); - assert.equal(scene.primitives.length, 2, 'the ring and the pulse disc'); - const { disc, count } = pulsePrimitives(scene); - assert.equal(count, 1, 'the gradient disc'); - assert.ok(disc); - // Never a click or tap target, and see-through. - assert.equal(disc.allowPicking, false); - assert.equal(disc.appearance.translucent, true); - const { material } = disc.appearance; - assert.ok( - Math.abs( - material.uniforms.depth - AWARENESS_RANGE_PULSE.gradientDepthFraction, - ) < 1e-9, - ); - assert.ok( - Math.abs( - material.uniforms.color.alpha - AWARENESS_RANGE_PULSE.gradientOpacity, - ) < 1e-6, - ); - // The pulse lines are drawn in the ring's colours and widths. - const core = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.color, - ); - const halo = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.outlineColor, - ); - assert.ok(material.uniforms.lineColor.equalsEpsilon(core, 1e-6)); - assert.ok(material.uniforms.haloColor.equalsEpsilon(halo, 1e-6)); - assert.equal(material.uniforms.lineWidth, AWARENESS_RANGE_PULSE.width); - assert.equal(material.uniforms.haloWidth, AWARENESS_RANGE_PULSE.outlineWidth); - // Each frame writes the pulses' radius (as a fraction of the range) and - // opacity into the shader, from the same curve the lines use, once the - // pulses have faded in. - assert.equal(scene.preRender.numberOfListeners, 1); loop.advance(AWARENESS_RANGE_PULSE.settleMs + 500); - scene.preRender.raiseEvent(scene); - assert.equal(disc.show, true); - const { radii, alphas } = material.uniforms; + const { band, bandSet } = drawn(ring); + assert.equal(bandSet.spec.pickable, false); + assert.equal(band.show, true); + assert.equal(band.height, 'absolute'); + const { geometry } = band; + assert.equal(geometry.kind, 'ellipse'); + assert.ok(Math.abs(geometry.center.lon - 3) < 1e-9); + assert.ok(Math.abs(geometry.center.lat - 27) < 1e-9); + assert.equal(geometry.center.height, CONTEXT_RIM_HEIGHT_M); + // Wide enough for the band to follow the subject `gradientRebuildM` off. + const spanM = AWARENESS_RADIUS_M + AWARENESS_RANGE_PULSE.gradientRebuildM; + assert.equal(geometry.semiMajor, spanM); + assert.equal(geometry.semiMinor, spanM); + const { canvas, key } = band.fill.image; + assert.equal(canvas.width, AWARENESS_BAND_PIXELS); + // Each step paints the other canvas under a new key. + loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS + 2); + const next = drawn(ring).band.fill.image; + assert.notEqual(next.key, key); + assert.notEqual(next.canvas, canvas); + // What it painted is the band of the pulses as they were at that step. + const at = state.visual.lastStepMs; + const level = awarenessPulseLevel(at, state.visual.wake); + const expected = { width: AWARENESS_BAND_PIXELS }; + expected.data = new Uint8ClampedArray(AWARENESS_BAND_PIXELS ** 2 * 4); + const radii = []; + const alphas = []; for (let index = 0; index < AWARENESS_RANGE_PULSE.count; index++) { - const radius = Cesium.Cartesian4.pack(radii, [])[index]; - const alpha = Cesium.Cartesian4.pack(alphas, [])[index]; - const expected = awarenessPulseState(loop.now(), index); - assert.ok(Math.abs(radius - expected.radiusM / AWARENESS_RADIUS_M) < 1e-6); - assert.ok(alpha >= 0 && alpha <= AWARENESS_RANGE_PULSE.peakOpacity); - assert.ok(Math.abs(alpha - expected.alpha) < 1e-6); + const pulse = awarenessPulseState(at, index); + radii.push(pulse.radiusM / AWARENESS_RADIUS_M); + alphas.push(pulse.alpha * level); } - // Unused shader slots stay empty. - assert.equal( - Cesium.Cartesian4.pack(alphas, [])[AWARENESS_PULSE_GRADIENT_MAX - 1], - 0, - ); - - // The disc follows by its model matrix and is rebuilt only past - // `gradientRebuildM` (20 km), keeping its material. - const built = Cesium.Cartesian3.fromDegrees(3, 27, 0); - for (const lon of [3.001, 3.01, 3.1, 3.19]) { - rendering.renderVisual(flight(lon)); - assert.equal(pulsePrimitives(scene).disc, disc, `${lon}`); - assert.ok(!disc.isDestroyed()); - // Concentric with the ring wherever the subject went, within a metre - // across the ground; the ellipsoid curves away from the rotation's - // sphere by tens of metres in height at most. - const at = Cesium.Cartographic.fromCartesian(discCenter(disc, built)); - const want = Cesium.Cartographic.fromCartesian(ring.state.visual.center); - const across = new Cesium.EllipsoidGeodesic(at, want).surfaceDistance; - assert.ok(across < 1, `${across} m off at ${lon}`); - assert.ok(Math.abs(at.height) < 50, `${at.height} m off the ground`); + paintAwarenessBand(expected, { + radii, + alphas, + rgb: rgba(AWARENESS_RANGE_RING_STYLE.color), + spanM, + rangeM: AWARENESS_RADIUS_M, + offset: { east: 0, north: 0 }, + }); + assert.deepEqual(next.canvas.painted.data, expected.data); + // Each front is a haloed line at its radius, faded with its pulse. + for (let index = 0; index < AWARENESS_RANGE_PULSE.count; index++) { + const core = drawn(ring).pulse(index); + const halo = drawn(ring).pulse(index, 'halo'); + assert.equal(core.show, true); + assert.equal(core.widthPx, AWARENESS_RANGE_PULSE.width); + assert.equal(halo.style.color.length, 4); + assert.equal( + core.style.outline.widthPx, + AWARENESS_RANGE_PULSE.outlineWidth / 2, + ); + const pulse = awarenessPulseState(at, index); + const ground = Cesium.Cartesian3.fromDegrees(3, 27, 0); + for (const d of surfaceDistances(ground, core.positions)) + assert.ok(Math.abs(d - pulse.radiusM) < 100, `${d} vs ${pulse.radiusM}`); + const want = rgba(AWARENESS_RANGE_RING_STYLE.color); + want[3] *= pulse.alpha * level; + assert.ok(close(core.style.color, want)); } - rendering.renderVisual(flight(3.25)); // ~25 km from where it was built - assert.equal(pulsePrimitives(scene).count, 1); - const moved = pulsePrimitives(scene).disc; - assert.notEqual(moved, disc); - assert.ok(disc.isDestroyed()); - assert.equal(moved.appearance.material, material); - assert.equal(moved.allowPicking, false); - - rendering.clearVisual(); - assert.equal(scene.primitives.length, 0); - assert.equal(scene.preRender.numberOfListeners, 0); + // The ellipse stands while the subject moves under `gradientRebuildM`, + // the canvas drawing the band about the subject; past it, it moves. + rendering.renderVisual(flight(3.15)); // ~15 km + assert.ok(Math.abs(drawn(ring).band.geometry.center.lon - 3) < 1e-9); + rendering.renderVisual(flight(3.25)); // ~25 km + assert.ok(Math.abs(drawn(ring).band.geometry.center.lon - 3.25) < 1e-6); }); -test("switching subjects keeps one pulse material in Cesium's global cache", (t) => { +test('switching subjects draws into the same sets', (t) => { const ring = ringRendering(t); - const { scene, rendering } = ring; + const { rendering } = ring; frameLoop(t, ring); - // Cesium keeps every new material type for the page's lifetime, so an - // unnamed fabric (a fresh GUID type each time) would grow it per subject. - const cached = () => - Object.keys(Cesium.Material._materialCache._materials).length; rendering.renderVisual({ ...flight(3), id: 'subject-0' }); - const first = pulsePrimitives(scene).disc.appearance.material; - const size = cached(); - let last = first; - for (let index = 1; index <= 6; index++) { + const sets = ringSets(ring.draw); + for (let index = 1; index <= 6; index++) rendering.renderVisual({ ...flight(3 + index), id: `subject-${index}` }); - last = pulsePrimitives(scene).disc.appearance.material; - } - assert.equal(cached(), size, 'subject switches add no cache entries'); - rendering.clearVisual(); - rendering.renderVisual(flight(3)); - assert.equal(cached(), size, 'nor does a reselect'); - // A material built from the cached template still owns its uniform values. - const again = pulsePrimitives(scene).disc.appearance.material; - assert.notEqual(again, last); - assert.notEqual(again.uniforms.radii, last.uniforms.radii); - assert.notEqual(again.uniforms.alphas, first.uniforms.alphas); - assert.ok(again.uniforms.radii instanceof Cesium.Cartesian4); - assert.ok(again.uniforms.lineColor instanceof Cesium.Color); - assert.equal(again.uniforms.lineWidth, AWARENESS_RANGE_PULSE.width); + const after = ringSets(ring.draw); + assert.equal(after.lines, sets.lines); + assert.equal(after.band, sets.band); + assert.equal(ring.draw.sets.size, 2, 'no set per subject'); }); -test('a resting pulse disc is not rebuilt as the subject moves, and catches up on wake', (t) => { +test('a resting band is not moved as the subject moves, and catches up on wake', (t) => { const ring = ringRendering(t); - const { scene, rendering } = ring; + const { rendering } = ring; const loop = frameLoop(t, ring); rendering.renderVisual(flight(3)); loop.advance(AWARENESS_RANGE_PULSE.activeMs + 500); - const resting = pulsePrimitives(scene).disc; - const restingMatrix = Cesium.Matrix4.clone(resting.modelMatrix); - // A flying subject keeps moving while the pulses rest: the hidden disc is - // neither moved nor rebuilt, even well past the rebuild distance. + const resting = drawn(ring).band; + assert.equal(resting.show, false); + const writes = drawn(ring).bandSet.writes; + // A flying subject keeps moving while the pulses rest: the hidden band is + // neither moved nor redrawn, even well past the rebuild distance. for (let lon = 3.01; lon < 3.4; lon += 0.01) rendering.renderVisual(flight(lon)); - assert.equal(pulsePrimitives(scene).disc, resting); - assert.ok(!resting.isDestroyed()); - assert.ok(Cesium.Matrix4.equals(resting.modelMatrix, restingMatrix)); - // Woken, the disc catches up at once: rebuilt around the subject. + assert.equal(drawn(ring).band, resting); + assert.equal(drawn(ring).bandSet.writes, writes); + // Woken, the band catches up at once, around the subject. rendering.wakePulses(); - const woken = pulsePrimitives(scene).disc; - assert.notEqual(woken, resting); - assert.ok(resting.isDestroyed()); - assert.equal(pulsePrimitives(scene).count, 1); - // Woken again without moving: the disc stays. - rendering.wakePulses(); - assert.equal(pulsePrimitives(scene).disc, woken); + loop.advance(AWARENESS_RANGE_PULSE.settleMs); + const woken = drawn(ring).band; + assert.equal(woken.show, true); + assert.ok(Math.abs(woken.geometry.center.lon - 3.39) < 0.011); }); -test('the ring and pulses never catch a click: no entities, every primitive unpickable', (t) => { +test('the ring and pulses never catch a click: no entities, every set unpickable', (t) => { for (const reducedMotion of [false, true]) { - const { entities, scene, rendering } = ringRendering(t, { reducedMotion }); - rendering.renderVisual(flight(3)); + const ring = ringRendering(t, { reducedMotion }); + ring.rendering.renderVisual(flight(3)); // Cesium always picks entities, so the awareness visual adds none. - assert.equal(entities.values.length, 0); - assert.ok(scene.primitives.length >= 1); - for (let i = 0; i < scene.primitives.length; i++) - assert.equal(scene.primitives.get(i).allowPicking, false); - rendering.clearVisual(); + assert.equal(ring.entities.values.length, 0); + for (const record of ring.draw.sets.values()) + assert.equal(record.spec.pickable, false, record.spec.id); + ring.rendering.clearVisual(); } }); -test('a camera below the rim height hides the pulse disc instead of sweeping the sky', (t) => { +test('a camera below the rim height hides the pulses instead of sweeping the sky', (t) => { const ring = ringRendering(t); - const { scene, rendering } = ring; + const { state, rendering } = ring; const loop = frameLoop(t, ring); rendering.renderVisual(flight(3)); loop.advance(AWARENESS_RANGE_PULSE.settleMs + 500); const cameraAt = (height) => { - scene.camera = { - positionCartographic: new Cesium.Cartographic(0, 0, height), - }; - scene.preRender.raiseEvent(scene); - return pulsePrimitives(scene).disc.show; + state.viewer.camera.positionCartographic = { height }; + loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS + 1); + loop.draw(); + return drawn(ring).band.show && drawn(ring).pulse(0).show; }; assert.equal(cameraAt(CONTEXT_RIM_HEIGHT_M + 500), true); assert.equal(cameraAt(CONTEXT_RIM_HEIGHT_M - 500), false, 'cockpit view'); - // Below the disc the pulses rest with it: the ring is steady at full, no + // Below the band the pulses rest with it: the ring is steady at full, no // echo lights and no frame is asked for. - const core = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.color, + assert.ok( + close(drawn(ring).core.style.color, rgba(AWARENESS_RANGE_RING_STYLE.color)), ); - assert.ok(Math.abs(ringColors(scene).color.alpha - core.alpha) < 1e-9); assert.equal(getAwarenessEchoField().level(loop.now()), 0); const frames = ring.pulseFrames(); loop.draw(); loop.advance(2000); assert.equal(ring.pulseFrames(), frames, 'no requests below the rim'); - assert.equal(cameraAt(800_000), true); + state.viewer.camera.positionCartographic = { height: 800_000 }; + loop.draw(); + loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS + 2); + assert.equal(drawn(ring).band.show, true); }); test('reduced motion keeps the static ring and drops the pulses', (t) => { t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }); - const { scene, rendering, pulseFrames } = ringRendering(t, { - reducedMotion: true, - }); + const ring = ringRendering(t, { reducedMotion: true }); + const { scene, rendering, pulseFrames } = ring; rendering.renderVisual(flight(3)); - assert.ok(pulsePrimitives(scene).ring); + assert.ok(drawn(ring).core); t.mock.timers.tick(1000); assert.equal(pulseFrames(), 0); - assert.equal(pulsePrimitives(scene).count, 0, 'no pulse disc'); + assert.deepEqual(drawn(ring).pulses, [], 'no pulse fronts'); + assert.equal(drawn(ring).band, undefined, 'no band'); assert.equal(scene.preRender.numberOfListeners, 0); assert.equal(scene.postRender.numberOfListeners, 0); }); @@ -1175,12 +1232,13 @@ test('turning reduced motion on mid-session stops the pulses, and off restarts t const loop = frameLoop(t, ring); state.subject = flight(3); rendering.renderVisual(state.subject); - assert.equal(pulsePrimitives(scene).count, 1); + assert.equal(drawn(ring).pulses.length, AWARENESS_RANGE_PULSE.count); loop.advance(1000); // The OS setting changes while the same aircraft stays tracked. motion.set(true); - assert.ok(pulsePrimitives(scene).ring); - assert.equal(pulsePrimitives(scene).count, 0); + assert.ok(drawn(ring).core); + assert.deepEqual(drawn(ring).pulses, []); + assert.equal(drawn(ring).band, undefined); assert.equal(scene.preRender.numberOfListeners, 0); assert.equal(scene.postRender.numberOfListeners, 0); assert.equal(getAwarenessEchoField(), null); @@ -1188,7 +1246,7 @@ test('turning reduced motion on mid-session stops the pulses, and off restarts t loop.advance(5000); assert.equal(ring.pulseFrames(), frames); motion.set(false); - assert.equal(pulsePrimitives(scene).count, 1); + assert.equal(drawn(ring).pulses.length, AWARENESS_RANGE_PULSE.count); assert.ok(getAwarenessEchoField()); // One media-query listener per visual; none once the ring is gone. assert.equal(motion.listeners(), 1); @@ -1197,43 +1255,39 @@ test('turning reduced motion on mid-session stops the pulses, and off restarts t }); test('a reduced-motion change reaches older Safari through addListener', (t) => { - const { scene, rendering, motion, state } = ringRendering(t, { - legacyQuery: true, - }); + const ring = ringRendering(t, { legacyQuery: true }); + const { scene, rendering, motion, state } = ring; state.subject = flight(3); rendering.renderVisual(state.subject); - assert.equal(pulsePrimitives(scene).count, 1); + assert.equal(drawn(ring).pulses.length, AWARENESS_RANGE_PULSE.count); assert.equal(motion.listeners(), 1); motion.set(true); - assert.equal(pulsePrimitives(scene).count, 0); + assert.deepEqual(drawn(ring).pulses, []); assert.equal(scene.preRender.numberOfListeners, 0); rendering.clearVisual(); assert.equal(motion.listeners(), 0); }); test('a refresh after reduced motion changed rebuilds the visual too', (t) => { - const { scene, rendering, motion } = ringRendering(t); + const ring = ringRendering(t); + const { scene, rendering, motion } = ring; rendering.renderVisual(flight(3)); - assert.equal(pulsePrimitives(scene).count, 1); + assert.equal(drawn(ring).pulses.length, AWARENESS_RANGE_PULSE.count); // No change event: the next same-subject refresh notices on its own. motion.setQuietly(true); rendering.renderVisual(flight(3)); - assert.ok(pulsePrimitives(scene).ring); - assert.equal(pulsePrimitives(scene).count, 0); + assert.ok(drawn(ring).core); + assert.deepEqual(drawn(ring).pulses, []); assert.equal(scene.preRender.numberOfListeners, 0); }); test('while pulses run the ring flashes as each one arrives, then rests', (t) => { const ring = ringRendering(t); - const { scene, rendering } = ring; + const { state, rendering } = ring; const loop = frameLoop(t, ring); rendering.renderVisual(flight(3)); - const core = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.color, - ); - const halo = Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.outlineColor, - ); + const core = rgba(AWARENESS_RANGE_RING_STYLE.color); + const halo = rgba(AWARENESS_RANGE_RING_STYLE.outlineColor); const { periodMs, count } = AWARENESS_RANGE_PULSE; const { flashMs, restOpacity } = AWARENESS_RANGE_RING_STYLE; // Full the moment a front reaches 250 km, gone `flashMs` later. @@ -1254,31 +1308,30 @@ test('while pulses run the ring flashes as each one arrives, then rests', (t) => wasLit = lit; } assert.equal(flashes, count); - // Once the pulses have faded in, the live colour tracks the flash, and - // never drops below `restOpacity`. + // Once the pulses have faded in, the drawn colour tracks the flash as it + // was at each step, and never drops below `restOpacity`. loop.advance(AWARENESS_RANGE_PULSE.settleMs); for (let step = 0; step < 40; step++) { loop.advance(100); - const { color, outlineColor } = ringColors(scene); - const flash = Math.max(restOpacity, awarenessRingFlash(loop.now())); - const expected = core.alpha * flash; - assert.ok( - Math.abs(color.alpha - expected) < 1e-9, - `${color.alpha} vs ${expected}`, + const flash = Math.max( + restOpacity, + awarenessRingFlash(state.visual.lastStepMs), ); - assert.ok(Math.abs(outlineColor.alpha - halo.alpha * flash) < 1e-9); + const { core: drawnCore, halo: drawnHalo } = drawn(ring); + assert.ok( + Math.abs(drawnCore.style.color[3] - core[3] * flash) < 1e-9, + `${drawnCore.style.color[3]} vs ${core[3] * flash}`, + ); + assert.ok(Math.abs(drawnHalo.style.color[3] - halo[3] * flash) < 1e-9); } }); test('without pulses the ring stays on screen at full strength', (t) => { - const { scene, rendering } = ringRendering(t, { reducedMotion: true }); - rendering.renderVisual(flight(3)); - assert.equal(scene.preRender.numberOfListeners, 0); - assert.equal( - ringColors(scene).color.toCssColorString(), - Cesium.Color.fromCssColorString( - AWARENESS_RANGE_RING_STYLE.color, - ).toCssColorString(), + const ring = ringRendering(t, { reducedMotion: true }); + ring.rendering.renderVisual(flight(3)); + assert.equal(ring.scene.preRender.numberOfListeners, 0); + assert.ok( + close(drawn(ring).core.style.color, rgba(AWARENESS_RANGE_RING_STYLE.color)), ); assert.equal(getAwarenessEchoField(), null); }); @@ -1314,44 +1367,35 @@ test('the echo field follows the subject while pulses run and clears with the ri assert.equal(getAwarenessEchoField(), null); }); -test('a ring drawn on one viewer leaves it when the layer moves to another, with or without primitives', (t) => { +test('a ring drawn on one viewer leaves it when the layer moves to another', (t) => { const ring = ringRendering(t); const { state, scene, rendering } = ring; - frameLoop(t, ring); + const loop = frameLoop(t, ring); rendering.renderVisual(flight(3)); - assert.equal(scene.primitives.length, 2, 'the ring and the pulse disc'); - // Re-initialized on a viewer that draws through the draw port only. + loop.advance(AWARENESS_RANGE_PULSE.settleMs + 200); + const first = ringSets(ring.draw); + assert.ok(first.lines.items.size > 0 && first.band.items.size === 1); + // Re-initialized on a viewer without frame hooks. const plain = { entities: ring.entities, scene: {} }; const { draw } = bindFakeDraw(plain); state.viewer = plain; rendering.renderVisual(flight(3)); - assert.equal(scene.primitives.length, 0, 'gone from the first viewer'); + assert.equal(first.lines.disposed, true, 'gone from the first viewer'); + assert.equal(first.band.disposed, true); assert.equal(scene.preRender.numberOfListeners, 0); assert.equal(scene.postRender.numberOfListeners, 0); assert.equal(getAwarenessEchoField(), null); - const [set] = [...draw.sets.values()]; - assert.equal(set.items.size, 2, 'the static ring on the second'); - // And back onto a viewer with primitives: the static ring goes. - const other = { - primitives: new Cesium.PrimitiveCollection(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - }; - state.viewer = { entities: ring.entities, scene: other }; + const second = ringSets(draw); + assert.equal(second.lines.items.size, 1, 'the static ring on the second'); + // And onto a viewer with frame hooks: drawn there with its pulses. + const third = viewerDouble(ring.entities); + state.viewer = third.viewer; rendering.renderVisual(flight(3)); - assert.equal(set.items.size, 0); - assert.equal(other.primitives.length, 2); - // Same subject, another viewer with primitives: redrawn there. - const third = { - primitives: new Cesium.PrimitiveCollection(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - }; - state.viewer = { entities: ring.entities, scene: third }; - rendering.renderVisual(flight(3)); - assert.equal(other.primitives.length, 0); - assert.equal(third.primitives.length, 2); + loop.advance(AWARENESS_RANGE_PULSE.settleMs + 200); + assert.equal(second.lines.disposed, true); + const drawnThird = ringSets(third.draw); + assert.equal(drawnThird.band.items.size, 1); rendering.disposeVisual(); - assert.equal(third.primitives.length, 0); - assert.equal(set.disposed, true); + assert.equal(drawnThird.lines.disposed, true); + assert.equal(drawnThird.band.disposed, true); }); diff --git a/src/layers/awareness/rangeRingCesium.js b/src/layers/awareness/rangeRingCesium.js deleted file mode 100644 index 87e963717..000000000 --- a/src/layers/awareness/rangeRingCesium.js +++ /dev/null @@ -1,641 +0,0 @@ -/** - * @module layers/awareness/rangeRingCesium - * @description The Global Context range ring and its sonar pulses, drawn - * with Cesium primitives: an unpickable polyline ring in an outline - * material whose opacity flashes, and one unpickable disc whose own material - * draws the pulse lines and the band behind them, following the subject by - * its model matrix. The renderer's draw port has no item that can draw the - * disc (a shape whose fill is computed per pixel from values set each - * frame), nor an outlined line whose colour changes without a rebuild, so - * this module reaches Cesium itself and is on the Cesium allow-list - * (`src/render/cesiumAllowList.json`) until the draw port can. It draws only - * on a viewer with a Cesium primitive collection (`drawsOn`); on any other - * renderer the layer draws the static ring through the draw port - * (`rendering.js`). - */ -import * as Cesium from 'cesium'; -import { CYBER_SONAR_RENDER_INTERVAL_MS } from '../../cyberSonar.js'; -import { AWARENESS_RADIUS_M } from '../../data/militaryAwarenessEngine.js'; -import { - AWARENESS_RANGE_ECHO, - AWARENESS_RANGE_PULSE, - AWARENESS_RANGE_RING_STYLE, - CONTEXT_RIM_HEIGHT_M, -} from './policy.js'; -import { - awarenessEchoStrength, - clearAwarenessEchoField, - setAwarenessEchoField, -} from '../../awarenessEcho.js'; - -/** - * A closed ring of positions `radiusM` along the surface from `groundCenter`, - * raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's - * radius of curvature in that direction (Euler's formula), which keeps the - * ring within ~50 m of the true geodesic radius at 250 km. - * @param {Cesium.Cartesian3} groundCenter Ring centre on the ellipsoid. - * @param {number} radiusM Surface radius in metres. - * @param {number} heightM Height of the ring above the ellipsoid. - * @param {number} [segments] Chords around the ring. - * @returns {Cesium.Cartesian3[]} `segments + 1` positions; the last repeats the first. - */ -export function awarenessRangeRingPositions( - groundCenter, - radiusM, - heightM, - segments = AWARENESS_RANGE_RING_STYLE.segments, -) { - const { latitude, longitude } = - Cesium.Cartographic.fromCartesian(groundCenter); - const { x: a, z: b } = Cesium.Ellipsoid.WGS84.radii; - const e2 = 1 - (b * b) / (a * a); - const sinLat = Math.sin(latitude); - const cosLat = Math.cos(latitude); - const sinLon = Math.sin(longitude); - const cosLon = Math.cos(longitude); - const w = 1 - e2 * sinLat * sinLat; - const meridional = (a * (1 - e2)) / (w * Math.sqrt(w)); - const primeVertical = a / Math.sqrt(w); - // Step along the great circle in 3D from the centre's up, north and east - // unit vectors. Unlike the latitude/longitude destination formula, this - // stays well conditioned at and next to the poles. - const up = [cosLat * cosLon, cosLat * sinLon, sinLat]; - const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat]; - const east = [-sinLon, cosLon, 0]; - const positions = []; - for (let i = 0; i <= segments; i++) { - const bearing = ((i % segments) / segments) * Cesium.Math.TWO_PI; - const cosB = Math.cos(bearing); - const sinB = Math.sin(bearing); - const angular = - radiusM * ((cosB * cosB) / meridional + (sinB * sinB) / primeVertical); - const cosA = Math.cos(angular); - const sinA = Math.sin(angular); - const [x, y, z] = up.map( - (u, k) => u * cosA + (north[k] * cosB + east[k] * sinB) * sinA, - ); - const lat = Math.atan2(z, Math.hypot(x, y)); - const lon = Math.atan2(y, x); - positions.push(Cesium.Cartesian3.fromRadians(lon, lat, heightM)); - } - return positions; -} - -/** - * Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at - * constant speed from `startFraction` of the range to the full range, fade in - * over `fadeInFraction` of the way, then fade as (1 - travel) to the - * `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim - * but still visible when it reaches the range ring. The opacity already - * includes `peakOpacity`. - * @param {number} nowMs Monotonic clock in milliseconds. - * @param {number} index Pulse number, 0 to `count - 1`. - * @param {number} [radiusM] Range the pulses grow to. - * @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`. - * @returns {{radiusM: number, alpha: number}} - */ -export function awarenessPulseState( - nowMs, - index, - radiusM = AWARENESS_RADIUS_M, - pulse = AWARENESS_RANGE_PULSE, -) { - const cycle = nowMs / pulse.periodMs + index / pulse.count; - const phase = cycle - Math.floor(cycle); - return { - radiusM: - radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase), - alpha: - pulse.peakOpacity * - Math.min(1, phase / pulse.fadeInFraction) * - (pulse.endOpacityFraction + - (1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower), - }; -} - -const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)'; - -/** Whether the viewer asked the system for less motion. */ -function prefersReducedMotion() { - return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false; -} - -/** - * How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over - * `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to - * `wake.untilMs`. - * @param {number} nowMs Monotonic clock in milliseconds. - * @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`. - * @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`. - * @returns {number} 0 to 1. - */ -export function awarenessPulseLevel( - nowMs, - wake, - pulse = AWARENESS_RANGE_PULSE, -) { - const level = Math.min( - (nowMs - wake.startMs) / pulse.settleMs, - (wake.untilMs - nowMs) / pulse.settleMs, - ); - return Math.max(0, Math.min(1, level)); -} - -/** - * Run the pulses for `activeMs` from `nowMs`. A wake while they already run - * keeps their current level, so they never jump back to full mid-fade. - * @param {{startMs: number, untilMs: number}} wake Updated in place. - * @param {number} nowMs Monotonic clock in milliseconds. - * @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`. - * @returns {{startMs: number, untilMs: number}} `wake`. - */ -export function wakeAwarenessPulses( - wake, - nowMs, - pulse = AWARENESS_RANGE_PULSE, -) { - wake.startMs = - nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs; - wake.untilMs = nowMs + pulse.activeMs; - return wake; -} - -/** - * How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a - * pulse front reaches it, fading over `flashMs`, so the ring appears once - * per arriving pulse instead of standing on screen. - * @param {number} nowMs Monotonic clock in milliseconds. - * @returns {number} 0 to 1. - */ -export function awarenessRingFlash(nowMs) { - return awarenessEchoStrength( - nowMs, - AWARENESS_RADIUS_M, - AWARENESS_RADIUS_M, - AWARENESS_RANGE_PULSE, - { fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs }, - ); -} - -/** Most pulses the pulse shader draws; its uniforms are vec4s. */ -export const AWARENESS_PULSE_GRADIENT_MAX = 4; - -/** The pulse disc's Cesium material type, one cached template per page. */ -const AWARENESS_PULSE_MATERIAL_TYPE = 'GevAwarenessPulseGradient'; - -// Ellipse texture coordinates put the centre at (0.5, 0.5) and the rim at -// distance 0.5, so `r` is the fraction of the range. Each pulse is a line -// `lineWidth` CSS pixels wide whose outer `haloWidth` is a dark halo, half -// on each side, as Cesium's polyline outline material draws it, with a band -// behind it that is strongest at the line and fades to nothing `depth` -// inward. Widths come from the screen-space gradient of `r`, as Cesium's -// contour material measures its lines; without derivatives the lines are -// left out and only the band shows. -const PULSE_GRADIENT_SOURCE = ` -uniform vec4 color; -uniform vec4 lineColor; -uniform vec4 haloColor; -uniform vec4 radii; -uniform vec4 alphas; -uniform float depth; -uniform float lineWidth; -uniform float haloWidth; -vec4 over(vec4 top, vec4 under) { - float a = top.a + under.a * (1.0 - top.a); - if (a <= 0.0) return vec4(0.0); - return vec4((top.rgb * top.a + under.rgb * under.a * (1.0 - top.a)) / a, a); -} -czm_material czm_getMaterial(czm_materialInput materialInput) { - czm_material material = czm_getDefaultMaterial(materialInput); - float r = length(materialInput.st - vec2(0.5)) * 2.0; - float band = 0.0; - for (int i = 0; i < 4; i++) { - float inside = radii[i] - r; - if (inside >= 0.0 && inside <= depth) { - float t = 1.0 - inside / depth; - band += alphas[i] * t * t; - } - } - vec4 result = vec4(color.rgb, clamp(band * color.a, 0.0, 1.0)); -#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives)) - // Change in r per CSS pixel: the gradient's length per device pixel, - // times the device pixels in one CSS pixel. - float cssPx = max(length(vec2(dFdx(r), dFdy(r))), 1e-7) * czm_pixelRatio; - float outerHalf = lineWidth * 0.5; - float coreHalf = max(lineWidth - haloWidth, 0.0) * 0.5; - for (int i = 0; i < 4; i++) { - float d = abs(radii[i] - r) / cssPx; - float cover = clamp(outerHalf + 0.5 - d, 0.0, 1.0); - if (cover <= 0.0) continue; - float core = clamp(coreHalf + 0.5 - d, 0.0, 1.0); - vec4 pulse = mix(haloColor, lineColor, core); - result = over(vec4(pulse.rgb, pulse.a * cover * alphas[i]), result); - } -#endif - material.diffuse = result.rgb; - material.alpha = result.a; - return material; -} -`; - -/** - * The pulses: one flat, translucent, unpickable disc the size of the range - * ring whose shader draws each pulse line and the band behind it. Drawing - * them here rather than as entities keeps them out of picking, so clicks and - * taps near a pulse still reach the contact underneath. Moving pulses only - * change its uniforms; the disc is rebuilt only when the subject moves. - * @param {Cesium.Cartesian3} groundCenter Disc centre on the ellipsoid. - * @param {Cesium.Material} material Shared pulse-gradient material. - * @returns {Cesium.Primitive} - */ -function createPulseGradient(groundCenter, material) { - return new Cesium.Primitive({ - geometryInstances: new Cesium.GeometryInstance({ - geometry: new Cesium.EllipseGeometry({ - center: groundCenter, - semiMajorAxis: AWARENESS_RADIUS_M, - semiMinorAxis: AWARENESS_RADIUS_M, - height: CONTEXT_RIM_HEIGHT_M, - granularity: Cesium.Math.toRadians( - AWARENESS_RANGE_PULSE.gradientGranularityDeg, - ), - vertexFormat: - Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat, - }), - }), - appearance: new Cesium.MaterialAppearance({ - material, - flat: true, - translucent: true, - faceForward: true, - }), - asynchronous: false, - allowPicking: false, - }); -} - -/** - * The ring's polyline geometry: `AWARENESS_RANGE_RING_STYLE.width` screen - * pixels, straight chords between the given positions (they already follow - * the surface), in the material appearance's vertex format. - * @param {Cesium.Cartesian3[]} positions Ring positions. - * @returns {object} PolylineGeometry options. - */ -export function awarenessRingGeometryOptions(positions) { - return { - positions, - width: AWARENESS_RANGE_RING_STYLE.width, - arcType: Cesium.ArcType.NONE, - vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT, - }; -} - -/** - * The 250 km ring as an unpickable polyline primitive in the ring's outline - * material, so a click or tap on its edge reaches the contact underneath. - * Its positions are geometry, so a moved subject rebuilds it; the material - * is shared between builds so a flash keeps going. - * @param {Cesium.Cartesian3[]} positions Ring positions. - * @param {Cesium.Material} material Shared PolylineOutline material. - * @returns {Cesium.Primitive} - */ -function createRingPrimitive(positions, material) { - return new Cesium.Primitive({ - geometryInstances: new Cesium.GeometryInstance({ - geometry: new Cesium.PolylineGeometry( - awarenessRingGeometryOptions(positions), - ), - }), - appearance: new Cesium.PolylineMaterialAppearance({ - material, - translucent: true, - }), - asynchronous: false, - allowPicking: false, - }); -} - -/** - * The rotation about the Earth's centre that carries `from` onto `to`, as a - * model matrix, so a disc built around `from` sits around `to`. - * @param {Cesium.Cartesian3} from Where the disc was built. - * @param {Cesium.Cartesian3} to Where it should be. - * @param {Cesium.Matrix4} [result] - * @returns {Cesium.Matrix4} - */ -export function discFollowMatrix(from, to, result = new Cesium.Matrix4()) { - const a = Cesium.Cartesian3.normalize(from, new Cesium.Cartesian3()); - const b = Cesium.Cartesian3.normalize(to, new Cesium.Cartesian3()); - const axis = Cesium.Cartesian3.cross(a, b, new Cesium.Cartesian3()); - const sin = Cesium.Cartesian3.magnitude(axis); - if (sin < 1e-12) return Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, result); - const angle = Math.atan2(sin, Cesium.Cartesian3.dot(a, b)); - const rotation = Cesium.Matrix3.fromQuaternion( - Cesium.Quaternion.fromAxisAngle( - Cesium.Cartesian3.divideByScalar(axis, sin, axis), - angle, - ), - ); - return Cesium.Matrix4.fromRotationTranslation( - rotation, - Cesium.Cartesian3.ZERO, - result, - ); -} - -/** Camera height above the ellipsoid, or NaN when the scene cannot say. */ -function cameraHeightM(scene) { - return scene.camera?.positionCartographic?.height ?? Number.NaN; -} - -/** - * The range ring and pulses of one awareness layer on its Cesium viewer. - * `layerState.visual` is what is drawn now, or null. - * @param {object} options - * @param {object} options.state - * @param {(reason: string) => void} options.governorRequestRender - * @param {(subject: object) => void} options.redraw Draws the subject's - * ring again by whichever path its viewer takes (a reduced-motion change). - */ -export function createRangeRingCesium({ - state: layerState, - governorRequestRender, - redraw, -}) { - /** Whether the ring and pulses can be drawn on `viewer`. */ - const drawsOn = (viewer) => - viewer?.scene?.primitives instanceof Cesium.PrimitiveCollection; - - /** - * Run the range pulses again for `activeMs`, after a camera move. Call it - * during a frame (lifecycle's preRender): that frame's postRender arms the - * next request, so waking asks for no extra frame of its own. - */ - function wakePulses() { - const wake = layerState.visual?.wake; - if (!wake) return; - wakeAwarenessPulses(wake, performance.now()); - followPulseDisc(); - } - - /** - * Keep the pulse disc centred on the subject. Within `gradientRebuildM` of - * where it was built, the disc is rotated about the Earth's centre onto - * the subject by its model matrix, which keeps it concentric with the ring - * at no build cost; the ellipsoid curves a little differently from that - * sphere, a few tens of metres in height at 20 km. Further away it is - * rebuilt, which costs a few milliseconds. - */ - function followPulseDisc() { - const { gradient, gradientCenter, center } = layerState.visual; - if (!gradient) return; - if ( - Cesium.Cartesian3.distance(gradientCenter, center) < - AWARENESS_RANGE_PULSE.gradientRebuildM - ) { - gradient.modelMatrix = discFollowMatrix( - gradientCenter, - center, - gradient.modelMatrix, - ); - return; - } - const { primitives } = layerState.visual; - layerState.visual.gradient = primitives.add( - createPulseGradient(center, gradient.appearance.material), - ); - // Primitive.destroy leaves the material alone, so the new disc keeps - // sharing it. - primitives.remove(gradient); - Cesium.Cartesian3.clone(center, gradientCenter); - } - - function clearVisual() { - layerState.visual?.stopPulses?.(); - layerState.visual?.removeMotionListener?.(); - // Out of the collection they were drawn in, which is another viewer's - // once the layer has been initialized again. - const primitives = layerState.visual?.primitives; - if (layerState.visual?.gradient) - primitives.remove(layerState.visual.gradient); - if (layerState.visual?.ringPrimitive) { - primitives.remove(layerState.visual.ringPrimitive); - // Idle mode renders only on request; a removed ring must not linger. - governorRequestRender('awareness-visual'); - } - clearAwarenessEchoField(); - layerState.visual = null; - } - - function renderVisual(subject) { - if (!layerState.viewer || !subject?.position) return; - const cartographic = Cesium.Cartographic.fromCartesian(subject.position); - if (!cartographic) return; - const groundCenter = Cesium.Cartesian3.fromRadians( - cartographic.longitude, - cartographic.latitude, - 0, - ); - const key = `${subject.layerId}:${subject.id}`; - const reducedMotion = prefersReducedMotion(); - // A reduced-motion change rebuilds the visual, with or without pulses; - // so does a ring drawn on another viewer (the layer re-initialized). - if ( - layerState.visual?.key === key && - layerState.visual.primitives === layerState.viewer.scene.primitives && - layerState.visual.reducedMotion === reducedMotion - ) { - // Move the ring only after a meaningful displacement so live tracking - // does not rebuild its geometry for sub-pixel motion every 750 ms. - if ( - Cesium.Cartesian3.distance(layerState.visual.center, groundCenter) >= - 250 - ) { - const positions = awarenessRangeRingPositions( - groundCenter, - AWARENESS_RADIUS_M, - CONTEXT_RIM_HEIGHT_M, - ); - // The echo field reads `visual.center` in place and follows on its - // own. The pulse disc follows by its model matrix and is rebuilt only - // every `gradientRebuildM`: a build costs a few milliseconds. - layerState.visual.ringPositions = positions; - const { ringPrimitive } = layerState.visual; - const { primitives } = layerState.visual; - layerState.visual.ringPrimitive = primitives.add( - createRingPrimitive(positions, ringPrimitive.appearance.material), - ); - primitives.remove(ringPrimitive); - Cesium.Cartesian3.clone(groundCenter, layerState.visual.center); - // A resting disc is hidden, so it catches up when the pulses wake. - if (performance.now() < layerState.visual.wake?.untilMs) - followPulseDisc(); - // Content actually changed — buy exactly one frame instead of holding. - governorRequestRender('awareness-visual'); - } - return; - } - clearVisual(); - - const scene = layerState.viewer.scene; - // A scene without a preRender hook (headless tools, partial stubs) gets - // the static ring only, as the Cyber sonar scene does. So does a viewer - // who prefers reduced motion. - const animate = Boolean( - !reducedMotion && - scene.preRender?.addEventListener && - scene.postRender?.addEventListener, - ); - // Pulses run from now until `wake.untilMs`, then rest. - const wake = animate - ? wakeAwarenessPulses( - { startMs: -Infinity, untilMs: -Infinity }, - performance.now(), - ) - : null; - // From a camera below the rim height the disc would sweep across the sky, - // so it is hidden there, and the pulses rest with it: no flash, no - // echoes, no frames. - const belowRim = () => cameraHeightM(scene) < CONTEXT_RIM_HEIGHT_M; - const levelAt = (nowMs) => - wake && !belowRim() ? awarenessPulseLevel(nowMs, wake) : 0; - - // A polyline, not an ellipse outline: WebGL draws ellipse outlines at - // 1 px whatever `outlineWidth` says, and the ring needs a halo. - const ring = AWARENESS_RANGE_RING_STYLE; - const core = Cesium.Color.fromCssColorString(ring.color); - const halo = Cesium.Color.fromCssColorString(ring.outlineColor); - const ringPositions = awarenessRangeRingPositions( - groundCenter, - AWARENESS_RADIUS_M, - CONTEXT_RIM_HEIGHT_M, - ); - // While pulses run, the ring flashes as each one arrives and otherwise - // dims to `restOpacity`; as they settle it returns to full and stays. - const ringAlpha = (nowMs) => { - const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs)); - return 1 - levelAt(nowMs) * (1 - pulsed); - }; - const ringMaterial = Cesium.Material.fromType('PolylineOutline', { - color: core.clone(), - outlineColor: halo.clone(), - outlineWidth: ring.outlineWidth, - }); - const ringPrimitive = scene.primitives.add( - createRingPrimitive(ringPositions, ringMaterial), - ); - - const center = Cesium.Cartesian3.clone(groundCenter); - let gradient = null; - let stopPulses = null; - if (animate) { - const pulse = AWARENESS_RANGE_PULSE; - const count = Math.min(pulse.count, AWARENESS_PULSE_GRADIENT_MAX); - const uniforms = { - color: core.clone(), - lineColor: core.clone(), - haloColor: halo.clone(), - radii: new Cesium.Cartesian4(), - alphas: new Cesium.Cartesian4(), - depth: pulse.gradientDepthFraction, - lineWidth: pulse.width, - haloWidth: pulse.outlineWidth, - }; - uniforms.color.alpha = pulse.gradientOpacity; - // A named type: Cesium caches every material type for the page's - // lifetime, so an unnamed fabric (a fresh GUID each time) would leave - // one entry per new visual. Built from the cached template, the - // uniforms come back as plain copies; restore this visual's own. - const material = new Cesium.Material({ - fabric: { - type: AWARENESS_PULSE_MATERIAL_TYPE, - uniforms, - source: PULSE_GRADIENT_SOURCE, - }, - translucent: true, - }); - Object.assign(material.uniforms, uniforms); - gradient = scene.primitives.add( - createPulseGradient(groundCenter, material), - ); - const radii = [0, 0, 0, 0]; - const alphas = [0, 0, 0, 0]; - const removePreRender = scene.preRender.addEventListener(() => { - const nowMs = performance.now(); - const level = levelAt(nowMs); - const alpha = ringAlpha(nowMs); - ringMaterial.uniforms.color.alpha = core.alpha * alpha; - ringMaterial.uniforms.outlineColor.alpha = halo.alpha * alpha; - // The disc is looked up each frame: a subject move swaps it. - const disc = layerState.visual?.gradient; - if (disc) disc.show = level > 0; - for (let index = 0; index < count; index++) { - const state = awarenessPulseState(nowMs, index); - radii[index] = state.radiusM / AWARENESS_RADIUS_M; - alphas[index] = state.alpha * level; - } - Cesium.Cartesian4.fromArray(radii, 0, material.uniforms.radii); - Cesium.Cartesian4.fromArray(alphas, 0, material.uniforms.alphas); - }); - // Each drawn frame, whoever asked for it, arms one request a Cyber - // sonar interval later, as the Cyber sonar scene does. Requests never - // land within 80 ms of a frame, so they cannot beat the detection - // lane's 80 ms gate, and they stop once the pulses rest. - let timer = null; - const removePostRender = scene.postRender.addEventListener(() => { - globalThis.clearTimeout(timer); - timer = null; - if (performance.now() < wake.untilMs && !belowRim()) - timer = globalThis.setTimeout(() => { - timer = null; - governorRequestRender('awareness-pulse'); - }, CYBER_SONAR_RENDER_INTERVAL_MS); - }); - stopPulses = () => { - removePreRender(); - removePostRender(); - globalThis.clearTimeout(timer); - timer = null; - }; - // The detection overlay pulses the brackets of flights and vessels a - // front crosses; it reads the centre in place, so it follows too. - setAwarenessEchoField({ - center, - radiusM: AWARENESS_RADIUS_M, - pulse, - echo: AWARENESS_RANGE_ECHO, - level: levelAt, - }); - } - - // Turning reduced motion on or off mid-session rebuilds the visual. - const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY); - const onMotionChange = () => { - if (layerState.subject) redraw(layerState.subject); - }; - // Safari before 14 has only the older addListener / removeListener. - if (motionQuery?.addEventListener) - motionQuery.addEventListener('change', onMotionChange); - else motionQuery?.addListener?.(onMotionChange); - - layerState.visual = { - key, - primitives: scene.primitives, - ringPrimitive, - ringPositions, - center, - gradient, - gradientCenter: Cesium.Cartesian3.clone(groundCenter), - reducedMotion, - wake, - stopPulses, - removeMotionListener: () => { - if (motionQuery?.removeEventListener) - motionQuery.removeEventListener('change', onMotionChange); - else motionQuery?.removeListener?.(onMotionChange); - }, - }; - governorRequestRender('awareness-visual'); - } - return { drawsOn, renderVisual, clearVisual, wakePulses }; -} diff --git a/src/layers/awareness/rendering.js b/src/layers/awareness/rendering.js index 25d170074..ebfde0346 100644 --- a/src/layers/awareness/rendering.js +++ b/src/layers/awareness/rendering.js @@ -9,22 +9,13 @@ import { AWARENESS_RADIUS_M, } from '../../data/militaryAwarenessEngine.js'; import { bearingBetweenCoordinates } from '../../cockpitMath.js'; -import { - AWARENESS_PAGE_SIZE, - AWARENESS_RANGE_RING_STYLE, - CONTEXT_RIM_HEIGHT_M, -} from './policy.js'; -import { - awarenessRangeRingPositions, - createRangeRingCesium, -} from './rangeRingCesium.js'; +import { AWARENESS_PAGE_SIZE } from './policy.js'; +import { createRangeRing } from './rangeRing.js'; import { formatAwarenessDirection } from './presentation.js'; -import { canvasOf, drawOf, findCamera } from '../../render/rendererOf.js'; +import { canvasOf, findCamera } from '../../render/rendererOf.js'; import { PI_OVER_TWO, - distance, dot, - fromDegrees, normalize, sub, toDegrees, @@ -34,18 +25,14 @@ import { // The ring's and the pulses' own arithmetic, for their tests. export { - AWARENESS_PULSE_GRADIENT_MAX, + AWARENESS_BAND_PIXELS, awarenessPulseLevel, awarenessPulseState, awarenessRangeRingPositions, awarenessRingFlash, - awarenessRingGeometryOptions, - discFollowMatrix, + paintAwarenessBand, wakeAwarenessPulses, -} from './rangeRingCesium.js'; - -/** Each instance's rim set id is its own. */ -let instances = 0; +} from './rangeRing.js'; export function createRendering({ state: layerState, @@ -55,15 +42,8 @@ export function createRendering({ }) { const { getKeyholeGeometry, celestialScreenAngle } = services.geometry; const { governorRequestRender } = services.render; - const rimSetId = `awareness:${++instances}:rim`; - /** The static range ring's draw set, and the viewer it draws on. */ - let rim = null; - /** - * The ring with its pulses, where the viewer can draw them - * (`rangeRingCesium.js`); elsewhere the static ring goes through the draw - * port, below. - */ - const pulsedRing = createRangeRingCesium({ + /** The range ring with its pulses (`rangeRing.js`). */ + const rangeRing = createRangeRing({ state: layerState, governorRequestRender, redraw: (subject) => renderVisual(subject), @@ -312,99 +292,20 @@ export function createRendering({ * next request, so waking asks for no extra frame of its own. */ function wakePulses() { - pulsedRing.wakePulses(); + rangeRing.wakePulses(); } function clearVisual() { - if (layerState.visual?.static) { - rim?.set.clear(); - // Idle mode renders only on request; a removed ring must not linger. - governorRequestRender('awareness-visual'); - layerState.visual = null; - } - pulsedRing.clearVisual(); + rangeRing.clearVisual(); } - /** Let the rim's draw set go, as the layer is destroyed. */ + /** Let the ring's draw sets go, as the layer is destroyed. */ function disposeVisual() { - clearVisual(); - rim?.set.dispose(); - rim = null; - } - - /** The static ring's draw set on the current viewer, made on first use. */ - function rimSet() { - if (rim?.viewer !== layerState.viewer) { - rim?.set.dispose(); - rim = { - viewer: layerState.viewer, - // Unpickable, so a click on the ring's edge reaches the contact - // underneath. - set: drawOf(layerState.viewer).lines({ id: rimSetId, pickable: false }), - }; - } - return rim.set; - } - - /** - * The range ring around a ground point as the draw port draws it: a - * bright core over a dark halo (`AWARENESS_RANGE_RING_STYLE`), straight - * chords between positions that already follow the surface. - */ - function rimItems(groundCenter) { - const ring = AWARENESS_RANGE_RING_STYLE; - const positions = awarenessRangeRingPositions( - groundCenter, - AWARENESS_RADIUS_M, - CONTEXT_RIM_HEIGHT_M, - ); - const line = (id, widthPx, color) => ({ - id, - positions, - widthPx, - mode: '3d', - style: { kind: 'solid', color }, - }); - return [ - line('halo', ring.width, ring.outlineColor), - // The halo is `outlineWidth` of the line's width in all, half on each - // side, as the outline material of the pulsed ring draws it. - line('core', ring.width - ring.outlineWidth, ring.color), - ]; + rangeRing.disposeVisual(); } function renderVisual(subject) { - if (!layerState.viewer || !subject?.position) return; - if (pulsedRing.drawsOn(layerState.viewer)) { - if (layerState.visual?.static) clearVisual(); - pulsedRing.renderVisual(subject); - return; - } - const location = toLonLatH(subject.position); - if (!location) return; - const { lon, lat } = location; - const groundCenter = fromDegrees(lon, lat, 0); - const key = `${subject.layerId}:${subject.id}`; - // A rim drawn on another viewer (the layer re-initialized) is redrawn. - if ( - layerState.visual?.static && - layerState.visual.key === key && - rim?.viewer === layerState.viewer - ) { - // Move the large ring only after a meaningful displacement so live - // tracking does not rebuild it for sub-pixel motion every 750 ms. - if (distance(layerState.visual.center, groundCenter) >= 250) { - rimSet().set(rimItems(groundCenter)); - layerState.visual.center = groundCenter; - // Content actually changed — buy exactly one frame instead of holding. - governorRequestRender('awareness-visual'); - } - return; - } - clearVisual(); - rimSet().set(rimItems(groundCenter)); - layerState.visual = { key, center: groundCenter, static: true }; - governorRequestRender('awareness-visual'); + rangeRing.renderVisual(subject); } return { ensureDirectionOverlay, diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 1432993f3..8a33afc62 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -1777,7 +1777,18 @@ export function createCesiumDraw({ source: FLOW_SOURCE, }; case 'solid': - return { type: 'Color', uniforms: { color: toColor(style.color) } }; + // An outlined line keeps its edge in one material: two lines + // stacked would darken where their translucent passes overlap. + return style.outline + ? { + type: 'PolylineOutline', + uniforms: { + color: toColor(style.color), + outlineColor: toColor(style.outline.color), + outlineWidth: style.outline.widthPx, + }, + } + : { type: 'Color', uniforms: { color: toColor(style.color) } }; case 'glow': return { type: 'PolylineGlow', @@ -2030,7 +2041,7 @@ export function createCesiumDraw({ if (!item.overlaid || !deep || revealed(item)) return false; if (!flatEquals(item.positions, part.overlayFrom)) return false; // Only its colour may have changed (`patchLines` checked its look). - deep.appearance.material.uniforms.color = toColor(item.style.color); + paintLine(deep.appearance.material, item.style); deep.depthFailAppearance.material.uniforms.color = toColor( item.style.color, ); @@ -2266,6 +2277,9 @@ export function createCesiumDraw({ // change it takes in place: kept for lines that can settle. shape: settled ? looks.shape(item) : null, positions: settled ? flatPositions(item.positions) : null, + // An outlined line, which never settles, takes its colours in + // place too: how it draws but for them. + outlined: item.style.outline ? looks.shape(item) : null, id, polyline, reveal, @@ -2343,6 +2357,23 @@ export function createCesiumDraw({ replaceHost(record, collect(own, ground), ground, own); } + /** A line style but for its colours, which its material takes in place. */ + const colourlessStyle = (style) => + style.outline + ? { + ...style, + color: undefined, + outline: { ...style.outline, color: undefined }, + } + : { ...style, color: undefined }; + + /** Give a line's material its style's colours, its outline's too. */ + function paintLine(material, style) { + material.uniforms.color = toColor(style.color); + if (style.outline && 'outlineColor' in material.uniforms) + material.uniforms.outlineColor = toColor(style.outline.color); + } + /** * How a line draws, but for where it runs, whether it shows and how much * of it is revealed: lines that keep it can be changed in place. @@ -2352,7 +2383,7 @@ export function createCesiumDraw({ item.mode, item.widthPx, item.clampTo, - colourless ? { ...item.style, color: undefined } : item.style, + colourless ? colourlessStyle(item.style) : item.style, // The same depth-fail style in any key order. item.depthFail ? [ @@ -2471,11 +2502,15 @@ export function createCesiumDraw({ /** * Whether an undraped line that can settle (in the collection or a - * static batch) changes only its colour: it takes the new one in place. + * static batch), or an outlined one in the collection, changes only its + * colours: it takes the new ones in place. */ const recolourableSolid = (was, item, looks) => - Boolean((was.polyline || was.batched) && was.shape) && - was.shape === looks.shape(item); + (Boolean((was.polyline || was.batched) && was.shape) && + was.shape === looks.shape(item)) || + (Boolean(was.polyline && was.outlined) && + !revealed(item) && + was.outlined === looks.shape(item)); /** * Whether a line drawn over the surface for a draped one changes only its @@ -2588,8 +2623,7 @@ export function createCesiumDraw({ if (!shared) return false; // Shared materials take their one colour once, before lines move off // them. - for (const [material, item] of shared) - material.uniforms.color = toColor(item.style.color); + for (const [material, item] of shared) paintLine(material, item.style); for (let k = 0; k < list.length; k++) { const item = list[k]; const was = parts.get(item.id); @@ -2600,8 +2634,7 @@ export function createCesiumDraw({ } if (was.look !== looks[k] && was.deep === undefined) { // A line drawing on a shared material took its colour above. - if (!was.shared || was.solo) - was.material.uniforms.color = toColor(item.style.color); + if (!was.shared || was.solo) paintLine(was.material, item.style); was.look = looks[k]; } if (was.deep !== undefined) { @@ -2697,6 +2730,8 @@ export function createCesiumDraw({ item.frame !== 'inertial' && !item.depthFail && item.style.kind === 'solid' && + // A batch draws one colour per line, no outline. + !item.style.outline && !revealed(item) && // The collection draws no line under half a pixel wide; a batch // would. @@ -2792,8 +2827,7 @@ export function createCesiumDraw({ const positions = linePositions(item); was.polyline.positions = positions; was.polyline.show = show; - if (recolour) - was.polyline.material.uniforms.color = toColor(item.style.color); + if (recolour) paintLine(was.polyline.material, item.style); if (was.reveal) was.reveal.uniforms.reveal = revealUniform( item.revealFraction, @@ -3575,6 +3609,7 @@ export function createCesiumDraw({ * hides it: a colour drawn opaque cannot become translucent in place. */ function solidPatchable(part, item) { + if (part.image) return imagePatchable(part, item); if (!colourOnly(part.look, item)) return false; if (part.fill?.isDestroyed?.() || part.outline?.isDestroyed?.()) return false; @@ -3594,6 +3629,52 @@ export function createCesiumDraw({ ); } + /** + * Whether an unclamped image fill's upsert changes only its image (a + * canvas, under a new key for new content), its show or its `meta`: its + * texture takes a new canvas in place. + */ + function imagePatchable(part, item) { + const fill = item.fill; + if (!fill || typeof fill !== 'object' || Array.isArray(fill)) return false; + if (!fill.image?.canvas || item.animate || part.pulse) return false; + if (!part.fill || part.fill.isDestroyed() || !part.fill.ready) return false; + const { fill: was, ...look } = part.look; + const { fill: now, show, meta, ...next } = item; + return ( + sameValues(look, next) && + sameValues(was.repeat ?? null, fill.repeat ?? null) + ); + } + + /** + * An image fill's texture takes `canvas`: copied into the texture it has + * where the size is the same, else a texture of its own, which the + * material holds (and destroys) from this frame on. Without a drawing + * context (a scene with no WebGL), the material takes the canvas, as it + * did when built. + */ + function writeImage(part, canvas) { + const image = part.image; + const context = scene.context; + if (!context) { + image.material.uniforms.image = canvas; + return; + } + const texture = image.texture; + if ( + texture && + !texture.isDestroyed() && + texture.width === canvas.width && + texture.height === canvas.height + ) { + texture.copyFrom({ source: canvas }); + return; + } + image.texture = new Cesium.Texture({ context, source: canvas }); + image.material.uniforms.image = image.texture; + } + /** An instance's colour, in a ready primitive. */ function colourOn(primitive, id, color) { const attributes = primitive.getGeometryInstanceAttributes(id); @@ -3605,6 +3686,9 @@ export function createCesiumDraw({ /** An unclamped shape changed in place: its colours, pulse, show and `meta`. */ function patchSolid(part, item) { + const image = part.image ? item.fill.image : null; + if (image && (image.key !== part.look.fill.image.key || !image.key)) + writeImage(part, image.canvas); part.look = lookOf(item); part.pulse = pulseOf(item); part.id.meta = item.meta; @@ -3632,7 +3716,12 @@ export function createCesiumDraw({ ? Cesium.Color.clone(base, result) : base.withAlpha(alpha, result); }; - if (look.fill && part.fill?.ready && !part.fill.isDestroyed()) + if ( + look.fill && + !part.image && + part.fill?.ready && + !part.fill.isDestroyed() + ) colourOn(part.fill, part.id, tint(look.fill, scratchColour)); if (look.outline) { if (part.outline?.ready && !part.outline.isDestroyed()) @@ -3941,7 +4030,10 @@ export function createCesiumDraw({ const material = ownMaterial( imageMaterial(toImage(imageFill.image), imageFill.repeat), ); - host.add( + // Its image is changed in place (`writeImage`); it never recolours. + part.image = { material, texture: null }; + part.translucent.fill = true; + part.fill = host.add( new Cesium.Primitive({ geometryInstances: new Cesium.GeometryInstance({ geometry: shape.fill, diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 8e12a44b0..789da624c 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -2208,19 +2208,24 @@ test('the context layer draws its static range ring as a haloed line on a viewer const linesOf = (from = scene) => { const [host] = from.added; const lines = []; - for (let i = 0; i < host.length; i++) { - const collection = host.get(i); + if (!host) return lines; + // Lines that never settle are drawn by the collection alone. + const collections = + host instanceof Cesium.PolylineCollection + ? [host] + : Array.from({ length: host.length }, (_, i) => host.get(i)); + for (const collection of collections) { if (!(collection instanceof Cesium.PolylineCollection)) continue; for (let j = 0; j < collection.length; j++) lines.push(collection.get(j)); } return lines.sort((x, y) => y.width - x.width); }; - const [halo, core] = linesOf(); - assert.equal(linesOf().length, 2, 'a halo and a core, nothing else'); - assert.equal(halo.width, 4); - assert.equal(core.width, 3); - assert.equal(core.material.type, 'Color'); + const [core] = linesOf(); + assert.equal(linesOf().length, 1, 'one line, its halo its outline'); + assert.equal(core.width, 4); + assert.equal(core.material.type, 'PolylineOutline'); + assert.equal(core.material.uniforms.outlineWidth, 1); assert.ok( core.material.uniforms.color.equalsEpsilon( Cesium.Color.fromCssColorString('rgba(98, 181, 255, 0.95)'), @@ -2228,7 +2233,7 @@ test('the context layer draws its static range ring as a haloed line on a viewer ), ); assert.ok( - halo.material.uniforms.color.equalsEpsilon( + core.material.uniforms.outlineColor.equalsEpsilon( Cesium.Color.fromCssColorString('rgba(4, 12, 16, 0.8)'), 1e-9, ), @@ -2247,15 +2252,15 @@ test('the context layer draws its static range ring as a haloed line on a viewer // Small moves keep the ring; one past 250 m moves it. const first = core.positions[0]; rendering.renderVisual(subject(0.001)); - assert.ok(Cesium.Cartesian3.equals(linesOf()[1].positions[0], first)); + assert.ok(Cesium.Cartesian3.equals(linesOf()[0].positions[0], first)); rendering.renderVisual(subject(0.01)); - assert.ok(!Cesium.Cartesian3.equals(linesOf()[1].positions[0], first)); + assert.ok(!Cesium.Cartesian3.equals(linesOf()[0].positions[0], first)); // Re-initialized on another viewer, the same subject's ring moves there. const other = drawOver().scene; state.viewer = { scene: other }; rendering.renderVisual(subject(0.01)); assert.equal(scene.added.length, 0, 'gone from the old viewer'); - assert.equal(linesOf(other).length, 2, 'drawn on the new one'); + assert.equal(linesOf(other).length, 1, 'drawn on the new one'); rendering.clearVisual(); assert.equal(linesOf(other).length, 0); rendering.disposeVisual(); @@ -2929,6 +2934,43 @@ test('many lines left beside a static batch settle as soon as they are unchanged set.dispose(); })); +test('an outlined solid line draws one outline material, recoloured in place, and never settles', () => + withImageClasses(() => { + const s = settlingSet(); + const outlined = (core, halo) => + settleStem('ring', 100, { + widthPx: 4, + style: { + kind: 'solid', + color: core, + outline: { color: halo, widthPx: 1 }, + }, + }); + s.set.set([outlined([0, 0.5, 1, 1], [0, 0, 0, 0.8]), settleStem('a', 200)]); + const line = () => { + const polylines = s.polylines(); + for (let i = 0; i < polylines.length; i++) + if (polylines.get(i).id?.id === 'ring') return polylines.get(i); + return null; + }; + const first = line(); + assert.equal(first.material.type, 'PolylineOutline'); + assert.equal(first.material.uniforms.outlineWidth, 1); + s.set.upsert([outlined([0, 0.5, 1, 0.4], [0, 0, 0, 0.32])]); + assert.equal(line(), first, 'the same line'); + assert.equal(first.material.uniforms.color.alpha, 0.4); + assert.ok( + Math.abs(first.material.uniforms.outlineColor.alpha - 0.32) < 1e-9, + ); + s.settle(); + const [batch] = s.batches(); + assert.deepEqual( + batch.geometryInstances.map((one) => one.id.id), + ['a'], + ); + s.set.dispose(); + })); + test('a line under half a pixel wide, which the collection does not draw, never settles', () => withImageClasses(() => { const s = settlingSet(); @@ -4149,6 +4191,58 @@ test('an unclamped shape filled with an image draws a textured primitive and fre ); })); +test('an unclamped image fill takes a new canvas in place; anything else about it rebuilds', () => + withImageClasses(() => { + const scene = fakeScene(); + const draw = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }).port; + const set = draw.shapes({ id: 'band' }); + const canvases = [new HTMLCanvasElement(), new HTMLCanvasElement()]; + const band = (k, extra = {}) => ({ + id: 'band', + geometry: { + kind: 'ellipse', + center: { lon: 10, lat: 20, height: 2500 }, + semiMajor: 50_000, + semiMinor: 50_000, + }, + fill: { image: { canvas: canvases[k % 2], key: `band:${k}` } }, + height: 'absolute', + ...extra, + }); + set.set([band(0)]); + const host = scene.added[0]; + const primitive = host.get(0); + const material = primitive.appearance.material; + assert.equal(material.uniforms.image, canvases[0]); + // Not yet drawn, it rebuilds. + set.upsert([band(1)]); + assert.notEqual(scene.added[0], host, 'not yet drawn: rebuilt'); + const drawn = scene.added[0].get(0); + drawn._ready = true; + const drawnMaterial = drawn.appearance.material; + // Drawn, a new canvas, its show and its meta change in place; with no + // drawing context the material takes the canvas itself. + set.upsert([band(2, { meta: 'm', show: false })]); + assert.equal(scene.added[0].get(0), drawn, 'changed in place'); + assert.equal(drawnMaterial.uniforms.image, canvases[0]); + assert.equal(drawn.show, false); + set.upsert([band(3)]); + assert.equal(scene.added[0].get(0), drawn); + assert.equal(drawnMaterial.uniforms.image, canvases[1]); + assert.equal(drawn.show, true); + // The same key is the same image: nothing is written. + drawnMaterial.uniforms.image = 'untouched'; + set.upsert([band(3)]); + assert.equal(drawnMaterial.uniforms.image, 'untouched'); + // Another shape or height rebuilds. + set.upsert([{ ...band(4), height: 'clampGround' }]); + assert.notEqual(scene.added[0].get?.(0), drawn, 'rebuilt'); + set.dispose(); + })); + test('a draped rectangle turns, its image fill with it, on a ground primitive that owns its material', () => withImageClasses(() => { const scene = fakeScene(); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 858fe4c43..fe51488c7 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -1 +1 @@ -["src/layers/awareness/rangeRingCesium.js"] +[] diff --git a/src/render/conformance/goldens/visual/lines-tilted.png b/src/render/conformance/goldens/visual/lines-tilted.png index b6a54860b..689ee620b 100644 Binary files a/src/render/conformance/goldens/visual/lines-tilted.png and b/src/render/conformance/goldens/visual/lines-tilted.png differ diff --git a/src/render/conformance/goldens/visual/lines-top.png b/src/render/conformance/goldens/visual/lines-top.png index d6b72e7db..b9eb8bece 100644 Binary files a/src/render/conformance/goldens/visual/lines-top.png and b/src/render/conformance/goldens/visual/lines-top.png differ diff --git a/src/render/conformance/scenes.js b/src/render/conformance/scenes.js index c6ff7d997..d4ddb3bb2 100644 --- a/src/render/conformance/scenes.js +++ b/src/render/conformance/scenes.js @@ -191,6 +191,18 @@ export const REFERENCE_SCENES = Object.freeze([ mode: '3d', style: { kind: 'solid', color: '#ff3b30' }, }, + { + // A bright core inside a dark edge 2 px wide on each side. + id: 'outlined', + positions: row(800), + widthPx: 8, + mode: '3d', + style: { + kind: 'solid', + color: '#30d158', + outline: { color: '#000000', widthPx: 2 }, + }, + }, { id: 'glow', positions: row(200), diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index 89fd671e9..1ea42ee37 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -192,7 +192,16 @@ export interface PointItem extends Placed { } export type LineStyle = - | { kind: 'solid'; color: Color } + | { + kind: 'solid'; + color: Color; + /** + * A band `widthPx` wide each side, inside the line's width, drawn in + * the same pass as the line: a translucent halo that does not darken + * where it meets the line. Its colour changes in place. + */ + outline?: { color: Color; widthPx: number }; + } | { kind: 'glow'; color: Color; power: number; taper?: number } | { kind: 'dash'; color: Color; length: number; pattern16?: number } | { kind: 'arrow'; color: Color } @@ -216,7 +225,10 @@ export interface LineItem { * How the parts behind the surface draw, solid or dashed; omitted or * `null` hides them. Ignored on draped lines, which are never behind it. */ - depthFail?: Extract | null; + depthFail?: + | { kind: 'solid'; color: Color } + | Extract + | null; /** Per-segment colours; changing them does not rebuild the line. */ segmentColors?: Color[]; segmentShow?: boolean[];