mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
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.
This commit is contained in:
1 parent
50cb7bd5f4
commit
fcd1c09565
12 files changed
+1414
-701
No files matched your search
@@ -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`,
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
Reference in new issue
Block a user