mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 17:22:19 +00:00
Merge main into german/i18n-plurals-context
The catalogs conflicted only on neighbouring lines: no key changed on both sides, so they are merged key by key in main's order. Main removed the rail timeline, the other user of plain "Latest", so that entry is pruned and the News test no longer checks the timeline's wording.
This commit is contained in:
commit
49409ba8f1
1502 files changed
+180715
-47887
No files matched your search
@@ -8,6 +8,7 @@ import { createWildlifeSightingsSource } from './source.js';
|
||||
import { wildlifeGridCellId } from './gridViewport.js';
|
||||
import { LayerLifecycle } from '../../data/lifecycle.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
|
||||
|
||||
const NOW = Date.UTC(2026, 10, 4, 18);
|
||||
const rectangle = { south: 10, west: 10, north: 12, east: 12 };
|
||||
@@ -60,6 +61,7 @@ function harness(source = { getSnapshot: async () => [] }) {
|
||||
failures: 0,
|
||||
controlsListener: () => notifications++,
|
||||
};
|
||||
bindWildlifeViewer(state.viewer);
|
||||
const services = {
|
||||
source,
|
||||
now: () => time,
|
||||
|
||||
@@ -58,9 +58,8 @@ export function createWildlifeBillboardModel({
|
||||
writes += 1;
|
||||
}
|
||||
for (const key of Object.keys(appearance)) {
|
||||
// Cesium clones Color and NearFarScalar values on assignment. Our
|
||||
// last descriptor, rather than getter reference identity, records
|
||||
// whether the appearance has actually changed.
|
||||
// Our last descriptor, rather than what the point now holds,
|
||||
// records whether the appearance has actually changed.
|
||||
if (old?.appearance?.[key] === appearance[key]) continue;
|
||||
point[key] = appearance[key];
|
||||
writes += 1;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
|
||||
import {
|
||||
ambientScore,
|
||||
selectWildlifeAmbientRows,
|
||||
@@ -456,6 +457,7 @@ function ambientFixture(rows, screens) {
|
||||
camera: { positionCartographic: { height: 30_000 } },
|
||||
},
|
||||
};
|
||||
bindWildlifeViewer(state.viewer);
|
||||
const photos = [];
|
||||
const painted = [];
|
||||
const entries = new Map();
|
||||
|
||||
+2
-2
@@ -3,6 +3,7 @@ import { msg } from '../../i18n/marker.js';
|
||||
import { translateFeedError } from '../../ui/statusText.js';
|
||||
import { wildlifeIconicGroup } from './model.js';
|
||||
import { formatAge } from './photoText.js';
|
||||
import { wildlifeEyeHeight } from './view.js';
|
||||
import {
|
||||
ICONIC_TINTS,
|
||||
ICONIC_LEGEND_ORDER,
|
||||
@@ -234,8 +235,7 @@ export function createControls({ state, services, parts }) {
|
||||
if (
|
||||
!state.error &&
|
||||
!state.query &&
|
||||
state.viewer?.camera?.positionCartographic?.height >
|
||||
WILDLIFE_GRID_HEIGHT_METERS
|
||||
wildlifeEyeHeight(state.viewer) > WILDLIFE_GRID_HEIGHT_METERS
|
||||
) {
|
||||
// i18n-ignore: feed-state protocol value
|
||||
stats.status = 'zoom-in';
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { wildlifeGridCellBounds } from './gridViewport.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { spriteDrawOrder } from '../../data/spriteOrder.js';
|
||||
import { createWildlifeIconCollection } from './iconCollection.js';
|
||||
import {
|
||||
WILDLIFE_GRID_SAMPLE_SPACING_PX,
|
||||
wildlifeGridCellBounds,
|
||||
} from './gridViewport.js';
|
||||
import {
|
||||
createWildlifeWorkQueue,
|
||||
drainWildlifeWork,
|
||||
@@ -13,7 +20,6 @@ const DENSITY_RAMP_GAMMA = 3;
|
||||
const METERS_PER_DEGREE = (2 * Math.PI * 6378137) / 360;
|
||||
const FADE_STEPS = 3;
|
||||
const FADE_STEP_MS = 60;
|
||||
const SPRITE_SIZE = 128;
|
||||
// Fade coarse splats before they read as haze across the whole Earth disc.
|
||||
const ALTITUDE_FADE_START = 3_000_000;
|
||||
const ALTITUDE_FADE_END = 8_000_000;
|
||||
@@ -130,16 +136,69 @@ function horizonTest(cameraPosition, radius) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Own noninteractive, world-sized glow splats, arrival fades and style changes. */
|
||||
/** A world-sized kernel fills the screen once the camera is inside it, e.g.
|
||||
* while flying in before the closer view's tiles arrive. Cesium fades it on the
|
||||
* GPU: gone within half its width, full beyond twice its width. */
|
||||
export const WILDLIFE_DENSITY_NEAR_FADE = Object.freeze({ near: 0.5, far: 2 });
|
||||
/**
|
||||
* A splat's drawn width, CSS pixels: the kernel spans
|
||||
* `WILDLIFE_DENSITY_OVERLAP` grid cells, and the grid is chosen so a cell
|
||||
* is about `WILDLIFE_GRID_SAMPLE_SPACING_PX` wide on screen.
|
||||
*/
|
||||
export const WILDLIFE_DENSITY_SPLAT_PX =
|
||||
WILDLIFE_DENSITY_OVERLAP * WILDLIFE_GRID_SAMPLE_SPACING_PX;
|
||||
|
||||
let glowSets = 0;
|
||||
|
||||
/**
|
||||
* The splats as an unpickable icons draw set under every sprite layer:
|
||||
* each splat a pixel-sized radial kernel drawn over depth. Positions are
|
||||
* ECEF metres, colours `[r, g, b, a]` in 0..1.
|
||||
*/
|
||||
function createGlowIcons(viewer, { image }) {
|
||||
const set = drawOf(viewer).icons({
|
||||
id: `wildlife-sightings:${++glowSets}:density`,
|
||||
pickable: false,
|
||||
drawOrder: spriteDrawOrder('cctv') - 1,
|
||||
});
|
||||
const points = createWildlifeIconCollection(set);
|
||||
let ids = 0;
|
||||
return {
|
||||
add({ position, color }) {
|
||||
return points.add({
|
||||
id: `density:${++ids}`,
|
||||
position,
|
||||
image,
|
||||
size: [WILDLIFE_DENSITY_SPLAT_PX, WILDLIFE_DENSITY_SPLAT_PX],
|
||||
color,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
pickable: false,
|
||||
});
|
||||
},
|
||||
setPosition(point, position) {
|
||||
point.position = position;
|
||||
},
|
||||
setColor(point, color) {
|
||||
point.color = color;
|
||||
},
|
||||
remove(point) {
|
||||
points.remove(point);
|
||||
},
|
||||
get length() {
|
||||
return points.length;
|
||||
},
|
||||
flush: () => points.flush(),
|
||||
destroy() {
|
||||
// Drops the batched writes too, so none reaches the disposed set.
|
||||
points.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The WGS84 polar radius, the inscribed sphere the horizon test fits in. */
|
||||
const MINIMUM_RADIUS = 6_356_752.314245;
|
||||
|
||||
/** Own noninteractive, world-sized glow splats, arrival fades and style changes. */
|
||||
export function createWildlifeDensity({
|
||||
cesium: C,
|
||||
viewer,
|
||||
positionForCell = (cell) => C.Cartesian3.fromDegrees(cell.lon, cell.lat),
|
||||
createGlow = createGlowIcons,
|
||||
positionForCell = (cell) => fromDegrees(cell.lon, cell.lat),
|
||||
requestRender = () => {},
|
||||
setTimer = (fn, delay) => setTimeout(fn, delay),
|
||||
clearTimer = (timer) => clearTimeout(timer),
|
||||
@@ -149,13 +208,11 @@ export function createWildlifeDensity({
|
||||
documentRef = globalThis.document,
|
||||
} = {}) {
|
||||
let collection = null;
|
||||
const nearFade = (width) =>
|
||||
new C.NearFarScalar(
|
||||
width * WILDLIFE_DENSITY_NEAR_FADE.near,
|
||||
0,
|
||||
width * WILDLIFE_DENSITY_NEAR_FADE.far,
|
||||
1,
|
||||
);
|
||||
/** Send the splats' batched writes, then ask for the frame that shows them. */
|
||||
const render = (reason) => {
|
||||
collection?.flush();
|
||||
requestRender(reason);
|
||||
};
|
||||
let metadata = new WeakMap();
|
||||
const entries = new Map();
|
||||
const fading = new Set();
|
||||
@@ -168,37 +225,22 @@ export function createWildlifeDensity({
|
||||
const fadeQueue = createWildlifeWorkQueue({ requestIdle, cancelIdle });
|
||||
const styleQueue = createWildlifeWorkQueue({ requestIdle, cancelIdle });
|
||||
|
||||
// BillboardCollection does not implement Primitive's allowPicking option.
|
||||
// Skipping its public pick update prevents its translucent quads from
|
||||
// intercepting observations, including pixels with a faint glow alpha.
|
||||
class DensityCollection extends C.BillboardCollection {
|
||||
constructor() {
|
||||
// Cesium's TRANSLUCENT-only option writes depth and occludes badges.
|
||||
super();
|
||||
this.allowPicking = false;
|
||||
}
|
||||
update(frameState) {
|
||||
if (frameState.passes?.pick) return;
|
||||
return super.update(frameState);
|
||||
}
|
||||
}
|
||||
|
||||
function color(entry) {
|
||||
const mix = (i) => tint.low[i] + (tint.high[i] - tint.low[i]) * entry.rank;
|
||||
return new C.Color(
|
||||
return [
|
||||
mix(0),
|
||||
mix(1),
|
||||
mix(2),
|
||||
(wildlifeDensityIntensity(entry.rank) * entry.opacity * entry.fade) /
|
||||
FADE_STEPS,
|
||||
);
|
||||
];
|
||||
}
|
||||
|
||||
function* styleWork() {
|
||||
let visits = 0;
|
||||
for (const entry of entries.values()) {
|
||||
if (visits++ % WILDLIFE_WORK_UNIT === 0) yield 'density-style';
|
||||
entry.point.color = color(entry);
|
||||
collection.setColor(entry.point, color(entry));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +249,7 @@ export function createWildlifeDensity({
|
||||
if (next === tint) return;
|
||||
tint = next;
|
||||
if (entries.size)
|
||||
styleQueue.start(styleWork(), () => requestRender('density-style'));
|
||||
styleQueue.start(styleWork(), () => render('density-style'));
|
||||
}
|
||||
|
||||
function onStyle(event) {
|
||||
@@ -219,16 +261,17 @@ export function createWildlifeDensity({
|
||||
setStyle(event?.detail?.style);
|
||||
}
|
||||
|
||||
/** The splat collection, made on first use. */
|
||||
function ensureCollection() {
|
||||
if (collection) return;
|
||||
collection = new DensityCollection();
|
||||
viewer.scene.primitives.add(collection);
|
||||
if (collection) return collection;
|
||||
collection = createGlow(viewer, { image: DENSITY_IMAGE });
|
||||
if (!listening) {
|
||||
tint = tintForStyle(documentRef?.documentElement?.dataset?.gevStyle);
|
||||
eventTarget?.addEventListener?.('gev:style-change', onStyle);
|
||||
eventTarget?.addEventListener?.('gev:vision-change', onVision);
|
||||
listening = true;
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
|
||||
function* fadeWork() {
|
||||
@@ -236,7 +279,7 @@ export function createWildlifeDensity({
|
||||
for (const entry of fading) {
|
||||
if (visits++ % WILDLIFE_WORK_UNIT === 0) yield 'density-fade';
|
||||
entry.fade++;
|
||||
entry.point.color = color(entry);
|
||||
collection.setColor(entry.point, color(entry));
|
||||
if (entry.fade >= FADE_STEPS) fading.delete(entry);
|
||||
}
|
||||
}
|
||||
@@ -247,7 +290,7 @@ export function createWildlifeDensity({
|
||||
fadeTimer = setTimer(() => {
|
||||
fadeTimer = null;
|
||||
fadeQueue.start(fadeWork(), () => {
|
||||
requestRender('density-fade');
|
||||
render('density-fade');
|
||||
scheduleFade();
|
||||
});
|
||||
}, FADE_STEP_MS);
|
||||
@@ -314,7 +357,8 @@ export function createWildlifeDensity({
|
||||
};
|
||||
let sightingCount = 0;
|
||||
let changed = false;
|
||||
const height = viewer.camera?.positionCartographic?.height ?? 0;
|
||||
const pose = findCamera(viewer)?.pose();
|
||||
const height = pose?.height ?? 0;
|
||||
const opacity = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
@@ -323,10 +367,7 @@ export function createWildlifeDensity({
|
||||
(ALTITUDE_FADE_END - ALTITUDE_FADE_START),
|
||||
),
|
||||
);
|
||||
const insideHorizon = horizonTest(
|
||||
viewer.camera?.positionWC,
|
||||
C.Ellipsoid?.WGS84?.minimumRadius ?? 6_356_752.314245,
|
||||
);
|
||||
const insideHorizon = horizonTest(pose?.position, MINIMUM_RADIUS);
|
||||
const rankOf = wildlifeDensityRanks(cells);
|
||||
for (const cell of cells) {
|
||||
if (operations.densityVisits++ % WILDLIFE_WORK_UNIT === 0) {
|
||||
@@ -359,17 +400,7 @@ export function createWildlifeDensity({
|
||||
entry = { data, rank, opacity, fade: 1, seen: token, point: null };
|
||||
entry.point = collection.add({
|
||||
position: data.position,
|
||||
image: DENSITY_IMAGE,
|
||||
// Cesium packs width in 16 bits even for meter-sized billboards.
|
||||
// Put the world diameter in its unrestricted scale attribute so
|
||||
// continental kernels never clamp into thin vertical ellipses.
|
||||
width: SPRITE_SIZE,
|
||||
height: SPRITE_SIZE,
|
||||
scale: data.width / SPRITE_SIZE,
|
||||
sizeInMeters: true,
|
||||
color: color(entry),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
translucencyByDistance: nearFade(data.width),
|
||||
});
|
||||
entries.set(data.id, entry);
|
||||
fading.add(entry);
|
||||
@@ -378,20 +409,14 @@ export function createWildlifeDensity({
|
||||
} else {
|
||||
entry.seen = token;
|
||||
if (entry.data.position !== data.position) {
|
||||
entry.point.position = data.position;
|
||||
operations.densityWrites++;
|
||||
changed = true;
|
||||
}
|
||||
if (entry.data.width !== data.width) {
|
||||
entry.point.scale = data.width / SPRITE_SIZE;
|
||||
entry.point.translucencyByDistance = nearFade(data.width);
|
||||
collection.setPosition(entry.point, data.position);
|
||||
operations.densityWrites++;
|
||||
changed = true;
|
||||
}
|
||||
if (entry.rank !== rank || entry.opacity !== opacity) {
|
||||
entry.rank = rank;
|
||||
entry.opacity = opacity;
|
||||
entry.point.color = color(entry);
|
||||
collection.setColor(entry.point, color(entry));
|
||||
operations.densityWrites++;
|
||||
changed = true;
|
||||
}
|
||||
@@ -413,7 +438,7 @@ export function createWildlifeDensity({
|
||||
}
|
||||
if (!entries.size && collection) clear(true);
|
||||
else scheduleFade();
|
||||
if (changed) requestRender('density');
|
||||
if (changed) render('density');
|
||||
onOperations(operations);
|
||||
return { sightingCount, changed, size: entries.size };
|
||||
}
|
||||
@@ -429,11 +454,7 @@ export function createWildlifeDensity({
|
||||
fading.clear();
|
||||
if (!keepMetadata) metadata = new WeakMap();
|
||||
if (collection) {
|
||||
if (
|
||||
viewer.scene.primitives.remove(collection) !== true &&
|
||||
!collection.isDestroyed?.()
|
||||
)
|
||||
collection.destroy();
|
||||
collection.destroy();
|
||||
collection = null;
|
||||
}
|
||||
if (listening) {
|
||||
@@ -447,6 +468,8 @@ export function createWildlifeDensity({
|
||||
return {
|
||||
updateWork,
|
||||
update: (cells, options) => drainWildlifeWork(updateWork(cells, options)),
|
||||
/** Send the glow's batched writes to its set now. */
|
||||
flush: () => collection?.flush?.(),
|
||||
clear,
|
||||
destroy() {
|
||||
clear();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../../geo/horizon.js';
|
||||
import { wildlifeGridCellBounds } from './gridViewport.js';
|
||||
import {
|
||||
createWildlifeDensity,
|
||||
@@ -8,9 +9,11 @@ import {
|
||||
wildlifeDensityRanks,
|
||||
wildlifeDensityKernel,
|
||||
WILDLIFE_DENSITY_MAX_ALPHA,
|
||||
WILDLIFE_DENSITY_NEAR_FADE,
|
||||
WILDLIFE_DENSITY_OVERLAP,
|
||||
WILDLIFE_DENSITY_SPLAT_PX,
|
||||
} from './density.js';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { WILDLIFE_WORK_UNIT } from './performance.js';
|
||||
|
||||
function cell(column, count = 1, options = {}) {
|
||||
@@ -25,25 +28,62 @@ function cell(column, count = 1, options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function harness({ documentStyle = 'normal', camera = {} } = {}) {
|
||||
function harness({
|
||||
documentStyle = 'normal',
|
||||
camera = { positionCartographic: { height: 0 } },
|
||||
} = {}) {
|
||||
const counts = { positions: 0, writes: 0, created: 0, updates: 0 };
|
||||
class BillboardCollection extends Cesium.BillboardCollection {
|
||||
add(options) {
|
||||
counts.created++;
|
||||
const point = super.add(options);
|
||||
return new Proxy(point, {
|
||||
get: (target, key) => Reflect.get(target, key, target),
|
||||
set(target, key, value) {
|
||||
counts.writes++;
|
||||
return Reflect.set(target, key, value, target);
|
||||
},
|
||||
});
|
||||
}
|
||||
update() {
|
||||
counts.updates++;
|
||||
}
|
||||
}
|
||||
const primitives = new Cesium.PrimitiveCollection();
|
||||
const draw = fakeDrawPort();
|
||||
const viewer = { camera, scene: {} };
|
||||
bindFakeCesiumCamera(viewer, { draw });
|
||||
const glowSets = () =>
|
||||
[...draw.sets.values()].filter(
|
||||
(record) => !record.disposed && record.spec.id.endsWith(':density'),
|
||||
);
|
||||
// Each splat reads its item live, by id, with its colour by channel.
|
||||
const views = new Map();
|
||||
const view = (record, id) => {
|
||||
if (!views.has(id))
|
||||
views.set(
|
||||
id,
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, key) {
|
||||
const item = glowSets()[0]?.items.get(id);
|
||||
if (key === 'color') {
|
||||
const [red, green, blue, alpha] = item.color;
|
||||
return { red, green, blue, alpha };
|
||||
}
|
||||
return item?.[key];
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
return views.get(id);
|
||||
};
|
||||
const glow = () => {
|
||||
const record = glowSets()[0];
|
||||
if (!record) return null;
|
||||
const ids = [...record.items.keys()];
|
||||
return {
|
||||
spec: record.spec,
|
||||
length: ids.length,
|
||||
get: (index) => view(record, ids[index]),
|
||||
};
|
||||
};
|
||||
// The draw port's writes to the glow, every batch counted once.
|
||||
Object.defineProperty(counts, 'writes', {
|
||||
get: () =>
|
||||
[...draw.sets.values()]
|
||||
.filter((record) => record.spec.id.endsWith(':density'))
|
||||
.reduce((sum, record) => sum + record.writes, 0),
|
||||
});
|
||||
const primitives = {
|
||||
get length() {
|
||||
return glowSets().length;
|
||||
},
|
||||
};
|
||||
let handle = 0;
|
||||
const timers = new Map();
|
||||
const idle = new Map();
|
||||
@@ -62,11 +102,10 @@ function harness({ documentStyle = 'normal', camera = {} } = {}) {
|
||||
},
|
||||
};
|
||||
const density = createWildlifeDensity({
|
||||
cesium: { ...Cesium, BillboardCollection },
|
||||
viewer: { scene: { primitives }, camera },
|
||||
viewer,
|
||||
positionForCell(row) {
|
||||
counts.positions++;
|
||||
return Cesium.Cartesian3.fromDegrees(row.lon, row.lat);
|
||||
return fromDegrees(row.lon, row.lat);
|
||||
},
|
||||
requestRender: (reason) => renders.push(reason),
|
||||
setTimer(fn) {
|
||||
@@ -98,6 +137,7 @@ function harness({ documentStyle = 'normal', camera = {} } = {}) {
|
||||
}
|
||||
return {
|
||||
density,
|
||||
glow,
|
||||
primitives,
|
||||
counts,
|
||||
renders,
|
||||
@@ -179,68 +219,43 @@ test('uniform occupied cells make a continuous field with no visible lattice', (
|
||||
assert.ok(modulation < 0.007, `${(100 * modulation).toFixed(3)}% modulation`);
|
||||
});
|
||||
|
||||
test('each glow kernel fades on the GPU as the camera comes inside it, scaled to its own width', () => {
|
||||
test('each glow kernel is a pixel-sized splat drawn over depth at its cell', () => {
|
||||
const h = harness();
|
||||
h.density.update([cell(0, 4), cell(1, 9)]);
|
||||
const collection = h.density.collection;
|
||||
const rows = [cell(0, 4), cell(1, 9)];
|
||||
h.density.update(rows);
|
||||
const collection = h.glow();
|
||||
assert.equal(collection.length, 2);
|
||||
for (let i = 0; i < collection.length; i++) {
|
||||
const point = collection.get(i);
|
||||
const width = point.scale * point.width;
|
||||
const fade = point.translucencyByDistance;
|
||||
assert.ok(fade, 'no screen-filling kernel when zoomed inside it');
|
||||
assert.ok(
|
||||
Math.abs(fade.near - width * WILDLIFE_DENSITY_NEAR_FADE.near) < 1e-6,
|
||||
);
|
||||
assert.equal(fade.nearValue, 0);
|
||||
assert.ok(
|
||||
Math.abs(fade.far - width * WILDLIFE_DENSITY_NEAR_FADE.far) < 1e-6,
|
||||
);
|
||||
assert.equal(fade.farValue, 1);
|
||||
assert.deepEqual(point.size, [
|
||||
WILDLIFE_DENSITY_SPLAT_PX,
|
||||
WILDLIFE_DENSITY_SPLAT_PX,
|
||||
]);
|
||||
assert.equal(point.disableDepthTest, Infinity);
|
||||
assert.ok(Math.abs(toLonLatH(point.pos).lon - rows[i].lon) < 1e-9);
|
||||
}
|
||||
h.density.destroy();
|
||||
});
|
||||
|
||||
test('occupied grid counts produce unlabelled world-sized glow billboards that never enter Cesium picking', () => {
|
||||
test('occupied grid counts produce unlabelled glow icons that never enter picking', () => {
|
||||
const h = harness();
|
||||
const rows = [cell(0, 1), cell(1, 100), cell(2, 1000000)];
|
||||
const result = h.density.update(rows);
|
||||
assert.equal(result.sightingCount, 1000101);
|
||||
assert.equal(h.primitives.length, 1);
|
||||
const collection = h.density.collection;
|
||||
assert.equal(collection.allowPicking, false);
|
||||
const collection = h.glow();
|
||||
assert.equal(collection.spec.pickable, false);
|
||||
assert.equal(
|
||||
collection.spec.blend,
|
||||
undefined,
|
||||
'the default blend, so translucent glow writes no depth over badges',
|
||||
);
|
||||
assert.equal(collection.length, 3);
|
||||
const first = collection.get(0);
|
||||
assert.equal(
|
||||
first.id,
|
||||
undefined,
|
||||
'density has no sighting identity or pick payload',
|
||||
);
|
||||
assert.equal(first.sizeInMeters, true);
|
||||
assert.equal(first.scaleByDistance, undefined);
|
||||
assert.equal(first.pickable, false, 'density has no pick payload');
|
||||
assert.doesNotMatch(first.id, /wildlife:/, 'nor a sighting identity');
|
||||
assert.match(decodeURIComponent(first.image), /radialGradient/);
|
||||
assert.doesNotMatch(decodeURIComponent(first.image), /text|badge|raven/);
|
||||
const bounds = wildlifeGridCellBounds(rows[0].id);
|
||||
const logicalHeight =
|
||||
(((bounds.north - bounds.south) * Math.PI) / 180) * 6378137;
|
||||
assert.ok(first.width * first.scale >= 1.5 * logicalHeight);
|
||||
assert.equal(first.width, first.height);
|
||||
assert.ok(
|
||||
first.width <= 65536,
|
||||
'encoded dimensions fit Cesium width packing',
|
||||
);
|
||||
assert.ok(
|
||||
first.width * first.scale > 65536,
|
||||
'continental splats retain their true footprint through scale',
|
||||
);
|
||||
collection.update({ passes: { pick: true } });
|
||||
assert.equal(
|
||||
h.counts.updates,
|
||||
0,
|
||||
'the real public pick update is suppressed',
|
||||
);
|
||||
collection.update({ passes: { render: true } });
|
||||
assert.equal(h.counts.updates, 1);
|
||||
h.settle();
|
||||
const rankOf = wildlifeDensityRanks(rows);
|
||||
for (let i = 0; i < collection.length; i++)
|
||||
@@ -258,7 +273,7 @@ test('progressive tile arrival fades only new cells and reuses existing glow wit
|
||||
const one = cell(0, 4);
|
||||
const two = cell(1, 10);
|
||||
h.density.update([one]);
|
||||
const first = h.density.collection.get(0);
|
||||
const first = h.glow().get(0);
|
||||
const starting = first.color.alpha;
|
||||
h.fadeStep();
|
||||
assert.ok(first.color.alpha > starting);
|
||||
@@ -272,7 +287,7 @@ test('progressive tile arrival fades only new cells and reuses existing glow wit
|
||||
1e-12,
|
||||
'a streamed tile re-ranks but does not restart incumbents',
|
||||
);
|
||||
assert.equal(h.density.collection.get(0), first);
|
||||
assert.equal(h.glow().get(0), first);
|
||||
assert.equal(h.density.size, 2);
|
||||
h.settle();
|
||||
const settled = first.color.alpha;
|
||||
@@ -280,7 +295,7 @@ test('progressive tile arrival fades only new cells and reuses existing glow wit
|
||||
assert.equal(first.color.alpha, settled);
|
||||
h.density.update([two]);
|
||||
assert.equal(h.density.size, 1);
|
||||
assert.equal(h.density.collection.length, 1);
|
||||
assert.equal(h.glow().length, 1);
|
||||
h.density.update([]);
|
||||
assert.equal(h.density.size, 0);
|
||||
assert.equal(
|
||||
@@ -327,21 +342,18 @@ test('visibility and antimeridian padding are applied on data/moveEnd work only'
|
||||
|
||||
test('density culls far-side cells and front-side kernels that would spill over the limb', () => {
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 5_000_000),
|
||||
positionWC: fromDegrees(0, 0, 5_000_000),
|
||||
positionCartographic: { height: 5_000_000 },
|
||||
};
|
||||
const h = harness({ camera });
|
||||
const occluder = new Cesium.EllipsoidalOccluder(
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
camera.positionWC,
|
||||
);
|
||||
const occluder = horizonFrom(camera.positionWC);
|
||||
const cells = [
|
||||
cell(0, 1, { lat: 0, lon: 0 }),
|
||||
cell(1, 2, { lat: 0, lon: 54 }),
|
||||
cell(2, 4, { lat: 0, lon: 110 }),
|
||||
];
|
||||
assert.equal(
|
||||
occluder.isPointVisible(Cesium.Cartesian3.fromDegrees(54, 0)),
|
||||
occluder.isPointVisible(fromDegrees(54, 0)),
|
||||
true,
|
||||
'the limb fixture has a visible centre but an overflowing footprint',
|
||||
);
|
||||
@@ -363,11 +375,11 @@ test('density fades from regional detail to a clear whole-globe view without fra
|
||||
const cells = [cell(0, 12)];
|
||||
h.density.update(cells);
|
||||
h.settle();
|
||||
const point = h.density.collection.get(0);
|
||||
const point = h.glow().get(0);
|
||||
const fullAlpha = point.color.alpha;
|
||||
camera.positionCartographic.height = 5_500_000;
|
||||
h.density.update(cells);
|
||||
assert.equal(h.density.collection.get(0), point);
|
||||
assert.equal(h.glow().get(0), point);
|
||||
assert.ok(Math.abs(point.color.alpha - fullAlpha / 2) < 1e-12);
|
||||
const writes = h.counts.writes;
|
||||
h.density.update(cells);
|
||||
@@ -385,7 +397,7 @@ test('density fades from regional detail to a clear whole-globe view without fra
|
||||
positions,
|
||||
'altitude changes reuse decoded positions',
|
||||
);
|
||||
assert.equal(h.density.collection.get(0).color.alpha, fullAlpha);
|
||||
assert.equal(h.glow().get(0).color.alpha, fullAlpha);
|
||||
h.density.destroy();
|
||||
});
|
||||
|
||||
@@ -393,7 +405,7 @@ test('styles follow persisted mono/CRT and cockpit vision overrides, without add
|
||||
const h = harness({ documentStyle: 'thermal' });
|
||||
h.density.update([cell(0)]);
|
||||
h.settle();
|
||||
const point = h.density.collection.get(0);
|
||||
const point = h.glow().get(0);
|
||||
assert.equal(point.color.red, point.color.green);
|
||||
assert.equal(point.color.green, point.color.blue);
|
||||
const alpha = point.color.alpha;
|
||||
@@ -417,15 +429,13 @@ test('styles follow persisted mono/CRT and cockpit vision overrides, without add
|
||||
h.density.destroy();
|
||||
});
|
||||
|
||||
test('clear/disable and destroy release the atlas, primitives, coordinates, timers and listeners', () => {
|
||||
test('clear/disable and destroy release the glow set, coordinates, timers and listeners', () => {
|
||||
const h = harness();
|
||||
const row = cell(0);
|
||||
h.density.update([row]);
|
||||
const old = h.density.collection;
|
||||
assert.equal(h.timers.size, 1);
|
||||
h.fadeStep();
|
||||
h.density.clear();
|
||||
assert.equal(old.isDestroyed(), true);
|
||||
assert.equal(h.density.collection, null);
|
||||
assert.equal(h.density.size, 0);
|
||||
assert.equal(h.primitives.length, 0);
|
||||
@@ -453,6 +463,18 @@ test('clear/disable and destroy release the atlas, primitives, coordinates, time
|
||||
assert.equal(h.idle.size, 0);
|
||||
});
|
||||
|
||||
test('destroy mid-update drops the glow writes still batched', async () => {
|
||||
const h = harness();
|
||||
const work = h.density.updateWork([cell(0), cell(1)]);
|
||||
while (!h.primitives.length && !work.next().done);
|
||||
assert.equal(h.primitives.length, 1, 'a splat is batched, not yet sent');
|
||||
h.density.destroy();
|
||||
// A batched write reaching the disposed set would throw here.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
assert.equal(h.primitives.length, 0);
|
||||
});
|
||||
|
||||
test('dense six-tile updates have a deterministic linear operation budget and no warmed writes/projections', (t) => {
|
||||
const h = harness();
|
||||
const cells = [];
|
||||
|
||||
@@ -114,17 +114,18 @@ export function wildlifeGridTiles({ boxes, z } = {}) {
|
||||
return [...tiles.values()].sort((a, b) => a.x - b.x || a.y - b.y);
|
||||
}
|
||||
|
||||
/** Unlike detail-row viewport queries, grids cover full globe views too. */
|
||||
export function wildlifeGridViewportBoxes(viewer) {
|
||||
const rectangle = viewer?.camera?.computeViewRectangle?.(
|
||||
viewer?.scene?.globe?.ellipsoid,
|
||||
);
|
||||
/**
|
||||
* Unlike detail-row viewport queries, grids cover full globe views too.
|
||||
* `rectangle` is the camera's view rectangle in degrees (the camera port's
|
||||
* `viewRectangle()`), or null.
|
||||
*/
|
||||
export function wildlifeGridViewportBoxes(rectangle) {
|
||||
if (!rectangle) return [];
|
||||
return normalizedBoxes([
|
||||
Object.fromEntries(
|
||||
['south', 'west', 'north', 'east'].map((key) => [
|
||||
key,
|
||||
Math.round(degrees(rectangle[key]) * 1e8) / 1e8,
|
||||
Math.round(rectangle[key] * 1e8) / 1e8,
|
||||
]),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -97,23 +97,18 @@ test('tile cap degrades zoom to preserve complete coverage and oversized direct
|
||||
});
|
||||
|
||||
test('grid camera viewport supports globe and antimeridian without detail-query degree limits', () => {
|
||||
const radians = (value) => (value * Math.PI) / 180;
|
||||
const viewer = {
|
||||
camera: {
|
||||
computeViewRectangle: () => ({
|
||||
south: radians(-80),
|
||||
west: radians(120),
|
||||
north: radians(80),
|
||||
east: radians(-120),
|
||||
}),
|
||||
},
|
||||
};
|
||||
const boxes = wildlifeGridViewportBoxes(viewer);
|
||||
// The camera port's view rectangle, in degrees.
|
||||
const boxes = wildlifeGridViewportBoxes({
|
||||
south: -80,
|
||||
west: 120,
|
||||
north: 80,
|
||||
east: -120,
|
||||
});
|
||||
assert.equal(boxes.length, 2);
|
||||
assert.ok(Math.abs(boxes[0].west - 120) < 1e-8);
|
||||
assert.equal(boxes[0].east, 180);
|
||||
assert.equal(boxes[1].west, -180);
|
||||
assert.deepEqual(wildlifeGridViewportBoxes({}), []);
|
||||
assert.deepEqual(wildlifeGridViewportBoxes(null), []);
|
||||
});
|
||||
|
||||
test('logical cell ids and bounds share geographic coverage and wrap antimeridian', () => {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* @module layers/wildlifeSightings/iconCollection
|
||||
* @description The sighting badges' icons draw set behind the small
|
||||
* collection shape the billboard model (`billboardModel.js`) reconciles:
|
||||
* `add` hands back a point whose property writes (`position`, `image`,
|
||||
* `show` and the appearance) are batched and sent to the set as one upsert
|
||||
* per task, and `remove`/`removeAll` take items off it. A point's `id` is
|
||||
* its item id, so a pick on a badge names it.
|
||||
*/
|
||||
|
||||
/** Item fields a point carries as they are (its appearance). */
|
||||
const PASSED = [
|
||||
'size',
|
||||
'color',
|
||||
'scale',
|
||||
'scaleByDistance',
|
||||
'disableDepthTest',
|
||||
'pickable',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {import('../../render/contract/draw').DrawSet<import('../../render/contract/draw').IconItem>} set
|
||||
* @param {{schedule?: (flush: () => void) => void}} [options] - How the
|
||||
* batched writes are flushed (a microtask by default).
|
||||
*/
|
||||
export function createWildlifeIconCollection(
|
||||
set,
|
||||
{ schedule = queueMicrotask } = {},
|
||||
) {
|
||||
/** @type {Map<string, object>} Points by item id. */
|
||||
const points = new Map();
|
||||
/** @type {Set<object>} Points written since the last flush. */
|
||||
const dirty = new Set();
|
||||
let scheduled = false;
|
||||
const canvasKeys = new WeakMap();
|
||||
let canvasCount = 0;
|
||||
|
||||
/** A sprite as the contract names it: a URL, or a canvas with its key. */
|
||||
function imageRef(image) {
|
||||
if (typeof image === 'string' || !image) return image;
|
||||
if (!canvasKeys.has(image))
|
||||
canvasKeys.set(image, `wildlife-sprite:${++canvasCount}`);
|
||||
return { canvas: image, key: canvasKeys.get(image) };
|
||||
}
|
||||
|
||||
function itemOf(point) {
|
||||
const item = {
|
||||
id: point.id,
|
||||
pos: point.position,
|
||||
image: imageRef(point.image),
|
||||
show: point.show !== false,
|
||||
};
|
||||
for (const key of PASSED)
|
||||
if (point[key] !== undefined) item[key] = point[key];
|
||||
return item;
|
||||
}
|
||||
|
||||
function flush() {
|
||||
scheduled = false;
|
||||
if (!dirty.size) return;
|
||||
const items = [];
|
||||
for (const point of dirty)
|
||||
if (points.get(point.id) === point) items.push(itemOf(point));
|
||||
dirty.clear();
|
||||
if (items.length) set.upsert(items);
|
||||
}
|
||||
|
||||
function touch(point) {
|
||||
dirty.add(point);
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
schedule(flush);
|
||||
}
|
||||
|
||||
return {
|
||||
/** Add a point (`id`, `position`, `image` and its appearance). */
|
||||
add(options) {
|
||||
const point = new Proxy(
|
||||
{ show: true, ...options },
|
||||
{
|
||||
set(target, key, value) {
|
||||
if (target[key] === value) return true;
|
||||
target[key] = value;
|
||||
touch(point);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
);
|
||||
points.set(point.id, point);
|
||||
touch(point);
|
||||
return point;
|
||||
},
|
||||
remove(point) {
|
||||
if (points.get(point?.id) !== point) return false;
|
||||
points.delete(point.id);
|
||||
dirty.delete(point);
|
||||
set.remove([point.id]);
|
||||
return true;
|
||||
},
|
||||
removeAll() {
|
||||
points.clear();
|
||||
dirty.clear();
|
||||
set.clear();
|
||||
},
|
||||
/** Take the set off the renderer. */
|
||||
dispose() {
|
||||
points.clear();
|
||||
dirty.clear();
|
||||
set.dispose();
|
||||
},
|
||||
/** Send the batched writes now. */
|
||||
flush,
|
||||
get show() {
|
||||
return set.show;
|
||||
},
|
||||
set show(value) {
|
||||
set.show = value;
|
||||
},
|
||||
get length() {
|
||||
return points.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { horizonOccluder } from '../../data/iconOrientation.js';
|
||||
import { horizonFrom } from '../../geo/horizon.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { findQuery } from '../../render/rendererOf.js';
|
||||
import { createPhotoSlots } from './photos.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createSelection } from './selection.js';
|
||||
@@ -10,7 +11,7 @@ import { createLifecycle } from './lifecycle.js';
|
||||
export function createWildlifeSightingsLayer({
|
||||
source,
|
||||
overlayHost = null,
|
||||
screenSpaceEventHandlerFactory = null,
|
||||
input = (viewer) => inputFor(viewer),
|
||||
picking = null,
|
||||
pointer = null,
|
||||
sprites = null,
|
||||
@@ -26,10 +27,8 @@ export function createWildlifeSightingsLayer({
|
||||
cancelIdleCallback,
|
||||
imageFactory,
|
||||
eventTarget = globalThis.window,
|
||||
cesium = Cesium,
|
||||
project = (scene, position) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(scene, position),
|
||||
occluderFactory = horizonOccluder,
|
||||
project = (viewer, position) => findQuery(viewer)?.project(position) ?? null,
|
||||
occluderFactory = horizonFrom,
|
||||
} = {}) {
|
||||
if (typeof source?.getSnapshot !== 'function')
|
||||
throw new TypeError('Wildlife sightings require a snapshot source');
|
||||
@@ -51,7 +50,7 @@ export function createWildlifeSightingsLayer({
|
||||
pointById: new Map(),
|
||||
positions: new Map(),
|
||||
cells: [],
|
||||
staging: null,
|
||||
cellSets: null,
|
||||
selectedId: null,
|
||||
selectedRow: null,
|
||||
carriers: new Map(),
|
||||
@@ -84,7 +83,7 @@ export function createWildlifeSightingsLayer({
|
||||
const services = {
|
||||
source,
|
||||
overlayHost,
|
||||
screenSpaceEventHandlerFactory,
|
||||
input,
|
||||
picking,
|
||||
pointer,
|
||||
sprites,
|
||||
@@ -99,7 +98,6 @@ export function createWildlifeSightingsLayer({
|
||||
requestIdleCallback,
|
||||
cancelIdleCallback,
|
||||
eventTarget,
|
||||
cesium,
|
||||
project,
|
||||
occluderFactory,
|
||||
};
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
wildlifeGridTiles,
|
||||
wildlifeGridCellId,
|
||||
} from './gridViewport.js';
|
||||
import { canvasOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { wildlifeEyeHeight, wildlifeViewRectangle } from './view.js';
|
||||
import { wildlifeViewportBoxes, snapWildlifeBox } from './viewport.js';
|
||||
import {
|
||||
WILDLIFE_DEBOUNCE_MS,
|
||||
@@ -125,15 +127,14 @@ export function createLifecycle({ state, services, parts }) {
|
||||
}
|
||||
|
||||
function currentQuery() {
|
||||
const height = state.viewer?.camera?.positionCartographic?.height;
|
||||
const height = wildlifeEyeHeight(state.viewer);
|
||||
state.band = getWildlifeHeightBand(height ?? Infinity, state.band);
|
||||
const rectangle = wildlifeViewRectangle(state.viewer);
|
||||
const boxes =
|
||||
state.band === 'global'
|
||||
? null
|
||||
: wildlifeViewportBoxes(state.viewer)?.map((box) =>
|
||||
snapWildlifeBox(box),
|
||||
);
|
||||
const visibleBoxes = wildlifeGridViewportBoxes(state.viewer);
|
||||
: wildlifeViewportBoxes(rectangle)?.map((box) => snapWildlifeBox(box));
|
||||
const visibleBoxes = wildlifeGridViewportBoxes(rectangle);
|
||||
const scope =
|
||||
state.band === 'global' ||
|
||||
(!boxes && (height ?? Infinity) > WILDLIFE_GRID_HEIGHT_METERS)
|
||||
@@ -147,7 +148,7 @@ export function createLifecycle({ state, services, parts }) {
|
||||
state.confirmed,
|
||||
state.taxa,
|
||||
]);
|
||||
const canvas = state.viewer?.scene?.canvas;
|
||||
const canvas = canvasOf(state.viewer);
|
||||
const zoom = visibleBoxes?.length
|
||||
? chooseWildlifeGridZoom({
|
||||
boxes: visibleBoxes,
|
||||
@@ -529,7 +530,7 @@ export function createLifecycle({ state, services, parts }) {
|
||||
}
|
||||
|
||||
const methods = {
|
||||
/** Attach this layer's Cesium resources to one viewer. */
|
||||
/** Attach this layer's draw sets and listeners to one viewer. */
|
||||
init(viewer, { signal } = {}) {
|
||||
if (state.viewer)
|
||||
throw new Error('Wildlife sightings layer is already initialized');
|
||||
@@ -559,25 +560,20 @@ export function createLifecycle({ state, services, parts }) {
|
||||
id.startsWith('wildlife:') &&
|
||||
state.rowById.has(id.slice(9)),
|
||||
);
|
||||
state.removeCamera = state.viewer.camera?.moveEnd?.addEventListener?.(
|
||||
() => {
|
||||
if (!state.enabled) return;
|
||||
wildlifeMeasure('moveEnd', () => {
|
||||
if (
|
||||
initialCameraDeadline &&
|
||||
services.now() < initialCameraDeadline
|
||||
) {
|
||||
initialCameraDeadline = services.now() + INITIAL_CAMERA_SETTLE_MS;
|
||||
refreshView();
|
||||
initialSettle?.schedule();
|
||||
} else {
|
||||
refreshView();
|
||||
scheduleRefresh();
|
||||
}
|
||||
parts.controls.notify();
|
||||
});
|
||||
},
|
||||
);
|
||||
state.removeCamera = findCamera(state.viewer)?.on('moveEnd', () => {
|
||||
if (!state.enabled) return;
|
||||
wildlifeMeasure('moveEnd', () => {
|
||||
if (initialCameraDeadline && services.now() < initialCameraDeadline) {
|
||||
initialCameraDeadline = services.now() + INITIAL_CAMERA_SETTLE_MS;
|
||||
refreshView();
|
||||
initialSettle?.schedule();
|
||||
} else {
|
||||
refreshView();
|
||||
scheduleRefresh();
|
||||
}
|
||||
parts.controls.notify();
|
||||
});
|
||||
});
|
||||
// A debounce can expire while the manager is still enabling and cannot
|
||||
// accept refreshLayer yet. Its settled visibility event is the one
|
||||
// catch-up edge; completed initial queries are skipped by their key.
|
||||
@@ -591,12 +587,8 @@ export function createLifecycle({ state, services, parts }) {
|
||||
)
|
||||
scheduleRefresh();
|
||||
}) || null;
|
||||
if (services.sprites?.restoreSpriteOrderOnEnable)
|
||||
services.sprites.restoreSpriteOrderOnEnable(
|
||||
'wildlife-sightings',
|
||||
state.viewer,
|
||||
);
|
||||
else services.sprites?.restoreSpriteOrder?.(state.viewer);
|
||||
// The badges' set keeps its place among the sprite layers by its draw
|
||||
// order (`spriteDrawOrder`), whichever layer was turned on first.
|
||||
return true;
|
||||
},
|
||||
/** Refresh observations and density independently for the current filters. */
|
||||
|
||||
@@ -6,6 +6,7 @@ import { layerFeedState } from '../../data/feedState.js';
|
||||
import { LayerLifecycle } from '../../data/lifecycle.js';
|
||||
import { ICONIC_LEGEND_ORDER, WILDLIFE_MAX_ROWS } from './policy.js';
|
||||
import { wildlifeGridCellId } from './gridViewport.js';
|
||||
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
|
||||
|
||||
const NOW = Date.parse('2026-11-04T18:00:00Z');
|
||||
const base = {
|
||||
@@ -52,67 +53,6 @@ function event() {
|
||||
};
|
||||
}
|
||||
|
||||
function primitives() {
|
||||
const values = [];
|
||||
const primitiveAdded = event();
|
||||
const primitiveRemoved = event();
|
||||
return {
|
||||
values,
|
||||
primitiveAdded,
|
||||
primitiveRemoved,
|
||||
get length() {
|
||||
return values.length;
|
||||
},
|
||||
get: (index) => values[index],
|
||||
add(value) {
|
||||
values.push(value);
|
||||
primitiveAdded.emit(value);
|
||||
return value;
|
||||
},
|
||||
remove(value) {
|
||||
const index = values.indexOf(value);
|
||||
if (index < 0) return false;
|
||||
values.splice(index, 1);
|
||||
primitiveRemoved.emit(value);
|
||||
value.destroy?.();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
class PointCollection {
|
||||
values = [];
|
||||
show = false;
|
||||
add(point) {
|
||||
this.values.push(point);
|
||||
return point;
|
||||
}
|
||||
remove(point) {
|
||||
const index = this.values.indexOf(point);
|
||||
if (index < 0) return false;
|
||||
this.values.splice(index, 1);
|
||||
return true;
|
||||
}
|
||||
removeAll() {
|
||||
this.values = [];
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
class Ground {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.ready = false;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
isDestroyed() {
|
||||
return !!this.destroyed;
|
||||
}
|
||||
}
|
||||
|
||||
function harness(
|
||||
source = { getSnapshot: async () => [base] },
|
||||
extra = {},
|
||||
@@ -126,8 +66,6 @@ function harness(
|
||||
const events = new EventTarget();
|
||||
const moveEnd = event();
|
||||
const postRender = event();
|
||||
const pointOwners = primitives();
|
||||
const groundOwners = primitives();
|
||||
const owners = new Map();
|
||||
const overlay = {
|
||||
entries: new Map(),
|
||||
@@ -147,8 +85,6 @@ function harness(
|
||||
const images = [];
|
||||
const viewer = {
|
||||
scene: {
|
||||
primitives: pointOwners,
|
||||
groundPrimitives: groundOwners,
|
||||
postRender,
|
||||
canvas: { clientWidth: width, clientHeight: height },
|
||||
globe: {
|
||||
@@ -159,7 +95,7 @@ function harness(
|
||||
sampleHeight: () =>
|
||||
assert.fail('scene.sampleHeight renders per call; use groundFloor'),
|
||||
pick: () => picked,
|
||||
requestRender: () => assert.fail('must use render governor'),
|
||||
requestRender: () => {},
|
||||
},
|
||||
camera: {
|
||||
positionCartographic: { height: 30_000 },
|
||||
@@ -178,6 +114,34 @@ function harness(
|
||||
removeStaticCredit: (credit) => credits.delete(credit),
|
||||
},
|
||||
};
|
||||
const ports = bindWildlifeViewer(viewer);
|
||||
// The camera port's own listener, there before the layer subscribes.
|
||||
const portMoveEnd = moveEnd.count();
|
||||
// The badges as the draw port holds them, with each item's position under
|
||||
// the name the tests read.
|
||||
clicks.collection = {
|
||||
get values() {
|
||||
// Each badge reads its item live, by id, as a billboard would.
|
||||
const items = () => ports.sets().badges?.items ?? new Map();
|
||||
return [...items().keys()].map(
|
||||
(id) =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get: (_target, key) =>
|
||||
key === 'position'
|
||||
? items().get(id)?.pos
|
||||
: key === 'id'
|
||||
? id
|
||||
: items().get(id)?.[key],
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
get show() {
|
||||
return ports.sets().badges?.show ?? false;
|
||||
},
|
||||
};
|
||||
const ground = { sample: () => 123, resolves: 0 };
|
||||
const layer = createWildlifeSightingsLayer({
|
||||
source,
|
||||
@@ -187,12 +151,6 @@ function harness(
|
||||
ground.resolves++;
|
||||
},
|
||||
},
|
||||
cesium: {
|
||||
...Cesium,
|
||||
BillboardCollection: PointCollection,
|
||||
GroundPrimitive: Ground,
|
||||
GroundPolylinePrimitive: Ground,
|
||||
},
|
||||
now: () => time,
|
||||
setTimer(fn, delay) {
|
||||
const id = ++nextTimer;
|
||||
@@ -241,13 +199,19 @@ function harness(
|
||||
hitTest: (_x, _y, { sourceId }) =>
|
||||
cardHit?.sourceId === sourceId ? cardHit : null,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction(fn) {
|
||||
clicks.callback = fn;
|
||||
},
|
||||
destroy() {
|
||||
clicks.destroyed = true;
|
||||
clicks.callback = null;
|
||||
input: () => ({
|
||||
onClick(fn) {
|
||||
clicks.callback = (click) =>
|
||||
fn({
|
||||
screenPosition: click.position,
|
||||
topHit: picked
|
||||
? { set: 'wildlife', id: picked.id ?? picked.primitive?.id }
|
||||
: null,
|
||||
});
|
||||
return () => {
|
||||
clicks.destroyed = true;
|
||||
clicks.callback = null;
|
||||
};
|
||||
},
|
||||
}),
|
||||
pointer: { isPointerFree: () => pointerFree },
|
||||
@@ -257,17 +221,7 @@ function harness(
|
||||
resolvePickId: (pick) => pick?.id ?? pick?.primitive?.id,
|
||||
isOwnedByOtherLayer: (_layerId, id) => id?.startsWith('other:'),
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteCollection: (_id, collection) => {
|
||||
clicks.collection = collection;
|
||||
},
|
||||
unregisterSpriteCollection: () => {
|
||||
clicks.unregistered = true;
|
||||
},
|
||||
restoreSpriteOrderOnEnable: (id) => {
|
||||
assert.equal(id, 'wildlife-sightings');
|
||||
},
|
||||
},
|
||||
sprites: { spriteDrawOrder: () => -9 },
|
||||
render: { governorRequestRender: (reason) => renders.push(reason) },
|
||||
focus: { requestWorldFocus: (request) => focus.push(request) },
|
||||
openExternal: (url) => links.push(url),
|
||||
@@ -322,11 +276,23 @@ function harness(
|
||||
links,
|
||||
credits,
|
||||
images,
|
||||
groundOwners,
|
||||
pointOwners,
|
||||
ports,
|
||||
events,
|
||||
postRender,
|
||||
moveEnd,
|
||||
/** The density glow's set as the draw port holds it, or undefined. */
|
||||
glow: () => {
|
||||
const set = ports.sets().glow;
|
||||
if (!set) return undefined;
|
||||
return {
|
||||
spec: set.spec,
|
||||
get values() {
|
||||
return [...set.items.values()];
|
||||
},
|
||||
};
|
||||
},
|
||||
/** The layer's own moveEnd listeners. */
|
||||
moveEndListeners: () => moveEnd.count() - portMoveEnd,
|
||||
store,
|
||||
timers,
|
||||
pick: (value) => {
|
||||
@@ -408,8 +374,8 @@ test('terrain warming resamples unchanged point, card and context anchors withou
|
||||
Math.abs(Cesium.Cartographic.fromCartesian(sea.position).height) < 0.01,
|
||||
);
|
||||
assert.equal(
|
||||
h.clicks.collection.values[0],
|
||||
point,
|
||||
h.clicks.collection.values[0].id,
|
||||
point.id,
|
||||
'resampling preserves the point primitive',
|
||||
);
|
||||
assert.deepEqual(
|
||||
@@ -450,50 +416,37 @@ test('terrain warming resamples unchanged point, card and context anchors withou
|
||||
|
||||
test('terrain provider, loaded tilesets and map-source changes refresh anchors and release listeners', async () => {
|
||||
const h = harness(undefined, {}, { autoEnable: false });
|
||||
const tileset = { allTilesLoaded: event() };
|
||||
h.pointOwners.add(tileset);
|
||||
let height = 20;
|
||||
h.ground.sample = () => height;
|
||||
h.layer.init(h.viewer);
|
||||
h.layer.enable(h.viewer);
|
||||
await h.update();
|
||||
const point = h.clicks.collection.values[0];
|
||||
const assertHeight = (expected) =>
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(point.position).height - expected,
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
h.clicks.collection.values[0].position,
|
||||
).height - expected,
|
||||
) < 0.01,
|
||||
);
|
||||
height = 200;
|
||||
h.viewer.scene.globe.terrainProviderChanged.emit({});
|
||||
assertHeight(200);
|
||||
// The base tiles in view finish loading.
|
||||
height = 400;
|
||||
tileset.allTilesLoaded.emit();
|
||||
h.ports.progress({ tilesPending: 1 });
|
||||
assertHeight(200);
|
||||
h.ports.progress({ tilesPending: 0 });
|
||||
assertHeight(400);
|
||||
const nextTileset = { allTilesLoaded: event() };
|
||||
// A tileset is shown or taken away.
|
||||
height = 600;
|
||||
h.pointOwners.add(nextTileset);
|
||||
assert.equal(
|
||||
nextTileset.allTilesLoaded.count(),
|
||||
1,
|
||||
'new tilesets are subscribed without polling',
|
||||
);
|
||||
nextTileset.allTilesLoaded.emit();
|
||||
h.ports.changeSurface();
|
||||
assertHeight(600);
|
||||
height = 800;
|
||||
h.events.dispatchEvent(new Event('gev:map-stack-changed'));
|
||||
assertHeight(800);
|
||||
height = 0;
|
||||
h.pointOwners.remove(nextTileset);
|
||||
assertHeight(0);
|
||||
assert.equal(nextTileset.allTilesLoaded.count(), 0);
|
||||
h.layer.disable();
|
||||
assert.equal(tileset.allTilesLoaded.count(), 0);
|
||||
assert.equal(h.pointOwners.primitiveAdded.count(), 0);
|
||||
assert.equal(h.pointOwners.primitiveRemoved.count(), 0);
|
||||
height = 1000;
|
||||
h.events.dispatchEvent(new Event('gev:map-stack-changed'));
|
||||
assertHeight(0);
|
||||
assert.equal(h.ports.progressListeners(), 0);
|
||||
h.layer.destroy();
|
||||
assert.equal(h.postRender.count(), 0);
|
||||
});
|
||||
@@ -581,7 +534,7 @@ test('sampled ground and sea heights keep badges on top and update them in place
|
||||
const h = harness({ getSnapshot: async () => rows });
|
||||
await h.update();
|
||||
const first = h.clicks.collection.values[0];
|
||||
assert.equal(first.disableDepthTestDistance, Infinity);
|
||||
assert.equal(first.disableDepthTest, Infinity);
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Cartographic.fromCartesian(first.position).height - 123) <
|
||||
0.01,
|
||||
@@ -593,7 +546,7 @@ test('sampled ground and sea heights keep badges on top and update them in place
|
||||
) < 0.01,
|
||||
);
|
||||
await h.update();
|
||||
assert.equal(h.clicks.collection.values[0], first);
|
||||
assert.equal(h.clicks.collection.values[0].id, first.id);
|
||||
for (const change of [
|
||||
{ lon: -122.3 },
|
||||
{ iconic: 'Fungi' },
|
||||
@@ -603,8 +556,8 @@ test('sampled ground and sea heights keep badges on top and update them in place
|
||||
rows = [{ ...rows[0], ...change }];
|
||||
await h.update();
|
||||
assert.equal(
|
||||
h.clicks.collection.values[0],
|
||||
before,
|
||||
h.clicks.collection.values[0].id,
|
||||
before.id,
|
||||
'changed contacts update in place',
|
||||
);
|
||||
}
|
||||
@@ -809,13 +762,7 @@ test('selection subscriptions publish current rows, accepted refreshes, reselect
|
||||
assert.deepEqual(metadata.at(-1), { explicitSelection: false });
|
||||
assert.equal(h.store.selectedEntityId, null);
|
||||
assert.equal(h.clicks.collection.values[0].scale, 1);
|
||||
assert.equal(
|
||||
Cesium.Color.equals(
|
||||
h.clicks.collection.values[0].color,
|
||||
Cesium.Color.WHITE,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(h.clicks.collection.values[0].color, [1, 1, 1, 1]);
|
||||
assert.deepEqual(h.overlay.entries.get('wildlife-sightings-selected'), []);
|
||||
assert.equal(h.layer.clearSightingSelection(), false);
|
||||
h.layer.selectSighting('inat:1');
|
||||
@@ -902,7 +849,7 @@ test('selection subscriptions retain omitted rows and clear on disable and destr
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test('privacy cells stage nonempty batches, request frames until ready, supersede and cancel cleanly', async () => {
|
||||
test('privacy cells drape as one batch per change, are replaced whole and cleared on disable', async () => {
|
||||
let rows = [
|
||||
{
|
||||
...base,
|
||||
@@ -912,36 +859,45 @@ test('privacy cells stage nonempty batches, request frames until ready, supersed
|
||||
];
|
||||
const h = harness({ getSnapshot: async () => rows });
|
||||
await h.update();
|
||||
assert.equal(h.groundOwners.values.length, 2);
|
||||
assert.equal(h.postRender.count(), 1);
|
||||
const pending = [...h.groundOwners.values];
|
||||
h.postRender.emit();
|
||||
assert.equal(h.renders.at(-1), 'wildlife-sightings-staging');
|
||||
const sets = () => h.ports.sets();
|
||||
assert.equal(sets().cells.spec.clampTo, 'both');
|
||||
assert.equal(sets().outlines.spec.clampTo, 'both');
|
||||
const [fill] = sets().cells.items.values();
|
||||
assert.deepEqual(fill.geometry, {
|
||||
kind: 'rectangle',
|
||||
rect: { west: -122.4, south: 47.6, east: -122.2, north: 47.8 },
|
||||
});
|
||||
assert.equal(fill.height, 'clampGround');
|
||||
assert.equal(fill.pickable, false);
|
||||
assert.equal(fill.fill[3], 0.25);
|
||||
const [outline] = sets().outlines.items.values();
|
||||
assert.equal(outline.mode, 'draped');
|
||||
assert.equal(outline.widthPx, 2);
|
||||
assert.equal(outline.positions.length, 5);
|
||||
assert.equal(outline.style.color[3], 0.8);
|
||||
rows = [{ ...rows[0], iconic: 'Fungi' }];
|
||||
await h.update();
|
||||
assert.ok(pending.every((primitive) => primitive.destroyed));
|
||||
assert.equal(h.groundOwners.values.length, 2);
|
||||
for (const primitive of h.groundOwners.values) primitive.ready = true;
|
||||
h.postRender.emit();
|
||||
assert.ok(h.groundOwners.values.every((primitive) => primitive.show));
|
||||
assert.equal(h.postRender.count(), 0);
|
||||
assert.equal(sets().cells.items.size, 1);
|
||||
assert.notDeepEqual(
|
||||
[...sets().cells.items.values()][0].fill,
|
||||
fill.fill,
|
||||
'a new tint replaces the cell',
|
||||
);
|
||||
const writes = sets().cells.writes;
|
||||
h.layer.selectSighting(base.stableId);
|
||||
assert.equal(h.focus.at(-1).kind, 'sighting-area');
|
||||
const selectedRing = h.clicks.collection.values[0];
|
||||
assert.equal(
|
||||
Cesium.Color.equals(selectedRing.color, Cesium.Color.WHITE),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(selectedRing.color, [1, 1, 1, 1]);
|
||||
assert.equal(selectedRing.scale, 1);
|
||||
assert.match(selectedRing.image, /^data:image\/svg/);
|
||||
assert.equal(
|
||||
h.postRender.count(),
|
||||
0,
|
||||
sets().cells.writes,
|
||||
writes,
|
||||
'selection reuses unchanged privacy geometry',
|
||||
);
|
||||
h.layer.disable();
|
||||
assert.equal(h.postRender.count(), 0);
|
||||
assert.equal(h.groundOwners.values.length, 0);
|
||||
assert.equal(sets().cells.items.size, 0);
|
||||
assert.equal(sets().outlines.items.size, 0);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
@@ -969,10 +925,9 @@ test('disable ignores late successes and failures, unregisters owners and hides
|
||||
assert.equal(h.credits.size, 0);
|
||||
assert.deepEqual([...h.overlay.visible.values()], [false, false, false]);
|
||||
assert.equal(h.overlay.entries.size, 0);
|
||||
assert.equal(h.moveEnd.count(), 0);
|
||||
assert.equal(h.moveEndListeners(), 0);
|
||||
h.layer.destroy();
|
||||
assert.equal(h.pointOwners.values.length, 0);
|
||||
assert.equal(h.clicks.unregistered, true);
|
||||
assert.equal(h.ports.sets().badges, undefined, 'the badges set is gone');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1200,7 +1155,7 @@ test('the real manager keeps first enable on after a pan supersedes either a suc
|
||||
await manager.destroyLayer(h.layer.id);
|
||||
}
|
||||
assert.equal(h.owners.size, 0);
|
||||
assert.equal(h.moveEnd.count(), 0);
|
||||
assert.equal(h.moveEndListeners(), 0);
|
||||
assert.equal(manager._listeners.size, 0);
|
||||
}
|
||||
}
|
||||
@@ -1788,9 +1743,7 @@ test('each arriving tile extends the density glow before the remaining tiles fin
|
||||
);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(h.clicks.collection.values.length, 0);
|
||||
const glow = h.pointOwners.values.find(
|
||||
(collection) => collection.allowPicking === false,
|
||||
);
|
||||
const glow = h.glow();
|
||||
assert.equal(glow.values.length, 1);
|
||||
assert.equal(h.layer.getStats().countLabel, '12 sightings in view');
|
||||
publishTile?.(
|
||||
@@ -1822,34 +1775,30 @@ test('grid-only views draw nonpickable glow without observation badges, labels o
|
||||
h.viewer.camera.positionCartographic.height = 1_500_000;
|
||||
await h.update();
|
||||
assert.equal(h.clicks.collection.values.length, 0);
|
||||
const glow = h.pointOwners.values.find(
|
||||
(collection) => collection.allowPicking === false,
|
||||
);
|
||||
const glow = h.glow();
|
||||
assert.ok(glow);
|
||||
assert.equal(glow.values.length, 1);
|
||||
assert.equal(glow.values[0].id, undefined, 'density has no pick identity');
|
||||
assert.equal(glow.spec.pickable, false, 'density takes no part in picks');
|
||||
assert.equal(glow.values[0].pickable, false);
|
||||
assert.equal(h.layer.getStats().countLabel, '12 sightings in view');
|
||||
assert.deepEqual(h.overlay.entries.get('wildlife-sightings-labels'), []);
|
||||
assert.deepEqual(h.overlay.entries.get('wildlife-sightings-selected'), []);
|
||||
assert.equal(h.focus.length, 0);
|
||||
assert.equal(h.postRender.count(), 0);
|
||||
h.layer.disable();
|
||||
assert.equal(glow.destroyed, true);
|
||||
assert.equal(h.glow(), undefined, 'the glow set is disposed');
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.equal(
|
||||
h.pointOwners.values.length,
|
||||
1,
|
||||
'only the empty observation collection remains',
|
||||
h.clicks.collection.values.length,
|
||||
0,
|
||||
'only the empty badges set remains',
|
||||
);
|
||||
h.layer.enable(h.viewer);
|
||||
await h.update();
|
||||
const restored = h.pointOwners.values.find(
|
||||
(collection) => collection.allowPicking === false,
|
||||
);
|
||||
assert.ok(restored);
|
||||
assert.ok(h.glow());
|
||||
h.layer.destroy();
|
||||
assert.equal(restored.destroyed, true);
|
||||
assert.equal(h.pointOwners.values.length, 0);
|
||||
assert.equal(h.glow(), undefined);
|
||||
assert.equal(h.ports.sets().badges, undefined);
|
||||
assert.equal(h.timers.size, 0);
|
||||
});
|
||||
|
||||
@@ -1930,8 +1879,8 @@ test('close and wide views wait for loaded common-name labels without unnamed la
|
||||
rows = [{ ...base, commonName: 'Red-tailed Hawk' }];
|
||||
await h.update();
|
||||
assert.equal(
|
||||
h.clicks.collection.values[0],
|
||||
point,
|
||||
h.clicks.collection.values[0].id,
|
||||
point.id,
|
||||
`${heightM}m: a newly known name reuses the icon`,
|
||||
);
|
||||
const labels = h.overlay.entries.get('wildlife-sightings-labels');
|
||||
@@ -1985,7 +1934,7 @@ test('unavailable grids fail closed to visible sampled sprites without a global
|
||||
h.viewer.camera.positionCartographic.height = 5_000_000;
|
||||
await h.update();
|
||||
assert.equal(h.clicks.collection.values[0].id, 'wildlife:inat:1');
|
||||
assert.ok(h.clicks.collection.values[0].width * 0.5 >= 8);
|
||||
assert.ok(h.clicks.collection.values[0].size[0] * 0.5 >= 8);
|
||||
assert.equal(h.layer.getStats().count, 1);
|
||||
assert.equal(h.layer.getStats().countLabel, '1 sighting in view');
|
||||
assert.equal(h.layer.getStats().partial, undefined);
|
||||
@@ -2104,7 +2053,7 @@ test('accepted observation refreshes publish immediately and disable clears thei
|
||||
for (const lon of [-122.35, -122.3, -122.25]) {
|
||||
rows = [{ ...base, lon }];
|
||||
await h.layer.update();
|
||||
assert.equal(h.clicks.collection.values[0], point);
|
||||
assert.equal(h.clicks.collection.values[0].id, point.id);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(point.position).longitude -
|
||||
@@ -2256,7 +2205,7 @@ test('cold ground cells start on the ellipsoid and one bounded resolve per batch
|
||||
warm = true;
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.ok(Math.abs(heightOf() - 250) < 0.01, 'resolved cell lifts in place');
|
||||
assert.equal(h.clicks.collection.values[0], point);
|
||||
assert.equal(h.clicks.collection.values[0].id, point.id);
|
||||
const before = reads;
|
||||
h.moveEnd.emit();
|
||||
assert.ok(reads - before <= h.clicks.collection.values.length);
|
||||
|
||||
@@ -38,7 +38,7 @@ export function wildlifeMeasure(stage, work) {
|
||||
}
|
||||
|
||||
// A unit is at most 128 cells/billboards. The one-millisecond target leaves
|
||||
// room for the last unit, Cesium setters and the overlay host within 4ms.
|
||||
// room for the last unit, draw-set writes and the overlay host within 4ms.
|
||||
export const WILDLIFE_WORK_UNIT = 128;
|
||||
const WILDLIFE_WORK_SLICE_MS = 1;
|
||||
export const WILDLIFE_SYNC_CELL_LIMIT = 256;
|
||||
|
||||
@@ -44,9 +44,6 @@ export const WILDLIFE_RENDER_LIMIT = 5_000;
|
||||
// Bound candidates before the overlay host's final declutter.
|
||||
export const WILDLIFE_LABEL_LIMIT = 150;
|
||||
export const WILDLIFE_LABEL_NAME_SEPARATION_PX = 80;
|
||||
// Hidden ground batches may need several render passes to compile. Retire a
|
||||
// failed staging batch after a bounded number instead of holding rendering.
|
||||
export const WILDLIFE_GROUND_READY_MAX_CHECKS = 16;
|
||||
|
||||
// Camera-height thresholds use +/-10% hysteresis to keep representations still
|
||||
// while a camera settles near a boundary.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
|
||||
import { createSelection } from './selection.js';
|
||||
|
||||
export const DENSE_CONTINENT_CELLS = 6 * 32 * 32;
|
||||
export const DENSE_CONTINENT_ROWS = 500;
|
||||
const NOW = Date.parse('2026-11-04T18:00:00Z');
|
||||
|
||||
/** The real render + selection pipeline with Cesium coordinates/billboards.
|
||||
* Only the WebGL scene and external overlay host are replaced. Six fully
|
||||
/** The real render + selection pipeline with ECEF anchors and badges on a
|
||||
* fake draw port. Only the renderer and external overlay host are replaced. Six fully
|
||||
* occupied logical tiles deliberately include off-window cells and collisions. */
|
||||
export function denseContinentalRendering({ onOperations } = {}) {
|
||||
const cells = [];
|
||||
@@ -41,17 +42,7 @@ export function denseContinentalRendering({ onOperations } = {}) {
|
||||
obscured: false,
|
||||
cell: null,
|
||||
}));
|
||||
const primitives = {
|
||||
add: (value) => value,
|
||||
remove(value) {
|
||||
value.destroy();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
const scene = {
|
||||
canvas: { clientWidth: 1440, clientHeight: 900 },
|
||||
primitives,
|
||||
};
|
||||
const scene = { canvas: { clientWidth: 1440, clientHeight: 900 } };
|
||||
const state = {
|
||||
enabled: true,
|
||||
viewer: {
|
||||
@@ -66,7 +57,7 @@ export function denseContinentalRendering({ onOperations } = {}) {
|
||||
pointById: new Map(),
|
||||
positions: new Map(),
|
||||
cells: [],
|
||||
staging: null,
|
||||
cellSets: null,
|
||||
taxa: 'all',
|
||||
selectedId: null,
|
||||
query: { visibleBoxes: [{ south: 5, west: -130, north: 75, east: -50 }] },
|
||||
@@ -77,10 +68,16 @@ export function denseContinentalRendering({ onOperations } = {}) {
|
||||
carriers: new Map(),
|
||||
contextIds: new Set(),
|
||||
};
|
||||
const centre = Cesium.Cartesian3.fromDegrees(-90, 42);
|
||||
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(centre);
|
||||
const east = Cesium.Matrix4.getColumn(frame, 0, new Cesium.Cartesian4());
|
||||
const north = Cesium.Matrix4.getColumn(frame, 1, new Cesium.Cartesian4());
|
||||
bindWildlifeViewer(state.viewer);
|
||||
// The local east and north axes at 42 N, 90 W.
|
||||
const lon = (-90 * Math.PI) / 180;
|
||||
const lat = (42 * Math.PI) / 180;
|
||||
const east = { x: -Math.sin(lon), y: Math.cos(lon), z: 0 };
|
||||
const north = {
|
||||
x: -Math.sin(lat) * Math.cos(lon),
|
||||
y: -Math.sin(lat) * Math.sin(lon),
|
||||
z: Math.cos(lat),
|
||||
};
|
||||
const metrics = { projections: 0, publications: 0, cartesianBuilds: 0 };
|
||||
let pan = 0;
|
||||
let nextIdle = 0;
|
||||
@@ -106,14 +103,9 @@ export function denseContinentalRendering({ onOperations } = {}) {
|
||||
performanceSlice(slice) {
|
||||
slices.push(slice);
|
||||
},
|
||||
cesium: {
|
||||
...Cesium,
|
||||
Cartesian3: class extends Cesium.Cartesian3 {
|
||||
static fromDegrees(...args) {
|
||||
metrics.cartesianBuilds++;
|
||||
return Cesium.Cartesian3.fromDegrees(...args);
|
||||
}
|
||||
},
|
||||
fromDegrees(...args) {
|
||||
metrics.cartesianBuilds++;
|
||||
return fromDegrees(...args);
|
||||
},
|
||||
project(_scene, anchor) {
|
||||
metrics.projections++;
|
||||
|
||||
@@ -6,6 +6,15 @@ import {
|
||||
} from './model.js';
|
||||
import { createWildlifeBillboardModel } from './billboardModel.js';
|
||||
import { createWildlifeDensity } from './density.js';
|
||||
import { createWildlifeIconCollection } from './iconCollection.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import {
|
||||
canvasOf,
|
||||
drawOf,
|
||||
findCamera,
|
||||
findGlobe,
|
||||
} from '../../render/rendererOf.js';
|
||||
import { wildlifeSpriteCache } from './sprites.js';
|
||||
import { isRecentWildlifeSighting } from './records.js';
|
||||
import {
|
||||
@@ -17,14 +26,24 @@ import {
|
||||
import {
|
||||
WILDLIFE_SCALE_BY_DISTANCE,
|
||||
WILDLIFE_BADGE_MAX_PX,
|
||||
WILDLIFE_GROUND_READY_MAX_CHECKS,
|
||||
WILDLIFE_SPRITE_PX,
|
||||
} from './policy.js';
|
||||
|
||||
/** Live layer instances, for set ids unique among a renderer's sets. */
|
||||
let instances = 0;
|
||||
|
||||
/** A rebuilt anchor that lands where the old one was. */
|
||||
function sameAnchor(a, b) {
|
||||
return !!a && !!b && a.x === b.x && a.y === b.y && a.z === b.z;
|
||||
}
|
||||
|
||||
/** Own sighting billboards, density glow and batched privacy cells. */
|
||||
export function createRendering({ state, services, parts }) {
|
||||
const C = services.cesium;
|
||||
const spriteDrawOrder =
|
||||
services.sprites?.spriteDrawOrder?.('wildlife-sightings') ?? 0;
|
||||
const badgeSprites = services.badgeSprites ?? wildlifeSpriteCache();
|
||||
// How anchors are built from degrees (a test may count the builds).
|
||||
const anchorAt = services.fromDegrees ?? fromDegrees;
|
||||
let batchDepth = 0;
|
||||
let pendingRenderReason = null;
|
||||
let billboards = null;
|
||||
@@ -46,12 +65,16 @@ export function createRendering({ state, services, parts }) {
|
||||
function surfaceAnchor(row) {
|
||||
const old = surfaceAnchors.get(row);
|
||||
if (old && old.lat === row.lat && old.lon === row.lon) return old.anchor;
|
||||
const anchor = C.Cartesian3.fromDegrees(row.lon, row.lat);
|
||||
const anchor = anchorAt(row.lon, row.lat);
|
||||
surfaceAnchors.set(row, { lat: row.lat, lon: row.lon, anchor });
|
||||
if (operations) operations.positionBuilds++;
|
||||
return anchor;
|
||||
}
|
||||
const requestRender = (reason) => {
|
||||
// Every write is followed by a render request: send the sets what was
|
||||
// written before the frame is asked for.
|
||||
state.points?.flush();
|
||||
density?.flush();
|
||||
if (batchDepth) {
|
||||
pendingRenderReason = reason;
|
||||
return;
|
||||
@@ -69,7 +92,6 @@ export function createRendering({ state, services, parts }) {
|
||||
requestRender(reason);
|
||||
}
|
||||
const surfaceRemovers = [];
|
||||
const tilesetRemovers = new Map();
|
||||
|
||||
// Reuse the shared ground cache. One bounded resolve lifts cold anchors
|
||||
// without per-sighting scene renders and pixel readback.
|
||||
@@ -84,7 +106,7 @@ export function createRendering({ state, services, parts }) {
|
||||
queueMicrotask(warmColdFloors);
|
||||
}
|
||||
return Number.isFinite(floor) && floor !== 0
|
||||
? C.Cartesian3.fromDegrees(row.lon, row.lat, floor)
|
||||
? anchorAt(row.lon, row.lat, floor)
|
||||
: surfaceAnchor(row);
|
||||
}
|
||||
|
||||
@@ -106,8 +128,8 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
|
||||
function occluder() {
|
||||
const camera = state.viewer?.camera;
|
||||
return camera?.positionWC ? services.occluderFactory?.(camera) : null;
|
||||
const eye = state.viewer ? findCamera(state.viewer)?.pose().position : null;
|
||||
return eye ? services.occluderFactory?.(eye) : null;
|
||||
}
|
||||
|
||||
function cull() {
|
||||
@@ -203,8 +225,7 @@ export function createRendering({ state, services, parts }) {
|
||||
const point = state.pointById.get(row.stableId);
|
||||
if (!point) continue;
|
||||
const anchor = position(row);
|
||||
if (C.Cartesian3.equals(anchor, state.positions.get(row.stableId)))
|
||||
continue;
|
||||
if (sameAnchor(anchor, state.positions.get(row.stableId))) continue;
|
||||
point.position = anchor;
|
||||
state.positions.set(row.stableId, anchor);
|
||||
changed = true;
|
||||
@@ -223,31 +244,15 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
}
|
||||
|
||||
function trackTileset(primitive) {
|
||||
if (
|
||||
tilesetRemovers.has(primitive) ||
|
||||
typeof primitive?.allTilesLoaded?.addEventListener !== 'function'
|
||||
)
|
||||
return false;
|
||||
tilesetRemovers.set(
|
||||
primitive,
|
||||
primitive.allTilesLoaded.addEventListener(resampleAnchors),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
function deactivate() {
|
||||
workQueue.cancel();
|
||||
operations = null;
|
||||
for (const remove of surfaceRemovers.splice(0)) remove?.();
|
||||
for (const remove of tilesetRemovers.values()) remove?.();
|
||||
tilesetRemovers.clear();
|
||||
}
|
||||
|
||||
function activate() {
|
||||
deactivate();
|
||||
if (!state.enabled || !state.viewer) return;
|
||||
const scene = state.viewer.scene;
|
||||
const refreshBadgeImages = () => {
|
||||
if (!state.enabled) return;
|
||||
appearances.clear();
|
||||
@@ -256,31 +261,24 @@ export function createRendering({ state, services, parts }) {
|
||||
};
|
||||
surfaceRemovers.push(badgeSprites.subscribe(refreshBadgeImages));
|
||||
refreshBadgeImages();
|
||||
const ownEvent = (event, listener) => {
|
||||
const remove = event?.addEventListener?.(listener);
|
||||
if (typeof remove === 'function') surfaceRemovers.push(remove);
|
||||
};
|
||||
ownEvent(scene.globe?.tileLoadProgressEvent, (pending) => {
|
||||
if (pending === 0) resampleAnchors();
|
||||
});
|
||||
// Scene forwards the globe event in Cesium; deduplicate that alias.
|
||||
for (const event of new Set([
|
||||
scene.terrainProviderChanged,
|
||||
scene.globe?.terrainProviderChanged,
|
||||
]))
|
||||
ownEvent(event, resampleAnchors);
|
||||
const primitives = scene.primitives;
|
||||
for (let i = 0; i < (primitives?.length || 0); i++)
|
||||
trackTileset(primitives.get(i));
|
||||
ownEvent(primitives?.primitiveAdded, (primitive) => {
|
||||
if (trackTileset(primitive)) resampleAnchors();
|
||||
});
|
||||
ownEvent(primitives?.primitiveRemoved, (primitive) => {
|
||||
if (!tilesetRemovers.has(primitive)) return;
|
||||
tilesetRemovers.get(primitive)?.();
|
||||
tilesetRemovers.delete(primitive);
|
||||
resampleAnchors();
|
||||
// Anchors follow the ground: resample once terrain or the base tiles in
|
||||
// view finish loading, and when what heights answer against changes
|
||||
// (terrain, the shown tilesets).
|
||||
const globe = findGlobe(state.viewer);
|
||||
let surface = globe?.surfaceVersion?.();
|
||||
// Loaded until the port says otherwise.
|
||||
let pending = { tilesPending: 0, terrainPending: 0 };
|
||||
const off = globe?.on?.('progress', (progress) => {
|
||||
const version = globe.surfaceVersion?.();
|
||||
const surfaceChanged = version !== surface;
|
||||
surface = version;
|
||||
const loaded =
|
||||
(progress.terrainPending === 0 && pending.terrainPending !== 0) ||
|
||||
(progress.tilesPending === 0 && pending.tilesPending !== 0);
|
||||
pending = progress;
|
||||
if (surfaceChanged || loaded) resampleAnchors();
|
||||
});
|
||||
if (typeof off === 'function') surfaceRemovers.push(off);
|
||||
services.eventTarget?.addEventListener?.(
|
||||
'gev:map-stack-changed',
|
||||
resampleAnchors,
|
||||
@@ -293,26 +291,12 @@ export function createRendering({ state, services, parts }) {
|
||||
);
|
||||
}
|
||||
|
||||
function removeCell(primitive) {
|
||||
const owners =
|
||||
state.viewer?.scene?.groundPrimitives || state.viewer?.scene?.primitives;
|
||||
if (owners?.remove?.(primitive) !== true && !primitive.isDestroyed?.())
|
||||
primitive.destroy?.();
|
||||
}
|
||||
|
||||
function cancelStaging() {
|
||||
const pending = state.staging;
|
||||
if (!pending) return;
|
||||
state.staging = null;
|
||||
pending.remove?.();
|
||||
for (const primitive of pending.primitives) removeCell(primitive);
|
||||
}
|
||||
|
||||
function clearCells() {
|
||||
cancelStaging();
|
||||
for (const primitive of state.cells) removeCell(primitive);
|
||||
state.cells = [];
|
||||
cellsSignature = null;
|
||||
if (!state.cellSets) return;
|
||||
state.cellSets.fills.clear();
|
||||
state.cellSets.outlines.clear();
|
||||
}
|
||||
|
||||
function stageCells(rows) {
|
||||
@@ -328,7 +312,6 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
const signature = JSON.stringify([...unique.keys()].sort());
|
||||
if (signature === cellsSignature) return false;
|
||||
cancelStaging();
|
||||
if (!unique.size) {
|
||||
clearCells();
|
||||
cellsSignature = signature;
|
||||
@@ -337,102 +320,44 @@ export function createRendering({ state, services, parts }) {
|
||||
cellsSignature = signature;
|
||||
const fills = [];
|
||||
const outlines = [];
|
||||
let index = 0;
|
||||
for (const row of unique.values()) {
|
||||
const { south, west, north, east } = row.cell;
|
||||
const tint = C.Color.fromCssColorString(wildlifeAccent(row.iconic));
|
||||
fills.push(
|
||||
new C.GeometryInstance({
|
||||
geometry: new C.RectangleGeometry({
|
||||
rectangle: C.Rectangle.fromDegrees(west, south, east, north),
|
||||
vertexFormat: C.PerInstanceColorAppearance.VERTEX_FORMAT,
|
||||
}),
|
||||
attributes: {
|
||||
color: C.ColorGeometryInstanceAttribute.fromColor(
|
||||
tint.withAlpha(0.25),
|
||||
),
|
||||
},
|
||||
}),
|
||||
);
|
||||
outlines.push(
|
||||
new C.GeometryInstance({
|
||||
geometry: new C.GroundPolylineGeometry({
|
||||
positions: C.Cartesian3.fromDegreesArray([
|
||||
west,
|
||||
south,
|
||||
east,
|
||||
south,
|
||||
east,
|
||||
north,
|
||||
west,
|
||||
north,
|
||||
west,
|
||||
south,
|
||||
]),
|
||||
width: 2,
|
||||
}),
|
||||
attributes: {
|
||||
color: C.ColorGeometryInstanceAttribute.fromColor(
|
||||
tint.withAlpha(0.8),
|
||||
),
|
||||
},
|
||||
}),
|
||||
);
|
||||
const tint = cssColor(wildlifeAccent(row.iconic)) ?? [1, 1, 1, 1];
|
||||
const id = `cell:${index++}`;
|
||||
fills.push({
|
||||
id,
|
||||
geometry: { kind: 'rectangle', rect: { west, south, east, north } },
|
||||
fill: [tint[0], tint[1], tint[2], 0.25],
|
||||
height: 'clampGround',
|
||||
pickable: false,
|
||||
});
|
||||
outlines.push({
|
||||
id,
|
||||
positions: [
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
[west, south],
|
||||
].map(([lon, lat]) => fromDegrees(lon, lat)),
|
||||
widthPx: 2,
|
||||
mode: 'draped',
|
||||
style: { kind: 'solid', color: [tint[0], tint[1], tint[2], 0.8] },
|
||||
pickable: false,
|
||||
});
|
||||
}
|
||||
// Hidden primitives still compile their geometry. Poll only these two
|
||||
// nonempty batches, then atomically retire the previous privacy cells.
|
||||
const primitives = [
|
||||
new C.GroundPrimitive({
|
||||
geometryInstances: fills,
|
||||
appearance: new C.PerInstanceColorAppearance({
|
||||
flat: true,
|
||||
translucent: true,
|
||||
}),
|
||||
classificationType: C.ClassificationType.BOTH,
|
||||
allowPicking: false,
|
||||
releaseGeometryInstances: false,
|
||||
show: false,
|
||||
}),
|
||||
new C.GroundPolylinePrimitive({
|
||||
geometryInstances: outlines,
|
||||
appearance: new C.PolylineColorAppearance(),
|
||||
classificationType: C.ClassificationType.BOTH,
|
||||
allowPicking: false,
|
||||
releaseGeometryInstances: false,
|
||||
show: false,
|
||||
}),
|
||||
];
|
||||
const owners =
|
||||
state.viewer.scene.groundPrimitives || state.viewer.scene.primitives;
|
||||
for (const primitive of primitives) owners.add(primitive);
|
||||
const pending = { primitives, remove: null, checks: 0 };
|
||||
state.staging = pending;
|
||||
const ready = () => {
|
||||
if (state.staging !== pending || !state.enabled) return;
|
||||
if (!primitives.every((primitive) => primitive.ready === true)) {
|
||||
pending.checks += 1;
|
||||
if (pending.checks >= WILDLIFE_GROUND_READY_MAX_CHECKS) {
|
||||
cancelStaging();
|
||||
cellsSignature = null;
|
||||
return;
|
||||
}
|
||||
requestRender('staging');
|
||||
return;
|
||||
}
|
||||
pending.remove?.();
|
||||
state.staging = null;
|
||||
for (const primitive of state.cells) removeCell(primitive);
|
||||
state.cells = primitives;
|
||||
for (const primitive of primitives) primitive.show = true;
|
||||
requestRender('render');
|
||||
};
|
||||
pending.remove = state.viewer.scene.postRender?.addEventListener?.(ready);
|
||||
ready();
|
||||
// Each set swaps its whole contents at once, so the previous privacy
|
||||
// cells go as the new ones arrive.
|
||||
state.cellSets.fills.set(fills);
|
||||
state.cellSets.outlines.set(outlines);
|
||||
state.cells = fills;
|
||||
requestRender('render');
|
||||
return true;
|
||||
}
|
||||
|
||||
function init() {
|
||||
density = createWildlifeDensity({
|
||||
cesium: C,
|
||||
viewer: state.viewer,
|
||||
positionForCell: surfaceAnchor,
|
||||
requestRender,
|
||||
@@ -442,14 +367,18 @@ export function createRendering({ state, services, parts }) {
|
||||
cancelIdle: services.cancelIdleCallback,
|
||||
eventTarget: services.eventTarget,
|
||||
});
|
||||
state.points = new C.BillboardCollection();
|
||||
state.points.show = false;
|
||||
state.viewer.scene.primitives.add(state.points);
|
||||
services.sprites?.registerSpriteCollection?.(
|
||||
'wildlife-sightings',
|
||||
state.points,
|
||||
const draw = drawOf(state.viewer);
|
||||
const prefix = `wildlife-sightings:${++instances}`;
|
||||
state.cellSets = {
|
||||
fills: draw.shapes({ id: `${prefix}:cells`, clampTo: 'both' }),
|
||||
outlines: draw.lines({ id: `${prefix}:cell-outlines`, clampTo: 'both' }),
|
||||
};
|
||||
state.points = createWildlifeIconCollection(
|
||||
draw.icons({ id: `${prefix}:badges`, drawOrder: spriteDrawOrder }),
|
||||
);
|
||||
const distanceScale = new C.NearFarScalar(...WILDLIFE_SCALE_BY_DISTANCE);
|
||||
state.points.show = false;
|
||||
const [near, nearValue, far, farValue] = WILDLIFE_SCALE_BY_DISTANCE;
|
||||
const distanceScale = { near, nearValue, far, farValue };
|
||||
billboards = createWildlifeBillboardModel({
|
||||
collection: state.points,
|
||||
pointById: state.pointById,
|
||||
@@ -459,14 +388,13 @@ export function createRendering({ state, services, parts }) {
|
||||
if (!appearances.has(group))
|
||||
appearances.set(group, {
|
||||
image: badgeSprites.get(group),
|
||||
width: WILDLIFE_SPRITE_PX,
|
||||
height: WILDLIFE_SPRITE_PX,
|
||||
size: [WILDLIFE_SPRITE_PX, WILDLIFE_SPRITE_PX],
|
||||
// The sprite includes its tint and white glyph. Multiplication
|
||||
// by a taxon colour would tint the glyph as well.
|
||||
color: C.Color.WHITE,
|
||||
color: [1, 1, 1, 1],
|
||||
scale: 1,
|
||||
scaleByDistance: distanceScale,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
return appearances.get(group);
|
||||
},
|
||||
@@ -505,7 +433,7 @@ export function createRendering({ state, services, parts }) {
|
||||
};
|
||||
const nowMs = services.now();
|
||||
const taxa = state.drawnParams?.taxa ?? state.taxa;
|
||||
const scene = state.viewer.scene;
|
||||
const canvas = canvasOf(state.viewer);
|
||||
const horizon = occluder();
|
||||
const densityResult = yield* density.updateWork(
|
||||
state.gridAvailable ? state.gridCells || [] : [],
|
||||
@@ -517,8 +445,6 @@ export function createRendering({ state, services, parts }) {
|
||||
onOperations: (counts) => Object.assign(operations, counts),
|
||||
},
|
||||
);
|
||||
if (densityResult.changed)
|
||||
services.sprites?.restoreSpriteOrder?.(state.viewer);
|
||||
const model = yield* wildlifeIconModelWork({
|
||||
rows: [...state.rows.values()].filter(
|
||||
(row) =>
|
||||
@@ -538,13 +464,13 @@ export function createRendering({ state, services, parts }) {
|
||||
cached.screen = null;
|
||||
if (horizon && horizon.isPointVisible(anchor) !== true)
|
||||
return null;
|
||||
const screen = services.project(scene, anchor);
|
||||
const screen = services.project(state.viewer, anchor);
|
||||
if (
|
||||
!screen ||
|
||||
screen.x < 0 ||
|
||||
screen.y < 0 ||
|
||||
screen.x >= (scene.canvas?.clientWidth ?? Infinity) ||
|
||||
screen.y >= (scene.canvas?.clientHeight ?? Infinity)
|
||||
screen.x >= (canvas?.clientWidth ?? Infinity) ||
|
||||
screen.y >= (canvas?.clientHeight ?? Infinity)
|
||||
)
|
||||
return null;
|
||||
cached.screen = screen;
|
||||
@@ -654,12 +580,11 @@ export function createRendering({ state, services, parts }) {
|
||||
function destroy() {
|
||||
deactivate();
|
||||
clear();
|
||||
services.sprites?.unregisterSpriteCollection?.(
|
||||
'wildlife-sightings',
|
||||
state.points,
|
||||
);
|
||||
if (state.points) state.viewer?.scene?.primitives?.remove?.(state.points);
|
||||
state.points?.dispose();
|
||||
state.points = null;
|
||||
state.cellSets?.fills.dispose();
|
||||
state.cellSets?.outlines.dispose();
|
||||
state.cellSets = null;
|
||||
billboards = null;
|
||||
density?.destroy();
|
||||
density = null;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { nearFarScalarValueAtDistance } from '../../data/focusDeemphasis.js';
|
||||
import { wildlifeGridCellId } from './gridViewport.js';
|
||||
import {
|
||||
WILDLIFE_GROUND_READY_MAX_CHECKS,
|
||||
WILDLIFE_SCALE_BY_DISTANCE,
|
||||
} from './policy.js';
|
||||
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { WILDLIFE_SCALE_BY_DISTANCE } from './policy.js';
|
||||
|
||||
const NOW = Date.parse('2026-11-04T18:00:00Z');
|
||||
const base = {
|
||||
@@ -40,104 +38,95 @@ function event() {
|
||||
}
|
||||
|
||||
function harness(rows = [base], extra = {}) {
|
||||
// Counts read after the badges' batched writes reach their set.
|
||||
const tally = { created: 0, removed: 0, cleared: 0, writes: [] };
|
||||
const flushed = (key) => () => {
|
||||
state.points?.flush();
|
||||
return tally[key];
|
||||
};
|
||||
const counts = {
|
||||
collections: 0,
|
||||
created: 0,
|
||||
removed: 0,
|
||||
cleared: 0,
|
||||
writes: [],
|
||||
get created() {
|
||||
return flushed('created')();
|
||||
},
|
||||
get removed() {
|
||||
return flushed('removed')();
|
||||
},
|
||||
get cleared() {
|
||||
return flushed('cleared')();
|
||||
},
|
||||
get writes() {
|
||||
return flushed('writes')();
|
||||
},
|
||||
};
|
||||
// What a badge's item changes, by the billboard property names it had.
|
||||
const tracked = {
|
||||
pos: 'position',
|
||||
image: 'image',
|
||||
color: 'color',
|
||||
scale: 'scale',
|
||||
show: 'show',
|
||||
size: 'width',
|
||||
scaleByDistance: 'scaleByDistance',
|
||||
};
|
||||
const tracked = new Set([
|
||||
'position',
|
||||
'image',
|
||||
'color',
|
||||
'scale',
|
||||
'show',
|
||||
'width',
|
||||
'height',
|
||||
'scaleByDistance',
|
||||
]);
|
||||
class BillboardCollection extends Cesium.BillboardCollection {
|
||||
constructor() {
|
||||
super();
|
||||
counts.collections += 1;
|
||||
}
|
||||
add(options) {
|
||||
counts.created += 1;
|
||||
const point = super.add(options);
|
||||
return new Proxy(point, {
|
||||
get: (target, key) => Reflect.get(target, key, target),
|
||||
set(target, key, value) {
|
||||
if (tracked.has(key)) counts.writes.push(key);
|
||||
return Reflect.set(target, key, value, target);
|
||||
},
|
||||
});
|
||||
}
|
||||
remove(point) {
|
||||
counts.removed += 1;
|
||||
return super.remove(point);
|
||||
}
|
||||
removeAll() {
|
||||
counts.cleared += 1;
|
||||
return super.removeAll();
|
||||
}
|
||||
}
|
||||
class GroundBatch {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.ready = false;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
isDestroyed() {
|
||||
return this.destroyed === true;
|
||||
}
|
||||
}
|
||||
function primitives() {
|
||||
const values = [];
|
||||
return {
|
||||
values,
|
||||
get length() {
|
||||
return values.length;
|
||||
},
|
||||
get: (i) => values[i],
|
||||
add(primitive) {
|
||||
values.push(primitive);
|
||||
return primitive;
|
||||
},
|
||||
remove(primitive) {
|
||||
const i = values.indexOf(primitive);
|
||||
if (i < 0) return false;
|
||||
values.splice(i, 1);
|
||||
primitive.destroy();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
const postRender = event();
|
||||
const terrain = event();
|
||||
const tileProgress = event();
|
||||
const scene = {
|
||||
primitives: primitives(),
|
||||
groundPrimitives: primitives(),
|
||||
postRender,
|
||||
terrainProviderChanged: terrain,
|
||||
globe: {
|
||||
terrainProviderChanged: terrain,
|
||||
tileLoadProgressEvent: tileProgress,
|
||||
},
|
||||
};
|
||||
const viewer = {
|
||||
scene,
|
||||
camera: { positionWC: {}, positionCartographic: { height: 0 } },
|
||||
};
|
||||
const ports = bindWildlifeViewer(viewer);
|
||||
// Count the badges set's item writes as billboard writes were counted.
|
||||
const icons = ports.draw.icons;
|
||||
ports.draw.icons = (spec) => {
|
||||
const set = icons(spec);
|
||||
if (!spec.id.endsWith(':badges')) return set;
|
||||
counts.collections += 1;
|
||||
const record = ports.draw.sets.get(spec.id);
|
||||
const upsert = set.upsert;
|
||||
set.upsert = (items) => {
|
||||
for (const item of items) {
|
||||
const old = record.items.get(item.id);
|
||||
if (!old) {
|
||||
tally.created += 1;
|
||||
continue;
|
||||
}
|
||||
for (const [key, name] of Object.entries(tracked))
|
||||
if (JSON.stringify(old[key]) !== JSON.stringify(item[key]))
|
||||
tally.writes.push(name);
|
||||
}
|
||||
upsert(items);
|
||||
};
|
||||
const remove = set.remove;
|
||||
set.remove = (ids) => {
|
||||
tally.removed += ids.length;
|
||||
remove(ids);
|
||||
};
|
||||
const clear = set.clear;
|
||||
set.clear = () => {
|
||||
tally.cleared += 1;
|
||||
clear();
|
||||
};
|
||||
return set;
|
||||
};
|
||||
const state = {
|
||||
enabled: true,
|
||||
viewer: { scene, camera: { positionWC: {} } },
|
||||
viewer,
|
||||
rows: new Map(rows.map((row) => [row.stableId, row])),
|
||||
renderedRows: [],
|
||||
rowById: new Map(),
|
||||
pointById: new Map(),
|
||||
positions: new Map(),
|
||||
cells: [],
|
||||
staging: null,
|
||||
cellSets: null,
|
||||
taxa: 'all',
|
||||
selectedId: null,
|
||||
query: { visibleBoxes: [{ south: -90, west: -180, north: 90, east: 180 }] },
|
||||
@@ -145,23 +134,13 @@ function harness(rows = [base], extra = {}) {
|
||||
};
|
||||
const renders = [];
|
||||
let visible = true;
|
||||
const registration = new Set();
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: {
|
||||
now: () => NOW,
|
||||
cesium: {
|
||||
...Cesium,
|
||||
BillboardCollection,
|
||||
GroundPrimitive: GroundBatch,
|
||||
GroundPolylinePrimitive: GroundBatch,
|
||||
},
|
||||
occluderFactory: () => ({ isPointVisible: () => visible }),
|
||||
render: { governorRequestRender: (reason) => renders.push(reason) },
|
||||
sprites: {
|
||||
registerSpriteCollection: (_id, value) => registration.add(value),
|
||||
unregisterSpriteCollection: (_id, value) => registration.delete(value),
|
||||
},
|
||||
sprites: { spriteDrawOrder: () => -9 },
|
||||
...extra,
|
||||
},
|
||||
parts: {
|
||||
@@ -180,13 +159,14 @@ function harness(rows = [base], extra = {}) {
|
||||
return {
|
||||
state,
|
||||
scene,
|
||||
ports,
|
||||
sets: () => ports.sets(),
|
||||
rendering,
|
||||
counts,
|
||||
renders,
|
||||
postRender,
|
||||
terrain,
|
||||
tileProgress,
|
||||
registration,
|
||||
visible(value) {
|
||||
visible = value;
|
||||
},
|
||||
@@ -196,7 +176,7 @@ function harness(rows = [base], extra = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
test('real Cesium billboard values update in place, and unchanged refreshes write nothing', () => {
|
||||
test('badge values update in place, and unchanged refreshes write nothing', () => {
|
||||
const second = { ...base, stableId: 'synthetic:2', lon: -120 };
|
||||
const h = harness([base, second]);
|
||||
h.rendering.rebuild();
|
||||
@@ -204,12 +184,15 @@ test('real Cesium billboard values update in place, and unchanged refreshes writ
|
||||
const incumbent = h.state.pointById.get(base.stableId);
|
||||
assert.equal(h.counts.collections, 1);
|
||||
assert.equal(h.counts.created, 2);
|
||||
assert.equal(incumbent.width * incumbent.scaleByDistance.farValue, 12);
|
||||
assert.deepEqual(
|
||||
incumbent.scaleByDistance,
|
||||
new Cesium.NearFarScalar(...WILDLIFE_SCALE_BY_DISTANCE),
|
||||
);
|
||||
assert.equal(incumbent.color.alpha, 1);
|
||||
assert.equal(incumbent.size[0] * incumbent.scaleByDistance.farValue, 12);
|
||||
const [near, nearValue, far, farValue] = WILDLIFE_SCALE_BY_DISTANCE;
|
||||
assert.deepEqual(incumbent.scaleByDistance, {
|
||||
near,
|
||||
nearValue,
|
||||
far,
|
||||
farValue,
|
||||
});
|
||||
assert.equal(incumbent.color[3], 1);
|
||||
h.counts.writes.length = 0;
|
||||
h.renders.length = 0;
|
||||
h.rows([{ ...second }, { ...base }]);
|
||||
@@ -231,8 +214,8 @@ test('real Cesium billboard values update in place, and unchanged refreshes writ
|
||||
assert.equal(h.counts.removed, 1);
|
||||
assert.equal(h.counts.cleared, 0);
|
||||
h.rendering.destroy();
|
||||
assert.equal(h.registration.size, 0);
|
||||
assert.equal(h.scene.primitives.length, 0);
|
||||
assert.deepEqual(Object.values(h.sets()).filter(Boolean), []);
|
||||
assert.equal(h.ports.progressListeners(), 0);
|
||||
assert.equal(h.state.pointById.size, 0);
|
||||
assert.equal(h.terrain.size, 0);
|
||||
assert.equal(h.tileProgress.size, 0);
|
||||
@@ -267,7 +250,7 @@ test('badge pixels stay between 12 and 22 at near, mid and far heights, includin
|
||||
0, 1000, 9000, 120_000, 400_000, 1_500_000, 8_000_000, 10_000_000,
|
||||
]) {
|
||||
const pixels =
|
||||
wildlife.width *
|
||||
wildlife.size[0] *
|
||||
wildlife.scale *
|
||||
nearFarScalarValueAtDistance(wildlife.scaleByDistance, heightM);
|
||||
assert.ok(
|
||||
@@ -278,7 +261,7 @@ test('badge pixels stay between 12 and 22 at near, mid and far heights, includin
|
||||
}
|
||||
assert.deepEqual(
|
||||
wildlife.color,
|
||||
Cesium.Color.WHITE,
|
||||
[1, 1, 1, 1],
|
||||
'keep the baked white glyph white',
|
||||
);
|
||||
h.rendering.destroy();
|
||||
@@ -293,9 +276,7 @@ test('adjacent 28px bucket edges never overlap badges or erase sighting counts',
|
||||
}));
|
||||
const h = harness(rows, {
|
||||
project: (_scene, anchor) => {
|
||||
const lon = Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(anchor).longitude,
|
||||
);
|
||||
const lon = toLonLatH(anchor).lon;
|
||||
return {
|
||||
x: rows.find((row) => Math.abs(row.lon - lon) < 1e-7).x,
|
||||
y: 100,
|
||||
@@ -366,17 +347,12 @@ test('sampled fallback buckets allocate only representatives at every height, wi
|
||||
);
|
||||
const h = harness(rows, {
|
||||
project: (_scene, anchor) => {
|
||||
const lon = Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(anchor).longitude,
|
||||
);
|
||||
const lon = toLonLatH(anchor).lon;
|
||||
return screens.get(lon.toFixed(6));
|
||||
},
|
||||
});
|
||||
h.state.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
|
||||
base.lon,
|
||||
base.lat,
|
||||
heightM,
|
||||
);
|
||||
h.state.viewer.camera.positionWC = fromDegrees(base.lon, base.lat, heightM);
|
||||
h.state.viewer.camera.positionCartographic = { height: heightM };
|
||||
h.rendering.rebuild();
|
||||
assert.equal(
|
||||
h.state.pointById.size,
|
||||
@@ -415,11 +391,12 @@ test('UTFGrid creates a dedicated unpickable glow and observations alone create
|
||||
cellCount,
|
||||
}));
|
||||
h.rendering.rebuild();
|
||||
const glow = h.rendering.density.collection;
|
||||
h.rendering.density.flush();
|
||||
const glow = h.sets().glow;
|
||||
assert.ok(glow);
|
||||
assert.equal(glow.allowPicking, false);
|
||||
assert.equal(glow.length, 3);
|
||||
assert.equal(h.scene.primitives.length, 2);
|
||||
assert.equal(glow.spec.pickable, false);
|
||||
assert.equal(glow.items.size, 3);
|
||||
assert.ok(h.sets().badges);
|
||||
assert.deepEqual([...h.state.pointById.keys()], [base.stableId]);
|
||||
assert.deepEqual(h.state.renderedRows, [base]);
|
||||
assert.equal(h.state.sightingCount, 53);
|
||||
@@ -428,14 +405,14 @@ test('UTFGrid creates a dedicated unpickable glow and observations alone create
|
||||
h.state.gridCells = [...h.state.gridCells].reverse();
|
||||
h.counts.writes.length = 0;
|
||||
assert.equal(h.rendering.rebuild(), false);
|
||||
assert.equal(h.rendering.density.collection, glow);
|
||||
assert.equal(h.sets().glow, glow);
|
||||
assert.deepEqual(h.counts.writes, []);
|
||||
h.rendering.clear();
|
||||
assert.equal(glow.isDestroyed(), true);
|
||||
assert.equal(h.scene.primitives.length, 1);
|
||||
assert.equal(glow.disposed, true);
|
||||
assert.ok(h.sets().badges);
|
||||
assert.equal(h.state.points.length, 0);
|
||||
h.rendering.destroy();
|
||||
assert.equal(h.scene.primitives.length, 0);
|
||||
assert.equal(h.sets().badges, undefined);
|
||||
});
|
||||
|
||||
test('tile arrival or loss cannot replace a real observation with a grid badge', () => {
|
||||
@@ -452,14 +429,16 @@ test('tile arrival or loss cannot replace a real observation with a grid badge',
|
||||
},
|
||||
];
|
||||
h.rendering.rebuild();
|
||||
const glow = h.rendering.density.collection;
|
||||
h.rendering.density.flush();
|
||||
const glow = h.sets().glow;
|
||||
assert.ok(glow);
|
||||
assert.equal(h.state.sightingCount, 10_000);
|
||||
assert.equal(h.state.pointById.get(base.stableId), badge);
|
||||
h.state.gridAvailable = false;
|
||||
h.rendering.rebuild();
|
||||
assert.equal(h.state.pointById.get(base.stableId), badge);
|
||||
assert.equal(h.state.sightingCount, 1);
|
||||
assert.equal(glow.isDestroyed(), true);
|
||||
assert.equal(glow.disposed, true);
|
||||
h.rendering.destroy();
|
||||
});
|
||||
|
||||
@@ -481,7 +460,7 @@ test('a selected observation remains rendered outside the viewport and observati
|
||||
h.rendering.destroy();
|
||||
});
|
||||
|
||||
test('privacy ground staging has a bounded readiness listener and complete teardown', () => {
|
||||
test('privacy cells draw as ground fills and outlines with no frame listener, and teardown disposes them', () => {
|
||||
const h = harness([
|
||||
{
|
||||
...base,
|
||||
@@ -490,14 +469,15 @@ test('privacy ground staging has a bounded readiness listener and complete teard
|
||||
},
|
||||
]);
|
||||
h.rendering.rebuild();
|
||||
assert.equal(h.postRender.size, 1);
|
||||
assert.equal(h.scene.groundPrimitives.length, 2);
|
||||
for (let i = 0; i < WILDLIFE_GROUND_READY_MAX_CHECKS; i++)
|
||||
h.postRender.emit();
|
||||
const { cells, outlines } = h.sets();
|
||||
assert.equal(cells.items.size, 1);
|
||||
assert.equal(outlines.items.size, 1);
|
||||
assert.equal(cells.spec.clampTo, 'both');
|
||||
assert.equal(outlines.spec.clampTo, 'both');
|
||||
assert.equal(h.postRender.size, 0);
|
||||
assert.equal(h.state.staging, null);
|
||||
assert.equal(h.scene.groundPrimitives.length, 0);
|
||||
h.rendering.destroy();
|
||||
assert.equal(cells.disposed, true);
|
||||
assert.equal(outlines.disposed, true);
|
||||
assert.equal(h.postRender.size, 0);
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import { t } from '../../i18n/index.js';
|
||||
import { wildlifeMeasure } from './performance.js';
|
||||
import { compareWildlifeIds } from './model.js';
|
||||
import { isRecentWildlifeSighting } from './records.js';
|
||||
import { canvasOf } from '../../render/rendererOf.js';
|
||||
import { wildlifeEyeHeight } from './view.js';
|
||||
import {
|
||||
ACARTIA_CREDIT,
|
||||
registerDynamicCredit,
|
||||
@@ -156,7 +158,7 @@ export function createSelection({ state, services, parts }) {
|
||||
const selected = selectionRow();
|
||||
if (
|
||||
selected &&
|
||||
(state.viewer.camera?.positionCartographic?.height ?? 0) <
|
||||
(wildlifeEyeHeight(state.viewer) ?? 0) <
|
||||
WILDLIFE_SELECTED_LABEL_FADE_HIGH_METERS
|
||||
)
|
||||
remember(selected);
|
||||
@@ -197,10 +199,10 @@ export function createSelection({ state, services, parts }) {
|
||||
|
||||
function refreshLabels() {
|
||||
if (!state.enabled || !overlay) return;
|
||||
const scene = state.viewer.scene;
|
||||
const canvas = canvasOf(state.viewer);
|
||||
const horizon = parts.rendering.occluder();
|
||||
const width = scene.canvas?.clientWidth || 0;
|
||||
const height = scene.canvas?.clientHeight || 0;
|
||||
const width = canvas?.clientWidth || 0;
|
||||
const height = canvas?.clientHeight || 0;
|
||||
// Rank during camera/data passes; the host handles pixel collisions.
|
||||
const nowMs = services.now();
|
||||
const candidates = [];
|
||||
@@ -212,7 +214,7 @@ export function createSelection({ state, services, parts }) {
|
||||
const position = state.positions.get(row.stableId);
|
||||
if (!position || (horizon && horizon.isPointVisible(position) !== true))
|
||||
continue;
|
||||
const screen = services.project(scene, position);
|
||||
const screen = services.project(state.viewer, position);
|
||||
if (
|
||||
!screen ||
|
||||
screen.x < 0 ||
|
||||
@@ -236,10 +238,10 @@ export function createSelection({ state, services, parts }) {
|
||||
}
|
||||
|
||||
function ambientCandidates(rows) {
|
||||
const scene = state.viewer.scene;
|
||||
const canvas = canvasOf(state.viewer);
|
||||
const horizon = parts.rendering.occluder();
|
||||
const width = scene.canvas?.clientWidth ?? Infinity;
|
||||
const height = scene.canvas?.clientHeight ?? Infinity;
|
||||
const width = canvas?.clientWidth ?? Infinity;
|
||||
const height = canvas?.clientHeight ?? Infinity;
|
||||
const screens = new Map();
|
||||
const nowMs = services.now();
|
||||
const taxa = state.drawnParams?.taxa ?? state.taxa;
|
||||
@@ -253,7 +255,7 @@ export function createSelection({ state, services, parts }) {
|
||||
const position = state.positions.get(row.stableId);
|
||||
if (!position || (horizon && horizon.isPointVisible(position) !== true))
|
||||
return false;
|
||||
const screen = services.project(scene, position);
|
||||
const screen = services.project(state.viewer, position);
|
||||
if (
|
||||
!screen ||
|
||||
screen.x < 0 ||
|
||||
@@ -272,8 +274,7 @@ export function createSelection({ state, services, parts }) {
|
||||
* photos survive; acquisition also checks the observation window/params. */
|
||||
function retainedAmbientRows() {
|
||||
if (!state.enabled) return [];
|
||||
const height =
|
||||
state.viewer?.camera?.positionCartographic?.height ?? Infinity;
|
||||
const height = wildlifeEyeHeight(state.viewer) ?? Infinity;
|
||||
if (height >= WILDLIFE_CARD_HIDE_MAX_METERS) return [];
|
||||
return ambientCandidates(state.ambientRows).eligible;
|
||||
}
|
||||
@@ -281,8 +282,7 @@ export function createSelection({ state, services, parts }) {
|
||||
function refreshAmbient() {
|
||||
if (!state.enabled) return;
|
||||
refreshLabels();
|
||||
const height =
|
||||
state.viewer?.camera?.positionCartographic?.height ?? Infinity;
|
||||
const height = wildlifeEyeHeight(state.viewer) ?? Infinity;
|
||||
if (state.ambientActive) {
|
||||
if (height >= WILDLIFE_CARD_HIDE_MAX_METERS) state.ambientActive = false;
|
||||
} else if (height <= WILDLIFE_CARD_SHOW_MAX_METERS)
|
||||
@@ -338,6 +338,8 @@ export function createSelection({ state, services, parts }) {
|
||||
// i18n-ignore: provider names and feed-supplied organism names are verbatim
|
||||
const label = `${name} · ${row.origin === 'acartia' ? 'Acartia' : 'iNaturalist'}`;
|
||||
services.context.registerEntityContext(carrier, {
|
||||
// Where voice's in-view scan projects it.
|
||||
targetPosition: carrier.__localBaseCartesian,
|
||||
id: row.stableId,
|
||||
layerId: 'wildlife-sightings',
|
||||
layerName: t('Wildlife Sightings'),
|
||||
@@ -469,30 +471,40 @@ export function createSelection({ state, services, parts }) {
|
||||
'gev:entity-selected',
|
||||
onContext,
|
||||
);
|
||||
if (typeof services.screenSpaceEventHandlerFactory !== 'function') return;
|
||||
state.clickHandler = services.screenSpaceEventHandlerFactory(state.viewer);
|
||||
state.clickHandler.setInputAction((click) => {
|
||||
// A viewer with no renderer input bound takes no clicks.
|
||||
let input = null;
|
||||
try {
|
||||
input = services.input?.(state.viewer) ?? null;
|
||||
} catch {
|
||||
input = null;
|
||||
}
|
||||
if (!input) return;
|
||||
state.clickHandler = input.onClick((click) => {
|
||||
if (!state.enabled || services.pointer?.isPointerFree?.() === false)
|
||||
return;
|
||||
const at = click.screenPosition;
|
||||
const hit =
|
||||
overlay?.hitTest?.(click.position?.x, click.position?.y, {
|
||||
overlay?.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: WILDLIFE_SELECTED_SOURCE_ID,
|
||||
}) ||
|
||||
overlay?.hitTest?.(click.position?.x, click.position?.y, {
|
||||
overlay?.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: WILDLIFE_OVERLAY_SOURCE_ID,
|
||||
}) ||
|
||||
overlay?.hitTest?.(click.position?.x, click.position?.y, {
|
||||
overlay?.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: WILDLIFE_LABEL_SOURCE_ID,
|
||||
});
|
||||
if (hit) {
|
||||
hit.entry?.activate?.();
|
||||
return;
|
||||
}
|
||||
const picked = state.viewer.scene.pick(click.position);
|
||||
const id =
|
||||
services.picking?.resolvePickId?.(picked) ??
|
||||
picked?.id ??
|
||||
picked?.primitive?.id;
|
||||
// A sighting icon's item id is its pick id, `wildlife:<stableId>`.
|
||||
// Read from what is exactly under the click, as the scene's pick was:
|
||||
// a touch's wider contact search would select a sighting the tap
|
||||
// missed, or keep one open for a tap near another layer's contact.
|
||||
const picked = click.topHit;
|
||||
const id = picked
|
||||
? (services.picking?.resolvePickId?.(picked) ?? picked.id ?? null)
|
||||
: null;
|
||||
if (
|
||||
typeof id === 'string' &&
|
||||
id.startsWith('wildlife:') &&
|
||||
@@ -505,11 +517,11 @@ export function createSelection({ state, services, parts }) {
|
||||
)
|
||||
return;
|
||||
clearAndRebuild();
|
||||
}, services.cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
});
|
||||
}
|
||||
|
||||
function remove() {
|
||||
state.clickHandler?.destroy();
|
||||
state.clickHandler?.();
|
||||
state.clickHandler = null;
|
||||
state.removeContext?.();
|
||||
state.removeContext = null;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createSelection } from './selection.js';
|
||||
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
|
||||
|
||||
const row = {
|
||||
stableId: 'inat:123',
|
||||
@@ -13,7 +14,7 @@ const row = {
|
||||
link: 'https://www.inaturalist.org/observations/123',
|
||||
};
|
||||
|
||||
function fixture(sighting = row) {
|
||||
function fixture(sighting = row, extraServices = {}) {
|
||||
const position = { x: 300, y: 300, z: 0 };
|
||||
const entries = new Map();
|
||||
const flights = [];
|
||||
@@ -21,7 +22,6 @@ function fixture(sighting = row) {
|
||||
const painted = new Set();
|
||||
let hit = null;
|
||||
let projections = 0;
|
||||
let picked = null;
|
||||
let click;
|
||||
const state = {
|
||||
enabled: true,
|
||||
@@ -37,13 +37,11 @@ function fixture(sighting = row) {
|
||||
ambientRows: [],
|
||||
labelRows: [],
|
||||
viewer: {
|
||||
scene: {
|
||||
pick: () => picked,
|
||||
canvas: { clientWidth: 1200, clientHeight: 900 },
|
||||
},
|
||||
scene: { canvas: { clientWidth: 1200, clientHeight: 900 } },
|
||||
camera: { positionCartographic: { height: 30_000 } },
|
||||
},
|
||||
};
|
||||
bindWildlifeViewer(state.viewer);
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {
|
||||
@@ -60,12 +58,14 @@ function fixture(sighting = row) {
|
||||
return anchor;
|
||||
},
|
||||
focus: { requestWorldFocus: (request) => flights.push(request) },
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction: (fn) => (click = fn),
|
||||
destroy() {},
|
||||
input: () => ({
|
||||
onClick(fn) {
|
||||
click = fn;
|
||||
return () => (click = null);
|
||||
},
|
||||
}),
|
||||
cesium: { ScreenSpaceEventType: { LEFT_CLICK: 0 } },
|
||||
eventTarget: new EventTarget(),
|
||||
...extraServices,
|
||||
},
|
||||
parts: {
|
||||
rendering: {
|
||||
@@ -99,9 +99,13 @@ function fixture(sighting = row) {
|
||||
for (const id of ids) painted.add(id);
|
||||
selection.photoCardsChanged();
|
||||
},
|
||||
click(id = `wildlife:${sighting.stableId}`) {
|
||||
picked = id ? { id } : null;
|
||||
click({ position: { x: 10, y: 20 } });
|
||||
click(id = `wildlife:${sighting.stableId}`, { touchId } = {}) {
|
||||
// The exact top hit, and the id a touch's wider contact search finds.
|
||||
click({
|
||||
screenPosition: { x: 10, y: 20 },
|
||||
topHit: id ? { set: 'wildlife', id } : null,
|
||||
id: touchId ?? id ?? undefined,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -299,3 +303,28 @@ test('empty clicks and layer removal release the selected row and its overlay',
|
||||
assert.equal(f.seen.at(-1).value, null);
|
||||
assert.equal(f.entries.size, 0);
|
||||
});
|
||||
|
||||
test('a tap selects only a sighting exactly under it, not one the touch search found near it', () => {
|
||||
const f = fixture();
|
||||
f.selection.install();
|
||||
f.click(null, { touchId: `wildlife:${row.stableId}` });
|
||||
assert.equal(f.state.selectedId, null);
|
||||
f.click();
|
||||
assert.ok(f.state.selectedId);
|
||||
f.click(null, { touchId: 'other:aircraft' });
|
||||
assert.equal(f.state.selectedId, null, 'a tap near another contact clears');
|
||||
});
|
||||
|
||||
test('each sighting in context carries the point voice projects to find what is in view', () => {
|
||||
const registered = [];
|
||||
const f = fixture(row, {
|
||||
context: {
|
||||
registerEntityContext: (entity, metadata) =>
|
||||
registered.push({ entity, metadata }),
|
||||
},
|
||||
});
|
||||
f.selection.refreshContexts();
|
||||
assert.equal(registered.length, 1);
|
||||
assert.equal(registered[0].metadata.id, row.stableId);
|
||||
assert.equal(registered[0].metadata.targetPosition, f.position);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @module layers/wildlifeSightings/view
|
||||
* @description What the layer reads of the eye, through the camera port.
|
||||
*/
|
||||
import { findCamera } from '../../render/rendererOf.js';
|
||||
|
||||
/** The eye's height above the ellipsoid, metres; undefined with no camera. */
|
||||
export function wildlifeEyeHeight(viewer) {
|
||||
return viewer ? findCamera(viewer)?.pose().height : undefined;
|
||||
}
|
||||
|
||||
/** The view rectangle in degrees (`viewRectangle()`), or null. */
|
||||
export function wildlifeViewRectangle(viewer) {
|
||||
return (viewer ? findCamera(viewer)?.viewRectangle() : null) ?? null;
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
|
||||
export { snapWildlifeBox } from './bounds.js';
|
||||
|
||||
const degrees = (radians) => (radians * 180) / Math.PI;
|
||||
const cleanDegree = (value) => Math.round(value * 1e8) / 1e8;
|
||||
|
||||
function validBox(box) {
|
||||
@@ -44,17 +43,13 @@ export function boxIntersects(a, b) {
|
||||
}
|
||||
|
||||
/** Split a local camera rectangle into noncrossing observation query boxes. */
|
||||
export function wildlifeViewportBoxes(viewer) {
|
||||
const camera = viewer?.camera;
|
||||
if (typeof camera?.computeViewRectangle !== 'function') return null;
|
||||
const rectangle = camera.computeViewRectangle(
|
||||
viewer?.scene?.globe?.ellipsoid,
|
||||
);
|
||||
export function wildlifeViewportBoxes(rectangle) {
|
||||
// `rectangle`: the camera's view rectangle in degrees, or null.
|
||||
if (!rectangle) return null;
|
||||
const box = Object.fromEntries(
|
||||
['south', 'west', 'north', 'east'].map((key) => [
|
||||
key,
|
||||
cleanDegree(degrees(rectangle[key])),
|
||||
cleanDegree(rectangle[key]),
|
||||
]),
|
||||
);
|
||||
if (!validBox(box) || box.north <= box.south) return null;
|
||||
|
||||
@@ -9,18 +9,8 @@ import {
|
||||
import { ACARTIA_GUARD_BOX } from './policy.js';
|
||||
import { getWildlifeHeightBand } from './model.js';
|
||||
|
||||
const viewer = ({ south, west, north, east }) => ({
|
||||
camera: {
|
||||
computeViewRectangle: () =>
|
||||
Object.fromEntries(
|
||||
Object.entries({ south, west, north, east }).map(([key, value]) => [
|
||||
key,
|
||||
(value * Math.PI) / 180,
|
||||
]),
|
||||
),
|
||||
},
|
||||
scene: { globe: { ellipsoid: {} } },
|
||||
});
|
||||
// The camera port's view rectangle is in degrees.
|
||||
const viewer = (rectangle) => rectangle;
|
||||
|
||||
test('local boxes snap outward to 0.1 degrees; wider views to whole degrees', () => {
|
||||
assert.deepEqual(
|
||||
@@ -112,7 +102,7 @@ test('viewport rectangles split at 180 degrees and reject overly large or missin
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(wildlifeViewportBoxes({}), null);
|
||||
assert.equal(wildlifeViewportBoxes(null), null);
|
||||
});
|
||||
|
||||
test('height bands retain representations across +/-5% and switch beyond +/-10%', () => {
|
||||
|
||||
Reference in new issue
Block a user