Draw nine layers' fills through engine.ground, one display each

Earthquakes, air quality, GNSS Integrity, fire perimeters, Prohibited &
Restricted Airspace, Active Fires, S2 GhostMaps, cyclone advisories and
submarine cables each have one render/display.js on the globe contract;
their render/cesium* and render/navara* files go. Their discs, cells,
polygons and corridors are engine.ground sets, so on Navara they come from
the one ground screen pass with exact colours instead of nine hand-written
classification passes and lit SDK vector layers. Cesium's look stays the
reference:

- Earthquake and air-quality discs have no outline (Cesium drew none on
  clamped ellipses); earthquake discs can now be picked on Navara too.
- Perimeters, drone zones and GhostMaps polygons outline their outer
  ring only, as Cesium did.
- GNSS cells stay out of the pick pass; cyclone cones, tracks and centres
  are culled by a port of Cesium's horizon occluder.
- Submarine cables are one ground corridor set, as Cesium batched them;
  landing points, tips and stems are movers and lines.
- FIRMS glows are a sprite set and its cells a ground set. The far-zoom
  heat raster, which no primitive draws yet, sits behind one seam,
  render/heatField.js, with a Cesium and a Navara backend.

The shared Navara ground helpers that only these layers used go
(navaraGroundCells, the cell and ground geometry, the zone renderers), as
does the ground prototype script.

Coupling: layer renderer lines fall from 1636/6953 to 1011/4832
(Cesium/Navara), Navara ground passes from 7 to 5, Cesium-importing files
from 65 to 53, engine.extensions reads from 26 to 19.
This commit is contained in:
German Khokhlov committed 2026-11-07 06:20:48 +04:00
1 parent 974a0b6361
commit 54fe0aea40
124 files changed
+8407 -9576

No files matched your search

+15 -34
View File
@@ -10,17 +10,22 @@ import {
selectEarthquakeOverlayCohort,
mapAnalystRecord,
} from './model.js';
import { createEarthquakesDisplay } from './render/display.js';
export * from './model.js';
export { createUsgsEarthquakeSource } from './source.js';
/**
* Own one earthquake display and its refresh lifecycle.
* renderer.create({viewer, engine}) owns drawing and returns:
* setVisible(boolean), replace(discs), destroy().
* Discs are plain ECEF anchors, metre radii and Rgba colours; renderers keep
* source order. The layer retains observations for queries while detached.
* renderer.create({ engine }) owns drawing (render/display.js by default)
* and returns: setVisible(boolean), replace(discs), destroy().
* Discs are degrees, metre radii and Rgba colours; renderers keep source
* order. The layer retains observations for queries while detached.
*/
export function createEarthquakesLayer({ source, overlayHost, renderer } = {}) {
export function createEarthquakesLayer({
source,
overlayHost,
renderer = { create: ({ engine }) => createEarthquakesDisplay(engine) },
} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Earthquakes require a snapshot source');
if (!overlayHost) throw new TypeError('Earthquakes require an overlay host');
@@ -57,7 +62,7 @@ export function createEarthquakesLayer({ source, overlayHost, renderer } = {}) {
throw new Error('Earthquake layer is already initialized');
initialized = true;
try {
if (viewer || engine) this.attachRenderer(viewer, { engine });
if (engine) this.attachRenderer(viewer, { engine });
} catch (error) {
this.destroy();
throw error;
@@ -68,7 +73,7 @@ export function createEarthquakesLayer({ source, overlayHost, renderer } = {}) {
attachRenderer(viewer, { engine = null } = {}) {
if (!initialized || _renderer)
throw new Error('Invalid earthquake scene attachment');
_renderer = renderer.create({ viewer, engine });
_renderer = renderer.create({ engine });
if (!_renderer) throw new Error('Earthquake renderer unavailable');
_renderer.setVisible(_enabled);
if (discs.length) _renderer.replace(discs);
@@ -117,38 +122,14 @@ export function createEarthquakesLayer({ source, overlayHost, renderer } = {}) {
let count = 0;
const overlayEntries = [];
for (const {
stableId,
usgsId,
lon,
lat,
depthKm,
mag,
place,
time,
} of rows) {
for (const { stableId, lon, lat, depthKm, mag } of rows) {
count++;
const baseRadius = Math.pow(2, mag) * 1000;
const color = depthColor(depthKm || 0);
const isSignificant = mag >= 5.0;
const fillAlpha = isSignificant ? 0.4 : 0.3;
const outlineAlpha = isSignificant ? 1.0 : 0.8;
const fillAlpha = mag >= 5.0 ? 0.4 : 0.3;
const position = geo.cartesian3.fromDegrees(lon, lat);
nextDiscs.push({
stableId,
usgsId,
position,
baseRadius,
color,
isSignificant,
fillAlpha,
outlineAlpha,
mag,
place,
time,
depthKm,
});
nextDiscs.push({ stableId, lon, lat, baseRadius, color, fillAlpha });
overlayEntries.push(
createEarthquakeOverlayEntry({
id: String(stableId),
+17 -30
View File
@@ -1,26 +1,13 @@
import { createEarthquakesCesiumRenderer } from './render/cesium.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFakeGroundHarness } from '../../testSupport/groundDisplayEngines.mjs';
import { createEarthquakesLayer } from './index.js';
import { createUsgsEarthquakeSource } from './source.js';
function harness(source) {
const sources = [];
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const ground = createFakeGroundHarness();
const layer = createEarthquakesLayer({
source,
renderer: {
create: ({ viewer }) => createEarthquakesCesiumRenderer(null, { viewer }),
},
overlayHost: {
setEntries(...args) {
events.push(args);
@@ -29,9 +16,9 @@ function harness(source) {
clearSource() {},
},
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
layer.init(null, { engine: ground.engine });
layer.enable();
return { layer, ground, events };
}
const row = {
stableId: 'event-a',
@@ -54,27 +41,27 @@ test('late refresh cannot publish after disable, re-enable, or destroy', async (
});
},
});
const pending = h.layer.update(h.viewer);
h.layer[action](h.viewer);
const pending = h.layer.update();
h.layer[action]();
assert.equal(signal.aborted, true);
if (action === 'disable') h.layer.enable(h.viewer);
if (action === 'disable') h.layer.enable();
resolve([row]);
assert.equal(await pending, false);
assert.equal(h.layer.getStats().count, 0);
assert.equal(h.events.length, 0);
h.layer.destroy(h.viewer);
h.layer.destroy();
}
});
test('two displays own separate data sources and destruction', async () => {
test('two displays own separate ground sets and destruction', async () => {
const a = harness({ getSnapshot: async () => [row] });
const b = harness({ getSnapshot: async () => [] });
await a.layer.update(a.viewer);
await b.layer.update(b.viewer);
await a.layer.update();
await b.layer.update();
assert.equal(a.layer.getStats().count, 1);
assert.equal(b.layer.getStats().count, 0);
a.layer.destroy();
assert.equal(a.sources.length, 0);
assert.equal(b.sources.length, 1);
assert.equal(a.ground.sets(), 0);
assert.equal(b.ground.sets(), 1);
b.layer.destroy();
});
test('USGS body completion honors cancellation even with an uncooperative transport', async () => {
@@ -107,15 +94,15 @@ test('an observation received between scenes is queryable and draws without a se
try {
const pending = h.layer.update();
h.layer.detachRenderer();
assert.equal(h.sources.length, 0);
assert.equal(h.ground.sets(), 0);
resolve([row]);
assert.equal(await pending, true);
const [record] = h.layer.getAnalystRecords();
assert.equal(record.id, row.usgsId);
assert.equal(record.lat, row.lat);
assert.equal(h.events.length, 0);
h.layer.attachRenderer(h.viewer);
assert.equal(h.sources[0].entities.values.length, 1);
h.layer.attachRenderer(null, { engine: h.ground.engine });
assert.equal(h.ground.set('earthquakes').items.length, 1);
assert.equal(h.events.length, 1);
assert.equal(polls, 1);
} finally {
-83
View File
@@ -1,83 +0,0 @@
// Native earthquake entities: static CLAMP_TO_GROUND ellipses with the
// layer's properties and analyst snapshot semantics.
import * as Cesium from 'cesium';
export function createEarthquakesCesiumRenderer(_engine, { viewer }) {
if (!viewer?.dataSources)
throw new TypeError('Earthquakes require a native viewer');
const dataSource = new Cesium.CustomDataSource('earthquakes');
dataSource.show = false;
viewer.dataSources.add(dataSource);
let destroyed = false;
return {
kind: 'cesium',
setVisible(show) {
if (!destroyed) dataSource.show = show !== false;
},
replace(discs) {
if (destroyed) return;
const entities = discs.map(
({
stableId,
usgsId,
position,
baseRadius,
color,
isSignificant,
fillAlpha,
outlineAlpha,
mag,
place,
time,
depthKm,
}) =>
new Cesium.Entity({
id: `earthquake:${stableId}`,
position,
ellipse: {
semiMajorAxis: baseRadius,
semiMinorAxis: baseRadius,
material: new Cesium.ColorMaterialProperty(
color.withAlpha(fillAlpha),
),
outline: true,
outlineColor: color.withAlpha(outlineAlpha),
outlineWidth: isSignificant ? 3 : 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
properties: { usgsId, mag, place, time, depth: depthKm },
}),
);
dataSource.entities.removeAll();
for (const entity of entities) dataSource.entities.add(entity);
},
records(limit) {
if (destroyed || !dataSource.show) return [];
const now = Cesium.JulianDate.now();
const rows = [];
for (const entity of dataSource.entities.values) {
if (rows.length >= limit) break;
const position = entity.position?.getValue(now);
const carto = position
? Cesium.Cartographic.fromCartesian(position)
: null;
const p = entity.properties;
rows.push({
id: p?.usgsId?.getValue(now) ?? null,
mag: p?.mag?.getValue(now),
place: p?.place?.getValue(now),
time: p?.time?.getValue(now),
depth: p?.depth?.getValue(now),
lat: carto ? Cesium.Math.toDegrees(carto.latitude) : null,
lon: carto ? Cesium.Math.toDegrees(carto.longitude) : null,
});
}
return rows;
},
destroy() {
if (destroyed) return;
destroyed = true;
viewer.dataSources.remove(dataSource, true);
},
};
}
@@ -1,162 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import * as geo from '../../../geo/index.js';
import { createEarthquakesLayer } from '../index.js';
import { createEarthquakesCesiumRenderer } from './cesium.js';
const rows = [
{
stableId: 'a',
usgsId: 'us-a',
lon: -122.42,
lat: 37.77,
depthKm: 8,
mag: 2.5,
place: 'A',
time: 1000,
},
{
stableId: 'b',
usgsId: 'us-b',
lon: 30,
lat: 20,
depthKm: 70,
mag: 5,
place: 'B',
time: 2000,
},
{
stableId: 'c',
usgsId: null,
lon: 150,
lat: -30,
depthKm: 300,
mag: 6,
place: 'C',
time: 3000,
},
];
function harness() {
const sources = new Set();
const viewer = {
dataSources: {
add(source) {
sources.add(source);
},
remove(source, destroy) {
assert.equal(destroy, true);
return sources.delete(source);
},
},
};
let snapshot = rows;
const layer = createEarthquakesLayer({
source: {
async getSnapshot() {
if (snapshot instanceof Error) throw snapshot;
return snapshot;
},
},
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderer: {
create: (options) => createEarthquakesCesiumRenderer(null, options),
},
});
layer.init(viewer);
layer.enable();
return {
viewer,
sources,
layer,
setSnapshot(value) {
snapshot = value;
},
};
}
test('extracted native ground discs preserve static axes, depth palette and analyst identity', async () => {
const h = harness();
try {
assert.equal(await h.layer.update(), true);
const dataSource = [...h.sources][0];
const now = Cesium.JulianDate.now();
const colors = [Cesium.Color.RED, Cesium.Color.ORANGE, Cesium.Color.YELLOW];
dataSource.entities.values.forEach((entity, index) => {
const row = rows[index];
const ellipse = entity.ellipse;
assert.equal(entity.id, `earthquake:${row.stableId}`);
assert.equal(ellipse.semiMajorAxis.isConstant, true);
assert.equal(ellipse.semiMinorAxis.getValue(now), 2 ** row.mag * 1000);
assert.equal(ellipse.semiMajorAxis.getValue(now), 2 ** row.mag * 1000);
assert.equal(
ellipse.heightReference.getValue(now),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
assert.equal(ellipse.outlineWidth.getValue(now), row.mag >= 5 ? 3 : 2);
assert.deepEqual(
{ ...ellipse.material.color.getValue(now) },
{ ...colors[index].withAlpha(row.mag >= 5 ? 0.4 : 0.3) },
);
const expected = Cesium.Cartesian3.fromDegrees(row.lon, row.lat);
assert.deepEqual(entity.position.getValue(now), expected);
assert.deepEqual(
{ ...geo.cartesian3.fromDegrees(row.lon, row.lat) },
{
x: expected.x,
y: expected.y,
z: expected.z,
},
);
});
const records = h.layer.getAnalystRecords();
assert.deepEqual(
records.map((r) => r.id),
['us-a', 'us-b', 'QUAKE-0002'],
);
assert.equal(h.layer.getAnalystRecords(1).length, 1);
assert.equal(h.layer.getAnalystRecords(0).length, 1);
assert.equal(h.layer.getAnalystRecords(Infinity).length, 3);
h.layer.disable();
assert.deepEqual(h.layer.getAnalystRecords(), []);
assert.equal(dataSource.show, false);
} finally {
h.layer.destroy();
}
assert.equal(h.sources.size, 0);
});
test('failed native refresh retains the last complete geometry and analyst snapshot', async () => {
const h = harness();
try {
await h.layer.update();
const source = [...h.sources][0];
const before = [...source.entities.values];
const records = h.layer.getAnalystRecords();
h.setSnapshot(new Error('fixture source unavailable'));
assert.equal(await h.layer.update(), false);
assert.deepEqual(source.entities.values, before);
assert.deepEqual(h.layer.getAnalystRecords(), records);
assert.equal(h.layer.getStats().error, 'fixture source unavailable');
h.setSnapshot([]);
assert.equal(await h.layer.update(), true);
assert.equal(source.entities.values.length, 0);
assert.equal(h.layer.getStats().error, null);
} finally {
h.layer.destroy();
}
});
test('renderer destroys its owner even when passed another viewer and repeated destroy is safe', () => {
const h = harness();
const alien = {
dataSources: {
remove() {
assert.fail('must not remove from another viewer');
},
},
};
h.layer.destroy(alien);
h.layer.destroy(alien);
assert.equal(h.sources.size, 0);
});
+50
View File
@@ -0,0 +1,50 @@
// The earthquake discs on the globe contract (engine.ground), the same on
// every engine: one ground disc per event, of its radius in metres, filled
// in its depth colour at its alpha, picked as `earthquake:${stableId}`. No
// outline: Cesium draws none on a ground-clamped ellipse, so none showed
// on either engine.
const SET_ID = 'earthquakes';
/** What a pick of an earthquake disc returns. */
export const earthquakePickId = (disc) => `earthquake:${disc.stableId}`;
/**
* The earthquake discs: `{ setVisible, replace(discs), destroy }`. A disc is
* `{ stableId, lon, lat, baseRadius, color (Rgba), fillAlpha }`; later discs
* draw on top.
* @param {import('../../../globe/contract.js').GlobeEngine} engine
*/
export function createEarthquakesDisplay(engine) {
if (!engine?.ground)
throw new TypeError('The earthquakes display needs a globe engine');
const set = engine.ground.createSet({
id: SET_ID,
kind: 'disc',
pickable: true,
});
set.show(false);
let destroyed = false;
return {
setVisible(show) {
if (!destroyed) set.show(show !== false);
},
replace(discs) {
if (destroyed) return;
set.replace(
discs.map((disc) => ({
center: [disc.lon, disc.lat],
radiusM: disc.baseRadius,
fill: disc.color.withAlpha(disc.fillAlpha).rgba(),
pickId: earthquakePickId(disc),
})),
);
set.commit();
},
destroy() {
if (destroyed) return;
destroyed = true;
set.destroy();
},
};
}
@@ -0,0 +1,249 @@
// The earthquake discs on the engine contract, on the fake engine and on the
// Cesium engine (its ground batches over fake primitives): radii, depth
// colours and alphas, no outline, picks, visibility through the layer,
// retained discs across a scene handoff and a failed refresh, and teardown.
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import * as geo from '../../../geo/index.js';
import {
GROUND_HARNESSES,
createFakeGroundHarness,
instanceColor,
} from '../../../testSupport/groundDisplayEngines.mjs';
import { createEarthquakesLayer } from '../index.js';
import { createEarthquakesDisplay } from './display.js';
const rows = [
{
stableId: 'a',
usgsId: 'us-a',
lon: -122.42,
lat: 37.77,
depthKm: 8,
mag: 2.5,
place: 'A',
time: 1000,
},
{
stableId: 'b',
usgsId: 'us-b',
lon: 30,
lat: 20,
depthKm: 70,
mag: 5,
place: 'B',
time: 2000,
},
{
stableId: 'c',
usgsId: null,
lon: 150,
lat: -30,
depthKm: 300,
mag: 6,
place: 'C',
time: 3000,
},
];
// Red, orange, yellow by depth; 0.4 from magnitude 5, else 0.3.
const FILLS = [
[1, 0, 0, 0.3],
[1, 165 / 255, 0, 0.4],
[1, 1, 0, 0.4],
];
function fixture(makeHarness) {
const h = makeHarness();
let snapshot = rows;
const layer = createEarthquakesLayer({
source: {
async getSnapshot() {
if (snapshot instanceof Error) throw snapshot;
return snapshot;
},
},
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
layer.init(null, { engine: h.engine });
layer.enable();
return {
...h,
layer,
setSnapshot(value) {
snapshot = value;
},
};
}
const near = (actual, expected, label, tolerance = 1e-9) =>
assert.ok(
Math.abs(actual - expected) < tolerance,
`${label}: ${actual} vs ${expected}`,
);
test('the display needs a globe engine', () => {
assert.throws(() => createEarthquakesDisplay(null), TypeError);
});
for (const makeHarness of GROUND_HARNESSES) {
const { name } = makeHarness();
test(`each event is a ground disc of 2^mag km in its depth colour, without an outline (${name})`, async () => {
const f = fixture(makeHarness);
try {
assert.equal(await f.layer.update(), true);
const set = f.set('earthquakes');
assert.equal(set.options.kind, 'disc');
assert.equal(set.options.pickable, true);
assert.equal(set.shown, true);
assert.deepEqual(
set.items.map(({ center, radiusM, pickId, outline }) => ({
center,
radiusM,
pickId,
outline,
})),
rows.map((row) => ({
center: [row.lon, row.lat],
radiusM: 2 ** row.mag * 1000,
pickId: `earthquake:${row.stableId}`,
outline: undefined,
})),
);
set.items.forEach(({ fill }, index) =>
fill.forEach((channel, at) =>
near(channel, FILLS[index][at], `fill ${index}.${at}`),
),
);
if (f.cesium) {
const { fills, lines } = f.primitives('earthquakes');
assert.equal(fills.length, 1, 'one ground batch');
assert.equal(lines.length, 0, 'no outline batch');
const { geometryInstances, classificationType, allowPicking } =
fills[0].options;
assert.equal(classificationType, Cesium.ClassificationType.BOTH);
assert.equal(allowPicking, true);
geometryInstances.forEach((instance, index) => {
const row = rows[index];
assert.ok(instance.geometry instanceof Cesium.EllipseGeometry);
assert.equal(instance.geometry._semiMajorAxis, 2 ** row.mag * 1000);
assert.equal(instance.geometry._semiMinorAxis, 2 ** row.mag * 1000);
const center = Cesium.Cartesian3.fromDegrees(row.lon, row.lat);
near(instance.geometry._center.x, center.x, 'centre x', 1e-6);
near(instance.geometry._center.y, center.y, 'centre y', 1e-6);
near(instance.geometry._center.z, center.z, 'centre z', 1e-6);
instanceColor(instance).forEach((channel, at) =>
near(channel, FILLS[index][at], `colour ${index}.${at}`, 0.5 / 255),
);
});
}
assert.deepEqual(
f.layer.getAnalystRecords().map((r) => r.id),
['us-a', 'us-b', 'QUAKE-0002'],
);
assert.equal(f.layer.getAnalystRecords(1).length, 1);
assert.equal(f.layer.getAnalystRecords(0).length, 1);
assert.equal(f.layer.getAnalystRecords(Infinity).length, 3);
f.layer.disable();
assert.deepEqual(f.layer.getAnalystRecords(), []);
assert.equal(f.set('earthquakes').shown, false);
if (f.cesium) assert.equal(f.collectionShown('earthquakes'), false);
} finally {
f.layer.destroy();
}
assert.equal(f.sets(), 0);
f.destroy();
});
test(`a failed refresh keeps the last discs and records (${name})`, async () => {
const f = fixture(makeHarness);
try {
await f.layer.update();
const before = f.set('earthquakes');
const records = f.layer.getAnalystRecords();
f.setSnapshot(new Error('fixture source unavailable'));
assert.equal(await f.layer.update(), false);
const after = f.set('earthquakes');
assert.equal(after.commits, before.commits);
assert.equal(after.items, before.items);
assert.deepEqual(f.layer.getAnalystRecords(), records);
assert.equal(f.layer.getStats().error, 'fixture source unavailable');
f.setSnapshot([]);
assert.equal(await f.layer.update(), true);
assert.equal(f.set('earthquakes').items.length, 0);
if (f.cesium) assert.equal(f.primitives('earthquakes').fills.length, 0);
assert.equal(f.layer.getStats().error, null);
} finally {
f.layer.destroy();
f.destroy();
}
});
test(`a pick of a disc names its event (${name})`, async () => {
const f = fixture(makeHarness);
try {
await f.layer.update();
let picked;
if (f.cesium) {
const [fills] = f.primitives('earthquakes').fills;
f.viewer.scene.pick = () => ({
id: fills.options.geometryInstances[1].id,
primitive: fills,
});
picked = f.engine.picker.pick({ x: 1, y: 1 });
} else {
// The fake picks its ground items on the CPU, under the camera.
f.engine.camera.setView({
destination: geo.cartesian3.fromDegrees(30, 20, 200_000),
});
const { width, height } = f.engine.host.size();
picked = f.engine.picker.pick({ x: width / 2, y: height / 2 });
}
assert.equal(picked.id, 'earthquake:b');
assert.equal(picked.owner, 'earthquakes');
assert.equal(picked.instance, 1);
} finally {
f.layer.destroy();
f.destroy();
}
});
test(`discs fetched between scenes draw on the next one without a second fetch (${name})`, async () => {
const f = fixture(makeHarness);
try {
await f.layer.update();
f.layer.detachRenderer();
assert.equal(f.sets(), 0);
const next = makeHarness();
f.layer.attachRenderer(null, { engine: next.engine });
assert.equal(next.set('earthquakes').items.length, 3);
assert.equal(next.set('earthquakes').shown, true);
f.layer.destroy();
assert.equal(next.sets(), 0);
next.destroy();
} finally {
f.layer.destroy();
f.destroy();
}
});
}
test('the display ignores calls after destroy and destroys once', () => {
const h = createFakeGroundHarness();
const display = createEarthquakesDisplay(h.engine);
assert.equal(h.set('earthquakes').shown, false, 'hidden until shown');
display.setVisible(true);
assert.equal(h.set('earthquakes').shown, true);
display.setVisible(false);
assert.equal(h.set('earthquakes').shown, false);
display.destroy();
display.destroy();
assert.equal(h.sets(), 0);
display.setVisible(true);
display.replace([]);
// A new display may take the set id again.
createEarthquakesDisplay(h.engine).destroy();
h.destroy();
});
-69
View File
@@ -1,69 +0,0 @@
// A prototype earthquake renderer on engine.ground, for every engine: each
// disc a ground disc of its radius in the Cesium renderer's fill, picked as
// `earthquake:${stableId}`. Without the outline cesium.js asks for: Cesium
// draws no outline on a ground-clamped ellipse, nor does navara.js, so none
// shows today. Not wired into the layer: scripts/qa-ground-prototypes.mjs
// draws it next to cesium.js to compare.
import * as geo from '../../../geo/index.js';
const rgba = (color, alpha) => [color.red, color.green, color.blue, alpha];
export function createEarthquakesGroundRenderer(engine) {
const set = engine.ground.createSet({
id: 'earthquakes',
kind: 'disc',
pickable: true,
});
set.show(false);
let visible = false;
let rows = [];
let destroyed = false;
return {
kind: 'ground',
setVisible(show) {
if (destroyed) return;
visible = show !== false;
set.show(visible);
},
replace(discs) {
if (destroyed) return;
const items = [];
const nextRows = [];
for (const disc of discs) {
const place = geo.cartographic.fromCartesian(disc.position);
if (!place) continue;
const lon = geo.math.toDegrees(place.longitude);
const lat = geo.math.toDegrees(place.latitude);
items.push({
center: [lon, lat],
radiusM: disc.baseRadius,
fill: rgba(disc.color, disc.fillAlpha),
pickId: `earthquake:${disc.stableId}`,
});
nextRows.push({
id: disc.usgsId ?? null,
mag: disc.mag,
place: disc.place,
time: disc.time,
depth: disc.depthKm,
lat,
lon,
});
}
set.replace(items);
set.commit();
rows = nextRows;
},
records(limit) {
return !destroyed && visible
? rows.slice(0, limit).map((row) => ({ ...row }))
: [];
},
destroy() {
if (destroyed) return;
destroyed = true;
rows = [];
set.destroy();
},
};
}
-309
View File
@@ -1,309 +0,0 @@
// Classify the real visible terrain/Google-tiles surface in a public
// Navara post-effect. Native ground colour blends in display space; doing
// it explicitly preserves translucent colours and overlap order.
import { Uniform } from 'three';
import {
createGroundTexture as texture,
createGroundStorage as storage,
groundSurfaceUniforms,
updateGroundSurface,
} from '../../shared/render/navaraGroundSurface.js';
import { defineGroundEffect } from '../../shared/render/navaraGroundEffect.js';
import * as geo from '../../../geo/index.js';
import {
DISC_EDGES,
discFrame,
viewFrame,
discClipBounds,
} from './navaraGeometry.js';
import { createDiscGrid, GRID_COLS, GRID_ROWS } from './navaraGrid.js';
const KEY = 'gevEarthquakeGround';
const fragmentShader = /* glsl */ `
uniform sampler2D tAllDepth;
uniform sampler2D tSurfaceDepth;
uniform sampler2D tEdges;
uniform sampler2D tFrames;
uniform sampler2D tGrid;
uniform sampler2D tCandidates;
uniform vec2 uEdgeSize;
uniform vec2 uFrameSize;
uniform vec2 uCandidateSize;
uniform mat4 uInverseProjection;
uniform float uLogDepthFC;
vec4 atSlot(sampler2D image,vec2 size,float slot) {
return texture2D(image,(vec2(mod(slot,size.x),floor(slot/size.x))+0.5)/size);
}
vec3 toDisplay(vec3 c) {
return mix(12.92*c,1.055*pow(max(c,vec3(0.0)),vec3(1.0/2.4))-0.055,step(vec3(0.0031308),c));
}
vec3 toLinear(vec3 c) {
return mix(c/12.92,pow((c+0.055)/1.055,vec3(2.4)),step(vec3(0.04045),c));
}
void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
outputColor=inputColor;
float depth=unpackRGBAToDepth(texture2D(tAllDepth,uv));
float distance=exp2(2.0*depth/uLogDepthFC)-1.0;
vec4 ray=uInverseProjection*vec4(uv*2.0-1.0,-1.0,1.0);
vec3 point=ray.xyz*(distance/-ray.z);
// Derivatives must be evaluated before divergent cell/feature branches.
// Inside the candidate loop adjacent pixels may be testing different IDs.
vec3 pointDx=dFdx(point),pointDy=dFdy(point);
if(depth>=1.0) return;
vec2 cell=clamp(floor(uv*vec2(${GRID_COLS}.0,${GRID_ROWS}.0)),vec2(0.0),vec2(${GRID_COLS - 1}.0,${GRID_ROWS - 1}.0));
vec2 range=texture2D(tGrid,(cell+0.5)/vec2(${GRID_COLS}.0,${GRID_ROWS}.0)).xy;
if(range.y<0.5) return;
float surface=texture2D(tSurfaceDepth,uv).r;
// Public MRT depth excludes forward custom meshes, which are not ground.
if(depth<surface-2e-7) return;
vec3 color=toDisplay(inputColor.rgb);
for(int k=0;k<int(range.y);k++) {
float id=atSlot(tCandidates,uCandidateSize,range.x+float(k)).x;
vec4 center=atSlot(tFrames,uFrameSize,id*5.0);
vec4 east=atSlot(tFrames,uFrameSize,id*5.0+1.0);
vec4 north=atSlot(tFrames,uFrameSize,id*5.0+2.0);
vec4 up=atSlot(tFrames,uFrameSize,id*5.0+3.0);
vec3 delta=point-center.xyz;
vec3 local=vec3(dot(delta,east.xyz),dot(delta,north.xyz),dot(delta,up.xyz));
vec2 localDx=vec2(dot(pointDx,east.xyz),dot(pointDx,north.xyz));
vec2 localDy=vec2(dot(pointDy,east.xyz),dot(pointDy,north.xyz));
if(local.z<east.w || local.z>north.w) continue;
float coverage=1.0;
// A convex boundary intersects a ray from its centre on exactly one
// edge. For large discs, binary-search that edge and its two neighbours;
// all other edges lie beyond the one-pixel AA band. Small/subpixel discs
// retain the full supporting-plane coverage calculation.
bool large=center.w>128.0*max(length(pointDx),length(pointDy));
int first=0;
if(large) {
float angle=mod(atan(local.x,-local.y)-up.w+6.28318530718,6.28318530718);
int low=0,high=${DISC_EDGES - 1};
for(int step=0;step<6;step++) {
int middle=(low+high+1)/2;
float start=atSlot(tEdges,uEdgeSize,id*${DISC_EDGES}.0+float(middle)).w;
if(angle>=start) low=middle;else high=middle-1;
}
first=low-1;
}
int count=large?3:${DISC_EDGES};
for(int k=0;k<count;k++) {
int i=(first+k+${DISC_EDGES})%${DISC_EDGES};
vec3 edge=atSlot(tEdges,uEdgeSize,id*${DISC_EDGES}.0+float(i)).xyz;
float d=edge.z-dot(edge.xy,local.xy);
float pixel=abs(dot(edge.xy,localDx))+abs(dot(edge.xy,localDy));
coverage=min(coverage,clamp(d/max(pixel,0.001)+0.5,0.0,1.0));
if(coverage<=0.0) break;
}
if(coverage<=0.0) continue;
vec4 fill=atSlot(tFrames,uFrameSize,id*5.0+4.0);
color=mix(color,fill.rgb,fill.a*coverage);
}
outputColor=vec4(toLinear(color),inputColor.a);
}
`;
function buildState(discs) {
const frames = discs.map(discFrame);
const edges = storage(discs.length * DISC_EDGES);
const packed = storage(discs.length * 5);
const grid = createDiscGrid(discs.length);
const gridData = new Float32Array(GRID_COLS * GRID_ROWS * 4);
const gridTexture = texture(gridData, GRID_COLS, GRID_ROWS);
let candidates = storage(1);
const scratch = new Float64Array(12),
bounds = new Float64Array(4);
const lastView = new Float64Array(16).fill(Number.NaN);
const lastProjection = new Float64Array(16).fill(Number.NaN);
let lastWidth = 0,
lastHeight = 0;
frames.forEach((frame, i) => edges.data.set(frame.edges, i * DISC_EDGES * 4));
const state = {
count: discs.length,
edges,
packed,
gridTexture,
get candidates() {
return candidates;
},
update(camera, ctx) {
const input = ctx.getInputBuffer();
const view = camera.matrixWorldInverse.elements;
const projection = camera.projectionMatrix.elements;
let changed = input.width !== lastWidth || input.height !== lastHeight;
for (let i = 0; i < 16 && !changed; i++)
changed =
view[i] !== lastView[i] || projection[i] !== lastProjection[i];
// All features are static. Depth still refreshes each frame, but their
// screen index/coordinates only change with the camera or viewport.
if (!changed) return;
lastView.set(view);
lastProjection.set(projection);
lastWidth = input.width;
lastHeight = input.height;
frames.forEach((frame, i) => {
viewFrame(frame, camera.matrixWorldInverse, scratch);
discClipBounds(frame, scratch, camera.projectionMatrix, bounds);
if (bounds[0] <= 1) {
bounds[0] -= 2 / Math.max(1, input.width);
bounds[2] += 2 / Math.max(1, input.width);
bounds[1] -= 2 / Math.max(1, input.height);
bounds[3] += 2 / Math.max(1, input.height);
}
grid.bounds.set(bounds, i * 4);
const offset = i * 20;
packed.data.set(
[scratch[0], scratch[1], scratch[2], frame.radius],
offset,
);
packed.data.set(
[scratch[3], scratch[4], scratch[5], frame.floor],
offset + 4,
);
packed.data.set(
[scratch[6], scratch[7], scratch[8], frame.ceiling],
offset + 8,
);
packed.data.set(
[scratch[9], scratch[10], scratch[11], frame.phase],
offset + 12,
);
const d = discs[i];
packed.data.set(
[d.color.red, d.color.green, d.color.blue, d.fillAlpha],
offset + 16,
);
});
const total = grid.pack();
if (candidates.data.length / 4 < total) {
candidates.texture.dispose();
candidates = storage(Math.max(total, (2 * candidates.data.length) / 4));
}
for (let i = 0; i < total; i++) candidates.data[i * 4] = grid.indices[i];
for (let i = 0; i < grid.counts.length; i++) {
gridData[i * 4] = grid.offsets[i];
gridData[i * 4 + 1] = grid.counts[i];
}
packed.texture.needsUpdate = true;
gridTexture.needsUpdate = true;
candidates.texture.needsUpdate = true;
},
dispose() {
edges.texture.dispose();
packed.texture.dispose();
gridTexture.dispose();
candidates.texture.dispose();
},
};
return state;
}
const groundEffect = defineGroundEffect({
key: KEY,
name: 'GevEarthquakeGround',
fragmentShader,
insertAfter: [
'gevObservedWeather',
'gevNepalEvent',
'gevRecentImagery',
'toneMapping',
],
insertBefore: [
'gevFirmsGround',
'gevPreSharpenOverlay',
'gevSharpen',
'smaa',
'fxaa',
'gevOverlay',
'final',
],
uniforms: () => [
...groundSurfaceUniforms(),
['tEdges', new Uniform(null)],
['tFrames', new Uniform(null)],
['tGrid', new Uniform(null)],
['tCandidates', new Uniform(null)],
['uEdgeSize', new Uniform([1, 1])],
['uFrameSize', new Uniform([1, 1])],
['uCandidateSize', new Uniform([1, 1])],
],
update() {
const state = this.owner.state,
camera = this.view.camera.raw,
mrt = this.find('mrt');
if (!this.effect || !camera || !state) return;
updateGroundSurface(this.effect, camera, this.ctx, mrt);
state.update(camera, this.ctx);
const u = this.effect.uniforms;
u.get('tEdges').value = state.edges.texture;
u.get('uEdgeSize').value = [state.edges.width, state.edges.height];
u.get('tFrames').value = state.packed.texture;
u.get('uFrameSize').value = [state.packed.width, state.packed.height];
u.get('tGrid').value = state.gridTexture;
u.get('tCandidates').value = state.candidates.texture;
u.get('uCandidateSize').value = [
state.candidates.width,
state.candidates.height,
];
},
});
export function createEarthquakesNavaraRenderer(
engine,
{ view, EffectDesc, NavaraEffect } = {},
) {
groundEffect.register(view, { EffectDesc, NavaraEffect });
let destroyed = false,
visible = false,
rows = [],
handle = null;
const owner = { state: buildState([]) };
const sync = () => {
const show = visible && owner.state.count > 0;
if (show && !handle)
handle = view.addEffect({ [KEY]: { owner }, visible: true });
else handle?.update({ visible: show });
};
return {
kind: 'navara',
setVisible(show) {
if (destroyed) return;
visible = show !== false;
sync();
engine.render.request('earthquake-visibility');
},
replace(discs) {
if (destroyed) return;
const nextRows = discs.map((d) => {
const place = geo.cartographic.fromCartesian(d.position);
return {
id: d.usgsId ?? null,
mag: d.mag,
place: d.place,
time: d.time,
depth: d.depthKm,
lat: place ? geo.math.toDegrees(place.latitude) : null,
lon: place ? geo.math.toDegrees(place.longitude) : null,
};
});
const next = buildState(discs),
previous = owner.state;
owner.state = next;
rows = nextRows;
sync();
previous.dispose();
engine.render.request('earthquake-refresh');
},
records(limit) {
return !destroyed && visible
? rows.slice(0, limit).map((row) => ({ ...row }))
: [];
},
destroy() {
if (destroyed) return;
destroyed = true;
visible = false;
rows = [];
handle?.delete();
owner.state.dispose();
engine.render.request('earthquake-destroy');
},
};
}
@@ -1,148 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../../../geo/index.js';
import { PerspectiveCamera } from 'three';
import { constantRgba } from '../../shared/color.js';
import { createEarthquakesNavaraRenderer } from './navara.js';
test('Navara earthquake effect is lazy, releases replaced textures and detaches on repeated destroy', () => {
const registered = [],
effects = [],
requests = [];
const view = {
camera: {},
registerEffect(key, desc) {
registered.push([key, desc]);
},
addEffect(config) {
const h = {
config,
updates: [],
deleted: 0,
update(value) {
this.updates.push(value);
},
delete() {
this.deleted++;
},
};
effects.push(h);
return h;
},
};
const engine = {
render: {
request(reason) {
requests.push(reason);
},
},
};
const renderer = createEarthquakesNavaraRenderer(engine, {
view,
EffectDesc: class {},
NavaraEffect: class {},
});
assert.equal(effects.length, 0);
renderer.setVisible(true);
assert.equal(effects.length, 0);
const disc = {
position: geo.cartesian3.fromDegrees(30, 20),
baseRadius: 32000,
color: constantRgba(1, 0, 0),
fillAlpha: 0.4,
usgsId: 'us-fixture',
mag: 5,
place: 'Fixture',
time: 1000,
depthKm: 8,
};
renderer.replace([disc]);
assert.equal(effects.length, 1);
const owner = effects[0].config.gevEarthquakeGround.owner;
const old = owner.state;
let disposed = 0;
for (const t of [
old.edges.texture,
old.packed.texture,
old.gridTexture,
old.candidates.texture,
])
t.addEventListener('dispose', () => disposed++);
const record = renderer.records(1)[0];
assert.equal(record.id, 'us-fixture');
record.id = 'mutated';
assert.equal(renderer.records(1)[0].id, 'us-fixture');
renderer.replace([disc]);
assert.equal(disposed, 4);
assert.notEqual(owner.state, old);
renderer.setVisible(false);
assert.deepEqual(renderer.records(1), []);
assert.deepEqual(effects[0].updates.at(-1), { visible: false });
renderer.destroy();
renderer.destroy();
assert.equal(effects[0].deleted, 1);
renderer.replace([disc]);
assert.equal(effects.length, 1);
const second = createEarthquakesNavaraRenderer(engine, {
view,
EffectDesc: class {},
NavaraEffect: class {},
});
second.destroy();
assert.equal(registered.length, 1);
});
test('static screen data uploads once and invalidates for camera, projection and viewport changes', () => {
let owner;
const view = {
camera: {},
registerEffect() {},
addEffect(config) {
owner = config.gevEarthquakeGround.owner;
return { update() {}, delete() {} };
},
};
const renderer = createEarthquakesNavaraRenderer(
{ render: { request() {} } },
{ view, EffectDesc: class {}, NavaraEffect: class {} },
);
renderer.setVisible(true);
const position = geo.cartesian3.fromDegrees(30, 20);
renderer.replace([
{
position,
baseRadius: 32000,
color: constantRgba(1, 0, 0),
fillAlpha: 0.4,
},
]);
const camera = new PerspectiveCamera(60, 1.6, 1, 30000000);
camera.position.set(position.x * 1.1, position.y * 1.1, position.z * 1.1);
camera.lookAt(position.x, position.y, position.z);
camera.updateMatrixWorld(true);
const viewport = { width: 1280, height: 800 };
const context = { getInputBuffer: () => viewport };
const version = () => owner.state.packed.texture.version;
owner.state.update(camera, context);
let previous = version();
assert.ok(
owner.state.candidates.width > 1,
'positive visible feature occupies grid cells',
);
for (let i = 0; i < 100; i++) owner.state.update(camera, context);
assert.equal(version(), previous, 'unchanged frames do not upload geometry');
camera.position.x += 10;
camera.updateMatrixWorld(true);
owner.state.update(camera, context);
assert.equal(version(), ++previous);
camera.fov = 45;
camera.updateProjectionMatrix();
owner.state.update(camera, context);
assert.equal(version(), ++previous);
viewport.width = 1600;
owner.state.update(camera, context);
assert.equal(version(), ++previous);
owner.state.update(camera, context);
assert.equal(version(), previous);
renderer.destroy();
});
@@ -1,84 +0,0 @@
// Native default circles have 48 boundary samples (1-degree granularity,
// multiplied by eight by EllipseGeometryLibrary). Reproduce the boundary
// mathematically, then classify the visible surface inside its convex sides.
import * as geo from '../../../geo/index.js';
export const DISC_EDGES = 48;
const ellipsoid = geo.ellipsoid.WGS84;
export function discFrame(disc) {
const center = { ...disc.position };
const magnitude = Math.hypot(center.x, center.y, center.z);
const unit = geo.cartesian3.normalize(center, geo.cartesian3.create());
const east = geo.cartesian3.create(-center.y, center.x, 0);
if (geo.cartesian3.magnitude(east) === 0) east.x = 1;
geo.cartesian3.normalize(east, east);
const sphericalNorth = geo.cartesian3.cross(
unit,
east,
geo.cartesian3.create(),
);
const up = ellipsoid.geodeticSurfaceNormal(center, geo.cartesian3.create());
const north = geo.cartesian3.cross(up, east, geo.cartesian3.create());
const angle = disc.baseRadius / magnitude;
const cosine = Math.cos(angle),
sine = Math.sin(angle);
const boundary = [];
for (let i = 0; i < DISC_EDGES; i++) {
const theta = (i * 2 * Math.PI) / DISC_EDGES;
const a = Math.sin(theta) * sine * magnitude;
const b = -Math.cos(theta) * sine * magnitude;
const p = geo.cartesian3.create(
center.x * cosine + east.x * a + sphericalNorth.x * b,
center.y * cosine + east.y * a + sphericalNorth.y * b,
center.z * cosine + east.z * a + sphericalNorth.z * b,
);
ellipsoid.scaleToGeodeticSurface(p, p);
const dx = p.x - center.x,
dy = p.y - center.y,
dz = p.z - center.z;
boundary.push({
x: dx * east.x + dy * east.y + dz * east.z,
y: dx * north.x + dy * north.y + dz * north.z,
world: p,
});
}
const phase = Math.atan2(boundary[0].x, -boundary[0].y);
const edges = new Float32Array(DISC_EDGES * 4);
for (let i = 0; i < DISC_EDGES; i++) {
const a = boundary[i],
b = boundary[(i + 1) % DISC_EDGES];
const length = Math.hypot(b.x - a.x, b.y - a.y);
let nx = (b.y - a.y) / length,
ny = -(b.x - a.x) / length;
let offset = nx * a.x + ny * a.y;
if (offset < 0) {
nx = -nx;
ny = -ny;
offset = -offset;
}
let angle = i === 0 ? 0 : Math.atan2(a.x, -a.y) - phase;
if (angle < 0) angle += 2 * Math.PI;
edges.set([nx, ny, offset, angle], i * 4);
}
const r = disc.baseRadius;
return {
center,
phase,
east,
north,
up,
edges,
boundary,
radius: r,
// At orbital LOD the rendered globe mesh can lie well below the
// ellipsoid (measured -26km over Alaska). Native GroundPrimitive uses
// -100km as its conservative default floor; do not clip that surface.
floor: -100000 - ((r * r) / (2 * ellipsoid.minimumRadius)) * 1.1,
ceiling: 12000,
};
}
export {
viewFrame,
groundClipBounds as discClipBounds,
} from '../../shared/render/navaraGroundGeometry.js';
@@ -1,237 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { PerspectiveCamera, Vector3 } from 'three';
import * as geo from '../../../geo/index.js';
import {
DISC_EDGES,
discFrame,
viewFrame,
discClipBounds,
} from './navaraGeometry.js';
test('Navara classifier boundary matches public native ground-circle geometry around the world', () => {
for (const [lon, lat] of [
[-122.42, 37.77],
[0, 0],
[179.95, 85],
[-179.95, -85],
[23, 90],
]) {
for (const mag of [2.5, 5, 7, 9, 10]) {
const position = geo.cartesian3.fromDegrees(lon, lat);
const radius = 2 ** mag * 1000;
const frame = discFrame({ position, baseRadius: radius });
const native = Cesium.EllipseOutlineGeometry.createGeometry(
new Cesium.EllipseOutlineGeometry({
center: Cesium.Cartesian3.fromDegrees(lon, lat),
semiMajorAxis: radius,
semiMinorAxis: radius,
}),
).attributes.position.values;
assert.equal(native.length, DISC_EDGES * 3);
for (const p of frame.boundary) {
let best = Infinity;
for (let i = 0; i < native.length; i += 3)
best = Math.min(
best,
Math.hypot(
p.world.x - native[i],
p.world.y - native[i + 1],
p.world.z - native[i + 2],
),
);
assert.ok(best < 1e-7, `boundary ${lon}/${lat}/M${mag}: ${best}m`);
for (let i = 0; i < DISC_EDGES; i++)
assert.ok(frame.edges[i * 4 + 2] > 0);
}
}
}
});
test('disc screen bounds contain every volume corner and cover a camera crossing the volume', () => {
const position = geo.cartesian3.fromDegrees(-122.42, 37.77);
const frame = discFrame({ position, baseRadius: 32000 });
const camera = new PerspectiveCamera(60, 1.6, 1, 30000000);
camera.position.copy(
new Vector3(position.x, position.y, position.z).multiplyScalar(1.1),
);
camera.lookAt(position.x, position.y, position.z);
camera.updateMatrixWorld(true);
const view = viewFrame(
frame,
camera.matrixWorldInverse,
new Float64Array(12),
);
const bounds = discClipBounds(
frame,
view,
camera.projectionMatrix,
new Float64Array(4),
);
assert.ok(bounds[0] < bounds[2] && bounds[1] < bounds[3]);
for (let i = 0; i < 8; i++) {
const p = new Vector3(position.x, position.y, position.z);
p.addScaledVector(
new Vector3(frame.east.x, frame.east.y, frame.east.z),
(i & 1 ? 1 : -1) * frame.radius,
);
p.addScaledVector(
new Vector3(frame.north.x, frame.north.y, frame.north.z),
(i & 2 ? 1 : -1) * frame.radius,
);
p.addScaledVector(
new Vector3(frame.up.x, frame.up.y, frame.up.z),
i & 4 ? frame.ceiling : frame.floor,
);
p.project(camera);
assert.ok(
p.x >= bounds[0] - 1e-12 &&
p.x <= bounds[2] + 1e-12 &&
p.y >= bounds[1] - 1e-12 &&
p.y <= bounds[3] + 1e-12,
);
}
const inside = new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]);
assert.deepEqual(
[
...discClipBounds(
frame,
inside,
camera.projectionMatrix,
new Float64Array(4),
),
],
[-1, -1, 1, 1],
);
inside[2] = 1000000;
assert.deepEqual(
[
...discClipBounds(
frame,
inside,
camera.projectionMatrix,
new Float64Array(4),
),
],
[2, 2, 2, 2],
);
});
test('classification volume includes the recorded far-LOD Alaska surface and excludes the far side of Earth', () => {
const position = geo.cartesian3.fromDegrees(-149.92, 61);
const frame = discFrame({ position, baseRadius: 2 ** 5.5 * 1000 });
const surface = {
x: -2674232.841211094,
y: -1508471.7568704002,
z: 5542920.923233327,
};
const height =
(surface.x - position.x) * frame.up.x +
(surface.y - position.y) * frame.up.y +
(surface.z - position.z) * frame.up.z;
assert.ok(
height < -20000,
'recorded public picker sample is below the previous floor',
);
assert.ok(height >= frame.floor && height <= frame.ceiling);
const farSideHeight =
-2 *
(position.x * frame.up.x +
position.y * frame.up.y +
position.z * frame.up.z);
assert.ok(
farSideHeight < frame.floor,
'opposite hemisphere remains outside the volume',
);
});
test('large-disc sector search preserves full 48-plane pixel coverage, including corners', () => {
const coverage = (frame, point, dx, dy, indices) => {
let result = 1;
for (const i of indices) {
const e = frame.edges.subarray(i * 4, i * 4 + 3);
const width =
Math.abs(e[0] * dx[0] + e[1] * dx[1]) +
Math.abs(e[0] * dy[0] + e[1] * dy[1]);
const distance = e[2] - e[0] * point[0] - e[1] * point[1];
result = Math.min(
result,
Math.max(0, Math.min(1, distance / Math.max(width, 0.001) + 0.5)),
);
}
return result;
};
const all = Array.from({ length: DISC_EDGES }, (_, i) => i);
for (const [lon, lat] of [
[-122.42, 37.77],
[0, 0],
[179.95, 85],
[-179.95, -85],
[23, 90],
]) {
for (const mag of [2.5, 5, 7, 9, 10]) {
const frame = discFrame({
position: geo.cartesian3.fromDegrees(lon, lat),
baseRadius: 2 ** mag * 1000,
});
const angles = [
...frame.boundary.map((p) => Math.atan2(p.x, -p.y)),
...Array.from({ length: 128 }, (_, i) => (i * Math.PI * 2) / 128),
];
for (let i = 1; i < DISC_EDGES; i++)
assert.ok(frame.edges[i * 4 + 3] > frame.edges[(i - 1) * 4 + 3]);
for (const angle of angles) {
const direction = [Math.sin(angle), -Math.cos(angle)];
let boundary = Infinity;
for (const i of all) {
const dot =
frame.edges[i * 4] * direction[0] +
frame.edges[i * 4 + 1] * direction[1];
if (dot > 0)
boundary = Math.min(boundary, frame.edges[i * 4 + 2] / dot);
}
const theta =
(((angle - frame.phase) % (2 * Math.PI)) + 2 * Math.PI) %
(2 * Math.PI);
let low = 0,
high = DISC_EDGES - 1;
for (let step = 0; step < 6; step++) {
const middle = Math.floor((low + high + 1) / 2);
if (theta >= frame.edges[middle * 4 + 3]) low = middle;
else high = middle - 1;
}
const adjacent = [(low + 47) % 48, low, (low + 1) % 48];
for (const divisor of [128.01, 512]) {
const pixel = frame.radius / divisor;
for (const offset of [-1.2, -0.4, 0, 0.4, 1.2]) {
const point = direction.map(
(value) => value * (boundary + offset * pixel),
);
for (const [dx, dy] of [
[
[pixel, 0],
[0, pixel],
],
[
[pixel * 0.7, pixel * 0.7],
[-pixel * 0.7, pixel * 0.7],
],
[
[pixel, 0],
[pixel * 0.2, pixel * 0.1],
],
]) {
const expected = coverage(frame, point, dx, dy, all);
const actual = coverage(frame, point, dx, dy, adjacent);
assert.ok(
Math.abs(actual - expected) < 1e-7,
`coverage ${lon}/${lat}/M${mag}: ${actual} != ${expected}`,
);
}
}
}
}
}
}
});
@@ -1,5 +0,0 @@
export {
GRID_COLS,
GRID_ROWS,
createGroundGrid as createDiscGrid,
} from '../../shared/render/navaraGroundGrid.js';
@@ -1,38 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createDiscGrid, GRID_COLS, GRID_ROWS } from './navaraGrid.js';
test('screen grid retains every overlapping feature in source order without a cell cap', () => {
const grid = createDiscGrid(513);
for (let i = 0; i < 513; i++) grid.bounds.set([-1, -1, 1, 1], i * 4);
assert.equal(grid.pack(), 513 * GRID_COLS * GRID_ROWS);
for (let i = 0; i < grid.counts.length; i++) {
assert.equal(grid.counts[i], 513);
assert.deepEqual(
[...grid.indices.subarray(grid.offsets[i], grid.offsets[i] + 513)],
Array.from({ length: 513 }, (_, i) => i),
);
}
grid.bounds.fill(2);
assert.equal(grid.pack(), 0);
assert.equal(
grid.counts.reduce((a, b) => a + b, 0),
0,
);
});
test('screen grid excludes off-screen/behind volumes and conservatively includes border cells', () => {
const grid = createDiscGrid(4);
grid.bounds.set([
-1, -1, -0.9, -0.9, 2, 2, 2, 2, -2, -2, -1.1, -1.1, 0, 0, 1, 1,
]);
grid.pack();
assert.equal(grid.counts[0], 1);
assert.equal(grid.indices[grid.offsets[0]], 0);
const last = grid.counts.length - 1;
assert.equal(grid.counts[last], 1);
assert.equal(grid.indices[grid.offsets[last]], 3);
for (let i = 0; i < grid.counts.length; i++)
for (let k = 0; k < grid.counts[i]; k++)
assert.ok([0, 3].includes(grid.indices[grid.offsets[i] + k]));
});