From fcd1c0956535192a53a47d966d95c45939864b62 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 9 Nov 2026 07:38:06 -0800 Subject: [PATCH] render: Cesium draws wind-streamline fields; the wind layer's flow uses the draw port The Cesium draw port now implements draw.field for the windStreamlines kind (src/render/cesium/drawStreamlines.js). It carries the flow shader, the 30-degree cells, horizon and frustum culling and the path tracing over from the wind layer. It moves the highlight on the page's own frames, at most every 32 ms, and only while the field shows, is unpaused, has alpha and some cell is in view on a visible page. A grid no path runs through, or one short of the whole globe, is refused. A rebuild that fails draws nothing and is never told drawn. The wind layer's GPU flow (src/layers/wind/gpuRendering.js) now builds the spec, fades it by camera height and pauses it through the draw, camera and frame ports, and no longer reaches Cesium, so it leaves the Cesium allow list. The layer runs no animation loop of its own while the renderer draws the flow; the canvas fallback is unchanged and still takes over wherever the field is refused. A new conformance check covers the field's 'drawn' events. --- scripts/format-scope.json | 2 + scripts/package-boundaries.json | 11 + src/layers/wind/gpuRendering.js | 340 +++++-------- src/layers/wind/gpuRendering.test.mjs | 517 ++++++------------- src/layers/wind/rendering.js | 41 +- src/layers/wind/rendering.test.mjs | 103 ++-- src/render/cesium/drawFields.js | 25 +- src/render/cesium/drawStreamlines.js | 469 ++++++++++++++++++ src/render/cesium/drawStreamlines.test.mjs | 547 +++++++++++++++++++++ src/render/cesium/harness.js | 1 + src/render/cesiumAllowList.json | 1 - src/render/conformance/checks/ports.js | 58 +++ 12 files changed, 1414 insertions(+), 701 deletions(-) create mode 100644 src/render/cesium/drawStreamlines.js create mode 100644 src/render/cesium/drawStreamlines.test.mjs diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 07f8d9110..e998893e2 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -873,6 +873,8 @@ "src/layers/weather/shellRendering.test.mjs", "src/render/cesium/drawFields.js", "src/render/cesium/drawFields.test.mjs", + "src/render/cesium/drawStreamlines.js", + "src/render/cesium/drawStreamlines.test.mjs", "src/layers/weather/infraredAlpha.js", "src/layers/weather/infraredAlpha.test.mjs", "src/layers/weather/infraredImage.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 5b9bbd12a..1a4e5ca21 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1071,6 +1071,9 @@ "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", @@ -1856,6 +1859,9 @@ "src/render/cesium/screenModulation.js", "src/render/cesium/draw.js", "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", @@ -3059,6 +3065,9 @@ "src/render/cesium/tileRequests.js", "src/render/cesium/draw.js", "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", @@ -3300,6 +3309,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawQuads.js", "src/render/cesium/drawModels.js", @@ -4313,6 +4323,7 @@ "src/render/cesium/heights.js", "src/render/cesium/draw.js", "src/render/cesium/drawFields.js", + "src/render/cesium/drawStreamlines.js", "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", "src/render/cesium/drawModels.js", diff --git a/src/layers/wind/gpuRendering.js b/src/layers/wind/gpuRendering.js index 0873fa63b..ec9ea018d 100644 --- a/src/layers/wind/gpuRendering.js +++ b/src/layers/wind/gpuRendering.js @@ -1,266 +1,172 @@ import { - bakeWindStreamlines, - groupWindPaths, WIND_DISPLAY_HEIGHT_METERS, - WIND_PATH_LIMIT, WIND_NARROW_PATH_LIMIT, + WIND_PATH_LIMIT, + WIND_PATH_STEPS, } from './streamlines.js'; +import { + canvasOf, + findCamera, + findDraw, + findFrame, + rendererOf, +} from '../../render/rendererOf.js'; const WIND_FADE_LOW_METERS = 15000; const WIND_FADE_HIGH_METERS = 60000; +// The streamlines' colour: the ghost and the trail; the moving tip brightens it. +const WIND_STREAMLINE_COLOR = '#80c9e6'; +const WIND_STREAMLINE_WIDTH_PX = 2.4; -// Original material: a persistent fine curve plus a moving, tapered highlight. -// The integer part of s identifies a path; its fractional part follows the wind. -const FLOW_MATERIAL = ` -in float v_windFacing; -czm_material czm_getMaterial(czm_materialInput materialInput) -{ - czm_material material = czm_getDefaultMaterial(materialInput); - float pathId = floor(materialInput.st.s); - float along = fract(materialInput.st.s); - float offset = fract((pathId + 1.0) * 0.61803398875); - float behind = fract(phaseTime * 0.16 + offset - along); - float tail = (1.0 - smoothstep(0.0, 0.32, behind)); - float tip = 1.0 - smoothstep(0.0, 0.045, behind); - float ends = smoothstep(0.0, 0.055, along) * (1.0 - smoothstep(0.945, 1.0, along)); - float edge = 1.0 - smoothstep(0.26, 0.5, abs(materialInput.st.t - 0.5)); - float horizon = smoothstep(0.0, 0.065, v_windFacing); - material.diffuse = mix(vec3(0.50, 0.79, 0.90), vec3(0.91, 0.99, 1.0), tip); - material.alpha = (ghostAlpha + 0.64 * tail + 0.16 * tip) * ends * edge * horizon * heightFade; - return material; -}`; +let fieldIds = 0; -/** Native Cesium geometry/material owner. No animation loop or DOM ownership. */ -export function createWindGpuRendering({ cesium: C, getViewer }) { - const cells = []; - let occluder = null; - let collection = null; - let material = null; +/** The streamline fade for a camera this high: none low down, full from 60 km. */ +export function windHeightFade(height) { + return Math.max( + 0, + Math.min( + 1, + (height - WIND_FADE_LOW_METERS) / + (WIND_FADE_HIGH_METERS - WIND_FADE_LOW_METERS), + ), + ); +} + +/** + * A wind grid as the draw port's `windStreamlines` field: samples are + * points, the first column at `lo1` and the first row at `la1`, rows + * running south; a grid that wraps the globe spans 360° of longitude. + */ +export function windStreamlineSpec(field, { id, pathBudget, alpha, paused }) { + const span = field.nx * field.dx; + const wraps = span >= 360 - 1e-9; + const west = field.lo1; + const north = field.la1; + return { + kind: 'windStreamlines', + id, + u: field.u, + v: field.v, + width: field.nx, + height: field.ny, + rectangle: { + west, + south: north - (field.ny - 1) * field.dy, + east: west + (wraps ? span : (field.nx - 1) * field.dx), + north, + }, + pathBudget, + steps: WIND_PATH_STEPS, + style: { color: WIND_STREAMLINE_COLOR, widthPx: WIND_STREAMLINE_WIDTH_PX }, + heightM: WIND_DISPLAY_HEIGHT_METERS, + alpha, + paused, + }; +} + +/** + * Streamlines through the draw port's `windStreamlines` field (capability + * `fields`): the renderer traces, draws, culls and animates them; this + * fades them by camera height and pauses them. Where the renderer has no + * such field, or refuses this one, `setField` answers false and the layer + * paints on its canvas instead. No animation loop or DOM ownership. + */ +export function createWindGpuRendering({ + getViewer, + drawOf = findDraw, + cameraOf = findCamera, + frameOf = findFrame, +} = {}) { + let handle = null; let paused = false; let destroyed = false; + let heightFade = 0; + let drawn = false; const emptyDiagnostics = () => ({ pathCount: 0, - vertexCount: 0, buildMs: 0, error: null, - cellCount: 0, - visibleCells: 0, - visibleVertexCount: 0, heightFade: 0, }); let diagnostics = emptyDiagnostics(); + const viewer = () => getViewer?.() ?? null; function supported() { - const scene = getViewer?.()?.scene; - return ( - !destroyed && - Boolean( - scene?.primitives && - C?.Primitive && - C?.GeometryInstance && - C?.GeometryInstanceAttribute && - C?.ComponentDatatype?.FLOAT !== undefined && - C?.PolylineGeometry && - C?.PolylineMaterialAppearance && - C?.Material && - C?.BoundingSphere?.fromPoints && - C?.Occluder && - C?.Ellipsoid?.WGS84 && - C?.Intersect && - C?.Cartesian3?.fromDegrees, - ) && - (C.SceneMode?.SCENE3D === undefined || - scene.mode === undefined || - scene.mode === C.SceneMode.SCENE3D) - ); + const host = viewer(); + if (destroyed || !host) return false; + const capabilities = rendererOf(host)?.capabilities; + if (capabilities && !capabilities.has('fields')) return false; + return typeof drawOf(host)?.field === 'function'; } function clear() { - for (const cell of cells) { - collection?.remove(cell.primitive); - if (!cell.primitive.isDestroyed?.()) cell.primitive.destroy?.(); - } - cells.length = 0; - occluder = null; - collection = null; - material?.destroy?.(); - material = null; + handle?.dispose(); + handle = null; + drawn = false; diagnostics = emptyDiagnostics(); } + function readFade() { + const height = cameraOf(viewer())?.pose?.().height; + return Number.isFinite(height) ? windHeightFade(height) : heightFade; + } + function setField(field) { clear(); if (!supported() || !field) return false; const started = globalThis.performance?.now?.() ?? Date.now(); + const width = canvasOf(viewer())?.clientWidth; + const pathBudget = + width > 0 && width < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT; + heightFade = readFade(); try { - const width = getViewer().scene.canvas?.clientWidth; - const budget = - width > 0 && width < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT; - const paths = bakeWindStreamlines(field, { count: budget }); - if (!paths.length) return false; - let vertexCount = 0; - material = new C.Material({ - fabric: { - type: 'GevWindStreamline', - uniforms: { - phaseTime: 0, - ghostAlpha: paused ? 0.34 : 0.25, - heightFade: 0, - }, - source: FLOW_MATERIAL, - }, - translucent: () => true, - }); - const base = new C.PolylineMaterialAppearance({ material }); - // Extend the public default shader rather than duplicate Cesium's polyline - // expansion/precision code. Explicit facing also masks the far hemisphere - // when a scene chooses not to preserve globe depth for translucent objects. - const source = base.vertexShaderSource; - if ( - !/void\s+main\s*\(\s*\)/.test(source) || - !/v_st\.s\s*=\s*st\.s\s*;/.test(source) - ) - throw new Error('Wind polyline shader entry unavailable'); - const seededSource = source.replace( - /v_st\.s\s*=\s*st\.s\s*;/, - 'v_st.s = st.s * 0.999 + czm_batchTable_windSeed(batchId);', + handle = drawOf(viewer()).field( + windStreamlineSpec(field, { + id: `wind-streamlines:${(fieldIds += 1)}`, + pathBudget, + alpha: heightFade, + paused, + }), ); - const vertexShaderSource = - `out float v_windFacing;\n${seededSource}`.replace( - /void\s+main\s*\(\s*\)\s*\{/, - `void main() {\nvec3 windWorld = (czm_model * vec4(position3DHigh + position3DLow, 1.0)).xyz;\nv_windFacing = dot(normalize(windWorld), normalize(czm_viewerPositionWC - windWorld));\n`, - ); - const scene = getViewer().scene; - collection = scene.primitives; - // EllipsoidalOccluder only tests points. Use Cesium's sphere occluder - // with an inscribed Earth sphere, independent of scene.globe.show. - occluder = new C.Occluder( - new C.BoundingSphere( - C.Cartesian3.ZERO, - C.Ellipsoid.WGS84.minimumRadius, - ), - scene.camera.positionWC, - ); - for (const group of groupWindPaths(paths)) { - const cellPositions = []; - let cellVertexCount = 0; - const instances = group.paths.map((path) => { - const positions = path.coordinates.map(([lon, lat]) => - C.Cartesian3.fromDegrees(lon, lat, WIND_DISPLAY_HEIGHT_METERS), - ); - // Pass the native description to Cesium's worker. Per-instance seed - // attributes avoid touching the expanded vertex buffer on the UI thread. - const geometry = new C.PolylineGeometry({ - positions, - width: 2.4, - arcType: C.ArcType?.NONE, - vertexFormat: C.PolylineMaterialAppearance.VERTEX_FORMAT, - }); - cellPositions.push(...positions); - cellVertexCount += positions.length * 4 - 4; - return new C.GeometryInstance({ - geometry, - attributes: { - windSeed: new C.GeometryInstanceAttribute({ - componentDatatype: C.ComponentDatatype.FLOAT, - componentsPerAttribute: 1, - value: [path.seed], - }), - }, - }); - }); - const appearance = new C.PolylineMaterialAppearance({ - material, - vertexShaderSource, - translucent: true, - renderState: { depthTest: { enabled: true }, depthMask: false }, - }); - const primitive = new C.Primitive({ - show: false, - geometryInstances: instances, - appearance, - asynchronous: true, - allowPicking: false, - releaseGeometryInstances: true, - compressVertices: false, - }); - const cell = { - primitive, - sphere: C.BoundingSphere.fromPoints(cellPositions), - vertexCount: cellVertexCount, - }; - cells.push(cell); - collection.add(primitive); - vertexCount += cellVertexCount; - } - diagnostics = { - ...emptyDiagnostics(), - cellCount: cells.length, - pathCount: paths.length, - vertexCount, - buildMs: (globalThis.performance?.now?.() ?? Date.now()) - started, - error: null, - }; - return true; } catch (error) { - clear(); + handle = null; diagnostics.error = // i18n-ignore: GPU diagnostics only; the panel never shows this field error instanceof Error ? error.message : 'Wind geometry unavailable'; return false; } + handle.on('drawn', () => { + drawn = true; + // One more frame, so a still scene shows the layer ready. + frameOf(viewer())?.requestRender?.('wind'); + }); + diagnostics = { + ...emptyDiagnostics(), + pathCount: pathBudget, + buildMs: (globalThis.performance?.now?.() ?? Date.now()) - started, + heightFade, + }; + return true; } - // Cesium reuses its frustum culling volume and the occluder's scratch vectors. - // This loop creates no positions, spheres, appearances or per-cell temporaries. - function updateVisibility(camera) { - const height = camera.positionCartographic.height; - const heightFade = Math.max( - 0, - Math.min( - 1, - (height - WIND_FADE_LOW_METERS) / - (WIND_FADE_HIGH_METERS - WIND_FADE_LOW_METERS), - ), - ); - diagnostics.heightFade = heightFade; - if (material) material.uniforms.heightFade = heightFade; - diagnostics.visibleCells = 0; - diagnostics.visibleVertexCount = 0; - let volume; - if (heightFade > 0 && cells.length) { - occluder.cameraPosition = camera.positionWC; - volume = camera.frustum.computeCullingVolume( - camera.positionWC, - camera.directionWC, - camera.upWC, - ); - } - for (let i = 0; i < cells.length; i++) { - const cell = cells[i]; - cell.primitive.show = - heightFade > 0 && - occluder.isBoundingSphereVisible(cell.sphere) && - volume.computeVisibility(cell.sphere) !== C.Intersect.OUTSIDE; - if (cell.primitive.show) { - diagnostics.visibleCells++; - diagnostics.visibleVertexCount += cell.vertexCount; - } - } - return diagnostics.visibleCells > 0 && heightFade > 0; + /** Fade by camera height; whether anything can draw. */ + function updateVisibility() { + const fade = readFade(); + diagnostics.heightFade = fade; + if (handle && fade !== heightFade) handle.update({ alpha: fade }); + heightFade = fade; + return Boolean(handle) && fade > 0; } return { supported, setField, updateVisibility, - tick(elapsedSeconds) { - if (material && !paused && Number.isFinite(elapsedSeconds)) - material.uniforms.phaseTime = Math.max(0, elapsedSeconds) % 10000; - }, setOptions(options = {}) { - if (typeof options.paused === 'boolean') paused = options.paused; - if (material) material.uniforms.ghostAlpha = paused ? 0.34 : 0.25; + if (typeof options.paused !== 'boolean' || options.paused === paused) + return; + paused = options.paused; + handle?.update({ paused }); }, clear, destroy() { @@ -270,7 +176,7 @@ export function createWindGpuRendering({ cesium: C, getViewer }) { getParticleCount: () => diagnostics.pathCount, getDiagnostics: () => ({ ...diagnostics, - ready: cells.length > 0 && cells.every((cell) => cell.primitive.ready), + ready: Boolean(handle) && drawn, mode: 'gpu-streamlines', displayHeightMeters: WIND_DISPLAY_HEIGHT_METERS, }), diff --git a/src/layers/wind/gpuRendering.test.mjs b/src/layers/wind/gpuRendering.test.mjs index 1a420e23b..0723c1711 100644 --- a/src/layers/wind/gpuRendering.test.mjs +++ b/src/layers/wind/gpuRendering.test.mjs @@ -1,147 +1,18 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { createWindGpuRendering } from './gpuRendering.js'; import { - BoundingSphere, - Cartesian3, - Ellipsoid, - Intersect, - Occluder, - PerspectiveFrustum, -} from 'cesium'; -import { bakeWindStreamlines } from './streamlines.js'; + createWindGpuRendering, + windHeightFade, + windStreamlineSpec, +} from './gpuRendering.js'; +import { + WIND_DISPLAY_HEIGHT_METERS, + WIND_NARROW_PATH_LIMIT, + WIND_PATH_LIMIT, + WIND_PATH_STEPS, +} from './streamlines.js'; -function harness({ width = 1000 } = {}) { - const members = new Set(); - let geometryBuilds = 0; - const spheres = []; - const visibility = { - horizon: () => true, - frustum: () => Intersect.INSIDE, - horizonTests: 0, - frustumTests: 0, - }; - let occluderBuilds = 0; - class Material { - constructor(options) { - this.uniforms = options.fabric.uniforms; - this.source = options.fabric.source; - } - destroy() { - assert.ok(!this.destroyed, 'owned resource destroyed once'); - this.destroyed = true; - } - } - class Appearance { - static VERTEX_FORMAT = {}; - constructor(options) { - Object.assign(this, options); - this.vertexShaderSource ??= - 'in vec3 position3DHigh; in vec3 position3DLow; void main() { gl_Position = vec4(0.0); v_st.s = st.s; }'; - } - } - class Polyline { - constructor(options) { - Object.assign(this, options); - } - static createGeometry(options) { - geometryBuilds++; - const st = new Float32Array(options.positions.length * 2); - for (let i = 0; i < options.positions.length; i++) - st[i * 2] = i / (options.positions.length - 1); - return { attributes: { st: { values: st } } }; - } - } - class Primitive { - constructor(options) { - Object.assign(this, options); - this.ready = true; - } - destroy() { - assert.ok(!this.destroyed, 'owned resource destroyed once'); - this.destroyed = true; - } - isDestroyed() { - return Boolean(this.destroyed); - } - } - const C = { - ComponentDatatype: { FLOAT: 5126 }, - GeometryInstanceAttribute: class { - constructor(options) { - Object.assign(this, options); - } - }, - Material, - PolylineMaterialAppearance: Appearance, - PolylineGeometry: Polyline, - Primitive, - GeometryInstance: class { - constructor(options) { - Object.assign(this, options); - } - }, - Cartesian3, - Ellipsoid, - Intersect, - BoundingSphere: class extends BoundingSphere { - static fromPoints(points) { - const sphere = BoundingSphere.fromPoints(points); - spheres.push({ sphere, points }); - return sphere; - } - }, - Occluder: class { - constructor(sphere, cameraPosition) { - occluderBuilds++; - this.cameraPosition = cameraPosition; - } - isBoundingSphereVisible(sphere) { - visibility.horizonTests++; - return visibility.horizon(sphere, this.cameraPosition); - } - }, - ArcType: { NONE: 0 }, - }; - const volume = { - computeVisibility(sphere) { - visibility.frustumTests++; - return visibility.frustum(sphere); - }, - }; - const scene = { - globe: { show: false }, - camera: { - positionWC: Cartesian3.fromDegrees(0, 0, 1e7), - positionCartographic: { height: 1e7 }, - directionWC: new Cartesian3(-1, 0, 0), - upWC: new Cartesian3(0, 0, 1), - frustum: { computeCullingVolume: () => volume }, - }, - canvas: { clientWidth: width }, - primitives: { - add(item) { - members.add(item); - }, - remove(item) { - const removed = members.delete(item); - if (removed) item.destroy(); - return removed; - }, - }, - }; - return { - C, - scene, - members, - builds: () => geometryBuilds, - spheres, - visibility, - occluderBuilds: () => occluderBuilds, - owner: createWindGpuRendering({ cesium: C, getViewer: () => ({ scene }) }), - }; -} -const field = () => ({ +const wind = () => ({ nx: 4, ny: 3, lo1: -180, @@ -152,248 +23,152 @@ const field = () => ({ v: new Float32Array(12), }); -test('GPU owner builds regional native batches; ticks update uniforms without rebuilding geometry', () => { - const h = harness(); - assert.equal(h.owner.setField(field()), true); - assert.equal(h.members.size, 72); - const batch = [...h.members][0]; - assert.equal(batch.allowPicking, false); - assert.equal(batch.asynchronous, true); - assert.ok(batch.appearance.vertexShaderSource.includes('v_windFacing = dot')); - assert.ok( - batch.appearance.material.source.includes( - 'smoothstep(0.0, 0.065, v_windFacing)', - ), - ); - const builds = h.builds(); - assert.equal(builds, 0, 'expanded geometry is deferred to Cesium workers'); - assert.ok( - batch.appearance.vertexShaderSource.includes( - 'czm_batchTable_windSeed(batchId)', - ), - ); - h.owner.tick(3); - assert.equal(batch.appearance.material.uniforms.phaseTime, 3); - h.owner.setOptions({ paused: true }); - h.owner.tick(8); - assert.equal(batch.appearance.material.uniforms.phaseTime, 3); - h.owner.setOptions({ paused: false }); - h.owner.tick(9); - assert.equal(batch.appearance.material.uniforms.phaseTime, 9); - assert.equal(h.builds(), builds); - const diagnostics = h.owner.getDiagnostics(); - assert.ok(diagnostics.pathCount <= 7200); - assert.ok( - diagnostics.pathCount > 7000, - 'desktop retains the requested doubled global density', - ); - assert.ok(diagnostics.vertexCount > 0); - assert.ok( - diagnostics.vertexCount <= 7200 * 128, - 'expanded geometry remains bounded', - ); - assert.equal(diagnostics.ready, true); - assert.equal(diagnostics.displayHeightMeters, 12000); - assert.equal(diagnostics.cellCount, 72); - assert.equal(h.spheres.length, 72); - assert.equal(new Set([...h.members].map((p) => p.appearance)).size, 72); - for (const cell of h.members) { - assert.equal(cell.appearance.material, batch.appearance.material); - assert.equal(cell.appearance.material.uniforms.phaseTime, 9); - assert.equal(cell.appearance.material.uniforms.ghostAlpha, 0.25); - assert.equal(cell.compressVertices, false); - assert.equal(cell.releaseGeometryInstances, true); - } - batch.ready = false; - assert.equal( - h.owner.getDiagnostics().ready, - false, - 'every cell must be ready', - ); - batch.ready = true; - const instances = [...h.members].flatMap((p) => p.geometryInstances); - const baked = bakeWindStreamlines(field()); - assert.equal(instances.length, baked.length); - const bySeed = new Map( - instances.map((i) => [i.attributes.windSeed.value[0], i]), - ); - for (const path of baked) { - assert.deepEqual( - bySeed.get(path.seed).geometry.positions, - path.coordinates.map(([lon, lat]) => - Cartesian3.fromDegrees(lon, lat, 12000), - ), - ); - } - for (const { sphere, points } of h.spheres) { - assert.deepEqual(sphere, BoundingSphere.fromPoints(points)); - for (const point of points) - assert.ok( - Cartesian3.distance(point, sphere.center) <= sphere.radius + 1e-6, - ); - } - for (const instance of instances) { - assert.ok(instance.geometry instanceof h.C.PolylineGeometry); - assert.equal(instance.geometry.width, 2.4); - assert.equal(instance.attributes.windSeed.componentsPerAttribute, 1); - assert.ok(Number.isInteger(instance.attributes.windSeed.value[0])); - } +// A draw port whose fields record what they were asked, a camera at +// `height` and a canvas `width` wide. +function harness({ width = 1000, height = 2_000_000, refuse = null } = {}) { + const fields = []; + const camera = { height }; + const viewer = { canvas: { clientWidth: width } }; + const draw = { + field(spec) { + if (refuse) throw refuse; + const listeners = []; + const handle = { + spec, + updates: [], + disposed: false, + show: true, + update(patch) { + this.updates.push(patch); + }, + on(event, cb) { + assert.equal(event, 'drawn'); + listeners.push(cb); + return () => {}; + }, + dispose() { + assert.equal(this.disposed, false, 'disposed once'); + this.disposed = true; + }, + tell: () => listeners.forEach((cb) => cb()), + }; + fields.push(handle); + return handle; + }, + }; + const frames = []; + const owner = createWindGpuRendering({ + getViewer: () => viewer, + drawOf: () => draw, + cameraOf: () => ({ pose: () => ({ height: camera.height }) }), + frameOf: () => ({ requestRender: (reason) => frames.push(reason) }), + }); + return { owner, fields, camera, viewer, draw, frames }; +} + +test('the fade by camera height is none below 15 km and full from 60 km', () => { + assert.equal(windHeightFade(10_000), 0); + assert.equal(windHeightFade(15_000), 0); + assert.equal(windHeightFade(37_500), 0.5); + assert.equal(windHeightFade(60_000), 1); + assert.equal(windHeightFade(2e7), 1); }); -test('replacement, clear and destroy dispose every owned cell and the shared material', () => { - const h = harness(); - const assertDisposed = (batches) => { - assert.equal(batches.length, 72); - for (const batch of batches) { - assert.equal(batch.destroyed, true); - assert.equal(batch.appearance.material.destroyed, true); - } - }; - h.owner.setField(field()); - const first = [...h.members]; - h.owner.setField(field()); - assertDisposed(first); - const second = [...h.members]; +test('a wind grid becomes a windStreamlines spec over the rectangle its samples span', () => { + const field = wind(); + const spec = windStreamlineSpec(field, { + id: 'w', + pathBudget: 100, + alpha: 0.5, + paused: true, + }); + assert.equal(spec.kind, 'windStreamlines'); + assert.deepEqual(spec.rectangle, { + west: -180, + south: -90, + east: 180, + north: 90, + }); + assert.equal(spec.width, 4); + assert.equal(spec.height, 3); + assert.equal(spec.steps, WIND_PATH_STEPS); + assert.equal(spec.heightM, WIND_DISPLAY_HEIGHT_METERS); + assert.equal(spec.alpha, 0.5); + assert.equal(spec.paused, true); + assert.equal(spec.u, field.u); + assert.equal(spec.v, field.v); + const regional = windStreamlineSpec( + { ...field, nx: 4, ny: 4, lo1: -100, la1: 50, dx: 10, dy: 10 }, + { id: 'r', pathBudget: 1 }, + ); + assert.deepEqual( + regional.rectangle, + { west: -100, south: 20, east: -70, north: 50 }, + 'a regional grid spans its samples and does not wrap', + ); +}); + +test('streamlines draw through the port, faded by height, paused and ready once drawn', () => { + const h = harness({ height: 37_500 }); + assert.equal(h.owner.supported(), true); + assert.equal(h.owner.setField(wind()), true); + const [field] = h.fields; + assert.equal(field.spec.pathBudget, WIND_PATH_LIMIT); + assert.equal(field.spec.alpha, 0.5); + assert.equal(field.spec.paused, false); + assert.equal(h.owner.getDiagnostics().ready, false); + assert.equal(h.owner.getDiagnostics().mode, 'gpu-streamlines'); + assert.equal(h.owner.getParticleCount(), WIND_PATH_LIMIT); + field.tell(); + assert.equal(h.owner.getDiagnostics().ready, true); + assert.deepEqual(h.frames, ['wind'], 'a still scene draws the ready state'); + assert.equal(h.owner.updateVisibility(), true); + assert.deepEqual(field.updates, [], 'an unchanged fade asks nothing'); + h.camera.height = 10_000; + assert.equal(h.owner.updateVisibility(), false, 'nothing draws low down'); + assert.deepEqual(field.updates, [{ alpha: 0 }]); + assert.equal(h.owner.getDiagnostics().heightFade, 0); + h.camera.height = 100_000; + assert.equal(h.owner.updateVisibility(), true); + h.owner.setOptions({ paused: true }); + h.owner.setOptions({ paused: true }); + h.owner.setOptions({ overlay: 'speed' }); + assert.deepEqual(field.updates, [ + { alpha: 0 }, + { alpha: 1 }, + { paused: true }, + ]); + h.owner.setField(wind()); + assert.equal(field.disposed, true, 'a new grid replaces the field'); + assert.equal(h.fields[1].spec.paused, true, 'and keeps the pause'); + assert.notEqual(h.fields[1].spec.id, field.spec.id); h.owner.clear(); - assertDisposed(second); - assert.equal(h.members.size, 0); + assert.equal(h.fields[1].disposed, true); assert.equal(h.owner.getParticleCount(), 0); assert.equal(h.owner.getDiagnostics().ready, false); - h.owner.setField(field()); - const third = [...h.members]; h.owner.destroy(); - assertDisposed(third); - assert.equal(h.members.size, 0); assert.equal(h.owner.supported(), false); - assert.equal(h.owner.setField(field()), false); -}); - -test('unsupported or failed geometry cleanly requests the existing fallback', () => { - const missing = createWindGpuRendering({ - cesium: {}, - getViewer: () => ({ scene: {} }), - }); - assert.equal(missing.setField(field()), false); - const h = harness(); - h.C.PolylineGeometry = class { - constructor() { - throw new Error('test build failure'); - } - }; - assert.equal(h.owner.setField(field()), false); - assert.equal(h.members.size, 0); - assert.match(h.owner.getDiagnostics().error, /test build failure/); + assert.equal(h.owner.setField(wind()), false); }); test('narrow canvases use a lower bounded path budget', () => { - const h = harness({ width: 390 }); - assert.equal(h.owner.setField(field()), true); - assert.ok(h.owner.getParticleCount() <= 1200); - assert.ok(h.owner.getParticleCount() > 1000); + const h = harness({ width: 600 }); + assert.equal(h.owner.setField(wind()), true); + assert.equal(h.fields[0].spec.pathBudget, WIND_NARROW_PATH_LIMIT); }); -test('cell visibility combines horizon, frustum and height with shared fade uniforms', () => { - const h = harness(); - h.owner.setField(field()); - const batches = [...h.members]; - const camera = h.scene.camera; - h.visibility.horizon = (sphere) => - h.spheres.findIndex((s) => s.sphere === sphere) % 2 === 0; - h.visibility.frustum = (sphere) => - h.spheres.findIndex((s) => s.sphere === sphere) % 3 === 0 - ? Intersect.INTERSECTING - : Intersect.OUTSIDE; - assert.equal(h.owner.updateVisibility(camera), true); - assert.equal(h.owner.getDiagnostics().visibleCells, 12); - let vertices = 0; - for (let i = 0; i < batches.length; i++) { - assert.equal(batches[i].show, i % 6 === 0); - if (batches[i].show) - vertices += batches[i].geometryInstances.reduce( - (sum, p) => sum + p.geometry.positions.length * 4 - 4, - 0, - ); - } - assert.equal(h.owner.getDiagnostics().visibleVertexCount, vertices); - assert.equal(h.visibility.horizonTests, 72); - assert.equal(h.visibility.frustumTests, 36); - for (const [height, fade] of [ - [60000, 1], - [37500, 0.5], - [15000, 0], - [1200, 0], - ]) { - camera.positionCartographic.height = height; - assert.equal(h.owner.updateVisibility(camera), fade > 0); - assert.equal(h.owner.getDiagnostics().heightFade, fade); - for (const batch of batches) { - assert.equal(batch.appearance.material.uniforms.heightFade, fade); - assert.match(batch.appearance.material.source, /horizon \* heightFade/); - if (!fade) assert.equal(batch.show, false); - } - } - assert.equal(h.owner.getDiagnostics().visibleVertexCount, 0); - assert.equal(h.owner.getDiagnostics().visibleCells, 0); - assert.equal( - h.visibility.horizonTests, - 216, - 'zero fade skips all sphere tests', - ); - assert.equal(h.visibility.frustumTests, 108); - assert.equal( - h.occluderBuilds(), - 1, - 'occluder is reused across camera updates', - ); -}); - -test('real Cesium sphere culling hides far hemisphere with globe hidden and rejects a sky-facing view', () => { - const h = harness(); - h.C.Occluder = Occluder; - h.owner.setField(field()); - const camera = h.scene.camera; - camera.frustum = new PerspectiveFrustum({ - fov: Math.PI / 3, - aspectRatio: 1.5, - near: 1, - far: 5e7, +test('a refused or missing field falls back to the canvas', () => { + const refused = harness({ refuse: new TypeError('no streamlines here') }); + assert.equal(refused.owner.setField(wind()), false); + assert.equal(refused.owner.getDiagnostics().error, 'no streamlines here'); + assert.equal(refused.owner.getParticleCount(), 0); + const none = createWindGpuRendering({ + getViewer: () => ({}), + drawOf: () => ({}), + cameraOf: () => null, }); - assert.equal(h.owner.updateVisibility(camera), true); - const facingEarth = h.owner.getDiagnostics(); - assert.ok(facingEarth.visibleCells > 0 && facingEarth.visibleCells < 72); - for (let i = 0; i < h.spheres.length; i++) { - const sphere = h.spheres[i].sphere; - if (sphere.center.x < -5e6) assert.equal([...h.members][i].show, false); - } - camera.directionWC.x = 1; - assert.equal(h.owner.updateVisibility(camera), false); - assert.equal(h.owner.getDiagnostics().visibleCells, 0); - camera.positionWC = Cartesian3.fromDegrees(180, 0, 1e7); - assert.equal( - h.owner.updateVisibility(camera), - true, - 'camera position updates the owned horizon test', - ); - h.owner.destroy(); -}); - -test('a failed later cell build releases already installed cells and shared material', () => { - const h = harness(); - const NativePrimitive = h.C.Primitive; - const built = []; - h.C.Primitive = class extends NativePrimitive { - constructor(options) { - if (built.length === 2) throw new Error('later cell failed'); - super(options); - built.push(this); - } - }; - assert.equal(h.owner.setField(field()), false); - assert.equal(h.members.size, 0); - assert.equal(built.length, 2); - for (const batch of built) { - assert.equal(batch.destroyed, true); - assert.equal(batch.appearance.material.destroyed, true); - } - assert.match(h.owner.getDiagnostics().error, /later cell failed/); + assert.equal(none.supported(), false); + assert.equal(none.setField(wind()), false); + const absent = createWindGpuRendering({ getViewer: () => null }); + assert.equal(absent.supported(), false); }); diff --git a/src/layers/wind/rendering.js b/src/layers/wind/rendering.js index cfcf324dc..050bbf362 100644 --- a/src/layers/wind/rendering.js +++ b/src/layers/wind/rendering.js @@ -159,12 +159,10 @@ export function createWindRendering({ let bounds = null; let cameraChanged = true; let painted = 0; - const gpu = createGpuRendering({ cesium, getViewer }); + const gpu = createGpuRendering({ getViewer, drawOf }); let gpuActive = false; - let gpuVisible = false; let reportedGpuReady = null; let gpuNarrow = false; - let flowTime = 0; const relief = createWindRelief({ cesium, getViewer }); const signature = Array(8).fill(null); const wind = { u: 0, v: 0 }; @@ -202,7 +200,7 @@ export function createWindRendering({ canvas && !hidden() && !still() && - (!gpuActive || gpuVisible) && + !gpuActive && frame === null ) frame = globalThis.requestAnimationFrame(draw); @@ -507,14 +505,8 @@ export function createWindRendering({ motionChanged(); visibilityUpdated = true; } - if (gpuActive && viewer && !visibilityUpdated) { - gpuVisible = gpu.updateVisibility(viewer.scene.camera); - if (gpuVisible) schedule(); - else { - cancel(); - lastTime = null; - } - } + // The renderer culls and animates the streamlines; this fades them. + if (gpuActive && viewer && !visibilityUpdated) gpu.updateVisibility(); const ready = gpuActive ? gpu.getDiagnostics().ready : null; if (ready !== reportedGpuReady) { reportedGpuReady = ready; @@ -542,12 +534,7 @@ export function createWindRendering({ const viewer = viewerReady(); if (gpuActive) { if (viewer) updateImageryFade(viewer.scene.camera); - gpuVisible = viewer ? gpu.updateVisibility(viewer.scene.camera) : false; - if (gpuVisible) { - gpu.tick(flowTime); - viewer.scene.requestRender(); - schedule(); - } + if (viewer) gpu.updateVisibility(); return; } if (still() && viewer) paint(viewer, 0, true); @@ -705,26 +692,17 @@ export function createWindRendering({ function draw(time) { frame = null; - if (!running || !field || hidden() || still()) return; - if (gpuActive && !gpuVisible) { - lastTime = null; - return; - } + if (!running || !field || hidden() || still() || gpuActive) return; const viewer = viewerReady(); if (!viewer) return; try { - const resized = !gpuActive && resize(viewer); + const resized = resize(viewer); if (resized) cameraChanged = true; const elapsed = lastTime === null ? 1 / 60 : Math.max(0, (time - lastTime) / 1000); // Limit full particle paints to 30 Hz while preserving elapsed-time motion/fading. if (lastTime === null || elapsed >= 0.032 || cameraChanged) { - if (gpuActive) { - flowTime += elapsed; - gpu.tick(flowTime); - viewer.scene.requestRender(); - cameraChanged = false; - } else paint(viewer, Math.min(0.1, elapsed), false, elapsed); + paint(viewer, Math.min(0.1, elapsed), false, elapsed); lastTime = time; } } catch (error) { @@ -773,7 +751,6 @@ export function createWindRendering({ if (!reuseGeometry) { gpuActive = gpu.supported() && gpu.setField(field); reportedGpuReady = gpuActive ? gpu.getDiagnostics().ready : null; - flowTime = 0; } clearPixels(); particles = []; @@ -827,9 +804,7 @@ export function createWindRendering({ gpu.clear(); relief.clear(); gpuActive = false; - gpuVisible = false; reportedGpuReady = null; - flowTime = 0; removeImagery(); imageryError = null; clearPixels(); diff --git a/src/layers/wind/rendering.test.mjs b/src/layers/wind/rendering.test.mjs index 815f8c90a..2006cecbc 100644 --- a/src/layers/wind/rendering.test.mjs +++ b/src/layers/wind/rendering.test.mjs @@ -453,11 +453,11 @@ test('scalar imagery builds once, survives pause, replaces cleanly, and releases for (const overlay of ['speed', 'pressure', 'temperature']) { test(`${overlay} imagery fades with log camera height and resumes from idle`, () => { + let camera = null; const gpu = { supported: () => true, setField: () => true, - updateVisibility: (camera) => camera.positionCartographic.height > 15000, - tick() {}, + updateVisibility: () => camera.positionCartographic.height > 15000, setOptions() {}, clear() {}, destroy() {}, @@ -465,7 +465,7 @@ for (const overlay of ['speed', 'pressure', 'temperature']) { getDiagnostics: () => ({ ready: true }), }; const h = harness({ createGpuRendering: () => gpu }); - const camera = h.viewer.scene.camera; + camera = h.viewer.scene.camera; const baseAlpha = overlay === 'temperature' ? 1 : 0.85; const snapshot = { grid: FIELD, @@ -673,11 +673,11 @@ test('world-anchored wind glyphs remain readable at low FPS without accelerating h.rendering.destroy(); }); -test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pauses cleanly', () => { +test('GPU flow leaves animation to the renderer, rebuilds only across viewport budgets, and pauses cleanly', () => { let builds = 0, - ticks = 0, cleared = 0, destroyed = 0; + const options = []; const gpu = { supported: () => true, updateVisibility: () => true, @@ -686,10 +686,9 @@ test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pa builds++; return true; }, - tick() { - ticks++; + setOptions(value) { + options.push(value.paused); }, - setOptions() {}, clear() { cleared++; }, @@ -700,16 +699,12 @@ test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pa getDiagnostics: () => ({ ready: true, pathCount: 1 }), }; const h = harness({ createGpuRendering: () => gpu }); - let renders = 0; - h.viewer.scene.requestRender = () => { - renders++; - }; h.rendering.attach(); h.rendering.setField({ grid: FIELD, u: FIELD.u, v: FIELD.v }); h.rendering.start(); - h.callbacks.shift()(16); assert.equal(h.rendering.getDiagnostics().renderMode, 'gpu-streamlines'); - assert.ok(ticks > 0 && renders > 0); + assert.equal(h.pending.size, 0, 'the renderer moves the highlight'); + assert.equal(options.at(-1), false); assert.equal(h.strokes.length, 0); h.viewer.scene.camera.positionWC.x = 10; h.preRender.emit(); @@ -719,7 +714,7 @@ test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pa 'camera changes project geometry without rebuilding paths', ); h.rendering.setOptions({ paused: true }); - assert.equal(h.pending.size, 0); + assert.equal(options.at(-1), true, 'the pause reaches the renderer'); h.canvas.clientWidth = 390; h.preRender.emit(); assert.equal(builds, 2, 'crossing the narrow viewport boundary rebakes once'); @@ -744,7 +739,6 @@ for (const paused of [false, true]) { ready = false; return true; }, - tick() {}, setOptions() {}, clear() {}, destroy() {}, @@ -796,9 +790,8 @@ for (const paused of [false, true]) { }); } -test('scalar snapshots retain identical GPU wind geometry and animation phase', () => { +test('scalar snapshots retain identical GPU wind geometry, and so its animation phase', () => { let builds = 0; - const times = []; const gpu = { supported: () => true, updateVisibility: () => true, @@ -806,9 +799,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase', builds++; return true; }, - tick(time) { - times.push(time); - }, setOptions() {}, clear() {}, destroy() {}, @@ -833,9 +823,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase', h.rendering.attach(); h.rendering.setField(snapshot()); h.rendering.start(); - h.callbacks.shift()(16); - h.callbacks.shift()(1016); - const phase = times.at(-1); h.rendering.setOptions({ overlay: 'temperature' }); h.rendering.setField( snapshot({ @@ -852,11 +839,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase', 'freshly decoded equal arrays reuse the worker-built primitive', ); assert.equal(h.imagery.length, 1, 'new scalar field is still installed'); - h.callbacks.shift()(1032); - assert.ok( - times.at(-1) >= phase, - 'scalar acquisition does not reset travelling highlights', - ); h.rendering.setField( snapshot({ scalar: { @@ -899,7 +881,6 @@ for (const [label, change] of Object.entries({ builds++; return true; }, - tick() {}, setOptions() {}, clear() {}, destroy() {}, @@ -927,25 +908,25 @@ for (const [label, change] of Object.entries({ } for (const eventName of ['preRender', 'moveEnd']) { - test(`GPU height suspension resumes from camera ${eventName} without preRender`, () => { - const times = []; + test(`GPU height fade follows camera ${eventName} with no frames of its own`, () => { let visible = false; - let inFrustum = true; + let fades = 0; + const options = []; const gpu = { supported: () => true, setField: () => true, - updateVisibility(camera) { - visible = camera.positionCartographic.height > 15000 && inFrustum; + updateVisibility() { + fades++; + visible = camera.positionCartographic.height > 15000; return visible; }, - tick(time) { - times.push(time); + setOptions(value) { + options.push(value.paused); }, - setOptions() {}, clear() {}, destroy() {}, getParticleCount: () => 1, - getDiagnostics: () => ({ ready: true, visibleCells: Number(visible) }), + getDiagnostics: () => ({ ready: true }), }; const h = harness({ createGpuRendering: () => gpu }); const camera = h.viewer.scene.camera; @@ -958,52 +939,27 @@ for (const eventName of ['preRender', 'moveEnd']) { h.preRender.emit(); assert.equal(h.pending.size, 0); assert.equal(renders, 0); - assert.equal(times.length, 0); + assert.equal(visible, false); assert.equal(camera.percentageChanged, 0.5); assert.equal(camera.changed.size, 0); camera.positionCartographic.height = 60000; + const before = fades; (eventName === 'preRender' ? h.preRender : camera.moveEnd).emit(); + assert.ok(fades > before, 'the fade follows the camera'); + assert.equal(visible, true); assert.equal( renders, eventName === 'preRender' ? 0 : 1, 'moveEnd wakes the parked scene', ); - assert.equal(h.pending.size, 1); - h.callbacks.shift()(16); - assert.equal(times.length, 1); - const phase = times.at(-1); - const queued = h.callbacks.shift(); - camera.positionCartographic.height = 15000; - h.preRender.emit(); - const parkedRenders = renders; - queued(100000); - assert.equal(h.pending.size, 0); - assert.equal(renders, parkedRenders); - assert.equal(times.length, 1, 'parked draw cannot tick or advance phase'); - - camera.positionCartographic.height = 60000; - (eventName === 'preRender' ? h.preRender : camera.moveEnd).emit(); - h.callbacks.shift()(200000); - assert.ok( - times.at(-1) - phase < 0.1, - 'idle time does not jump animation phase', - ); - inFrustum = false; - h.preRender.emit(); - assert.equal(h.pending.size, 0, 'frustum-hidden cells also park'); - inFrustum = true; + assert.equal(h.pending.size, 0, 'the renderer animates, not the layer'); h.rendering.setOptions({ paused: true }); - (eventName === 'preRender' ? h.preRender : camera.moveEnd).emit(); - assert.equal(h.pending.size, 0, 'camera events respect pause'); + assert.equal(options.at(-1), true); h.rendering.setOptions({ paused: false }); - globalThis.document.hidden = true; - h.visibility.emit(); - (eventName === 'preRender' ? h.preRender : camera.moveEnd).emit(); - assert.equal(h.pending.size, 0, 'camera events respect hidden documents'); - globalThis.document.hidden = false; - h.visibility.emit(); - assert.equal(h.pending.size, 1); + assert.equal(options.at(-1), false); + h.rendering.stop(); + assert.equal(options.at(-1), true, 'a stopped layer holds the flow still'); h.rendering.destroy(); assert.equal(h.pending.size, 0); assert.equal(camera.changed.size, 0); @@ -1107,7 +1063,6 @@ for (const overlay of ['speed', 'temperature', 'pressure']) { supported: () => true, setField: () => true, updateVisibility: () => true, - tick() {}, setOptions() {}, clear() {}, destroy() {}, diff --git a/src/render/cesium/drawFields.js b/src/render/cesium/drawFields.js index 4d95244b4..5a44f8dc4 100644 --- a/src/render/cesium/drawFields.js +++ b/src/render/cesium/drawFields.js @@ -1,10 +1,11 @@ /** * @module render/cesium/drawFields - * @description The Cesium draw port's `field` handles. It draws one kind: - * `rasterShell`, a raster on a rectangle raised above the ellipsoid, drawn - * flat in the opaque pass in the scene's primitive order (ascending height), - * alpha-blended, without depth writes and never picked. Other kinds are - * refused loudly. + * @description The Cesium draw port's `field` handles. It draws two kinds: + * `windStreamlines` (drawStreamlines.js) and `rasterShell`, a raster on a + * rectangle raised above the ellipsoid, drawn flat in the opaque pass in + * the scene's primitive order (ascending height), alpha-blended, without + * depth writes and never picked. Other kinds (`scalarRaster`) are refused + * loudly. * * Choices the contract leaves open, taken conservatively: * - An image is read when it is first named, as a Cesium material reads @@ -25,6 +26,7 @@ */ import * as Cesium from 'cesium'; import { listenerList, uncaught } from './common.js'; +import { createWindStreamlines } from './drawStreamlines.js'; const MATERIAL_TYPE = 'DrawRasterShell'; // Renders after an image swap: one queues the upload, one uploads and draws, one spare. @@ -632,6 +634,19 @@ export function createCesiumFields({ if (fields.has(spec?.id)) throw new Error(`a field with id ${spec.id} is live`); if (spec?.kind === 'rasterShell') return rasterShell(spec); + if (spec?.kind === 'windStreamlines') { + const handle = createWindStreamlines({ + scene, + spec, + report, + cesium, + onDispose: () => { + if (fields.get(spec.id) === handle) fields.delete(spec.id); + }, + }); + fields.set(spec.id, handle); + return handle; + } throw new TypeError( `the Cesium renderer draws no ${spec?.kind} fields yet`, ); diff --git a/src/render/cesium/drawStreamlines.js b/src/render/cesium/drawStreamlines.js new file mode 100644 index 000000000..d39e4b9b7 --- /dev/null +++ b/src/render/cesium/drawStreamlines.js @@ -0,0 +1,469 @@ +/** + * @module render/cesium/drawStreamlines + * @description The Cesium draw port's `windStreamlines` fields: paths + * traced once through the wind grid (`bakeWindStreamlines`), drawn as + * polylines at `heightM` in 30° cells, each a primitive of its own. A + * highlight moves along each path in the wind's direction; a faint ghost + * of the whole path stays. Cells the eye cannot see (behind the Earth or + * outside the view) are not drawn, and nothing animates while no cell is. + * + * Choices the contract leaves open, taken conservatively: + * - The grid's samples are points: the first column at `rectangle.west` + * and the first row at `rectangle.north`, rows running south. A grid + * whose rectangle spans 360° of longitude wraps (`width` columns over + * the whole circle); any other is `width - 1` steps from west to east. + * - `style.color` is the ghost's and the trail's colour; the moving tip + * brightens it towards white. `speedFactor` scales how fast the tip + * moves (1 by default). + * - The highlight moves on the page's own clock, at most 30 times a + * second, asking for the frames it needs; `paused` holds it where it is + * and raises the ghost. `alpha` scales everything, and 0 draws nothing. + * - Without `heightM` the paths are drawn at the ellipsoid's surface. + * - Any change but `alpha`, `paused` and `style` traces the paths again. + * - Scenes not in 3D refuse the field, as does a grid no path runs through. + */ +import * as Cesium from 'cesium'; +import { + bakeWindStreamlines, + groupWindPaths, +} from '../../layers/wind/streamlines.js'; +import { listenerList, uncaught } from './common.js'; + +// How fast the highlight runs along a path, in path lengths per second. +const TIP_SPEED = 0.16; +const GHOST_ALPHA = 0.25; +const GHOST_ALPHA_PAUSED = 0.34; +// The highlight moves at most this often (seconds between frames). +const STEP_SECONDS = 0.032; + +// A persistent fine curve plus a moving, tapered highlight. The integer part +// of s identifies a path; its fractional part follows the wind. +const FLOW_MATERIAL = ` +in float v_windFacing; +czm_material czm_getMaterial(czm_materialInput materialInput) +{ + czm_material material = czm_getDefaultMaterial(materialInput); + float pathId = floor(materialInput.st.s); + float along = fract(materialInput.st.s); + float offset = fract((pathId + 1.0) * 0.61803398875); + float behind = fract(phaseTime * tipSpeed + offset - along); + float tail = (1.0 - smoothstep(0.0, 0.32, behind)); + float tip = 1.0 - smoothstep(0.0, 0.045, behind); + float ends = smoothstep(0.0, 0.055, along) * (1.0 - smoothstep(0.945, 1.0, along)); + float edge = 1.0 - smoothstep(0.26, 0.5, abs(materialInput.st.t - 0.5)); + float horizon = smoothstep(0.0, 0.065, v_windFacing); + material.diffuse = mix(baseColor.rgb, vec3(0.91, 0.99, 1.0), tip); + material.alpha = (ghostAlpha + 0.64 * tail + 0.16 * tip) * ends * edge * horizon * heightFade; + return material; +}`; + +const DEFAULT_COLOR = '#80c9e6'; + +/** A contract colour as Cesium's; one Cesium cannot read is the default. */ +function toColor(C, color) { + const Color = C.Color ?? Cesium.Color; + if (Array.isArray(color)) + return new Color(color[0], color[1], color[2], color[3] ?? 1); + return ( + Color.fromCssColorString(String(color ?? DEFAULT_COLOR)) ?? + Color.fromCssColorString(DEFAULT_COLOR) + ); +} + +/** + * The spec's grid as the wind sampler reads it. A rectangle across the + * antimeridian (west east of east) runs east past 180°. + */ +export function windGridOf(spec) { + const { west, south, north } = spec.rectangle; + let { east } = spec.rectangle; + if (east < west) east += 360; + const span = east - west; + const wraps = span >= 360 - 1e-9; + return { + u: spec.u, + v: spec.v, + nx: spec.width, + ny: spec.height, + lo1: west, + la1: north, + dx: span / (wraps ? spec.width : spec.width - 1), + dy: (north - south) / (spec.height - 1), + }; +} + +/** + * One `windStreamlines` field over `scene`. + * @param {{scene: object, spec: object, report?: (error: unknown) => void, + * cesium?: object, + * requestFrame?: (cb: (time: number) => void) => number, + * cancelFrame?: (id: number) => void, onDispose?: () => void}} options + */ +export function createWindStreamlines({ + scene, + spec, + report = uncaught, + cesium: C = Cesium, + requestFrame = (cb) => globalThis.requestAnimationFrame(cb), + cancelFrame = (id) => globalThis.cancelAnimationFrame(id), + onDispose = () => {}, +}) { + if ( + C.SceneMode?.SCENE3D !== undefined && + scene.mode !== undefined && + scene.mode !== C.SceneMode.SCENE3D + ) + throw new TypeError( + 'the Cesium renderer draws wind streamlines in 3D only', + ); + + const live = () => !scene.isDestroyed?.(); + const requestRender = () => { + if (live()) scene.requestRender(); + }; + let current = { ...spec, style: { ...spec.style } }; + let alpha = spec.alpha ?? 1; + let paused = spec.paused === true; + let shown = true; + let disposed = false; + const cells = []; + let material = null; + let occluder = null; + let phaseTime = 0; + let visibleCells = 0; + let diagnostics = { pathCount: 0, vertexCount: 0, buildMs: 0, cellCount: 0 }; + // The animation frame asked for, and when the highlight last moved. + let frameId = null; + let lastTime = null; + // 'drawn' is owed for the latest change, made at `changedAt`. + let owed = true; + let renders = 0; + let changedAt = 0; + const frameNumber = () => scene.frameState?.frameNumber ?? renders; + const drawnListeners = listenerList(report); + + function clear() { + for (const cell of cells) { + if (live() && scene.primitives && !scene.primitives.isDestroyed?.()) + scene.primitives.remove(cell.primitive); + if (!cell.primitive.isDestroyed?.()) cell.primitive.destroy?.(); + } + cells.length = 0; + if (material && !material.isDestroyed?.()) material.destroy?.(); + material = null; + occluder = null; + visibleCells = 0; + } + + function styleUniforms() { + if (!material) return; + const color = toColor(C, current.style?.color); + material.uniforms.baseColor = color; + material.uniforms.tipSpeed = TIP_SPEED * (current.style?.speedFactor ?? 1); + material.uniforms.ghostAlpha = paused ? GHOST_ALPHA_PAUSED : GHOST_ALPHA; + material.uniforms.heightFade = alpha; + } + + /** Trace and build; a failure leaves nothing built and throws. */ + function build() { + try { + buildCells(); + } catch (error) { + clear(); + diagnostics = { pathCount: 0, vertexCount: 0, buildMs: 0, cellCount: 0 }; + throw error; + } + } + function buildCells() { + clear(); + const started = performance.now(); + // The paths are traced round the whole globe, the wind wrapping east and + // west: a grid that does not span it is refused, not drawn wrapped. + const grid = windGridOf(current); + const { west, east } = current.rectangle; + if ((east < west ? east + 360 : east) - west < 360 - 1e-9) + throw new RangeError( + 'the Cesium renderer draws wind streamlines over the whole globe only', + ); + const paths = bakeWindStreamlines(grid, { + count: current.pathBudget, + steps: current.steps, + }); + // A grid no path runs through is refused, so its caller can draw it + // some other way. + if (!paths.length) + throw new RangeError('no wind streamlines run through this grid'); + let vertexCount = 0; + material = new C.Material({ + fabric: { + type: 'DrawWindStreamline', + uniforms: { + phaseTime, + ghostAlpha: GHOST_ALPHA, + heightFade: 0, + tipSpeed: TIP_SPEED, + baseColor: toColor(C, DEFAULT_COLOR), + }, + source: FLOW_MATERIAL, + }, + translucent: () => true, + }); + styleUniforms(); + const base = new C.PolylineMaterialAppearance({ material }); + // Extend Cesium's own polyline shader rather than duplicate its + // expansion and precision code. Explicit facing also masks the far + // hemisphere when a scene keeps no globe depth for translucent objects. + const source = base.vertexShaderSource; + if ( + !/void\s+main\s*\(\s*\)/.test(source) || + !/v_st\.s\s*=\s*st\.s\s*;/.test(source) + ) + throw new Error('Wind polyline shader entry unavailable'); + const seededSource = source.replace( + /v_st\.s\s*=\s*st\.s\s*;/, + 'v_st.s = st.s * 0.999 + czm_batchTable_windSeed(batchId);', + ); + const vertexShaderSource = + `out float v_windFacing;\n${seededSource}`.replace( + /void\s+main\s*\(\s*\)\s*\{/, + `void main() {\nvec3 windWorld = (czm_model * vec4(position3DHigh + position3DLow, 1.0)).xyz;\nv_windFacing = dot(normalize(windWorld), normalize(czm_viewerPositionWC - windWorld));\n`, + ); + // EllipsoidalOccluder only tests points: a sphere occluder with an + // inscribed Earth sphere, whether or not the globe shows. + occluder = new C.Occluder( + new C.BoundingSphere(C.Cartesian3.ZERO, C.Ellipsoid.WGS84.minimumRadius), + scene.camera.positionWC, + ); + const height = Number(current.heightM) || 0; + const width = current.style?.widthPx ?? 2.4; + for (const group of groupWindPaths(paths)) { + const cellPositions = []; + let cellVertexCount = 0; + const instances = group.paths.map((path) => { + const positions = path.coordinates.map(([lon, lat]) => + C.Cartesian3.fromDegrees(lon, lat, height), + ); + // Cesium's worker expands the lines; per-instance seeds keep the + // expanded vertex buffer off the main thread. + const geometry = new C.PolylineGeometry({ + positions, + width, + arcType: C.ArcType?.NONE, + vertexFormat: C.PolylineMaterialAppearance.VERTEX_FORMAT, + }); + cellPositions.push(...positions); + cellVertexCount += positions.length * 4 - 4; + return new C.GeometryInstance({ + geometry, + attributes: { + windSeed: new C.GeometryInstanceAttribute({ + componentDatatype: C.ComponentDatatype.FLOAT, + componentsPerAttribute: 1, + value: [path.seed], + }), + }, + }); + }); + const appearance = new C.PolylineMaterialAppearance({ + material, + vertexShaderSource, + translucent: true, + renderState: { depthTest: { enabled: true }, depthMask: false }, + }); + const primitive = new C.Primitive({ + show: false, + geometryInstances: instances, + appearance, + asynchronous: true, + allowPicking: false, + releaseGeometryInstances: true, + compressVertices: false, + }); + cells.push({ + primitive, + sphere: C.BoundingSphere.fromPoints(cellPositions), + vertexCount: cellVertexCount, + }); + scene.primitives.add(primitive); + vertexCount += cellVertexCount; + } + diagnostics = { + pathCount: paths.length, + vertexCount, + buildMs: performance.now() - started, + cellCount: cells.length, + }; + } + + // Which cells the eye can see, before each frame draws. + function cull() { + visibleCells = 0; + const camera = scene.camera; + const draws = shown && alpha > 0 && cells.length > 0 && camera; + let volume; + if (draws) { + occluder.cameraPosition = camera.positionWC; + volume = camera.frustum.computeCullingVolume( + camera.positionWC, + camera.directionWC, + camera.upWC, + ); + } + for (const cell of cells) { + cell.primitive.show = Boolean( + draws && + occluder.isBoundingSphereVisible(cell.sphere) && + volume.computeVisibility(cell.sphere) !== C.Intersect.OUTSIDE, + ); + if (cell.primitive.show) visibleCells += 1; + } + } + const page = globalThis.document; + const animating = () => + !disposed && + shown && + !paused && + alpha > 0 && + visibleCells > 0 && + page?.hidden !== true; + function step(time) { + frameId = null; + if (!animating()) { + lastTime = null; + return; + } + const elapsed = lastTime === null ? null : (time - lastTime) / 1000; + // A first frame (after a pause, a hidden page or nothing in view) moves + // one tick; otherwise the highlight moves by the time passed, and a frame + // is drawn, at most every STEP_SECONDS. + let moved = true; + if (elapsed === null) phaseTime += 1 / 60; + else if (elapsed >= STEP_SECONDS) phaseTime += elapsed; + else moved = false; + if (moved) { + lastTime = time; + if (material) material.uniforms.phaseTime = phaseTime % 10000; + requestRender(); + } + frameId = requestFrame(step); + } + function animate() { + if (animating()) frameId ??= requestFrame(step); + else if (frameId !== null) { + cancelFrame(frameId); + frameId = null; + lastTime = null; + } + } + + const ready = () => cells.every((cell) => cell.primitive.ready); + function changed() { + owed = true; + changedAt = frameNumber(); + requestRender(); + } + // A field that cannot be built is refused, holding nothing. + build(); + const offPreRender = scene.preRender.addEventListener(() => { + cull(); + animate(); + }); + // A hidden page stops the highlight; shown again, it starts afresh rather + // than jumping by the time it was hidden. + const onVisibility = () => { + lastTime = null; + animate(); + }; + page?.addEventListener?.('visibilitychange', onVisibility); + const offPostRender = scene.postRender.addEventListener(() => { + renders += 1; + // Nothing built (a rebuild failed) is never told drawn. + if (!owed || !shown || disposed || !cells.length) return; + if (!ready() || frameNumber() <= changedAt) { + requestRender(); + return; + } + owed = false; + drawnListeners.fire(); + }); + + changed(); + + return { + id: spec.id, + get show() { + return shown; + }, + set show(value) { + const next = Boolean(value); + if (disposed || next === shown) return; + shown = next; + if (!shown) { + for (const cell of cells) cell.primitive.show = false; + visibleCells = 0; + animate(); + } + changedAt = frameNumber(); + requestRender(); + }, + update(patch = {}) { + if (disposed) return; + if (patch.kind !== undefined && patch.kind !== 'windStreamlines') + throw new TypeError('a field keeps its kind'); + const retrace = + ['u', 'v', 'width', 'height', 'pathBudget', 'steps', 'heightM'].some( + (key) => key in patch && patch[key] !== current[key], + ) || + (patch.rectangle !== undefined && + ['west', 'south', 'east', 'north'].some( + (edge) => patch.rectangle[edge] !== current.rectangle?.[edge], + )); + const restroke = + patch.style?.widthPx !== undefined && + patch.style.widthPx !== current.style?.widthPx; + current = { + ...current, + ...patch, + style: { ...current.style, ...patch.style }, + }; + if ('alpha' in patch) alpha = patch.alpha ?? 1; + if ('paused' in patch) paused = patch.paused === true; + if (retrace || restroke) + try { + build(); + } catch (error) { + // It draws nothing until a change builds again. + report(error); + } + else styleUniforms(); + cull(); + animate(); + changed(); + }, + on(event, cb) { + if (event !== 'drawn') return () => {}; + return drawnListeners.on(cb); + }, + dispose() { + if (disposed) return; + disposed = true; + if (frameId !== null) cancelFrame(frameId); + frameId = null; + offPreRender(); + offPostRender(); + page?.removeEventListener?.('visibilitychange', onVisibility); + drawnListeners.clear(); + clear(); + requestRender(); + onDispose(); + }, + /** For tests and diagnostics: what it built and draws. */ + diagnostics: () => ({ + ...diagnostics, + visibleCells, + ready: ready(), + animating: frameId !== null, + phaseTime, + }), + }; +} diff --git a/src/render/cesium/drawStreamlines.test.mjs b/src/render/cesium/drawStreamlines.test.mjs new file mode 100644 index 000000000..58d8e3aeb --- /dev/null +++ b/src/render/cesium/drawStreamlines.test.mjs @@ -0,0 +1,547 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + BoundingSphere, + Cartesian3, + Ellipsoid, + Event, + Intersect, + Occluder, + PerspectiveFrustum, +} from 'cesium'; +import { createWindStreamlines, windGridOf } from './drawStreamlines.js'; +import { createCesiumFields } from './drawFields.js'; +import { bakeWindStreamlines } from '../../layers/wind/streamlines.js'; + +const grid = () => ({ + nx: 4, + ny: 3, + lo1: -180, + la1: 90, + dx: 90, + dy: 90, + u: new Float32Array(12).fill(15), + v: new Float32Array(12), +}); +// The grid above as a field spec: 4 columns wrapping the globe, 3 rows. +const SPEC = Object.freeze({ + kind: 'windStreamlines', + id: 'wind', + u: new Float32Array(12).fill(15), + v: new Float32Array(12), + width: 4, + height: 3, + rectangle: { west: -180, south: -90, east: 180, north: 90 }, + pathBudget: 7200, + steps: 16, + style: { color: '#80c9e6', widthPx: 2.4 }, + heightM: 12000, +}); + +function harness() { + const members = new Set(); + let geometryBuilds = 0; + const spheres = []; + const visibility = { + horizon: () => true, + frustum: () => Intersect.INSIDE, + horizonTests: 0, + frustumTests: 0, + }; + let occluderBuilds = 0; + class Material { + constructor(options) { + this.uniforms = options.fabric.uniforms; + this.source = options.fabric.source; + } + destroy() { + assert.ok(!this.destroyed, 'owned resource destroyed once'); + this.destroyed = true; + } + } + class Appearance { + static VERTEX_FORMAT = {}; + constructor(options) { + Object.assign(this, options); + this.vertexShaderSource ??= + 'in vec3 position3DHigh; in vec3 position3DLow; void main() { gl_Position = vec4(0.0); v_st.s = st.s; }'; + } + } + class Polyline { + constructor(options) { + Object.assign(this, options); + } + static createGeometry(options) { + geometryBuilds++; + const st = new Float32Array(options.positions.length * 2); + for (let i = 0; i < options.positions.length; i++) + st[i * 2] = i / (options.positions.length - 1); + return { attributes: { st: { values: st } } }; + } + } + class Primitive { + constructor(options) { + Object.assign(this, options); + this.ready = true; + } + destroy() { + assert.ok(!this.destroyed, 'owned resource destroyed once'); + this.destroyed = true; + } + isDestroyed() { + return Boolean(this.destroyed); + } + } + const C = { + ComponentDatatype: { FLOAT: 5126 }, + GeometryInstanceAttribute: class { + constructor(options) { + Object.assign(this, options); + } + }, + Material, + PolylineMaterialAppearance: Appearance, + PolylineGeometry: Polyline, + Primitive, + GeometryInstance: class { + constructor(options) { + Object.assign(this, options); + } + }, + Cartesian3, + Ellipsoid, + Intersect, + BoundingSphere: class extends BoundingSphere { + static fromPoints(points) { + const sphere = BoundingSphere.fromPoints(points); + spheres.push({ sphere, points }); + return sphere; + } + }, + Occluder: class { + constructor(sphere, cameraPosition) { + occluderBuilds++; + this.cameraPosition = cameraPosition; + } + isBoundingSphereVisible(sphere) { + visibility.horizonTests++; + return visibility.horizon(sphere, this.cameraPosition); + } + }, + ArcType: { NONE: 0 }, + }; + const volume = { + computeVisibility(sphere) { + visibility.frustumTests++; + return visibility.frustum(sphere); + }, + }; + const frames = []; + const preRender = new Event(); + const postRender = new Event(); + let renders = 0; + const scene = { + preRender, + postRender, + requestRender() { + renders += 1; + }, + get renders() { + return renders; + }, + globe: { show: false }, + camera: { + positionWC: Cartesian3.fromDegrees(0, 0, 1e7), + positionCartographic: { height: 1e7 }, + directionWC: new Cartesian3(-1, 0, 0), + upWC: new Cartesian3(0, 0, 1), + frustum: { computeCullingVolume: () => volume }, + }, + primitives: { + add(item) { + members.add(item); + }, + remove(item) { + const removed = members.delete(item); + if (removed) item.destroy(); + return removed; + }, + }, + }; + return { + C, + scene, + members, + builds: () => geometryBuilds, + spheres, + visibility, + occluderBuilds: () => occluderBuilds, + frames, + make: (patch = {}) => + createWindStreamlines({ + scene, + cesium: C, + spec: { ...SPEC, ...patch }, + requestFrame: (cb) => { + frames.push(cb); + return frames.length; + }, + cancelFrame: (id) => { + frames[id - 1] = null; + }, + }), + /** One render: the frame events around it. */ + render() { + preRender.raiseEvent(); + postRender.raiseEvent(); + }, + }; +} +const field = () => ({ + nx: 4, + ny: 3, + lo1: -180, + la1: 90, + dx: 90, + dy: 90, + u: new Float32Array(12).fill(15), + v: new Float32Array(12), +}); + +test('the spec reads back as the wind grid it came from', () => { + const { u, v, ...rest } = windGridOf(SPEC); + const { u: gu, v: gv, ...want } = grid(); + assert.deepEqual(rest, want); + assert.deepEqual([...u], [...gu]); + const regional = windGridOf({ + ...SPEC, + rectangle: { west: -100, south: 20, east: -70, north: 50 }, + }); + assert.equal(regional.dx, 10, 'a regional grid does not wrap'); + assert.equal(regional.dy, 15); + const across = windGridOf({ + ...SPEC, + rectangle: { west: 170, south: 20, east: -170, north: 50 }, + }); + assert.equal(across.lo1, 170); + assert.equal(across.dx, 20 / 3, 'across the antimeridian it runs east'); +}); + +test('streamlines build native cells; the highlight moves without rebuilding', () => { + const h = harness(); + const field = h.make(); + assert.equal(h.members.size, 72); + const batch = [...h.members][0]; + assert.equal(batch.allowPicking, false); + assert.equal(batch.asynchronous, true); + assert.ok(batch.appearance.vertexShaderSource.includes('v_windFacing = dot')); + assert.ok( + batch.appearance.vertexShaderSource.includes( + 'czm_batchTable_windSeed(batchId)', + ), + ); + const { uniforms, source } = batch.appearance.material; + assert.ok(source.includes('smoothstep(0.0, 0.065, v_windFacing)')); + assert.ok(source.includes('mix(baseColor.rgb')); + assert.equal( + h.builds(), + 0, + 'expanded geometry is deferred to Cesium workers', + ); + const diagnostics = field.diagnostics(); + assert.ok(diagnostics.pathCount > 7000 && diagnostics.pathCount <= 7200); + assert.ok(diagnostics.vertexCount > 0); + assert.equal(diagnostics.cellCount, 72); + const instances = [...h.members].flatMap((p) => p.geometryInstances); + const baked = bakeWindStreamlines(grid()); + assert.equal(instances.length, baked.length); + const bySeed = new Map( + instances.map((i) => [i.attributes.windSeed.value[0], i]), + ); + for (const path of baked) + assert.deepEqual( + bySeed.get(path.seed).geometry.positions, + path.coordinates.map(([lon, lat]) => + Cartesian3.fromDegrees(lon, lat, 12000), + ), + ); + for (const instance of instances) assert.equal(instance.geometry.width, 2.4); + for (const cell of h.members) { + assert.equal(cell.appearance.material, batch.appearance.material); + assert.equal(cell.compressVertices, false); + assert.equal(cell.releaseGeometryInstances, true); + } + assert.equal(uniforms.ghostAlpha, 0.25); + assert.equal(uniforms.heightFade, 1); + assert.ok(Math.abs(uniforms.tipSpeed - 0.16) < 1e-12); + // A render culls the cells and starts the highlight on the page's frames. + h.render(); + assert.equal(h.frames.length, 1); + h.frames.at(-1)(1000); + const first = uniforms.phaseTime; + assert.ok(first > 0); + const asked = h.scene.renders; + h.frames.at(-1)(1010); + assert.equal(uniforms.phaseTime, first, 'at most 30 steps a second'); + assert.equal(h.scene.renders, asked, 'and no frame drawn between them'); + h.frames.at(-1)(1040); + assert.ok(Math.abs(uniforms.phaseTime - first - 0.04) < 1e-9); + assert.equal(h.scene.renders, asked + 1); + field.update({ paused: true }); + assert.equal(uniforms.ghostAlpha, 0.34, 'paused raises the ghost'); + const held = uniforms.phaseTime; + assert.equal(h.frames.at(-1), null, 'paused stops the frames'); + field.update({ paused: false, alpha: 0.5, style: { speedFactor: 2 } }); + assert.equal(uniforms.heightFade, 0.5); + assert.ok(Math.abs(uniforms.tipSpeed - 0.32) < 1e-12); + assert.equal(uniforms.phaseTime, held); + assert.equal(h.members.size, 72, 'style, alpha and pause never rebuild'); + field.dispose(); + assert.equal(h.members.size, 0); + assert.equal(h.scene.preRender.numberOfListeners, 0); + assert.equal(h.scene.postRender.numberOfListeners, 0); +}); + +test("streamlines tell 'drawn' once every cell is ready, never while hidden", () => { + const h = harness(); + const field = h.make(); + let drawn = 0; + field.on('drawn', () => (drawn += 1)); + const [batch] = h.members; + batch.ready = false; + h.render(); + h.render(); + assert.equal(drawn, 0, 'every cell must be ready'); + batch.ready = true; + h.render(); + assert.equal(drawn, 1); + h.render(); + assert.equal(drawn, 1); + field.show = false; + field.update({ alpha: 0.4 }); + h.render(); + h.render(); + assert.equal(drawn, 1, 'never while hidden'); + assert.equal(batch.show, false); + field.show = true; + h.render(); + h.render(); + assert.equal(drawn, 2, 'told once shown'); + field.update({ u: new Float32Array(12).fill(10) }); + assert.equal(batch.destroyed, true, 'a new grid traces again'); + h.render(); + h.render(); + assert.equal(drawn, 3); + field.dispose(); +}); + +test('a failed build is refused, holding nothing', () => { + const h = harness(); + const NativePrimitive = h.C.Primitive; + const built = []; + h.C.Primitive = class extends NativePrimitive { + constructor(options) { + if (built.length === 2) throw new Error('later cell failed'); + super(options); + built.push(this); + } + }; + assert.throws(() => h.make(), /later cell failed/); + assert.equal(h.members.size, 0); + for (const batch of built) { + assert.equal(batch.destroyed, true); + assert.equal(batch.appearance.material.destroyed, true); + } + assert.equal(h.scene.preRender.numberOfListeners, 0); +}); + +test('a grid no path runs through is refused, holding nothing', () => { + const h = harness(); + assert.throws( + () => h.make({ u: new Float32Array(12), v: new Float32Array(12) }), + /no wind streamlines/, + ); + assert.equal(h.members.size, 0); + assert.equal(h.scene.preRender.numberOfListeners, 0); +}); + +test('the Cesium fields draw wind streamlines under their id until disposed', () => { + const h = harness(); + const fields = createCesiumFields({ scene: h.scene, cesium: h.C }); + const field = fields.field({ ...SPEC }); + assert.ok(h.members.size > 0); + assert.equal(fields.has('wind'), true); + assert.throws(() => fields.field({ ...SPEC }), /is live/); + field.dispose(); + assert.equal(fields.has('wind'), false); + assert.equal(h.members.size, 0); + fields.field({ ...SPEC }); + fields.dispose(); + assert.equal(fields.has('wind'), false); + assert.equal(h.members.size, 0); +}); + +test('a grid short of the whole globe is refused, not drawn wrapped', () => { + const h = harness(); + for (const rectangle of [ + { west: -100, south: -90, east: 80, north: 90 }, + // Four columns over 300°: its samples nearly span the globe; it does not. + { west: -150, south: -90, east: 150, north: 90 }, + ]) + assert.throws(() => h.make({ rectangle }), /whole globe only/); + assert.equal(h.members.size, 0); + const across = h.make({ + rectangle: { west: 0, south: -90, east: -0.000000000001, north: 90 }, + }); + assert.ok(h.members.size > 0, 'a rectangle across the antimeridian wraps'); + across.dispose(); +}); + +test('a rebuild that fails draws nothing and is never told drawn', () => { + const reported = []; + const h = harness(); + const field = createWindStreamlines({ + scene: h.scene, + cesium: h.C, + spec: { ...SPEC }, + report: (error) => reported.push(error), + requestFrame: () => 1, + cancelFrame() {}, + }); + let drawn = 0; + field.on('drawn', () => (drawn += 1)); + h.render(); + h.render(); + assert.equal(drawn, 1); + const asked = h.scene.renders; + field.update({ u: new Float32Array(12), v: new Float32Array(12) }); + assert.equal(reported.length, 1); + assert.equal(h.members.size, 0); + h.render(); + h.render(); + assert.equal(drawn, 1, 'nothing drawn is never told'); + assert.ok(h.scene.renders - asked <= 1, 'and asks no frames for it'); + field.dispose(); +}); + +test('the highlight stops when hidden, transparent or out of view, and starts again', () => { + const h = harness(); + const field = h.make(); + const live = () => h.frames.filter(Boolean).length; + h.render(); + assert.equal(live(), 1); + field.show = false; + assert.equal(live(), 0, 'hidden'); + field.show = true; + h.render(); + assert.equal(live(), 1); + field.update({ alpha: 0 }); + assert.equal(live(), 0, 'transparent'); + field.update({ alpha: 1 }); + h.render(); + assert.equal(live(), 1); + h.visibility.horizon = () => false; + h.render(); + assert.equal(live(), 0, 'every cell behind the Earth'); + h.visibility.horizon = () => true; + h.render(); + assert.equal(live(), 1, 'the next render in view starts it'); + field.dispose(); + assert.equal(live(), 0, 'dispose cancels the frame it asked for'); +}); + +test('a hidden page stops the highlight; shown again, it starts afresh', () => { + const listeners = new Set(); + const document = globalThis.document; + const page = { + hidden: false, + addEventListener: (type, cb) => listeners.add(cb), + removeEventListener: (type, cb) => listeners.delete(cb), + }; + globalThis.document = page; + try { + const h = harness(); + const field = h.make(); + // Whether the frame asked for last is still pending. + const pending = () => h.frames.at(-1) !== null; + const { uniforms } = [...h.members][0].appearance.material; + h.render(); + h.frames.at(-1)(1000); + h.frames.at(-1)(1100); + const before = uniforms.phaseTime; + assert.ok(Math.abs(before - 1 / 60 - 0.1) < 1e-9, 'time passed moves it'); + h.frames.at(-1)(1400); + assert.ok( + Math.abs(uniforms.phaseTime - before - 0.3) < 1e-9, + 'a stall still moves it by the time passed', + ); + page.hidden = true; + for (const cb of listeners) cb(); + assert.equal(pending(), false, 'a hidden page asks no frames'); + page.hidden = false; + for (const cb of listeners) cb(); + assert.equal(pending(), true); + const shown = uniforms.phaseTime; + h.frames.at(-1)(60_000); + assert.ok(Math.abs(uniforms.phaseTime - shown - 1 / 60) < 1e-9); + field.dispose(); + assert.equal(listeners.size, 0); + } finally { + globalThis.document = document; + } +}); + +test('a scene not in 3D refuses streamlines', () => { + const h = harness(); + h.C.SceneMode = { SCENE3D: 3 }; + h.scene.mode = 2; + assert.throws(() => h.make(), /3D only/); +}); + +test('cell visibility combines horizon, frustum and alpha', () => { + const h = harness(); + const field = h.make(); + const batches = [...h.members]; + h.visibility.horizon = (sphere) => + h.spheres.findIndex((s) => s.sphere === sphere) % 2 === 0; + h.visibility.frustum = (sphere) => + h.spheres.findIndex((s) => s.sphere === sphere) % 3 === 0 + ? Intersect.INTERSECTING + : Intersect.OUTSIDE; + h.render(); + assert.equal(field.diagnostics().visibleCells, 12); + for (let i = 0; i < batches.length; i++) + assert.equal(batches[i].show, i % 6 === 0); + assert.equal(h.visibility.horizonTests, 72); + assert.equal(h.visibility.frustumTests, 36); + field.update({ alpha: 0 }); + h.render(); + assert.equal(field.diagnostics().visibleCells, 0); + for (const batch of batches) assert.equal(batch.show, false); + assert.equal(h.visibility.horizonTests, 72, 'alpha 0 tests nothing'); + assert.equal(h.occluderBuilds(), 1, 'the occluder is reused'); + field.dispose(); +}); + +test('real Cesium sphere culling hides the far hemisphere and a sky-facing view', () => { + const h = harness(); + h.C.Occluder = Occluder; + const field = h.make(); + const camera = h.scene.camera; + camera.frustum = new PerspectiveFrustum({ + fov: Math.PI / 3, + aspectRatio: 1.5, + near: 1, + far: 5e7, + }); + h.render(); + const facing = field.diagnostics().visibleCells; + assert.ok(facing > 0 && facing < 72); + for (let i = 0; i < h.spheres.length; i++) + if (h.spheres[i].sphere.center.x < -5e6) + assert.equal([...h.members][i].show, false); + camera.directionWC.x = 1; + h.render(); + assert.equal(field.diagnostics().visibleCells, 0); + field.dispose(); +}); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 53ded5cff..7b7c5e0d4 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -41,6 +41,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.drawOrder', 'draw.drillPick', 'draw.field.rasterShell', + 'draw.field.windStreamlines', 'draw.icons.distance', 'draw.icons.update', 'draw.lines.depthFailDash', diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 5b7efdead..0473f91a3 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -5,7 +5,6 @@ "src/app/scene.js", "src/app/viewer.js", "src/data/geoImportPins.js", - "src/layers/wind/gpuRendering.js", "src/layers/wind/relief.js", "src/layers/wind/rendering.js", "src/maps/catalog.js", diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 450abc3d2..258fc71df 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -786,6 +786,64 @@ export function portChecks() { }, { capability: 'fields' }, ), + check( + 'draw.field.windStreamlines', + "streamlines' 'drawn' comes once per change, never while hidden", + async (h, r) => { + await overAustin(h, r, 2000000); + const width = 8; + const height = 5; + const errors = []; + const offError = r.on('error', (e) => errors.push(e)); + const field = r.draw.field({ + kind: 'windStreamlines', + id: 'conf:wind', + u: new Float32Array(width * height).fill(12), + v: new Float32Array(width * height).fill(4), + width, + height, + rectangle: { west: -180, south: -80, east: 180, north: 80 }, + pathBudget: 200, + steps: 8, + style: { color: '#80c9e6', widthPx: 2 }, + heightM: 12000, + alpha: 1, + }); + let drawnCount = 0; + const off = field.on('drawn', () => (drawnCount += 1)); + // Frames until 'drawn' has come `want` times, for at most 20 s. + const until = async (want) => { + const deadline = Date.now() + 20000; + while (drawnCount < want && Date.now() < deadline) + await drawn(h, r, 1); + }; + try { + await until(1); + equal(drawnCount, 1, 'drawn once made'); + await drawn(h, r, 4); + equal(drawnCount, 1, 'not again while nothing changes'); + field.update({ alpha: 0.5 }); + await until(2); + equal(drawnCount, 2, 'drawn after a new alpha'); + field.update({ paused: true }); + await until(3); + equal(drawnCount, 3, 'drawn once paused'); + field.show = false; + field.update({ alpha: 0.4 }); + await drawn(h, r, 6); + equal(drawnCount, 3, 'never while hidden'); + field.show = true; + await until(4); + equal(drawnCount, 4, 'drawn once shown again'); + deepEqual(errors, [], 'no errors'); + } finally { + off(); + offError(); + field.dispose(); + } + }, + { capability: 'fields' }, + ), check( 'draw.drawOrder', 'of sets drawn over depth, the higher draw order is on top and picked',