mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Move scene effects and imported geometry behind the globe contract
Move Cesium viewer, map, sky, projection, trail and sonar internals into its engine. Drive styles, bloom, sharpening and contact sonar through engine.render. Count camera-input suspensions across all three engines and migrate the feature callers. Preserve Cesium's effects and input behaviour; fix transit lens clicks on Cesium and make zero sharpening on Navara disable sharpening, as it does on Cesium. Parse imported files into plain records and draw them through movers, lines, ground and imagery on both engines. Follow Cesium's KML style precedence, preserve local KMZ images and frame the drawable records. Open overlays use imagery when the engine has no native map-overlay API. Run every imported-display case on fake and headless Cesium engines. The shared import path retains these known differences from Cesium's old DataSources: wall fills, extruded prisms and gx:LatLonQuad are undrawn; raised polygon fills drape while outlines retain altitude; GroundOverlay rotation, altitude and RGB tint are not applied; rhumb lines become great circles. Ground heights use the loaded surface synchronously instead of waiting for most-detailed sampling. Supported KMZ ground overlays now draw on Navara too. Document the limits rather than claiming full parity. Combine batches B and C because their disjoint path manifests cannot place the shared boundary and format files in a later commit while keeping B independently valid. This combined commit owns the shared docs, package boundaries, format scope, locale catalogs and coupling baseline. Remove five obsolete import strings from all eleven catalogs. Make the load-time source scan include new files and skip deleted paths so the same checks work before and after recording the moves. Coupling: Navara renderer lines fall from 1695 to 1294, Cesium import files from 25 to 9, viewer lines from 1177 to 1026, SDK loads from 4 to 3 and engine-name lines from 62 to 42. No count grows. The full unit suite and the boundary, format and coupling checks pass. Browser validation remains to be run. Browser checks to run GOOGLE_MAPS_API_KEY= CESIUM_ION_TOKEN= npm run dev -- --port 4291 node scripts/qa-contract-suite.mjs http://localhost:4291 node scripts/qa-navara-visual-styles.mjs http://localhost:4291 node scripts/qa-navara-bloom.mjs http://localhost:4291 node scripts/qa-navara-sonar.mjs http://localhost:4291 QA_BASE_URL=http://localhost:4291 node scripts/qa-visual-effects.mjs QA_BASE_URL=http://localhost:4291 node scripts/qa-zoom-out-guard.mjs node scripts/qa-sky-model-lighting.mjs --url http://localhost:4291 node scripts/qa-geo-import.mjs http://localhost:4291 node scripts/qa-geo-import-regressions.mjs http://localhost:4291 node scripts/qa-geo-import-large.mjs http://localhost:4291 node scripts/qa-navara-geo-import.mjs http://localhost:4291 Use the keyless server for every check. Photoreal-only cases remain unverified; do not enable paid tiles to run them.
This commit is contained in:
1 parent
c079b329d0
commit
97c4dc76ce
130 files changed
+4763
-3495
No files matched your search
@@ -67,7 +67,7 @@ test('disposing an active Cockpit releases the supplied render owner without ret
|
||||
services: { releaseContinuousRender: (reason) => released.push(reason) },
|
||||
});
|
||||
const ridden = env.cockpit.aircraft();
|
||||
env.engine.input.setCameraInputs(false);
|
||||
owner.host.inputs(false);
|
||||
ridden.show = false;
|
||||
Object.assign(owner, { active: true, trackedEntity: ridden });
|
||||
owner.dispose();
|
||||
|
||||
@@ -10,6 +10,7 @@ import { routeViewerDoubleClick } from '../globe/cesium/doubleClick.js';
|
||||
* the Cockpit's goes first; Navara has none to route around.
|
||||
*/
|
||||
export function cockpitHost(engine, { viewer = null } = {}) {
|
||||
let resumeInputs = null;
|
||||
const aircraft = () => {
|
||||
const target = engine.camera.following()?.native;
|
||||
return target?.resumeAircraftFollow ? target : null;
|
||||
@@ -27,7 +28,14 @@ export function cockpitHost(engine, { viewer = null } = {}) {
|
||||
cartographic: () => engine.camera.pose().cartographic,
|
||||
terrainHeight: (place) => engine.surface.terrainHeight(place),
|
||||
surface: engine,
|
||||
inputs: (enabled) => engine.input.setCameraInputs(enabled),
|
||||
// The cockpit holds the camera through a suspension of the user's
|
||||
// camera inputs: leaving it puts back whatever they were.
|
||||
inputs(enabled) {
|
||||
if (enabled) {
|
||||
resumeInputs?.();
|
||||
resumeInputs = null;
|
||||
} else resumeInputs ??= engine.input.suspendCameraInputs();
|
||||
},
|
||||
canvasPosition: (world) => engine.projector.worldToWindow(world) ?? null,
|
||||
routeDoubleClick: (handle) =>
|
||||
viewer
|
||||
|
||||
@@ -108,7 +108,11 @@ test('bloom and sharpen render their state, slider and readout', async (t) => {
|
||||
await nextTick();
|
||||
assert.equal($('bloom-toggle').classList.contains('active'), false);
|
||||
assert.equal($('bloom-slider-row').classList.contains('visible'), false);
|
||||
assert.equal($('bloom-intensity-value').textContent, '140%', 'the amount stays');
|
||||
assert.equal(
|
||||
$('bloom-intensity-value').textContent,
|
||||
'140%',
|
||||
'the amount stays',
|
||||
);
|
||||
});
|
||||
|
||||
test('a publish never rewrites a slider the user is dragging', async (t) => {
|
||||
@@ -331,7 +335,10 @@ test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
|
||||
assert.equal(coreClasses(button), 'pp-toggle-btn active');
|
||||
assert.equal(button.getAttribute('aria-pressed'), 'true');
|
||||
assert.equal(row.classList.contains('visible'), true);
|
||||
assert.equal($('models3d-mode-proximity').getAttribute('aria-checked'), 'true');
|
||||
assert.equal(
|
||||
$('models3d-mode-proximity').getAttribute('aria-checked'),
|
||||
'true',
|
||||
);
|
||||
|
||||
// The button leaves the row to its own sync.
|
||||
owner._setModels3dEnabled(false);
|
||||
@@ -347,7 +354,10 @@ test('the 3D aircraft group renders what AircraftDisplay shows', async (t) => {
|
||||
await nextTick();
|
||||
assert.equal(all.classList.contains('active'), true);
|
||||
assert.equal(all.getAttribute('aria-checked'), 'true');
|
||||
assert.equal($('models3d-mode-proximity').classList.contains('active'), false);
|
||||
assert.equal(
|
||||
$('models3d-mode-proximity').classList.contains('active'),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(params.at(-1), ['military', { models3dMode: 'all' }]);
|
||||
|
||||
owner._syncModels3dFromLayerState({
|
||||
@@ -376,12 +386,18 @@ test('the Draw controls render what the draw tool publishes', async (t) => {
|
||||
assert.equal(segment('area').getAttribute('aria-label'), 'Area');
|
||||
assert.equal(segment('area').title, 'Area');
|
||||
assert.equal(segment('area').textContent, 'pentagon');
|
||||
const swatch = (color) => document.querySelector(`#draw-colors [data-color="${color}"]`);
|
||||
const swatch = (color) =>
|
||||
document.querySelector(`#draw-colors [data-color="${color}"]`);
|
||||
assert.equal(swatch('primary').getAttribute('aria-checked'), 'true');
|
||||
assert.equal(swatch('amber').getAttribute('aria-label'), 'Amber');
|
||||
assert.equal($('draw-hint').textContent, '');
|
||||
|
||||
store.publishDraw({ active: true, shape: 'line', color: 'amber', hint: 'Click to add points.' });
|
||||
store.publishDraw({
|
||||
active: true,
|
||||
shape: 'line',
|
||||
color: 'amber',
|
||||
hint: 'Click to add points.',
|
||||
});
|
||||
await nextTick();
|
||||
assert.equal(swatch('amber').getAttribute('aria-checked'), 'true');
|
||||
assert.equal(swatch('primary').classList.contains('active'), false);
|
||||
@@ -408,14 +424,28 @@ test('the imported files render what the file import publishes and keep focus',
|
||||
assert.equal(list.children.length, 0);
|
||||
assert.equal($('geo-import-hint').textContent, '');
|
||||
|
||||
const viewer = {
|
||||
container: document.createElement('div'),
|
||||
scene: { requestRender() {} },
|
||||
dataSources: { add: async (ds) => ds, remove: () => true },
|
||||
// A globe engine double the files draw on.
|
||||
const engine = {
|
||||
host: { container: document.createElement('div'), canvas: null },
|
||||
camera: { moveEnd: { addEventListener: () => () => {} } },
|
||||
surface: { tilesLoaded: () => true },
|
||||
render: { request() {} },
|
||||
};
|
||||
const tool = createGeoFileImport({
|
||||
drawFile: async () => ({
|
||||
report: { undrawn: 0 },
|
||||
setShow() {},
|
||||
refreshGround: async () => {},
|
||||
destroy() {},
|
||||
}),
|
||||
load: async (file) => ({
|
||||
dataSource: { show: true },
|
||||
records: {
|
||||
points: [],
|
||||
lines: [],
|
||||
polygons: [],
|
||||
overlays: [],
|
||||
undrawn: {},
|
||||
},
|
||||
name: file.name,
|
||||
format: file.name.endsWith('.kml') ? 'kml' : 'geojson',
|
||||
entityCount: 2,
|
||||
@@ -429,7 +459,7 @@ test('the imported files render what the file import publishes and keep focus',
|
||||
return () => store.detach(token);
|
||||
},
|
||||
});
|
||||
tool.attachScene({ viewer });
|
||||
tool.attachScene({ engine });
|
||||
t.after(() => tool.destroy());
|
||||
await tool.importFiles([{ name: '<b>a</b>.geojson' }, { name: 'b.kml' }]);
|
||||
await nextTick();
|
||||
@@ -477,7 +507,10 @@ test('the imported files render what the file import publishes and keep focus',
|
||||
assert.equal(document.activeElement === button(first, 'toggle'), true);
|
||||
assert.equal(button(first, 'toggle').getAttribute('aria-pressed'), 'true');
|
||||
assert.equal(button(first, 'fly').title, 'Fly to <b>a</b>.geojson');
|
||||
assert.equal(button(first, 'remove').getAttribute('aria-label'), 'Remove <b>a</b>.geojson');
|
||||
assert.equal(
|
||||
button(first, 'remove').getAttribute('aria-label'),
|
||||
'Remove <b>a</b>.geojson',
|
||||
);
|
||||
|
||||
await press(button(first, 'remove'));
|
||||
assert.equal(rowsNow().length, 1);
|
||||
@@ -593,7 +626,11 @@ test('VisualSettings publishes a style’s parameters and writes a moved slider
|
||||
assert.equal(store.parameters, null, 'the sliders go with their owner');
|
||||
assert.equal($('param-slider-panel').classList.contains('active'), false);
|
||||
assert.equal(store.act('setStyleParameter', 'grainAmt', 0.2), undefined);
|
||||
assert.equal(owner.stages.noir.uniforms.grainAmt, 0.3, 'a stopped owner no longer answers');
|
||||
assert.equal(
|
||||
owner.stages.noir.uniforms.grainAmt,
|
||||
0.3,
|
||||
'a stopped owner no longer answers',
|
||||
);
|
||||
// An older owner's stop leaves a newer owner's rows.
|
||||
const newer = { style: 'noir', rows: [] };
|
||||
owner._parameters = { style: 'noir', rows: [] };
|
||||
@@ -605,10 +642,16 @@ test('VisualSettings publishes a style’s parameters and writes a moved slider
|
||||
test('the four Cockpit groups teleport to the published slots and back to their places', async (t) => {
|
||||
const { store, $ } = fixture(t);
|
||||
const groupOf = (id) => $(id).closest('.pp-toggle-group') ?? $(id);
|
||||
const ids = ['hud-toggle', 'detection-toggle', 'param-slider-panel', 'models3d-toggle'];
|
||||
const ids = [
|
||||
'hud-toggle',
|
||||
'detection-toggle',
|
||||
'param-slider-panel',
|
||||
'models3d-toggle',
|
||||
];
|
||||
const body = $('pp-toggles').querySelector('.pp-panel-body');
|
||||
const order = () =>
|
||||
[...body.children].filter((el) => el.matches('.pp-toggle-group, #param-slider-panel'))
|
||||
[...body.children]
|
||||
.filter((el) => el.matches('.pp-toggle-group, #param-slider-panel'))
|
||||
.map((el) => el.id || el.querySelector('[id]')?.id);
|
||||
const home = order();
|
||||
const popover = document.body.appendChild(document.createElement('div'));
|
||||
|
||||
+24
-83
@@ -1,96 +1,37 @@
|
||||
/** Frame the complete finite footprint of a session-local file. */
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../geo/index.js';
|
||||
import { fromPoints } from '../geo/boundingSphere.js';
|
||||
import { guardCameraAboveGround } from '../cameraGroundGuard.js';
|
||||
import { rangeForBoundingSphere } from '../data/cameraFraming.js';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
|
||||
/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */
|
||||
export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
|
||||
const points = [];
|
||||
const add = (position, grounded = false) => {
|
||||
if (
|
||||
!position ||
|
||||
![position.x, position.y, position.z].every(Number.isFinite)
|
||||
)
|
||||
return;
|
||||
const c = Cesium.Cartographic.fromCartesian(position);
|
||||
if (c && Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
|
||||
points.push([
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
grounded ? 0 : c.height,
|
||||
]);
|
||||
};
|
||||
if (dataSource?.show === false) return points;
|
||||
for (const entity of dataSource?.importedEntities ??
|
||||
dataSource?.entities?.values ??
|
||||
[]) {
|
||||
if (entity.isShowing === false) continue;
|
||||
add(
|
||||
entity.position?.getValue?.(time),
|
||||
entity.billboard?.heightReference?.getValue?.(time) ===
|
||||
Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
);
|
||||
for (const graphic of [entity.polyline, entity.wall])
|
||||
for (const position of graphic?.positions?.getValue?.(time) || [])
|
||||
add(position, graphic.clampToGround?.getValue?.(time) === true);
|
||||
const rings = [entity.polygon?.hierarchy?.getValue?.(time)];
|
||||
while (rings.length) {
|
||||
const ring = rings.pop();
|
||||
for (const position of ring?.positions || [])
|
||||
add(
|
||||
position,
|
||||
entity.polygon?.perPositionHeight?.getValue?.(time) !== true,
|
||||
);
|
||||
for (const hole of ring?.holes || []) rings.push(hole);
|
||||
}
|
||||
const rectangle = entity.rectangle?.coordinates?.getValue?.(time);
|
||||
if (rectangle) {
|
||||
const bounds = Cesium.RectangleGeometry.computeRectangle({
|
||||
rectangle,
|
||||
rotation: entity.rectangle.rotation?.getValue?.(time) || 0,
|
||||
});
|
||||
for (const corner of [
|
||||
'southwest',
|
||||
'southeast',
|
||||
'northwest',
|
||||
'northeast',
|
||||
]) {
|
||||
const c = Cesium.Rectangle[corner](bounds);
|
||||
if (Number.isFinite(c.longitude) && Number.isFinite(c.latitude))
|
||||
points.push([
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
entity.rectangle.height?.getValue?.(time) || 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fly synchronously to the footprint; later navigation always owns its
|
||||
* camera. `engine` is the globe engine (Cesium or Navara), which flies the
|
||||
* sphere through the contract's flyToSphere.
|
||||
* Fly synchronously to a footprint: `points` as [lon, lat, height]
|
||||
* (src/data/geoImportRecords.js recordFootprint), straight down at the
|
||||
* ground under its centre; later navigation always owns its camera.
|
||||
* `engine` is the globe engine (Cesium or Navara), which flies the sphere
|
||||
* through the contract's flyToSphere. False for an empty footprint.
|
||||
*/
|
||||
export function flyToDataSource(
|
||||
export function flyToFootprint(
|
||||
engine,
|
||||
dataSource,
|
||||
points,
|
||||
{ duration = 1.5, ground = null } = {},
|
||||
) {
|
||||
const points = dataSourcePoints(dataSource);
|
||||
if (!points.length) return false;
|
||||
cancelCameraArrival(engine);
|
||||
const positions = points.map(([lon, lat, height]) =>
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, height),
|
||||
const finite = (points ?? []).filter(
|
||||
([lon, lat, height = 0]) =>
|
||||
Number.isFinite(lon) && Number.isFinite(lat) && Number.isFinite(height),
|
||||
);
|
||||
const sphere = Cesium.BoundingSphere.fromPoints(positions);
|
||||
if (!finite.length) return false;
|
||||
cancelCameraArrival(engine);
|
||||
const positions = finite.map(([lon, lat, height = 0]) =>
|
||||
geo.cartesian3.fromDegrees(lon, lat, height),
|
||||
);
|
||||
const sphere = fromPoints(positions);
|
||||
const center =
|
||||
Cesium.Cartographic.fromCartesian(sphere.center) ||
|
||||
Cesium.Cartographic.fromDegrees(points[0][0], points[0][1]);
|
||||
const lat = Cesium.Math.toDegrees(center.latitude),
|
||||
lon = Cesium.Math.toDegrees(center.longitude);
|
||||
geo.cartographic.fromCartesian(sphere.center) ||
|
||||
geo.cartographic.fromDegrees(finite[0][0], finite[0][1], 0);
|
||||
const lat = geo.math.toDegrees(center.latitude),
|
||||
lon = geo.math.toDegrees(center.longitude);
|
||||
const terrain = engine.surface.terrainHeightSupported
|
||||
? engine.surface.terrainHeight(center)
|
||||
: undefined;
|
||||
@@ -104,7 +45,7 @@ export function flyToDataSource(
|
||||
? terrain
|
||||
: 0;
|
||||
ground?.warmGroundFloor?.([{ lat, lon }]);
|
||||
sphere.center = Cesium.Cartesian3.fromRadians(
|
||||
sphere.center = geo.cartesian3.fromRadians(
|
||||
center.longitude,
|
||||
center.latitude,
|
||||
Math.max(0, height, center.height),
|
||||
@@ -113,7 +54,7 @@ export function flyToDataSource(
|
||||
for (const position of positions)
|
||||
sphere.radius = Math.max(
|
||||
sphere.radius,
|
||||
Cesium.Cartesian3.distance(sphere.center, position),
|
||||
geo.cartesian3.distance(sphere.center, position),
|
||||
);
|
||||
const pose = engine.camera.pose();
|
||||
const aspect = pose.aspectRatio ?? 1;
|
||||
|
||||
+122
-155
@@ -1,187 +1,154 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../geo/index.js';
|
||||
import { cancelCameraArrival } from '../data/cameraArrival.js';
|
||||
import { createCesiumEngine } from '../globe/cesium/createCesiumEngine.js';
|
||||
import { createFakeViewer } from '../globe/cesium/testing/fakeViewer.mjs';
|
||||
import { dataSourcePoints, flyToDataSource } from './flyToDataSource.js';
|
||||
import { recordFootprint } from '../data/geoImportRecords.js';
|
||||
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
|
||||
import { flyToFootprint } from './flyToDataSource.js';
|
||||
|
||||
/** The Cesium engine over a recording viewer, and the sphere flights it made. */
|
||||
function cesiumEngine() {
|
||||
const viewer = createFakeViewer();
|
||||
const engine = createCesiumEngine(viewer, { requestRender() {} });
|
||||
/** The fake engine and the sphere flights it made. */
|
||||
function engineWith({ terrain = 0, width, height } = {}) {
|
||||
const engine = createFakeEngine({ kind: 'cesium', width, height });
|
||||
engine.fake.script('terrainHeight', terrain);
|
||||
const calls = () =>
|
||||
viewer
|
||||
.callsOf('camera.flyToBoundingSphere')
|
||||
engine.fake
|
||||
.callsOf('camera.flyToSphere')
|
||||
.map(({ args: [sphere, options] }) => ({ sphere, options }));
|
||||
return { viewer, engine, calls };
|
||||
return { engine, calls };
|
||||
}
|
||||
|
||||
function source() {
|
||||
const ds = new Cesium.CustomDataSource('t');
|
||||
ds.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(-122.4862, 37.7694, -2667),
|
||||
billboard: { heightReference: Cesium.HeightReference.CLAMP_TO_GROUND },
|
||||
});
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.49, 37.77, -122.48, 37.771,
|
||||
]),
|
||||
/** A file's records: a pin buried below the ellipsoid, a line, a polygon. */
|
||||
const records = () => ({
|
||||
points: [
|
||||
{
|
||||
position: [-122.4862, 37.7694, -2667],
|
||||
altitude: 'ground',
|
||||
icon: {},
|
||||
},
|
||||
});
|
||||
ds.entities.add({
|
||||
polygon: {
|
||||
hierarchy: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.5, 37.76, -122.49, 37.76, -122.49, 37.765,
|
||||
]),
|
||||
],
|
||||
lines: [
|
||||
{
|
||||
positions: [
|
||||
[-122.49, 37.77, 0],
|
||||
[-122.48, 37.771, 0],
|
||||
],
|
||||
ground: true,
|
||||
},
|
||||
});
|
||||
return ds;
|
||||
}
|
||||
],
|
||||
polygons: [
|
||||
{
|
||||
rings: [
|
||||
[
|
||||
[-122.5, 37.76, 0],
|
||||
[-122.49, 37.76, 0],
|
||||
[-122.49, 37.765, 0],
|
||||
],
|
||||
],
|
||||
raised: false,
|
||||
},
|
||||
],
|
||||
overlays: [],
|
||||
undrawn: {},
|
||||
});
|
||||
|
||||
test('points come from positions, lines and polygons, as lon/lat only', () => {
|
||||
const points = dataSourcePoints(source());
|
||||
assert.equal(points.length, 6);
|
||||
assert.ok(Math.abs(points[0][0] + 122.4862) < 1e-6);
|
||||
assert.ok(Math.abs(points[0][1] - 37.7694) < 1e-6);
|
||||
test('the footprint comes from points, lines, polygons and overlay corners', () => {
|
||||
const points = recordFootprint({
|
||||
...records(),
|
||||
overlays: [
|
||||
{
|
||||
url: null,
|
||||
rectangle: { west: 179, south: 0, east: -179, north: 1 },
|
||||
color: [1, 1, 1, 1],
|
||||
rotation: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(points.length, 10);
|
||||
assert.deepEqual(points[0], [-122.4862, 37.7694, 0], 'a ground pin at 0');
|
||||
// Across the antimeridian: corners at 179 and -179.
|
||||
assert.deepEqual(
|
||||
points.slice(6).map(([lon]) => lon),
|
||||
[179, 179, -179, -179],
|
||||
);
|
||||
});
|
||||
|
||||
test('raised features keep their heights; non-finite positions are left out', () => {
|
||||
const points = recordFootprint({
|
||||
points: [
|
||||
{ position: [10, 10, 500], altitude: 'absolute' },
|
||||
{ position: [Number.NaN, 1, 2], altitude: 'absolute' },
|
||||
],
|
||||
lines: [{ positions: [[20, 20, 900]], ground: false }],
|
||||
polygons: [],
|
||||
overlays: [],
|
||||
});
|
||||
assert.deepEqual(points, [
|
||||
[10, 10, 500],
|
||||
[20, 20, 900],
|
||||
]);
|
||||
});
|
||||
|
||||
test('the camera frames the footprint at the surface, never a buried center', () => {
|
||||
const { engine, calls } = cesiumEngine();
|
||||
assert.equal(flyToDataSource(engine, source()), true);
|
||||
const { engine, calls } = engineWith();
|
||||
assert.equal(flyToFootprint(engine, recordFootprint(records())), true);
|
||||
const [flight] = calls();
|
||||
const center = Cesium.Cartographic.fromCartesian(flight.sphere.center);
|
||||
const center = geo.cartographic.fromCartesian(flight.sphere.center);
|
||||
assert.ok(Math.abs(center.height) < 50, `center height ${center.height}`);
|
||||
assert.ok(flight.options.offset.range >= 800);
|
||||
assert.ok(flight.options.range >= 800);
|
||||
assert.equal(
|
||||
typeof flight.options.complete,
|
||||
'function',
|
||||
'the ground guard runs on landing',
|
||||
);
|
||||
assert.equal(
|
||||
flyToDataSource(engine, new Cesium.CustomDataSource('empty')),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
calls().length,
|
||||
1,
|
||||
'empty sources never start deferred navigation',
|
||||
);
|
||||
assert.equal(flyToFootprint(engine, []), false);
|
||||
assert.equal(calls().length, 1, 'an empty footprint never flies');
|
||||
cancelCameraArrival(engine);
|
||||
});
|
||||
|
||||
test('a very long track is framed without spreading it into a call', () => {
|
||||
// 400k vertices: `push(...line)` throws RangeError (too many arguments)
|
||||
// well below this; the walk keeps a bounded sample and both ends.
|
||||
// well below this.
|
||||
const n = 400_000;
|
||||
const line = new Array(n);
|
||||
for (let i = 0; i < n; i++)
|
||||
line[i] = Cesium.Cartesian3.fromDegrees(-120 + (i / n) * 2, 40);
|
||||
const ds = new Cesium.CustomDataSource('long');
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({ position: Cesium.Cartesian3.fromDegrees(-110, 41) });
|
||||
const points = dataSourcePoints(ds);
|
||||
for (let i = 0; i < n; i++) line[i] = [-120 + (i / n) * 2, 40, 0];
|
||||
const points = recordFootprint({
|
||||
points: [{ position: [-110, 41, 0], altitude: 'ground' }],
|
||||
lines: [{ positions: line, ground: true }],
|
||||
polygons: [],
|
||||
overlays: [],
|
||||
});
|
||||
assert.equal(points.length, n + 1, 'every vertex contributes to framing');
|
||||
const lons = points.map(([lon]) => lon);
|
||||
assert.ok(
|
||||
lons.reduce((a, b) => Math.min(a, b), Infinity) < -119.99 &&
|
||||
lons.reduce((a, b) => Math.max(a, b), -Infinity) > -110.01,
|
||||
);
|
||||
assert.ok(lons.some((lon) => Math.abs(lon - -118.000005) < 0.01));
|
||||
});
|
||||
|
||||
test('framing includes a sparse interior outlier, walls and rotated overlays', () => {
|
||||
const ds = new Cesium.CustomDataSource('bounds');
|
||||
const line = Array.from({ length: 200031 }, () =>
|
||||
Cesium.Cartesian3.fromDegrees(0, 0),
|
||||
);
|
||||
line[12345] = Cesium.Cartesian3.fromDegrees(20, 10);
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({
|
||||
wall: { positions: Cesium.Cartesian3.fromDegreesArray([30, 10, 31, 11]) },
|
||||
});
|
||||
ds.entities.add({
|
||||
rectangle: {
|
||||
coordinates: Cesium.Rectangle.fromDegrees(40, 0, 41, 1),
|
||||
rotation: Math.PI / 4,
|
||||
},
|
||||
});
|
||||
const points = dataSourcePoints(ds);
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 20) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 31) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => lon > 41));
|
||||
});
|
||||
|
||||
test('portrait framing accounts for FOV, high ground and symmetric extents', () => {
|
||||
const ds = new Cesium.CustomDataSource('view');
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([-105, 39, -104.9, 39]),
|
||||
},
|
||||
});
|
||||
const { viewer, engine, calls } = cesiumEngine();
|
||||
viewer.scene.globe.getHeight = () => 2600;
|
||||
// A 60° field of view on the narrower side, as Cesium's frustum keeps it:
|
||||
// vertical in portrait, horizontal in landscape.
|
||||
const { frustum } = viewer.camera;
|
||||
frustum.aspectRatio = 390 / 844;
|
||||
frustum.fovy = Math.PI / 3;
|
||||
flyToDataSource(engine, ds);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(calls()[0].sphere.center).height - 2600,
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.equal(calls()[0].options.offset.pitch, -Math.PI / 2);
|
||||
frustum.aspectRatio = 16 / 9;
|
||||
frustum.fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / frustum.aspectRatio);
|
||||
flyToDataSource(engine, ds);
|
||||
assert.ok(calls()[0].options.offset.range > calls()[1].options.offset.range);
|
||||
const symmetric = {
|
||||
entities: {
|
||||
values: [
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(6378137, 0, 0) } },
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(-6378137, 0, 0) } },
|
||||
],
|
||||
},
|
||||
};
|
||||
assert.doesNotThrow(() => flyToDataSource(engine, symmetric));
|
||||
assert.ok(Number.isFinite(calls().at(-1).options.offset.range));
|
||||
assert.doesNotThrow(() => calls().at(-1).options.complete());
|
||||
const { engine, calls } = engineWith();
|
||||
assert.equal(flyToFootprint(engine, points), true);
|
||||
assert.ok(calls()[0].sphere.radius > 400_000);
|
||||
cancelCameraArrival(engine);
|
||||
});
|
||||
|
||||
test('non-finite positions and hidden features never enter the camera footprint', () => {
|
||||
const position = (p) => ({ position: { getValue: () => p } });
|
||||
const points = dataSourcePoints({
|
||||
entities: {
|
||||
values: [
|
||||
position(new Cesium.Cartesian3(NaN, 1, 2)),
|
||||
{
|
||||
...position(Cesium.Cartesian3.fromDegrees(10, 10)),
|
||||
isShowing: false,
|
||||
},
|
||||
position(Cesium.Cartesian3.fromDegrees(20, 20)),
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(points.length, 1);
|
||||
assert.ok(Math.abs(points[0][0] - 20) < 1e-6);
|
||||
});
|
||||
|
||||
test('on a globe engine the footprint is flown to through flyToSphere, straight down at the surface', async () => {
|
||||
const { createFakeEngine } = await import('../globe/testing/fakeEngine.js');
|
||||
const engine = createFakeEngine({ kind: 'navara' });
|
||||
engine.fake.script('terrainHeight', 120);
|
||||
assert.equal(flyToDataSource(engine, source(), { duration: 0.5 }), true);
|
||||
const [call] = engine.fake.callsOf('camera.flyToSphere');
|
||||
assert.ok(call, 'one sphere flight');
|
||||
const [sphere, options] = call.args;
|
||||
const center = Cesium.Cartographic.fromCartesian(sphere.center);
|
||||
assert.ok(Math.abs(center.height - 120) < 1, 'centre on the terrain');
|
||||
assert.ok(sphere.radius > 100);
|
||||
assert.equal(options.pitch, -Math.PI / 2);
|
||||
assert.equal(options.duration, 0.5);
|
||||
assert.ok(options.range >= 800);
|
||||
assert.equal(typeof options.complete, 'function');
|
||||
test('framing is straight down, on high ground, and wider in portrait', () => {
|
||||
const footprint = [
|
||||
[-105, 39, 0],
|
||||
[-104.9, 39, 0],
|
||||
];
|
||||
const portrait = engineWith({ terrain: 2600, width: 390, height: 844 });
|
||||
flyToFootprint(portrait.engine, footprint, { duration: 0.5 });
|
||||
const [first] = portrait.calls();
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
geo.cartographic.fromCartesian(first.sphere.center).height - 2600,
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.equal(first.options.pitch, -Math.PI / 2);
|
||||
assert.equal(first.options.duration, 0.5);
|
||||
const landscape = engineWith({ terrain: 2600, width: 1600, height: 900 });
|
||||
flyToFootprint(landscape.engine, footprint);
|
||||
assert.ok(first.options.range > landscape.calls()[0].options.range);
|
||||
// Points on opposite sides of the Earth still give a finite range.
|
||||
flyToFootprint(landscape.engine, [
|
||||
[0, 0, 0],
|
||||
[180, 0, 0],
|
||||
]);
|
||||
assert.ok(Number.isFinite(landscape.calls().at(-1).options.range));
|
||||
assert.doesNotThrow(() => landscape.calls().at(-1).options.complete());
|
||||
cancelCameraArrival(portrait.engine);
|
||||
cancelCameraArrival(landscape.engine);
|
||||
});
|
||||
+67
-86
@@ -4,8 +4,10 @@ import {
|
||||
MAX_IMPORTED_FILES,
|
||||
loadGeoFile,
|
||||
} from '../data/geoFileImport.js';
|
||||
import { drawImportedFile } from '../data/geoImportDisplay.js';
|
||||
import { recordFootprint } from '../data/geoImportRecords.js';
|
||||
import { formatNumber, t, tn, translateKnown } from '../i18n/index.js';
|
||||
import { flyToDataSource } from './flyToDataSource.js';
|
||||
import { flyToFootprint } from './flyToDataSource.js';
|
||||
|
||||
// One color per file, in import order, from the whiteboard palette.
|
||||
const COLORS = ['#39d0ff', '#ffb547', '#5dff9f', '#ff6b6b', '#8be9ff'];
|
||||
@@ -22,31 +24,31 @@ function localizedValues(values) {
|
||||
|
||||
/**
|
||||
* The Import control for the page session.
|
||||
* @param {{load?: Function, document?: Document, publish?: Function,
|
||||
* connect?: Function}} deps
|
||||
* `load(file, {viewer, color})` defaults to `loadGeoFile`; tests pass a double.
|
||||
* `publish({rows, hint})` hands the file list and hint to the view that
|
||||
* renders them. `connect(actions)` answers the view's pick and row buttons
|
||||
* and returns their disconnect.
|
||||
* @param {{load?: Function, drawFile?: Function, document?: Document,
|
||||
* publish?: Function, connect?: Function}} deps
|
||||
* `load(file, {color, signal})` defaults to `loadGeoFile` (the file's
|
||||
* plain records) and `drawFile(engine, records, {visible})` to
|
||||
* `drawImportedFile` (their drawing: { report, setShow, refreshGround,
|
||||
* destroy }); tests pass doubles. `publish({rows, hint})` hands the file
|
||||
* list and hint to the view that renders them. `connect(actions)` answers
|
||||
* the view's pick and row buttons and returns their disconnect.
|
||||
*
|
||||
* The imported files belong to the session; their drawing belongs to the
|
||||
* attached globe. `attachScene({ viewer, engine })` draws them on a Cesium
|
||||
* viewer (its engine flies the camera to them);
|
||||
* `attachScene({ engine, draw })` on a globe engine without one (Navara),
|
||||
* where `draw(dataSource)` resolves with that engine's drawing of a file
|
||||
* ({ report, setShow, refresh, destroy }: src/layers/shared/render/navaraStory.js).
|
||||
* A file kept while no globe was attached is read again from its bytes; the
|
||||
* control listens for drops and camera gestures on the attached globe.
|
||||
* `detachScene()` takes the files off the globe and keeps the list. Without a
|
||||
* globe the list stays, and import and fly-to wait for one.
|
||||
* attached globe. `attachScene({ engine })` draws them on a globe engine,
|
||||
* the same on every engine, and flies its camera to them. A file kept while
|
||||
* no globe was attached is read again from its bytes; the control listens
|
||||
* for drops and camera gestures on the attached globe. `detachScene()` takes
|
||||
* the files off the globe and keeps the list. Without a globe the list
|
||||
* stays, and import and fly-to wait for one.
|
||||
* @returns {{destroy: Function, importFiles: Function, list: Function,
|
||||
* setVisible: Function, flyTo: Function, remove: Function,
|
||||
* diagnostics: Function, attachScene: Function, detachScene: Function}|null}
|
||||
*/
|
||||
export function createGeoFileImport({
|
||||
load = loadGeoFile,
|
||||
drawFile = drawImportedFile,
|
||||
document: doc = globalThis.document,
|
||||
flyToSource = flyToDataSource,
|
||||
flyToSource = flyToFootprint,
|
||||
navigation = null,
|
||||
ground = null,
|
||||
subscribeMapSource = null,
|
||||
@@ -67,8 +69,7 @@ export function createGeoFileImport({
|
||||
let cameraIntent = 0;
|
||||
let hint = '';
|
||||
const lifetime = new AbortController();
|
||||
// The attached globe ({ viewer, engine, draw, controller }): a Cesium
|
||||
// viewer and its engine, or an engine and its drawing; null while none is
|
||||
// The attached globe ({ engine, controller }); null while none is
|
||||
// attached.
|
||||
let scene = null;
|
||||
|
||||
@@ -81,15 +82,14 @@ export function createGeoFileImport({
|
||||
hint = text || '';
|
||||
present();
|
||||
};
|
||||
const render = () => {
|
||||
if (scene?.viewer) scene.viewer.scene?.requestRender?.();
|
||||
else scene?.engine?.render.request('geo-import');
|
||||
};
|
||||
const render = () => scene?.engine?.render.request('geo-import');
|
||||
let groundTimer,
|
||||
groundQueued = false,
|
||||
groundAgain = false;
|
||||
groundAgain = false,
|
||||
// Refreshes left while the map's tiles are still loading.
|
||||
groundWaits = 0;
|
||||
let groundRemovers = [];
|
||||
const scheduleGround = () => {
|
||||
const scheduleGround = (delay = 200) => {
|
||||
if (destroyed || !scene || !imports.length) return;
|
||||
if (groundQueued) {
|
||||
groundAgain = true;
|
||||
@@ -99,18 +99,23 @@ export function createGeoFileImport({
|
||||
groundTimer = setTimeout(() => {
|
||||
groundQueued = true;
|
||||
const attached = scene;
|
||||
let retry = false;
|
||||
queue = queue
|
||||
.catch(() => {})
|
||||
.then(async () => {
|
||||
try {
|
||||
for (const item of imports) {
|
||||
if (destroyed || scene !== attached) return;
|
||||
if (item.visible) {
|
||||
await item.refreshGround?.(attached.controller.signal);
|
||||
item.drawing?.refresh?.();
|
||||
}
|
||||
if (item.visible)
|
||||
await item.drawing?.refreshGround(attached.controller.signal);
|
||||
}
|
||||
render();
|
||||
// The ground is read from the tiles drawn now: read it again
|
||||
// once they have loaded.
|
||||
retry =
|
||||
attached.engine.surface.tilesLoaded?.() === false &&
|
||||
groundWaits > 0;
|
||||
groundWaits = retry ? groundWaits - 1 : 0;
|
||||
} catch {
|
||||
if (!destroyed && scene === attached)
|
||||
setHint(
|
||||
@@ -123,10 +128,10 @@ export function createGeoFileImport({
|
||||
if (groundAgain) {
|
||||
groundAgain = false;
|
||||
scheduleGround();
|
||||
}
|
||||
} else if (retry) scheduleGround(1000);
|
||||
}
|
||||
});
|
||||
}, 200);
|
||||
}, delay);
|
||||
};
|
||||
const ownEvent = (event, listener) => {
|
||||
const remove = event?.addEventListener?.(listener);
|
||||
@@ -179,7 +184,6 @@ export function createGeoFileImport({
|
||||
const item = find(id);
|
||||
if (!item) return false;
|
||||
item.visible = Boolean(visible);
|
||||
if (item.dataSource) item.dataSource.show = item.visible;
|
||||
item.drawing?.setShow(item.visible);
|
||||
if (item.visible) scheduleGround();
|
||||
present();
|
||||
@@ -188,9 +192,9 @@ export function createGeoFileImport({
|
||||
}
|
||||
|
||||
const fly = (item) => {
|
||||
if (!scene?.engine || !item.dataSource) return false;
|
||||
if (!scene?.engine || !item.drawing) return false;
|
||||
if (!item.visible) setVisible(item.id, true);
|
||||
flyToSource(scene.engine, item.dataSource, { ground });
|
||||
flyToSource(scene.engine, recordFootprint(item.records), { ground });
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -200,7 +204,7 @@ export function createGeoFileImport({
|
||||
*/
|
||||
function flyTo(id) {
|
||||
const item = find(id);
|
||||
if (!item || !scene || !item.dataSource) return false;
|
||||
if (!item || !scene || !item.drawing) return false;
|
||||
if (typeof navigation?.runImmediateNavigation === 'function')
|
||||
return (
|
||||
navigation.runImmediateNavigation('file', () => fly(item)) !== false
|
||||
@@ -223,15 +227,12 @@ export function createGeoFileImport({
|
||||
};
|
||||
|
||||
/** Take one file's drawing off the globe; the file stays in the list. */
|
||||
function undraw(item, from = scene) {
|
||||
if (item.dataSource)
|
||||
from?.viewer?.dataSources?.remove?.(item.dataSource, true);
|
||||
function undraw(item) {
|
||||
item.drawing?.destroy();
|
||||
item.drawing = null;
|
||||
item.revoke?.();
|
||||
item.dataSource = null;
|
||||
item.records = null;
|
||||
item.revoke = null;
|
||||
item.refreshGround = null;
|
||||
}
|
||||
|
||||
/** Remove one imported file from the globe and the list. */
|
||||
@@ -247,26 +248,22 @@ export function createGeoFileImport({
|
||||
|
||||
/** Draw a file read for the attached globe. False once that globe went. */
|
||||
async function draw(item, attached, loaded) {
|
||||
item.dataSource = loaded.dataSource;
|
||||
item.records = loaded.records;
|
||||
item.revoke = loaded.revoke;
|
||||
item.refreshGround = loaded.refreshGround;
|
||||
item.dataSource.show = item.visible;
|
||||
if (attached.viewer) await attached.viewer.dataSources.add(item.dataSource);
|
||||
else {
|
||||
try {
|
||||
item.drawing = await attached.draw(item.dataSource);
|
||||
} catch (error) {
|
||||
undraw(item, attached);
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
item.drawing = await drawFile(attached.engine, loaded.records, {
|
||||
visible: item.visible,
|
||||
});
|
||||
} catch (error) {
|
||||
undraw(item);
|
||||
throw error;
|
||||
}
|
||||
if (destroyed || scene !== attached) {
|
||||
undraw(item, attached);
|
||||
undraw(item);
|
||||
return false;
|
||||
}
|
||||
// What this globe leaves out of the file (Navara: labels, models...).
|
||||
// What no engine draws of the file (walls, extruded polygons...).
|
||||
item.undrawn = item.drawing?.report?.undrawn ?? 0;
|
||||
loaded.mount?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -322,8 +319,6 @@ export function createGeoFileImport({
|
||||
let loaded;
|
||||
try {
|
||||
loaded = await load(file, {
|
||||
viewer: attached.viewer,
|
||||
engine: attached.engine,
|
||||
color,
|
||||
signal: attached.controller.signal,
|
||||
});
|
||||
@@ -358,17 +353,14 @@ export function createGeoFileImport({
|
||||
visible: true,
|
||||
// The bytes, so a later globe can read the file again.
|
||||
file,
|
||||
dataSource: null,
|
||||
records: null,
|
||||
drawing: null,
|
||||
undrawn: 0,
|
||||
revoke: null,
|
||||
refreshGround: null,
|
||||
};
|
||||
try {
|
||||
if (!(await draw(item, attached, loaded))) break;
|
||||
} catch (error) {
|
||||
// A Cesium viewer's own failure stops the batch, as it always did.
|
||||
if (attached.viewer) throw error;
|
||||
} catch {
|
||||
outcomes.push({
|
||||
name: fileName,
|
||||
ok: false,
|
||||
@@ -401,11 +393,9 @@ export function createGeoFileImport({
|
||||
async function redraw(attached) {
|
||||
for (const item of [...imports]) {
|
||||
if (destroyed || scene !== attached) return;
|
||||
if (item.dataSource || !imports.includes(item)) continue;
|
||||
if (item.drawing || !imports.includes(item)) continue;
|
||||
try {
|
||||
const loaded = await load(item.file, {
|
||||
viewer: attached.viewer,
|
||||
engine: attached.engine,
|
||||
color: item.color,
|
||||
signal: attached.controller.signal,
|
||||
});
|
||||
@@ -454,40 +444,32 @@ export function createGeoFileImport({
|
||||
target.removeEventListener(type, listener, options);
|
||||
dragDepth = 0;
|
||||
setDragging(false);
|
||||
for (const item of imports) undraw(item, previous);
|
||||
for (const item of imports) undraw(item);
|
||||
}
|
||||
|
||||
function attachScene({
|
||||
viewer = null,
|
||||
engine = null,
|
||||
draw: drawOnEngine = null,
|
||||
navigation: nextNavigation = navigation,
|
||||
subscribeMapSource: nextMapSource = subscribeMapSource,
|
||||
} = {}) {
|
||||
if (destroyed) return;
|
||||
detachScene();
|
||||
if (!viewer && !(engine && drawOnEngine)) return;
|
||||
if (!engine) return;
|
||||
// The shell and the map sources of this attachment.
|
||||
navigation = nextNavigation;
|
||||
const offMapSource = nextMapSource?.(scheduleGround);
|
||||
const ground = () => {
|
||||
groundWaits = 10;
|
||||
scheduleGround();
|
||||
};
|
||||
const offMapSource = nextMapSource?.(ground);
|
||||
if (typeof offMapSource === 'function') groundRemovers.push(offMapSource);
|
||||
const attached = (scene = {
|
||||
viewer,
|
||||
engine,
|
||||
draw: viewer ? null : drawOnEngine,
|
||||
controller: new AbortController(),
|
||||
});
|
||||
ownEvent(
|
||||
viewer ? viewer.camera?.moveEnd : engine.camera.moveEnd,
|
||||
scheduleGround,
|
||||
);
|
||||
ownEvent(viewer?.scene?.globe?.tileLoadProgressEvent, (pending) => {
|
||||
if (!pending) scheduleGround();
|
||||
});
|
||||
const container = viewer ? viewer.container : engine.host.container;
|
||||
const canvas = viewer
|
||||
? viewer.scene?.canvas || container
|
||||
: engine.host.canvas;
|
||||
ownEvent(engine.camera.moveEnd, ground);
|
||||
const container = engine.host.container;
|
||||
const canvas = engine.host.canvas || container;
|
||||
listen(canvas, 'pointerdown', gesture, { passive: true });
|
||||
listen(canvas, 'wheel', gesture, { passive: true });
|
||||
listen(container, 'dragenter', (event) => {
|
||||
@@ -514,7 +496,7 @@ export function createGeoFileImport({
|
||||
const files = [...(event.dataTransfer?.files || [])];
|
||||
if (files.length) void importFiles(files);
|
||||
});
|
||||
if (imports.some((item) => !item.dataSource)) {
|
||||
if (imports.some((item) => !item.drawing)) {
|
||||
const run = queue.then(() => redraw(attached));
|
||||
queue = run.catch(() => {});
|
||||
}
|
||||
@@ -543,7 +525,7 @@ export function createGeoFileImport({
|
||||
detachScene,
|
||||
diagnostics: () => ({
|
||||
files: imports.length,
|
||||
drawn: imports.filter((item) => item.dataSource).length,
|
||||
drawn: imports.filter((item) => item.drawing).length,
|
||||
entities: imports.reduce((n, item) => n + item.entityCount, 0),
|
||||
listeners: listeners.length,
|
||||
attached: Boolean(scene),
|
||||
@@ -551,12 +533,11 @@ export function createGeoFileImport({
|
||||
}),
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
const last = scene;
|
||||
detachScene();
|
||||
destroyed = true;
|
||||
disconnect();
|
||||
lifetime.abort();
|
||||
for (const item of imports.splice(0)) undraw(item, last);
|
||||
for (const item of imports.splice(0)) undraw(item);
|
||||
setDragging(false);
|
||||
setHint('');
|
||||
if (globalThis.window?.__gevGeoImport === handle)
|
||||
|
||||
+138
-144
@@ -1,14 +1,16 @@
|
||||
// Behavioral tests for DISPLAY ▸ Import: the controller is driven against
|
||||
// fake DOM and viewer doubles with an injected loader, and its observable
|
||||
// effects are asserted — data sources added and removed, the rows and hint it
|
||||
// publishes, drop handling, the file limit, and what destroy() gives back.
|
||||
// The Display panel renders the published list (`displayPanel.test.mjs`);
|
||||
// real parsing and rendering run in `scripts/qa-geo-import.mjs`.
|
||||
// fake DOM and engine doubles with an injected loader and drawing, and its
|
||||
// observable effects are asserted — drawings made and destroyed, the rows
|
||||
// and hint it publishes, drop handling, the file limit, and what destroy()
|
||||
// gives back. The Display panel renders the published list
|
||||
// (`displayPanel.test.mjs`); real parsing and drawing run in
|
||||
// `scripts/qa-geo-import.mjs` and `scripts/qa-navara-geo-import.mjs`.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createGeoFileImport, summarize } from './geoFileImport.js';
|
||||
import { GeoImportError, MAX_IMPORTED_FILES } from '../data/geoFileImport.js';
|
||||
import { emptyRecords } from '../data/geoImportRecords.js';
|
||||
|
||||
class FakeClassList {
|
||||
constructor() {
|
||||
@@ -59,7 +61,41 @@ class FakeElement {
|
||||
}
|
||||
}
|
||||
|
||||
function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
/** A globe engine double: its host, camera moves and render requests. */
|
||||
function fakeEngine() {
|
||||
const moveEnd = new Set();
|
||||
const engine = {
|
||||
kind: 'fake',
|
||||
host: {
|
||||
container: new FakeElement('div', 'cesiumContainer'),
|
||||
canvas: new FakeElement('canvas'),
|
||||
},
|
||||
camera: {
|
||||
moveEnd: {
|
||||
addEventListener: (fn) => (moveEnd.add(fn), () => moveEnd.delete(fn)),
|
||||
},
|
||||
},
|
||||
surface: { tilesLoaded: () => true },
|
||||
renders: 0,
|
||||
render: { request: () => (engine.renders += 1) },
|
||||
moveEnd,
|
||||
};
|
||||
return engine;
|
||||
}
|
||||
|
||||
/** A file's records with one point, as the loader reads them. */
|
||||
const pointRecords = (lon = 1, lat = 2) => ({
|
||||
...emptyRecords(),
|
||||
points: [{ position: [lon, lat, 0], altitude: 'ground', icon: {} }],
|
||||
});
|
||||
|
||||
function setup({
|
||||
load,
|
||||
navigation,
|
||||
flyToSource,
|
||||
subscribeMapSource,
|
||||
drawFile,
|
||||
} = {}) {
|
||||
const els = {
|
||||
'geo-import-button': new FakeElement('button', 'geo-import-button'),
|
||||
};
|
||||
@@ -71,27 +107,27 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
const added = [];
|
||||
const removed = [];
|
||||
const flights = [];
|
||||
let renders = 0;
|
||||
let shown = null;
|
||||
// The view's pick and row buttons, as the display store holds them.
|
||||
let actions = null;
|
||||
const viewer = {
|
||||
container: new FakeElement('div', 'cesiumContainer'),
|
||||
scene: { requestRender: () => (renders += 1) },
|
||||
dataSources: {
|
||||
add: async (ds) => {
|
||||
added.push(ds);
|
||||
return ds;
|
||||
},
|
||||
remove: (ds, destroy) => {
|
||||
removed.push({ ds, destroy });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
flyTo: (target) => flights.push(target),
|
||||
// The globe engine the files draw on and fly to.
|
||||
const engine = fakeEngine();
|
||||
const host = engine.host;
|
||||
// Each file's drawing: what it shows and whether it went.
|
||||
const defaultDraw = async (on, records, { visible }) => {
|
||||
const drawing = {
|
||||
engine: on,
|
||||
records,
|
||||
show: visible,
|
||||
refreshed: 0,
|
||||
report: { drawn: 1, undrawn: records.undrawn?.left ?? 0 },
|
||||
setShow: (next) => (drawing.show = next),
|
||||
refreshGround: async () => drawing.refreshed++,
|
||||
destroy: () => removed.push({ ds: drawing }),
|
||||
};
|
||||
added.push(drawing);
|
||||
return drawing;
|
||||
};
|
||||
// The viewer's globe engine, which flies the camera to a file.
|
||||
const engine = { kind: 'cesium' };
|
||||
const flownOn = [];
|
||||
const revoked = [];
|
||||
const loads = [];
|
||||
@@ -100,7 +136,7 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
if (file.fail) throw new GeoImportError(file.fail);
|
||||
if (file.crash) throw new Error('boom');
|
||||
return {
|
||||
dataSource: { show: true },
|
||||
records: pointRecords(),
|
||||
name: file.name,
|
||||
format: 'geojson',
|
||||
entityCount: 3,
|
||||
@@ -110,14 +146,15 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
};
|
||||
const tool = createGeoFileImport({
|
||||
load: load || defaultLoad,
|
||||
drawFile: drawFile || defaultDraw,
|
||||
document,
|
||||
...(navigation ? { navigation } : {}),
|
||||
...(subscribeMapSource ? { subscribeMapSource } : {}),
|
||||
flyToSource:
|
||||
flyToSource ||
|
||||
((target, ds) => {
|
||||
((target, points) => {
|
||||
flownOn.push(target);
|
||||
flights.push(ds);
|
||||
flights.push(points);
|
||||
}),
|
||||
publish: (view) => {
|
||||
shown = view;
|
||||
@@ -127,12 +164,12 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
return () => (actions = null);
|
||||
},
|
||||
});
|
||||
tool?.attachScene({ viewer, engine });
|
||||
tool?.attachScene({ engine });
|
||||
return {
|
||||
tool,
|
||||
els,
|
||||
document,
|
||||
viewer,
|
||||
host,
|
||||
engine,
|
||||
added,
|
||||
removed,
|
||||
@@ -140,7 +177,7 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
|
||||
flownOn,
|
||||
revoked,
|
||||
loads,
|
||||
renders: () => renders,
|
||||
renders: () => engine.renders,
|
||||
shown: () => shown,
|
||||
actions: () => actions,
|
||||
/** A control's change, as the view sends it. */
|
||||
@@ -176,7 +213,7 @@ test('a pick imports each file', async () => {
|
||||
);
|
||||
assert.equal(rows(t).length, 2);
|
||||
assert.equal(t.flights.length, 1, 'the first file of a batch is flown to');
|
||||
assert.equal(t.flownOn[0], t.engine, "the viewer's engine flies there");
|
||||
assert.equal(t.flownOn[0], t.engine, 'the attached engine flies there');
|
||||
assert.equal(t.shown().hint, 'Added 2 files.');
|
||||
assert.deepEqual(
|
||||
t.tool.list().map((f) => f.name),
|
||||
@@ -205,9 +242,9 @@ test('row buttons hide, show, fly to and remove a file', async () => {
|
||||
assert.equal(action(rows(t)[0], 'toggle').label, 'Show a.gpx');
|
||||
glyphClick('fly');
|
||||
assert.equal(ds.show, true, 'flying to a hidden file shows it');
|
||||
assert.equal(t.flights.at(-1), ds);
|
||||
assert.deepEqual(t.flights.at(-1), [[1, 2, 0]], 'its footprint');
|
||||
glyphClick('remove');
|
||||
assert.deepEqual(t.removed, [{ ds, destroy: true }]);
|
||||
assert.deepEqual(t.removed, [{ ds }]);
|
||||
assert.deepEqual(t.revoked, ['a.gpx']);
|
||||
assert.equal(t.tool.list().length, 0);
|
||||
assert.deepEqual(rows(t), []);
|
||||
@@ -251,7 +288,7 @@ test('the number of files on the globe is bounded', async () => {
|
||||
|
||||
test('dropping files on the globe imports them; other drags are left alone', async () => {
|
||||
const t = setup();
|
||||
const c = t.viewer.container;
|
||||
const c = t.host.container;
|
||||
const files = { types: ['Files'], files: [file('drop.kmz')] };
|
||||
let ev = { dataTransfer: { types: ['text/plain'] } };
|
||||
t.document.emit('dragover', ev);
|
||||
@@ -289,7 +326,7 @@ test('destroy removes every file and listener and the window handle', async () =
|
||||
t.tool.destroy();
|
||||
assert.equal(t.removed.length, 2);
|
||||
assert.deepEqual(t.revoked.sort(), ['a.geojson', 'b.geojson']);
|
||||
assert.equal(t.viewer.container.listeners.length, 0);
|
||||
assert.equal(t.host.container.listeners.length, 0);
|
||||
assert.equal(t.document.listeners.length, 0);
|
||||
assert.equal(t.actions(), null, 'the view is disconnected');
|
||||
assert.deepEqual(t.shown(), { rows: [], hint: '' });
|
||||
@@ -308,7 +345,7 @@ test('a file that finishes loading after destroy is released, not added', async
|
||||
load: async () => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
records: pointRecords(),
|
||||
name: 'late',
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
@@ -344,7 +381,7 @@ test('the application composition wires the import and owns its teardown', () =>
|
||||
tools.slice(importAt, importAt + 400),
|
||||
/navigation: styleManager/,
|
||||
);
|
||||
// The session owns the files; this viewer only their drawing.
|
||||
// The session owns the files; this globe only their drawing.
|
||||
assert.ok(
|
||||
tools.indexOf('defer(() => geoFileImport?.detachScene());') > importAt,
|
||||
);
|
||||
@@ -423,13 +460,13 @@ test('a direct camera gesture cancels the fly-to of a file still being read', as
|
||||
name: 'slow.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
records: pointRecords(),
|
||||
};
|
||||
},
|
||||
});
|
||||
const result = t.tool.importFiles([file('slow.geojson')]);
|
||||
await new Promise((r) => setImmediate(r));
|
||||
t.viewer.container.emit(gesture);
|
||||
t.engine.host.canvas.emit(gesture);
|
||||
release();
|
||||
await result;
|
||||
assert.equal(t.added.length, 1);
|
||||
@@ -459,7 +496,7 @@ test('dropping on panel controls is accepted and file drags prevent browser navi
|
||||
test('ground refresh coalesces map changes and releases its subscription on teardown', async () => {
|
||||
let changed,
|
||||
unsubscribed = 0,
|
||||
refreshed = 0;
|
||||
refreshed;
|
||||
const t = setup({
|
||||
subscribeMapSource: (listener) => {
|
||||
changed = listener;
|
||||
@@ -469,20 +506,20 @@ test('ground refresh coalesces map changes and releases its subscription on tear
|
||||
name: 'point.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
refreshGround: async () => refreshed++,
|
||||
records: pointRecords(),
|
||||
}),
|
||||
});
|
||||
await t.tool.importFiles([file('point.geojson')]);
|
||||
refreshed = () => t.added[0].refreshed;
|
||||
changed();
|
||||
changed();
|
||||
changed();
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
assert.equal(refreshed, 1);
|
||||
assert.equal(refreshed(), 1);
|
||||
t.tool.destroy();
|
||||
changed();
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
assert.equal(refreshed, 1);
|
||||
assert.equal(refreshed(), 1);
|
||||
assert.equal(unsubscribed, 1);
|
||||
});
|
||||
|
||||
@@ -520,7 +557,7 @@ test('a slow import does not fly once something newer took the camera', async ()
|
||||
load: async (f) => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
records: pointRecords(),
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
@@ -554,7 +591,7 @@ test('a queued import cannot fly over navigation that happened while it waited',
|
||||
load: async (f) => {
|
||||
if (f.name === 'first.geojson') await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
records: pointRecords(),
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
@@ -589,7 +626,7 @@ test('a refused deferred stamp (Cockpit) imports without flying', async () => {
|
||||
test('KML and KMZ rows say they keep their own styles instead of showing a color', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
records: pointRecords(),
|
||||
name: f.name,
|
||||
format: f.name.endsWith('.kml') ? 'kml' : 'gpx',
|
||||
entityCount: 2,
|
||||
@@ -608,7 +645,7 @@ test('KML and KMZ rows say they keep their own styles instead of showing a color
|
||||
test('the map-object count in a row title keeps digit grouping', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
records: pointRecords(),
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 12345,
|
||||
@@ -640,49 +677,46 @@ test('a refusal shows its counts in the language’s numerals, not the browser
|
||||
t.tool.destroy();
|
||||
});
|
||||
|
||||
test('an engine switch keeps the files and draws them again on the next viewer', async () => {
|
||||
test('an engine switch keeps the files and draws them again on the next engine', async () => {
|
||||
const t = setup();
|
||||
await t.tool.importFiles([file('a.geojson'), file('b.geojson')]);
|
||||
const [a, b] = rows(t);
|
||||
press(t, b, 'toggle');
|
||||
t.tool.detachScene();
|
||||
// The drawing left the viewer; the list and its rows stayed.
|
||||
// The drawing left the globe; the list and its rows stayed.
|
||||
assert.equal(t.removed.length, 2);
|
||||
assert.deepEqual(t.revoked.sort(), ['a.geojson', 'b.geojson']);
|
||||
assert.deepEqual(
|
||||
rows(t).map((row) => row.id),
|
||||
[a.id, b.id],
|
||||
);
|
||||
assert.equal(t.viewer.container.listeners.length, 0);
|
||||
assert.equal(t.host.container.listeners.length, 0);
|
||||
assert.equal(t.document.listeners.length, 0);
|
||||
assert.equal(t.tool.flyTo(a.id), false);
|
||||
const refused = await t.tool.importFiles([file('c.geojson')]);
|
||||
assert.equal(refused[0].ok, false);
|
||||
assert.equal(t.tool.list().length, 2);
|
||||
|
||||
// The next viewer reads the kept files again, as they were.
|
||||
const next = {
|
||||
container: new FakeElement('div', 'cesiumContainer'),
|
||||
scene: { requestRender() {} },
|
||||
dataSources: {
|
||||
added: [],
|
||||
add: async (ds) => next.dataSources.added.push(ds),
|
||||
remove() {},
|
||||
},
|
||||
};
|
||||
// The next engine reads the kept files again, as they were.
|
||||
const next = fakeEngine();
|
||||
t.loads.length = 0;
|
||||
t.tool.attachScene({ viewer: next });
|
||||
t.added.length = 0;
|
||||
t.tool.attachScene({ engine: next });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.deepEqual(
|
||||
t.loads.map(({ file, opts }) => [file.name, opts.viewer === next]),
|
||||
t.loads.map(({ file, opts }) => [file.name, opts.color]),
|
||||
[
|
||||
['a.geojson', true],
|
||||
['b.geojson', true],
|
||||
['a.geojson', '#39d0ff'],
|
||||
['b.geojson', '#ffb547'],
|
||||
],
|
||||
'each file keeps its colour',
|
||||
);
|
||||
assert.equal(next.dataSources.added.length, 2);
|
||||
assert.equal(next.dataSources.added[1].show, false, 'b stays hidden');
|
||||
assert.deepEqual(
|
||||
t.added.map((drawing) => drawing.engine),
|
||||
[next, next],
|
||||
);
|
||||
assert.equal(t.added[1].show, false, 'b stays hidden');
|
||||
assert.deepEqual(
|
||||
t.tool.list().map(({ id, visible }) => [id, visible]),
|
||||
[
|
||||
@@ -690,98 +724,58 @@ test('an engine switch keeps the files and draws them again on the next viewer',
|
||||
[b.id, false],
|
||||
],
|
||||
);
|
||||
assert.ok(next.container.listeners.length > 0);
|
||||
assert.ok(next.host.container.listeners.length > 0);
|
||||
assert.equal(t.tool.diagnostics().drawn, 2);
|
||||
t.tool.destroy();
|
||||
});
|
||||
|
||||
test('on Navara the files draw through the engine drawing, report what it leaves out and switch back to Cesium', async () => {
|
||||
const t = setup();
|
||||
await t.tool.importFiles([file('a.geojson')]);
|
||||
t.tool.detachScene();
|
||||
const canvas = new FakeElement('canvas');
|
||||
const container = new FakeElement('div', 'cesiumContainer');
|
||||
const moveEnd = new Set();
|
||||
const requests = [];
|
||||
const engine = {
|
||||
host: { canvas, container },
|
||||
camera: {
|
||||
moveEnd: {
|
||||
addEventListener: (fn) => (moveEnd.add(fn), () => moveEnd.delete(fn)),
|
||||
},
|
||||
},
|
||||
render: { request: (reason) => requests.push(reason) },
|
||||
};
|
||||
const drawings = [];
|
||||
const draw = async (dataSource) => {
|
||||
const drawing = {
|
||||
dataSource,
|
||||
shown: [],
|
||||
destroyed: false,
|
||||
report: { drawn: 2, undrawn: 3, kinds: { label: 3 } },
|
||||
setShow: (show) => drawing.shown.push(show),
|
||||
refresh() {},
|
||||
destroy() {
|
||||
drawing.destroyed = true;
|
||||
},
|
||||
};
|
||||
drawings.push(drawing);
|
||||
return drawing;
|
||||
};
|
||||
t.loads.length = 0;
|
||||
t.tool.attachScene({ engine, draw });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
// The kept file is read again for the engine and drawn by it.
|
||||
assert.deepEqual(
|
||||
t.loads.map(({ opts }) => [opts.viewer, opts.engine === engine]),
|
||||
[[null, true]],
|
||||
);
|
||||
assert.equal(drawings.length, 1);
|
||||
assert.match(t.shown().hint, /leaves out of a\.geojson: 3/);
|
||||
test('what no engine draws of a file is reported, and the drawing follows the engine', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
records: { ...pointRecords(), undrawn: { left: 3 } },
|
||||
name: f.name,
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
removed: 0,
|
||||
revoke() {},
|
||||
}),
|
||||
});
|
||||
await t.tool.importFiles([file('a.kml')]);
|
||||
assert.match(t.shown().hint, /Added 1 file\. .*leaves out of a\.kml: 3/);
|
||||
assert.equal(t.tool.list()[0].undrawn, 3);
|
||||
assert.ok(canvas.listeners.length > 0, 'gestures on the engine canvas');
|
||||
assert.ok(container.listeners.length > 0, 'drops on its container');
|
||||
assert.equal(moveEnd.size, 1);
|
||||
// A new file: drawn, counted, reported in the batch hint.
|
||||
const outcomes = await t.tool.importFiles([file('b.geojson')]);
|
||||
assert.deepEqual(
|
||||
outcomes.map(({ ok, undrawn }) => [ok, undrawn]),
|
||||
[[true, 3]],
|
||||
);
|
||||
assert.match(t.shown().hint, /Added 1 file\. .*leaves out of b\.geojson: 3/);
|
||||
t.tool.detachScene();
|
||||
const engine = fakeEngine();
|
||||
t.tool.attachScene({ engine });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
// The kept file is drawn again on the next engine, and says so.
|
||||
assert.equal(t.added.at(-1).engine, engine);
|
||||
assert.match(t.shown().hint, /leaves out of a\.kml: 3/);
|
||||
assert.ok(engine.host.canvas.listeners.length > 0, 'gestures on its canvas');
|
||||
assert.ok(engine.host.container.listeners.length > 0, 'drops on it');
|
||||
assert.equal(engine.moveEnd.size, 1);
|
||||
const [a] = rows(t);
|
||||
press(t, a, 'toggle');
|
||||
assert.deepEqual(drawings[0].shown, [false]);
|
||||
// Fly-to goes to the engine.
|
||||
assert.equal(t.added.at(-1).show, false);
|
||||
assert.equal(t.tool.flyTo(a.id), true);
|
||||
assert.equal(t.flights.length > 0, true);
|
||||
// A switch to Cesium takes the drawing off the engine.
|
||||
assert.equal(t.flownOn.at(-1), engine, 'fly-to goes to the engine');
|
||||
t.tool.detachScene();
|
||||
assert.ok(drawings.every((drawing) => drawing.destroyed));
|
||||
assert.equal(canvas.listeners.length, 0);
|
||||
assert.equal(moveEnd.size, 0);
|
||||
t.tool.attachScene({ viewer: t.viewer });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.equal(t.tool.diagnostics().drawn, 2);
|
||||
assert.equal(engine.host.canvas.listeners.length, 0);
|
||||
assert.equal(engine.moveEnd.size, 0);
|
||||
t.tool.destroy();
|
||||
});
|
||||
|
||||
test('an engine drawing that fails reports the file instead of stopping the batch', async () => {
|
||||
const t = setup();
|
||||
t.tool.detachScene();
|
||||
const engine = {
|
||||
host: { canvas: new FakeElement('canvas'), container: new FakeElement() },
|
||||
camera: { moveEnd: { addEventListener: () => () => {} } },
|
||||
render: { request() {} },
|
||||
};
|
||||
test('a drawing that fails reports the file instead of stopping the batch', async () => {
|
||||
let calls = 0;
|
||||
t.tool.attachScene({
|
||||
engine,
|
||||
draw: async () => {
|
||||
const t = setup({
|
||||
drawFile: async () => {
|
||||
if (calls++ === 0) throw new Error('no GPU');
|
||||
return { report: { undrawn: 0 }, setShow() {}, destroy() {} };
|
||||
return {
|
||||
report: { undrawn: 0 },
|
||||
setShow() {},
|
||||
refreshGround: async () => {},
|
||||
destroy() {},
|
||||
};
|
||||
},
|
||||
});
|
||||
const outcomes = await t.tool.importFiles([
|
||||
|
||||
@@ -23,18 +23,6 @@ import { msg } from '../i18n/index.js';
|
||||
/** The id this tool claims the pointer under. */
|
||||
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
|
||||
|
||||
/**
|
||||
* The camera held still until the returned release: the engine's counted
|
||||
* suspension where it has one (Navara keeps the app's own setCameraInputs
|
||||
* choice under it), else camera inputs off and on again.
|
||||
*/
|
||||
function freezeCamera(input) {
|
||||
if (typeof input.suspendCameraInputs === 'function')
|
||||
return input.suspendCameraInputs();
|
||||
input.setCameraInputs(false);
|
||||
return () => input.setCameraInputs(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the box tool.
|
||||
* @param {{ engine: import('../globe/contract.js').GlobeEngine,
|
||||
@@ -123,7 +111,9 @@ export function initImageryBoxTool({
|
||||
anchor = point;
|
||||
corner = point;
|
||||
pointerId = event.pointerId;
|
||||
thaw = freezeCamera(engine.input);
|
||||
// The engine counts suspensions: the camera inputs are back as they
|
||||
// were once the drag ends.
|
||||
thaw = engine.input.suspendCameraInputs();
|
||||
canvas.setPointerCapture?.(pointerId);
|
||||
onPreview(dragBox());
|
||||
}
|
||||
|
||||
@@ -12,9 +12,9 @@ import {
|
||||
} from './imageryBoxTool.js';
|
||||
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
|
||||
|
||||
function fixture(options = {}, fakeOptions = {}) {
|
||||
function fixture(options = {}) {
|
||||
resetPointerOwnership();
|
||||
const fakes = boxToolFakes(fakeOptions);
|
||||
const fakes = boxToolFakes();
|
||||
const boxes = [];
|
||||
const cancels = [];
|
||||
const actives = [];
|
||||
@@ -163,11 +163,11 @@ test('destroy mid-drag restores the camera, releases the claim and clears the pr
|
||||
});
|
||||
|
||||
test('blur and a cancelled pointer during a drag return the camera, the preview and the pointer', () => {
|
||||
const f = fixture({}, { suspend: true });
|
||||
const f = fixture();
|
||||
f.tool.start();
|
||||
f.down({ x: 250, y: 125 });
|
||||
assert.equal(f.camera.suspended, 1, "the engine's counted suspension");
|
||||
assert.equal(f.camera.inputs, true, 'the app choice is left alone');
|
||||
assert.equal(f.camera.choice, true, 'the app choice is left alone');
|
||||
f.windowRef.dispatch('blur', {});
|
||||
assert.equal(f.camera.suspended, 0);
|
||||
assert.equal(f.previews.at(-1), null);
|
||||
|
||||
@@ -501,14 +501,6 @@ export class ShellFacade {
|
||||
return this._visualSettings.sharpenEnabled;
|
||||
}
|
||||
|
||||
get _bloomStage() {
|
||||
return this._visualEffects.bloomStage;
|
||||
}
|
||||
|
||||
get _sharpenStage() {
|
||||
return this._visualEffects.sharpenStage;
|
||||
}
|
||||
|
||||
/** Settle only the search generation that still owns the shared input UI. */
|
||||
_settleLocationSearchUi(generation, options) {
|
||||
return this._navigation._settleLocationSearchUi(...arguments);
|
||||
|
||||
+69
-140
@@ -1,4 +1,3 @@
|
||||
import { PostProcessStage } from 'cesium';
|
||||
import {
|
||||
bloomStrengthFromIntensity,
|
||||
clampBloomIntensity,
|
||||
@@ -6,17 +5,16 @@ import {
|
||||
} from '../bloom.js';
|
||||
import {
|
||||
STYLES,
|
||||
SHARPEN_SHADER,
|
||||
TRANSITION_DURATION_MS,
|
||||
sharpenAmount,
|
||||
} from './visualPresets.js';
|
||||
|
||||
/**
|
||||
* A style stage drawn by the globe engine (render.setStyle) instead of a
|
||||
* Cesium post stage: the same { uniforms, enabled } shape, so the owner of
|
||||
* the stages writes its uniforms as it writes a Cesium stage's; each write
|
||||
* reaches the engine. A value the engine refuses (NaN from an old link,
|
||||
* say) stays here and is reported, as a Cesium uniform would just draw it.
|
||||
* A style stage drawn by the globe engine (render.setStyle), in a Cesium
|
||||
* post stage's { uniforms, enabled } shape, so the owner of the stages
|
||||
* writes its uniforms as it wrote a stage's; each write reaches the engine.
|
||||
* A value the engine refuses (NaN from an old link, say) stays here and is
|
||||
* reported.
|
||||
*/
|
||||
function engineStyleStage(render, name, shader) {
|
||||
const values = { intensity: 0 };
|
||||
@@ -47,17 +45,21 @@ function engineStyleStage(render, name, shader) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Own the post-process stages and their animation, without DOM dependencies. */
|
||||
/**
|
||||
* Own the visual styles, bloom and sharpening and their animation, without
|
||||
* DOM dependencies, on the globe engine that draws them (render.setStyle,
|
||||
* render.setBloom, render.setSharpen: Cesium through its post stages,
|
||||
* Navara in its pipeline).
|
||||
*/
|
||||
export class VisualEffects {
|
||||
/**
|
||||
* @param {object} options - Viewer, render ownership callbacks and optional clocks.
|
||||
* Without a viewer, `engine` (the globe engine) draws the sharpening
|
||||
* through render.setSharpen, and the styles and bloom through
|
||||
* render.setStyle and render.setBloom when it has them. Construction is inert; initStyles and
|
||||
* @param {object} options - The globe engine, render ownership callbacks
|
||||
* and optional clocks. The styles and bloom reach the engine when it has
|
||||
* them (the visualStyles and bloom capabilities); without an engine the
|
||||
* controls change nothing. Construction is inert; initStyles and
|
||||
* initPostProcess retain startup ordering.
|
||||
*/
|
||||
constructor({
|
||||
viewer,
|
||||
engine = null,
|
||||
requestRender,
|
||||
holdRender,
|
||||
@@ -66,29 +68,20 @@ export class VisualEffects {
|
||||
cancelFrame = (id) => cancelAnimationFrame(id),
|
||||
now = () => performance.now(),
|
||||
wallNow = () => Date.now(),
|
||||
createStage = (options) => new PostProcessStage(options),
|
||||
}) {
|
||||
this.viewer = viewer;
|
||||
// Cesium sharpens with its own post stage below, and the engine's
|
||||
// render.sharpen() mirrors that stage (the Cesium engine keeps the state
|
||||
// only); an engine without a viewer (Navara) sharpens in its pipeline.
|
||||
this.engineRender =
|
||||
typeof engine?.render?.setSharpen === 'function' ? engine.render : null;
|
||||
// Without a viewer, an engine that draws the styles itself
|
||||
// (render.setStyle) gets them through stand-in stages (initStyles).
|
||||
// (The visualStyles and bloom capabilities of src/globe/contract.js
|
||||
// engineCapabilities, read by member: this package stays engine-free.)
|
||||
this.engine = engine;
|
||||
const render = engine?.render;
|
||||
this.engineRender =
|
||||
typeof render?.setSharpen === 'function' ? render : null;
|
||||
// The visualStyles and bloom capabilities of src/globe/contract.js
|
||||
// engineCapabilities, read by member: this package stays engine-free.
|
||||
this.engineStyles =
|
||||
!viewer &&
|
||||
Array.isArray(render?.visualStyles) &&
|
||||
typeof render.setStyle === 'function' &&
|
||||
typeof render.style === 'function'
|
||||
? render
|
||||
: null;
|
||||
// Likewise the bloom (render.setBloom) for Cesium's bloom stage.
|
||||
this.engineBloom =
|
||||
!viewer &&
|
||||
typeof render?.setBloom === 'function' &&
|
||||
typeof render.bloom === 'function'
|
||||
? render
|
||||
@@ -100,7 +93,6 @@ export class VisualEffects {
|
||||
this.cancelFrame = cancelFrame;
|
||||
this.now = now;
|
||||
this.wallNow = wallNow;
|
||||
this.createStage = createStage;
|
||||
this.stages = {};
|
||||
this.transitions = new Map();
|
||||
this.startTime = wallNow();
|
||||
@@ -108,106 +100,46 @@ export class VisualEffects {
|
||||
this.sharpenEnabled = false;
|
||||
this.bloomIntensity = BLOOM_INTENSITY_DEFAULT;
|
||||
this.sharpenIntensity = 0.49;
|
||||
this.bloomStage = null;
|
||||
this.sharpenStage = null;
|
||||
this.postProcessReady = false;
|
||||
// What the engine was last told about the sharpening: it starts off.
|
||||
this.sharpenShown = false;
|
||||
this.frameId = null;
|
||||
this.stopped = false;
|
||||
this.destroyed = false;
|
||||
this.stageEntries = [];
|
||||
this.previousBloom = null;
|
||||
}
|
||||
|
||||
// Post-process stages are Cesium's. Without a viewer (the Navara engine)
|
||||
// an engine that draws the styles gets stand-in stages (engineStyleStage),
|
||||
// which start every style at 0 on it; otherwise there are none and the
|
||||
// style controls change nothing (the engine sharpens, see engineRender).
|
||||
// The styles the engine draws get stand-in stages (engineStyleStage),
|
||||
// which start every style at 0 on it; an engine without them gets none
|
||||
// and the style controls change nothing.
|
||||
initStyles() {
|
||||
if (this.stopped || this.stageEntries.length) return;
|
||||
if (!this.viewer) {
|
||||
if (!this.engineStyles) return;
|
||||
const drawn = this.engineStyles.visualStyles;
|
||||
for (const [name, shader] of Object.entries(STYLES))
|
||||
if (drawn.includes(name))
|
||||
this.stages[name] = engineStyleStage(this.engineStyles, name, shader);
|
||||
this.stageEntries = Object.entries(this.stages);
|
||||
return;
|
||||
}
|
||||
for (const [name, shader] of Object.entries(STYLES)) {
|
||||
const uniforms = { intensity: 0.0 };
|
||||
if (shader.fragmentShader.includes('uniform float time'))
|
||||
uniforms.time = 0.0;
|
||||
for (const [name, meta] of Object.entries(shader.uniforms || {}))
|
||||
uniforms[name] = meta.default;
|
||||
const stage = this.createStage({
|
||||
name: `godsEyeView_${name}`,
|
||||
fragmentShader: shader.fragmentShader,
|
||||
uniforms,
|
||||
});
|
||||
stage.enabled = false;
|
||||
this.viewer.scene.postProcessStages.add(stage);
|
||||
this.stages[name] = stage;
|
||||
}
|
||||
if (this.stopped || this.stageEntries.length || !this.engineStyles) return;
|
||||
const drawn = this.engineStyles.visualStyles;
|
||||
for (const [name, shader] of Object.entries(STYLES))
|
||||
if (drawn.includes(name))
|
||||
this.stages[name] = engineStyleStage(this.engineStyles, name, shader);
|
||||
this.stageEntries = Object.entries(this.stages);
|
||||
}
|
||||
|
||||
initPostProcess(sharpenIntensity = this.sharpenIntensity) {
|
||||
if (this.stopped || this.sharpenStage) return;
|
||||
// An engine that blooms starts from this owner's bloom (off), whatever
|
||||
// a previous owner left on it.
|
||||
if (!this.viewer) {
|
||||
this.engineBloom?.setBloom({
|
||||
enabled: false,
|
||||
strength: bloomStrengthFromIntensity(this.bloomIntensity),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.bloomStage = this.viewer.scene.postProcessStages.bloom;
|
||||
const names = [
|
||||
'glowOnly',
|
||||
'contrast',
|
||||
'brightness',
|
||||
'delta',
|
||||
'sigma',
|
||||
'stepSize',
|
||||
];
|
||||
this.previousBloom = {
|
||||
enabled: this.bloomStage.enabled,
|
||||
uniforms: Object.fromEntries(
|
||||
names.map((name) => [name, this.bloomStage.uniforms[name]]),
|
||||
),
|
||||
};
|
||||
this.bloomStage.enabled = false;
|
||||
Object.assign(this.bloomStage.uniforms, {
|
||||
glowOnly: false,
|
||||
contrast: 256.0,
|
||||
brightness: -0.35,
|
||||
delta: 0.25,
|
||||
sigma: 0.35,
|
||||
stepSize: 1.0,
|
||||
if (this.stopped || this.postProcessReady) return;
|
||||
this.postProcessReady = true;
|
||||
// The engine starts from this owner's bloom and sharpening (off),
|
||||
// whatever a previous owner left on it.
|
||||
this.engineBloom?.setBloom({
|
||||
enabled: false,
|
||||
strength: bloomStrengthFromIntensity(this.bloomIntensity),
|
||||
});
|
||||
this.sharpenStage = this.createStage({
|
||||
name: 'godsEyeView_sharpen',
|
||||
fragmentShader: SHARPEN_SHADER,
|
||||
uniforms: { amount: 1.3 },
|
||||
});
|
||||
this.sharpenStage.enabled = false;
|
||||
this.viewer.scene.postProcessStages.add(this.sharpenStage);
|
||||
this.sharpenShown = false;
|
||||
this.engineRender?.setSharpen({ enabled: false });
|
||||
this.applySharpenIntensity(sharpenIntensity);
|
||||
}
|
||||
|
||||
setStageIntensity(stage, value) {
|
||||
if (this.stopped || !stage) return;
|
||||
// The engine fades its stars with Anime (render.setStyle).
|
||||
stage.uniforms.intensity = value;
|
||||
stage.enabled = value > 0.001;
|
||||
// Anime's bands turn the faint Milky Way into blotches, and depth cannot
|
||||
// tell the sky from far geometry, so the glow fades with the style.
|
||||
// The engine fades its own stars with Anime (render.setStyle).
|
||||
if (
|
||||
stage === this.stages.anime &&
|
||||
this.viewer?.scene.skyBox?.milkyWayVisibility !== undefined
|
||||
)
|
||||
this.viewer.scene.skyBox.milkyWayVisibility = 1 - value;
|
||||
if (stage.enabled && stage.uniforms.time !== undefined)
|
||||
this.startAnimationLoop();
|
||||
this.requestRender('style-stage');
|
||||
@@ -218,12 +150,13 @@ export class VisualEffects {
|
||||
this.setStageIntensity(stage, stage.uniforms.intensity);
|
||||
}
|
||||
|
||||
// The engine eases the strength above its 0.06 dead zone (Cesium's bloom
|
||||
// stage); under it, nothing glows with the toggle on.
|
||||
syncBloomEnabled() {
|
||||
if (this.stopped) return;
|
||||
const enabled =
|
||||
this.bloomEnabled &&
|
||||
bloomStrengthFromIntensity(this.bloomIntensity) > 0.06;
|
||||
if (this.bloomStage) this.bloomStage.enabled = enabled;
|
||||
this.engineBloom?.setBloom({ enabled });
|
||||
}
|
||||
|
||||
@@ -231,21 +164,10 @@ export class VisualEffects {
|
||||
if (this.stopped) return;
|
||||
this.bloomIntensity = clampBloomIntensity(intensity);
|
||||
this.requestRender('bloom');
|
||||
if (this.engineBloom) {
|
||||
this.engineBloom.setBloom({
|
||||
strength: bloomStrengthFromIntensity(this.bloomIntensity),
|
||||
});
|
||||
this.syncBloomEnabled();
|
||||
}
|
||||
if (!this.bloomStage) return;
|
||||
const rawStrength = bloomStrengthFromIntensity(this.bloomIntensity);
|
||||
const strength = rawStrength <= 0.06 ? 0.0 : (rawStrength - 0.06) / 0.94;
|
||||
const eased = strength * strength * (3.0 - 2.0 * strength);
|
||||
this.bloomStage.uniforms.contrast = 255.0 - eased * 168.0;
|
||||
this.bloomStage.uniforms.brightness = -0.5 + eased * 0.36;
|
||||
this.bloomStage.uniforms.sigma = 0.28 + eased * 6.3;
|
||||
this.bloomStage.uniforms.delta = 0.2 + eased * 2.25;
|
||||
this.bloomStage.uniforms.stepSize = 1.0 + eased * 1.25;
|
||||
if (!this.engineBloom) return;
|
||||
this.engineBloom.setBloom({
|
||||
strength: bloomStrengthFromIntensity(this.bloomIntensity),
|
||||
});
|
||||
this.syncBloomEnabled();
|
||||
}
|
||||
|
||||
@@ -262,18 +184,18 @@ export class VisualEffects {
|
||||
* on the Arc, 2026-10-24), and `0.1 + value * 2` still sharpened at 0.
|
||||
*/
|
||||
syncSharpenEnabled() {
|
||||
if (this.stopped || !this.sharpenStage) return;
|
||||
this.sharpenStage.enabled =
|
||||
this.sharpenEnabled && this.sharpenIntensity > 0.001;
|
||||
if (this.stopped) return;
|
||||
const enabled = this.sharpenEnabled && this.sharpenIntensity > 0.001;
|
||||
if (enabled === this.sharpenShown) return;
|
||||
this.sharpenShown = enabled;
|
||||
this.engineRender?.setSharpen({ enabled });
|
||||
}
|
||||
|
||||
applySharpenIntensity(value) {
|
||||
if (this.stopped) return;
|
||||
this.sharpenIntensity = value;
|
||||
if (this.sharpenStage)
|
||||
this.sharpenStage.uniforms.amount = sharpenAmount(value);
|
||||
this.syncSharpenEnabled();
|
||||
this.engineRender?.setSharpen({ amount: sharpenAmount(value) });
|
||||
this.syncSharpenEnabled();
|
||||
this.requestRender('sharpen');
|
||||
}
|
||||
|
||||
@@ -281,7 +203,6 @@ export class VisualEffects {
|
||||
if (this.stopped) return;
|
||||
this.sharpenEnabled = !!enabled;
|
||||
this.syncSharpenEnabled();
|
||||
this.engineRender?.setSharpen({ enabled: this.sharpenEnabled });
|
||||
this.requestRender('sharpen');
|
||||
}
|
||||
|
||||
@@ -337,18 +258,26 @@ export class VisualEffects {
|
||||
this.transitions.clear();
|
||||
}
|
||||
|
||||
/** Remove owned stages and restore the borrowed bloom stage after callers release it. */
|
||||
/**
|
||||
* Turn every style, the bloom and the sharpening off on the engine after
|
||||
* callers release them, as removing Cesium's stages did: the engine keeps
|
||||
* the frame of a later owner, which starts them again (initStyles,
|
||||
* initPostProcess).
|
||||
*/
|
||||
destroy() {
|
||||
if (this.destroyed) return;
|
||||
this.stop();
|
||||
this.destroyed = true;
|
||||
if (!this.viewer) return;
|
||||
const stages = this.viewer.scene.postProcessStages;
|
||||
for (const [, stage] of this.stageEntries) stages.remove(stage);
|
||||
if (this.sharpenStage) stages.remove(this.sharpenStage);
|
||||
if (this.bloomStage && this.previousBloom) {
|
||||
Object.assign(this.bloomStage.uniforms, this.previousBloom.uniforms);
|
||||
this.bloomStage.enabled = this.previousBloom.enabled;
|
||||
}
|
||||
if (!this.engine || this.engine.isDestroyed?.()) return;
|
||||
for (const [name, stage] of this.stageEntries)
|
||||
if (stage.uniforms.intensity !== 0) {
|
||||
try {
|
||||
this.engineStyles.setStyle(name, { intensity: 0 });
|
||||
} catch {
|
||||
// The engine went with its scene.
|
||||
}
|
||||
}
|
||||
if (this.postProcessReady) this.engineBloom?.setBloom({ enabled: false });
|
||||
if (this.sharpenShown) this.engineRender?.setSharpen({ enabled: false });
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@ import test from 'node:test';
|
||||
import { VisualEffects } from './visualEffects.js';
|
||||
import { STYLES } from './visualPresets.js';
|
||||
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
|
||||
import { MILKY_WAY_INTENSITY, StarrySky } from '../sky/starrySky.js';
|
||||
import { createCesiumRender } from '../globe/cesium/render.js';
|
||||
import { MILKY_WAY_INTENSITY, StarrySky } from '../globe/cesium/starrySky.js';
|
||||
import {
|
||||
GLOBAL_POST_DEFAULTS,
|
||||
STYLE_PRESET_DEFAULTS,
|
||||
@@ -14,7 +15,9 @@ import {
|
||||
sharpenAmount,
|
||||
} from './visualPresets.js';
|
||||
|
||||
function fixture(engine = null) {
|
||||
// VisualEffects on the Cesium engine's render (src/globe/cesium/render.js)
|
||||
// over a scene whose post stages and bloom stage the test reads.
|
||||
function fixture() {
|
||||
let time = 0;
|
||||
let next = 0;
|
||||
const frames = new Map();
|
||||
@@ -42,11 +45,21 @@ function fixture(engine = null) {
|
||||
return stages.delete(stage);
|
||||
},
|
||||
};
|
||||
const scene = {
|
||||
postProcessStages: pipeline,
|
||||
skyBox: { milkyWayVisibility: 1 },
|
||||
requestRender() {},
|
||||
};
|
||||
const cesium = createCesiumRender(
|
||||
{ scene },
|
||||
{
|
||||
requestRender: (reason) => requests.push(reason),
|
||||
createStage: (options) => ({ ...options, enabled: true }),
|
||||
},
|
||||
);
|
||||
const engine = { render: cesium.render, isDestroyed: () => false };
|
||||
const effects = new VisualEffects({
|
||||
engine,
|
||||
viewer: {
|
||||
scene: { postProcessStages: pipeline, skyBox: { milkyWayVisibility: 1 } },
|
||||
},
|
||||
requestRender: (reason) => requests.push(reason),
|
||||
holdRender: (reason) => holds.add(reason),
|
||||
releaseRender: (reason) => holds.delete(reason),
|
||||
@@ -58,7 +71,6 @@ function fixture(engine = null) {
|
||||
cancelFrame: (id) => frames.delete(id),
|
||||
now: () => time,
|
||||
wallNow: () => 10_000 + time,
|
||||
createStage: (options) => ({ ...options, enabled: true }),
|
||||
});
|
||||
function tick(value) {
|
||||
time = value;
|
||||
@@ -66,15 +78,22 @@ function fixture(engine = null) {
|
||||
frames.clear();
|
||||
for (const callback of pending) callback();
|
||||
}
|
||||
/** The scene's post stage by its style name, or 'sharpen'. */
|
||||
const stage = (name) =>
|
||||
[...stages].find((entry) => entry.name === `godsEyeView_${name}`);
|
||||
return {
|
||||
effects,
|
||||
engine,
|
||||
scene,
|
||||
frames,
|
||||
stages,
|
||||
stage,
|
||||
holds,
|
||||
requests,
|
||||
bloom,
|
||||
originalBloom,
|
||||
tick,
|
||||
destroyEngine: () => cesium.destroy(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,11 +104,17 @@ test('construction is inert and initialization creates one owned pipeline', () =
|
||||
f.effects.initStyles();
|
||||
f.effects.initPostProcess();
|
||||
assert.equal(f.stages.size, 6);
|
||||
assert.deepEqual(
|
||||
[...f.stages].map(({ name }) => name),
|
||||
[...Object.keys(STYLES), 'sharpen'].map((name) => `godsEyeView_${name}`),
|
||||
'the styles in their order, then the sharpening',
|
||||
);
|
||||
assert.ok(
|
||||
Object.values(f.effects.stages).every(
|
||||
(stage) => !stage.enabled && stage.uniforms.intensity === 0,
|
||||
),
|
||||
);
|
||||
assert.ok([...f.stages].every((stage) => !stage.enabled));
|
||||
f.effects.initStyles();
|
||||
f.effects.initPostProcess();
|
||||
assert.equal(f.stages.size, 6);
|
||||
@@ -113,6 +138,8 @@ test('crossfade uses the established 500ms easing and settles without idle frame
|
||||
assert.equal(f.effects.stages.noir.uniforms.intensity, 0.5);
|
||||
f.tick(500);
|
||||
assert.equal(f.effects.stages.noir.uniforms.intensity, 1);
|
||||
assert.equal(f.stage('noir').uniforms.intensity, 1);
|
||||
assert.equal(f.stage('noir').enabled, true);
|
||||
assert.equal(f.effects.transitions.size, 0);
|
||||
// Noir's shader has no animated time uniform.
|
||||
assert.equal(f.frames.size, 0);
|
||||
@@ -147,6 +174,7 @@ test('only visible animated stages keep the animation clock and render hold aliv
|
||||
f.effects.setStageIntensity(animated, 1);
|
||||
f.tick(1000);
|
||||
assert.equal(animated.uniforms.time, 1);
|
||||
assert.equal(f.stage('retro').uniforms.time, 1);
|
||||
assert.equal(f.frames.size, 1);
|
||||
assert.equal(f.holds.size, 1);
|
||||
f.effects.setStageIntensity(animated, 0);
|
||||
@@ -172,7 +200,7 @@ test('the anime stage fades the Milky Way out with its own intensity', () => {
|
||||
const f = fixture();
|
||||
const sky = new StarrySky({ requestRender: () => {} });
|
||||
const glow = () => sky._milkyWayUniforms.u_intensity();
|
||||
f.effects.viewer.scene.skyBox = sky;
|
||||
f.scene.skyBox = sky;
|
||||
f.effects.initStyles();
|
||||
f.effects.setStageIntensity(f.effects.stages.thermal, 1);
|
||||
assert.equal(glow(), MILKY_WAY_INTENSITY, 'other styles keep the glow');
|
||||
@@ -189,7 +217,7 @@ test('the anime stage fades the Milky Way out with its own intensity', () => {
|
||||
for (const skyBox of [undefined, null, {}]) {
|
||||
test(`anime works without StarrySky (${JSON.stringify(skyBox)})`, () => {
|
||||
const f = fixture();
|
||||
f.effects.viewer.scene.skyBox = skyBox;
|
||||
f.scene.skyBox = skyBox;
|
||||
f.effects.initStyles();
|
||||
f.effects.setStageIntensity(f.effects.stages.anime, 1);
|
||||
assert.equal(f.effects.stages.anime.enabled, true);
|
||||
@@ -203,6 +231,8 @@ for (const skyBox of [undefined, null, {}]) {
|
||||
test('bloom retains its dead zone, normalized intensity and independent toggle', () => {
|
||||
const f = fixture();
|
||||
f.effects.initPostProcess();
|
||||
assert.equal(f.bloom.enabled, false, 'a new owner starts with no bloom');
|
||||
assert.equal(f.bloom.uniforms.glowOnly, false);
|
||||
f.effects.setBloomEnabled(true);
|
||||
f.effects.applyBloomIntensity(0);
|
||||
assert.equal(f.bloom.enabled, false);
|
||||
@@ -220,14 +250,15 @@ test('bloom retains its dead zone, normalized intensity and independent toggle',
|
||||
test('sharpen uses the existing uniform scale and keeps values while disabled', () => {
|
||||
const f = fixture();
|
||||
f.effects.initPostProcess(0.49);
|
||||
assert.equal(f.effects.sharpenStage.uniforms.amount, 1.08);
|
||||
assert.equal(f.stage('sharpen').uniforms.amount, 1.08);
|
||||
f.effects.applySharpenIntensity(1);
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.uniforms.amount, 2.1);
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.equal(f.stage('sharpen').uniforms.amount, 2.1);
|
||||
assert.equal(f.stage('sharpen').enabled, true);
|
||||
assert.deepEqual(f.engine.render.sharpen(), { enabled: true, amount: 2.1 });
|
||||
f.effects.setSharpenEnabled(false);
|
||||
assert.equal(f.effects.sharpenIntensity, 1);
|
||||
assert.equal(f.effects.sharpenStage.enabled, false);
|
||||
assert.equal(f.stage('sharpen').enabled, false);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
@@ -235,21 +266,17 @@ test('sharpen at 0 runs no pass, and comes back with the slider', () => {
|
||||
const f = fixture();
|
||||
f.effects.initPostProcess(0.49);
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.equal(f.stage('sharpen').enabled, true);
|
||||
f.effects.applySharpenIntensity(0);
|
||||
assert.equal(
|
||||
f.effects.sharpenStage.enabled,
|
||||
false,
|
||||
'no residual sharpen at 0',
|
||||
);
|
||||
assert.equal(f.stage('sharpen').enabled, false, 'no residual sharpen at 0');
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.enabled, false, 'on at 0 is still off');
|
||||
assert.equal(f.stage('sharpen').enabled, false, 'on at 0 is still off');
|
||||
f.effects.applySharpenIntensity(0.2);
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.equal(f.stage('sharpen').enabled, true);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('stop revokes pending work immediately but retains stages until final destruction', () => {
|
||||
test('stop revokes pending work immediately and destruction turns the effects off', () => {
|
||||
const f = fixture();
|
||||
f.effects.initStyles();
|
||||
f.effects.initPostProcess();
|
||||
@@ -268,28 +295,38 @@ test('stop revokes pending work immediately but retains stages until final destr
|
||||
f.effects.setStageIntensity(f.effects.stages.retro, 1);
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(f.effects.stages.retro.uniforms.intensity, intensity);
|
||||
f.effects.setBloomEnabled(true);
|
||||
f.effects.destroy();
|
||||
assert.ok(
|
||||
[...f.stages].every((stage) => !stage.enabled),
|
||||
'nothing draws after the owner',
|
||||
);
|
||||
assert.equal(f.bloom.enabled, false);
|
||||
f.effects.destroy();
|
||||
// The engine removes its stages and gives the bloom stage back.
|
||||
f.destroyEngine();
|
||||
assert.equal(f.stages.size, 0);
|
||||
assert.deepEqual(
|
||||
f.bloom,
|
||||
f.originalBloom,
|
||||
'borrowed bloom configuration is restored',
|
||||
);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('destroying one instance does not remove another pipeline or clock', () => {
|
||||
test('destroying one instance does not stop another pipeline or clock', () => {
|
||||
const a = fixture();
|
||||
const b = fixture();
|
||||
for (const f of [a, b]) {
|
||||
f.effects.initStyles();
|
||||
f.effects.startTransition('retro', 0, 1);
|
||||
}
|
||||
a.tick(250);
|
||||
a.effects.destroy();
|
||||
b.tick(250);
|
||||
assert.equal(a.stages.size, 0);
|
||||
assert.equal(b.stages.size, 5);
|
||||
assert.equal(a.stage('retro').enabled, false);
|
||||
assert.equal(b.stages.size, 6);
|
||||
assert.equal(b.effects.stages.retro.uniforms.intensity, 0.5);
|
||||
assert.equal(b.stage('retro').enabled, true);
|
||||
b.effects.destroy();
|
||||
});
|
||||
|
||||
@@ -311,14 +348,13 @@ test('existing baseline and military presets keep one detection default', () =>
|
||||
assert.equal(STYLE_PRESET_DEFAULTS.normal, undefined);
|
||||
});
|
||||
|
||||
test('without a viewer the engine sharpens with the same amount scale', () => {
|
||||
test('an engine sharpens with the same amount scale, only while on and above 0', () => {
|
||||
const sharpen = [];
|
||||
const requests = [];
|
||||
const engine = {
|
||||
render: { setSharpen: (options) => sharpen.push(options) },
|
||||
};
|
||||
const effects = new VisualEffects({
|
||||
viewer: null,
|
||||
engine,
|
||||
requestRender: (reason) => requests.push(reason),
|
||||
holdRender() {},
|
||||
@@ -326,18 +362,27 @@ test('without a viewer the engine sharpens with the same amount scale', () => {
|
||||
});
|
||||
effects.initStyles();
|
||||
effects.initPostProcess(0.49);
|
||||
assert.equal(effects.sharpenStage, null);
|
||||
effects.applySharpenIntensity(0.8);
|
||||
effects.setSharpenEnabled(true);
|
||||
effects.applySharpenIntensity(0);
|
||||
effects.applySharpenIntensity(0.3);
|
||||
effects.setSharpenEnabled(false);
|
||||
assert.deepEqual(sharpen, [
|
||||
{ enabled: false },
|
||||
{ amount: sharpenAmount(0.49) },
|
||||
{ amount: 1.7000000000000002 },
|
||||
{ enabled: true },
|
||||
{ amount: sharpenAmount(0) },
|
||||
{ enabled: false },
|
||||
{ amount: sharpenAmount(0.3) },
|
||||
{ enabled: true },
|
||||
{ enabled: false },
|
||||
]);
|
||||
assert.equal(sharpen[0].amount, sharpenAmount(0.8));
|
||||
assert.deepEqual(requests, ['sharpen', 'sharpen', 'sharpen']);
|
||||
assert.equal(sharpen[2].amount, sharpenAmount(0.8));
|
||||
assert.ok(requests.every((reason) => reason === 'sharpen'));
|
||||
effects.setSharpenEnabled(true);
|
||||
effects.destroy();
|
||||
assert.deepEqual(sharpen.at(-1), { enabled: false });
|
||||
});
|
||||
|
||||
// A fake engine drawing the app's styles (render.setStyle), as Navara does.
|
||||
@@ -365,7 +410,6 @@ function engineFixture(engine = styledEngine()) {
|
||||
const holds = new Set();
|
||||
const requests = [];
|
||||
const effects = new VisualEffects({
|
||||
viewer: null,
|
||||
engine,
|
||||
requestRender: (reason) => requests.push(reason),
|
||||
holdRender: (reason) => holds.add(reason),
|
||||
@@ -388,7 +432,7 @@ function engineFixture(engine = styledEngine()) {
|
||||
return { engine, effects, holds, requests, tick };
|
||||
}
|
||||
|
||||
test('without a viewer an engine that draws styles gets stand-in stages', () => {
|
||||
test('an engine that draws styles gets stand-in stages', () => {
|
||||
const { engine, effects } = engineFixture();
|
||||
effects.initStyles();
|
||||
assert.deepEqual(Object.keys(effects.stages), Object.keys(STYLES));
|
||||
@@ -405,7 +449,7 @@ test('without a viewer an engine that draws styles gets stand-in stages', () =>
|
||||
palette: 0,
|
||||
time: 0,
|
||||
});
|
||||
// A uniform write reaches the engine, as a Cesium stage uniform would.
|
||||
// A uniform write reaches the engine.
|
||||
effects.stages.thermal.uniforms.palette = 1;
|
||||
assert.equal(engine.render.style('thermal').uniforms.palette, 1);
|
||||
assert.equal(effects.stages.thermal.uniforms.palette, 1);
|
||||
@@ -451,15 +495,16 @@ test('an engine crossfade eases both styles and animates time on the engine', ()
|
||||
effects.destroy();
|
||||
});
|
||||
|
||||
test('Anime on an engine without a viewer reaches no sky box', () => {
|
||||
test('Anime reaches the engine, which fades its own sky', () => {
|
||||
const { engine, effects } = engineFixture();
|
||||
effects.initStyles();
|
||||
effects.setStageIntensity(effects.stages.anime, 0.7);
|
||||
assert.equal(engine.render.style('anime').intensity, 0.7);
|
||||
effects.destroy();
|
||||
assert.equal(engine.render.style('anime').intensity, 0, 'off after it');
|
||||
});
|
||||
|
||||
test('without a viewer an engine that blooms gets the slider strength and dead zone', () => {
|
||||
test('an engine that blooms gets the slider strength and dead zone', () => {
|
||||
const { engine, effects, requests } = engineFixture(
|
||||
createFakeEngine({ kind: 'navara', bloom: true }),
|
||||
);
|
||||
@@ -482,7 +527,6 @@ test('without a viewer an engine that blooms gets the slider strength and dead z
|
||||
effects.setBloomEnabled(false);
|
||||
assert.equal(engine.render.bloom().enabled, false);
|
||||
assert.ok(requests.includes('bloom'));
|
||||
assert.equal(effects.bloomStage, null);
|
||||
effects.destroy();
|
||||
});
|
||||
|
||||
@@ -493,35 +537,6 @@ test('without the visualStyles capability an engine gets no stages', () => {
|
||||
effects.destroy();
|
||||
});
|
||||
|
||||
test('with a viewer the Cesium stage sharpens and the engine mirrors its state', () => {
|
||||
let state = { enabled: false, amount: 1 };
|
||||
const engine = {
|
||||
render: {
|
||||
setSharpen: (options) => {
|
||||
state = { ...state, ...options };
|
||||
},
|
||||
sharpen: () => ({ ...state }),
|
||||
},
|
||||
};
|
||||
const f = fixture(engine);
|
||||
f.effects.initPostProcess(0.49);
|
||||
assert.deepEqual(engine.render.sharpen(), {
|
||||
enabled: false,
|
||||
amount: f.effects.sharpenStage.uniforms.amount,
|
||||
});
|
||||
f.effects.applySharpenIntensity(0.8);
|
||||
f.effects.setSharpenEnabled(true);
|
||||
assert.equal(f.effects.sharpenStage.uniforms.amount, sharpenAmount(0.8));
|
||||
assert.equal(f.effects.sharpenStage.enabled, true);
|
||||
assert.deepEqual(engine.render.sharpen(), {
|
||||
enabled: true,
|
||||
amount: sharpenAmount(0.8),
|
||||
});
|
||||
f.effects.setSharpenEnabled(false);
|
||||
assert.equal(engine.render.sharpen().enabled, false);
|
||||
f.effects.destroy();
|
||||
});
|
||||
|
||||
test('presets and the baseline take the engine default sharpen: Cesium 49 %, Navara 80 %', () => {
|
||||
assert.deepEqual(SHARPEN_INTENSITY_DEFAULTS, { cesium: 49, navara: 80 });
|
||||
for (const preset of [
|
||||
|
||||
@@ -202,7 +202,6 @@ export class VisualSettings {
|
||||
setStyleParameter: (name, value) => this.setStyleParameter(name, value),
|
||||
});
|
||||
this._visualEffects = new VisualEffects({
|
||||
viewer,
|
||||
engine,
|
||||
requestRender: services.governorRequestRender,
|
||||
holdRender: services.holdContinuousRender,
|
||||
|
||||
Reference in new issue
Block a user