mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-21 18:52:18 +00:00
Fix the review findings across the engines, layers, data and QA
Navara now matches Cesium where the review found it diverging: a flight holds the camera inputs, camera.changed counts turns as Cesium does, render requests made during a frame survive it, follow pinches zoom, ground widths follow the pixel ratio and Cyber sonar reaches glyph caches and models. On Cesium, a staged imagery swap keeps loading tiles, setView replaces a running flight, and a cleared weather detail goes away. The contract gains MoverSet.failed, maps.terrainRevision, render.maxTextureSize and surface.sampleTerrainMostDetailed on every engine, so layers retry failed models, key road heights by terrain, size weather textures to the GPU and place Bhote Koshi cards on detailed terrain. Engine switches keep the live view, follows, focus, layer options and cards: a pick hands over the exact pose, applies no address options and pans no carried-over card; a history visit still applies its entry. Layers put GhostMaps pins, cable landings, OSM Places and directions on the measured surface without per-frame sampling, draw the Cockpit contact dot, hide disabled CCTV on attach, and keep ALPR running outside secure contexts. KML imports draw raised polygon fills, rotated and coloured ground overlays and north-referenced icon headings, and report files with nothing to draw. QA scripts read the contract instead of Cesium internals (test:track is 109/109 again), wait for the camera to rest before clicking, and give cold switches and parked engines realistic time. Docs follow the code.
This commit is contained in:
1 parent
69fbf5b38d
commit
0ef29781e5
276 files changed
+7217
-1517
No files matched your search
@@ -0,0 +1,141 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { isEngineEvent } from '../contract.js';
|
||||
import { orientationVectors } from '../cameraMath.js';
|
||||
import { createCameraModel } from './cameraModel.js';
|
||||
|
||||
const { cartesian2, cartesian3, math, matrix4 } = geo;
|
||||
const near = (actual, expected, tolerance, label) =>
|
||||
assert.ok(
|
||||
Math.abs(actual - expected) <= tolerance,
|
||||
`${label}: ${actual} is not within ${tolerance} of ${expected}`,
|
||||
);
|
||||
|
||||
// A stand-in for Navara's camera: setCamera lands on the next update with
|
||||
// Navara's ±89.99° pitch clamp; flights resolve when the test says so.
|
||||
function createFakePort() {
|
||||
const port = {
|
||||
applied: [],
|
||||
flights: [],
|
||||
stops: 0,
|
||||
frames: 0,
|
||||
drawn: null,
|
||||
width: 1280,
|
||||
height: 800,
|
||||
apply(pose) {
|
||||
port.applied.push(pose);
|
||||
},
|
||||
read: () => port.drawn,
|
||||
fly(pose, options) {
|
||||
let settle;
|
||||
const promise = new Promise((resolve) => (settle = resolve));
|
||||
port.flights.push({ pose, options, settle });
|
||||
return promise;
|
||||
},
|
||||
stop() {
|
||||
port.stops++;
|
||||
},
|
||||
size: () => ({ width: port.width, height: port.height }),
|
||||
requestFrame() {
|
||||
port.frames++;
|
||||
},
|
||||
/** Navara's update: draw a newly applied pose (pitch clamped). */
|
||||
drawnCount: 0,
|
||||
update() {
|
||||
if (port.applied.length === port.drawnCount) return;
|
||||
port.drawnCount = port.applied.length;
|
||||
const pose = port.applied.at(-1);
|
||||
const pitch = Math.max(-89.99, Math.min(89.99, pose.pitch));
|
||||
const position = cartesian3.fromDegrees(pose.lng, pose.lat, pose.height);
|
||||
port.drawn = {
|
||||
position,
|
||||
...orientationVectors(
|
||||
cartesian3.fromDegrees(pose.lng, pose.lat, 0),
|
||||
math.toRadians(pose.heading),
|
||||
math.toRadians(pitch),
|
||||
math.toRadians(pose.roll),
|
||||
),
|
||||
};
|
||||
},
|
||||
};
|
||||
return port;
|
||||
}
|
||||
|
||||
function createClock() {
|
||||
const clock = {
|
||||
time: 0,
|
||||
timers: [],
|
||||
now: () => clock.time,
|
||||
setTimeout(fn, ms) {
|
||||
const timer = { fn, at: clock.time + ms };
|
||||
clock.timers.push(timer);
|
||||
return timer;
|
||||
},
|
||||
clearTimeout(timer) {
|
||||
clock.timers = clock.timers.filter((entry) => entry !== timer);
|
||||
},
|
||||
advance(ms) {
|
||||
clock.time += ms;
|
||||
for (const timer of [...clock.timers])
|
||||
if (timer.at <= clock.time) {
|
||||
clock.clearTimeout(timer);
|
||||
timer.fn();
|
||||
}
|
||||
},
|
||||
};
|
||||
return clock;
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const port = createFakePort();
|
||||
const clock = createClock();
|
||||
const model = createCameraModel({ port, clock });
|
||||
// One Navara frame: update, preRender sync, postRender events.
|
||||
const frame = (ms = 16) => {
|
||||
clock.advance(ms);
|
||||
port.update();
|
||||
model.sync();
|
||||
model.afterFrame();
|
||||
};
|
||||
return { port, clock, model, camera: model.camera, frame };
|
||||
}
|
||||
|
||||
// Cesium's Camera._updateCameraChanged: direction angle / (fovy / 2), and
|
||||
// heading or roll change / π, each against percentageChanged (0.5).
|
||||
test('turning in place raises changed as Cesium does', () => {
|
||||
const { camera, frame } = setup();
|
||||
const destination = cartesian3.fromDegrees(10, 45, 5000);
|
||||
camera.setView({
|
||||
destination,
|
||||
orientation: { heading: 0, pitch: -math.PI_OVER_TWO, roll: 0 },
|
||||
});
|
||||
frame();
|
||||
frame();
|
||||
let changed = 0;
|
||||
camera.changed.addEventListener(() => changed++);
|
||||
// Tilt from straight down to 45° on the spot: 45° > half the fovy.
|
||||
camera.setView({
|
||||
destination,
|
||||
orientation: { heading: 0, pitch: -(Math.PI / 4), roll: 0 },
|
||||
});
|
||||
frame();
|
||||
assert.equal(changed, 1, 'a 45° tilt in place');
|
||||
// Heading +170° looking straight down (north-up reset): direction unchanged.
|
||||
camera.setView({
|
||||
destination,
|
||||
orientation: { heading: 0, pitch: -math.PI_OVER_TWO, roll: 0 },
|
||||
});
|
||||
frame();
|
||||
const before = changed;
|
||||
camera.setView({
|
||||
destination,
|
||||
orientation: {
|
||||
heading: math.toRadians(170),
|
||||
pitch: -math.PI_OVER_TWO,
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
frame();
|
||||
assert.equal(changed, before + 1, 'a 170° heading turn in the nadir');
|
||||
});
|
||||
@@ -12,7 +12,9 @@
|
||||
// wall time (Cesium's cameraEventWaitTime), changed past percentageChanged.
|
||||
//
|
||||
// The port is the engine's thin layer over the Navara view (apply, read, fly,
|
||||
// stop, size, requestFrame); see createNavaraEngine.js.
|
||||
// stop, size, requestFrame, suspendCameraInputs); see createNavaraEngine.js.
|
||||
// A flight suspends the camera inputs until it ends, as Cesium's
|
||||
// CameraFlightPath turns them off: a gesture cannot cut it short.
|
||||
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { createEngineEvent } from '../contract.js';
|
||||
@@ -81,6 +83,7 @@ function posesNear(a, b, distance, angle) {
|
||||
* stop: () => void,
|
||||
* size: () => { width: number, height: number },
|
||||
* requestFrame: () => void,
|
||||
* suspendCameraInputs?: () => () => void,
|
||||
* },
|
||||
* clock?: { now: () => number, setTimeout: Function, clearTimeout: Function },
|
||||
* }} options
|
||||
@@ -124,6 +127,11 @@ export function createCameraModel({
|
||||
let lastSeen = initial ? copyPose(initial) : null;
|
||||
let lastFramePose = copyPose(state);
|
||||
let lastChangedPose = copyPose(state);
|
||||
let changedAngles = headingPitchRoll(
|
||||
state.position,
|
||||
state.direction,
|
||||
state.up,
|
||||
);
|
||||
let moving = false;
|
||||
let lastMoveAt = 0;
|
||||
let moveEndTimer = null;
|
||||
@@ -175,6 +183,7 @@ export function createCameraModel({
|
||||
function endFlight(current, outcome) {
|
||||
if (flight !== current) return;
|
||||
flight = null;
|
||||
current.resume?.();
|
||||
if (outcome === 'cancel') current.options.cancel?.();
|
||||
}
|
||||
|
||||
@@ -197,7 +206,7 @@ export function createCameraModel({
|
||||
options.complete?.();
|
||||
return;
|
||||
}
|
||||
const current = { options };
|
||||
const current = { options, resume: port.suspendCameraInputs?.() };
|
||||
flight = current;
|
||||
// Navara moves the camera from here on; read it back every frame.
|
||||
pushed = null;
|
||||
@@ -212,7 +221,7 @@ export function createCameraModel({
|
||||
(arrived) => {
|
||||
if (flight !== current || destroyed) return;
|
||||
if (!arrived) return endFlight(current, 'cancel');
|
||||
flight = null;
|
||||
endFlight(current, 'complete');
|
||||
land(options, target);
|
||||
options.complete?.();
|
||||
},
|
||||
@@ -261,13 +270,28 @@ export function createCameraModel({
|
||||
}
|
||||
lastFramePose = pose;
|
||||
const turn =
|
||||
angleBetween(pose.direction, lastChangedPose.direction) / Math.PI;
|
||||
angleBetween(pose.direction, lastChangedPose.direction) /
|
||||
(view().fovy / 2);
|
||||
const altitude = Math.max(
|
||||
1,
|
||||
cartographic.fromCartesian(pose.position, WGS84).height,
|
||||
);
|
||||
const shift =
|
||||
cartesian3.distance(pose.position, lastChangedPose.position) / altitude;
|
||||
const angles = headingPitchRoll(pose.position, pose.direction, pose.up);
|
||||
const delta = (a, b) => {
|
||||
const angle = Math.abs(a - b) % (2 * Math.PI);
|
||||
return Math.min(angle, 2 * Math.PI - angle) / Math.PI;
|
||||
};
|
||||
// Heading and roll are raised on their own, as Camera._updateCameraChanged
|
||||
// does: a turn about the line of sight (heading at nadir, roll) moves
|
||||
// neither the direction nor the position.
|
||||
for (const angle of ['heading', 'roll']) {
|
||||
const amount = delta(angles[angle], changedAngles[angle]);
|
||||
if (amount <= percentageChanged) continue;
|
||||
changedAngles[angle] = angles[angle];
|
||||
events.changed.raiseEvent(amount);
|
||||
}
|
||||
const amount = Math.max(turn, shift);
|
||||
if (amount > percentageChanged) {
|
||||
lastChangedPose = pose;
|
||||
@@ -311,6 +335,7 @@ export function createCameraModel({
|
||||
if (!options?.destination)
|
||||
throw new TypeError('setView needs a destination');
|
||||
announce();
|
||||
cancelCurrentFlight();
|
||||
place(viewFor(options.destination, options.orientation));
|
||||
},
|
||||
flyTo(options) {
|
||||
@@ -395,11 +420,6 @@ export function createCameraModel({
|
||||
camera,
|
||||
sync,
|
||||
afterFrame,
|
||||
/**
|
||||
* Ends a running flight (its `cancel` runs) without camera.commanded:
|
||||
* for the user's own gestures, which are not a new camera owner.
|
||||
*/
|
||||
stopFlight: () => cancelCurrentFlight(),
|
||||
/**
|
||||
* Whether nothing else drives the camera: no flight and no lookAt target
|
||||
* (identity transform). The engine's ground floor acts only then.
|
||||
|
||||
@@ -525,3 +525,26 @@ test('pose carries the view aspect ratio', () => {
|
||||
const { width, height } = port.size();
|
||||
assert.equal(camera.pose().aspectRatio, width / height);
|
||||
});
|
||||
|
||||
test('setView cancels a model flight before its promise settles', async () => {
|
||||
const { camera, port } = setup();
|
||||
const outcome = [];
|
||||
camera.flyTo({
|
||||
destination: cartesian3.fromDegrees(0, 0, 50000),
|
||||
duration: 2,
|
||||
cancel: () => outcome.push('cancel'),
|
||||
complete: () => outcome.push('complete'),
|
||||
});
|
||||
const destination = cartesian3.fromDegrees(0, 0, 200000);
|
||||
camera.setView({ destination });
|
||||
assert.equal(camera.flightActive(), false);
|
||||
assert.deepEqual(outcome, ['cancel']);
|
||||
port.flights[0].settle(true);
|
||||
await Promise.resolve();
|
||||
near(
|
||||
cartesian3.distance(camera.pose().position, destination),
|
||||
0,
|
||||
1e-6,
|
||||
'setView stays',
|
||||
);
|
||||
});
|
||||
@@ -34,6 +34,8 @@ import { createNavaraSurface } from './surface.js';
|
||||
import { createGroundFloor } from './groundFloor.js';
|
||||
|
||||
const { cartesian3, math } = geo;
|
||||
// Past the far side of the Earth: a ray from any camera to any tile.
|
||||
const TILE_PICK_FAR_M = 2e7;
|
||||
|
||||
// Navara's drawn camera (view.camera.raw, a three PerspectiveCamera in
|
||||
// Earth-fixed metres): matrixWorld columns are right, up, back, position.
|
||||
@@ -129,6 +131,7 @@ export function createNavaraEngine(
|
||||
stop: () => view.setCamera({}),
|
||||
size,
|
||||
requestFrame: () => view.forceUpdate(),
|
||||
suspendCameraInputs: () => input.input.suspendCameraInputs(),
|
||||
},
|
||||
...(clock ? { clock } : {}),
|
||||
});
|
||||
@@ -162,6 +165,15 @@ export function createNavaraEngine(
|
||||
// Between the view's preRender and postRender: a change made then shows
|
||||
// in the frame being drawn and asks for no other.
|
||||
let drawing = false;
|
||||
// Navara clears its frame request after the frame it draws, so a
|
||||
// render.request made during one (preRender to the end of postRender) is
|
||||
// made again once that frame is done: the next frame follows, as on Cesium.
|
||||
let frameOpen = false;
|
||||
let requestedInFrame = false;
|
||||
const requestRender = () => {
|
||||
view.forceUpdate();
|
||||
if (frameOpen) requestedInFrame = true;
|
||||
};
|
||||
const handlers = {
|
||||
preUpdate: (time) => {
|
||||
// Before the view decides whether it is idle (internals.js).
|
||||
@@ -171,6 +183,13 @@ export function createNavaraEngine(
|
||||
},
|
||||
preRender: (time) => {
|
||||
drawing = true;
|
||||
frameOpen = true;
|
||||
queueMicrotask(() => {
|
||||
frameOpen = false;
|
||||
if (!requestedInFrame || destroyed) return;
|
||||
requestedInFrame = false;
|
||||
view.forceUpdate();
|
||||
});
|
||||
model.sync();
|
||||
// After the user's camera is read, before anything draws.
|
||||
followStep.raiseEvent();
|
||||
@@ -202,11 +221,7 @@ export function createNavaraEngine(
|
||||
lines: () => linesPort?.pickables?.() ?? [],
|
||||
resolveBatch: (batchId) => moversPort?.resolvePick?.(batchId) ?? null,
|
||||
});
|
||||
const input = createNavaraInput(view, {
|
||||
// A gesture is the user, not a new camera owner: no camera.commanded.
|
||||
onCameraInput: () => model.stopFlight(),
|
||||
picker: picking,
|
||||
});
|
||||
const input = createNavaraInput(view, { picker: picking });
|
||||
const credits = createNavaraCredits(view);
|
||||
const maps = createNavaraMaps(view, fetch ? { fetch } : {});
|
||||
const imagery =
|
||||
@@ -216,7 +231,9 @@ export function createNavaraEngine(
|
||||
credits: credits.credits,
|
||||
photorealActive: () => maps.maps.photorealActive(),
|
||||
}) ?? null;
|
||||
const { surface } = createNavaraSurface(view, hooks);
|
||||
const { surface } = createNavaraSurface(view, hooks, (positions) =>
|
||||
maps.sampleTerrain(positions),
|
||||
);
|
||||
// Navara's controller zooms through the ground; keep the camera above it.
|
||||
// With the camera inputs off or suspended nothing zooms, and the app places
|
||||
// the camera itself (the cockpit eye, 12 m up): the floor's 30 m would
|
||||
@@ -233,14 +250,28 @@ export function createNavaraEngine(
|
||||
...(clock ? { now: () => clock.now() } : {}),
|
||||
});
|
||||
|
||||
// Ground items are picked on the CPU at the globe under the pointer
|
||||
// (src/globe/ground.js), under every mover and line.
|
||||
// Ground items are picked on the CPU at the visible surface under the pointer
|
||||
// (src/globe/ground.js), under every mover and line: the 3D tiles while
|
||||
// they show, else the globe. A CPU ray, not the depth read, which answers
|
||||
// with the near plane until a frame after Navara's pick of a click.
|
||||
const tilesUnder = (screen) => {
|
||||
if (!maps.maps.photorealActive()) return undefined;
|
||||
const ray = model.camera.pickRay(screen);
|
||||
return ray
|
||||
? surface.raycast({
|
||||
origin: ray.origin,
|
||||
direction: ray.direction,
|
||||
far: TILE_PICK_FAR_M,
|
||||
})?.position
|
||||
: undefined;
|
||||
};
|
||||
const removeGroundPicks = picking.registerMeshPicker(
|
||||
createGroundPicks({
|
||||
pickGlobe: (screen) => picker.pickGlobe(screen),
|
||||
pickGlobe: (screen) => tilesUnder(screen) ?? picker.pickGlobe(screen),
|
||||
camera: model.camera,
|
||||
size,
|
||||
sets: () => groundPort?.pickables?.() ?? [],
|
||||
surface: () => (maps.maps.photorealActive() ? 'tiles' : 'terrain'),
|
||||
}),
|
||||
);
|
||||
const picker = {
|
||||
@@ -326,6 +357,33 @@ export function createNavaraEngine(
|
||||
},
|
||||
}
|
||||
: {};
|
||||
let maxTextureSize = null;
|
||||
// Movers on screen now: shown, not transparent, their anchor in the view
|
||||
// and over the horizon.
|
||||
const clip = geo.matrix4.create();
|
||||
const at = geo.cartesian3.create();
|
||||
const visibleContacts = () => {
|
||||
model.viewProjection(clip);
|
||||
let shown = 0;
|
||||
for (const { store } of moversPort?.pickables?.() ?? []) {
|
||||
const { positions, shows, colors, count } = store;
|
||||
for (let index = 0; index < count; index++) {
|
||||
if (shows[index] !== 1 || colors[index * 4 + 3] <= 0) continue;
|
||||
at.x = positions[index * 3];
|
||||
at.y = positions[index * 3 + 1];
|
||||
at.z = positions[index * 3 + 2];
|
||||
const w = clip[3] * at.x + clip[7] * at.y + clip[11] * at.z + clip[15];
|
||||
if (w <= 0) continue;
|
||||
const x =
|
||||
(clip[0] * at.x + clip[4] * at.y + clip[8] * at.z + clip[12]) / w;
|
||||
const y =
|
||||
(clip[1] * at.x + clip[5] * at.y + clip[9] * at.z + clip[13]) / w;
|
||||
if (Math.abs(x) > 1 || Math.abs(y) > 1) continue;
|
||||
if (model.horizonVisible(at)) shown++;
|
||||
}
|
||||
}
|
||||
return shown;
|
||||
};
|
||||
let bloom = { ...BLOOM_INITIAL };
|
||||
const bloomRender = bloomPort
|
||||
? {
|
||||
@@ -385,11 +443,19 @@ export function createNavaraEngine(
|
||||
},
|
||||
frames,
|
||||
render: {
|
||||
request: () => view.forceUpdate(),
|
||||
request: requestRender,
|
||||
setContinuous(enabled) {
|
||||
view.animation = Boolean(enabled);
|
||||
},
|
||||
isContinuous: () => view.animation === true,
|
||||
// The canvas's own context (getContext hands back the one the view
|
||||
// made); Navara has no public renderer to ask.
|
||||
maxTextureSize: () =>
|
||||
(maxTextureSize ??= (() => {
|
||||
const gl =
|
||||
canvas.getContext?.('webgl2') ?? canvas.getContext?.('webgl');
|
||||
return gl?.getParameter(gl.MAX_TEXTURE_SIZE) ?? 0;
|
||||
})()),
|
||||
setSharpen(options) {
|
||||
const next = mergeSharpen(sharpen, options);
|
||||
const changed =
|
||||
@@ -415,6 +481,13 @@ export function createNavaraEngine(
|
||||
ground: groundPort.ground,
|
||||
meshes: meshes.meshes,
|
||||
imagery: imagery.imagery,
|
||||
// Not in the contract, as Cesium's (src/cyberSonarEngine.js reads it):
|
||||
// the treatment runs in the movers' shaders; `contacts` is how many are
|
||||
// on screen, so an empty view lets the sonar go idle.
|
||||
contactSonarDiagnostics: () => ({
|
||||
supported: true,
|
||||
contacts: visibleContacts(),
|
||||
}),
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
|
||||
@@ -446,7 +446,79 @@ test("Navara's fov follows Cesium's vertical fov, also after a resize", () => {
|
||||
near(engine.camera.pose().fovy, Math.PI / 3, 1e-15, 'pose fovy');
|
||||
});
|
||||
|
||||
test('cancelFlight stops Navara with an empty setCamera; user input cancels a flight', () => {
|
||||
test('contactSonarDiagnostics counts the movers on screen', () => {
|
||||
const view = fakeView();
|
||||
// The camera is 10 000 km over (0°, 0°), looking down.
|
||||
const places = [
|
||||
[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
[180, 0, 1],
|
||||
];
|
||||
const positions = new Float64Array(places.length * 3);
|
||||
const colors = new Float32Array(places.length * 4).fill(1);
|
||||
const shows = new Uint8Array(places.length).fill(1);
|
||||
places.forEach(([lon, lat, show], index) => {
|
||||
const position = cartesian3.fromDegrees(lon, lat, 0);
|
||||
positions.set([position.x, position.y, position.z], index * 3);
|
||||
shows[index] = show;
|
||||
});
|
||||
colors[1 * 4 + 3] = 0;
|
||||
const store = { positions, colors, shows, count: places.length };
|
||||
const engine = createNavaraEngine(view, {
|
||||
...ports,
|
||||
movers: { ...ports.movers, pickables: () => [{ store }] },
|
||||
hooks,
|
||||
});
|
||||
// Shown and opaque, in view: the first; the second is transparent, the
|
||||
// third hidden, the fourth behind the Earth.
|
||||
assert.deepEqual(engine.contactSonarDiagnostics(), {
|
||||
supported: true,
|
||||
contacts: 1,
|
||||
});
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test("maxTextureSize reads the canvas's WebGL limit once", () => {
|
||||
const view = fakeView();
|
||||
const asked = [];
|
||||
view.canvas.getContext = (type) => {
|
||||
asked.push(type);
|
||||
return type === 'webgl2'
|
||||
? { MAX_TEXTURE_SIZE: 0x0d33, getParameter: () => 8192 }
|
||||
: null;
|
||||
};
|
||||
const engine = createNavaraEngine(view, { ...ports, hooks });
|
||||
assert.equal(engine.render.maxTextureSize(), 8192);
|
||||
assert.equal(engine.render.maxTextureSize(), 8192);
|
||||
assert.deepEqual(asked, ['webgl2']);
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('a render requested while a frame draws asks for the next frame', async () => {
|
||||
const { engine, view } = setup();
|
||||
const requests = () =>
|
||||
view.calls.filter(([name]) => name === 'forceUpdate').length;
|
||||
// The wind's flow asks for its next frame from preRender.
|
||||
const off = engine.frames.preRender.addEventListener(() =>
|
||||
engine.render.request('wind'),
|
||||
);
|
||||
view.emit('preRender', 1);
|
||||
view.emit('postRender', 1);
|
||||
// Navara clears its request flag once the frame is drawn.
|
||||
const drawn = requests();
|
||||
await Promise.resolve();
|
||||
assert.equal(requests(), drawn + 1, 'requested again after the frame');
|
||||
off();
|
||||
view.emit('preRender', 2);
|
||||
view.emit('postRender', 2);
|
||||
const idle = requests();
|
||||
await Promise.resolve();
|
||||
assert.equal(requests(), idle, 'no request, no next frame');
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('cancelFlight stops Navara with an empty setCamera; user input leaves a flight running', () => {
|
||||
const { engine, view } = setup();
|
||||
const outcome = [];
|
||||
engine.camera.flyTo({
|
||||
@@ -463,8 +535,9 @@ test('cancelFlight stops Navara with an empty setCamera; user input cancels a fl
|
||||
cancel: () => outcome.push('input'),
|
||||
});
|
||||
view.canvas.dispatchEvent(new Event('wheel'));
|
||||
assert.deepEqual(outcome, ['cancel', 'input']);
|
||||
assert.equal(engine.camera.flightActive(), false);
|
||||
assert.deepEqual(outcome, ['cancel']);
|
||||
assert.equal(engine.camera.flightActive(), true);
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('pickPosition reads Navara depth at client coordinates; pick finds no tiles', () => {
|
||||
@@ -536,7 +609,7 @@ test('pickGlobe meets the terrain along the pick ray, or the ellipsoid', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('a user gesture cancels a flight without raising camera.commanded', () => {
|
||||
test('a user gesture leaves a flight running without raising camera.commanded', () => {
|
||||
const { engine, view } = setup();
|
||||
const outcome = [];
|
||||
let commanded = 0;
|
||||
@@ -548,8 +621,8 @@ test('a user gesture cancels a flight without raising camera.commanded', () => {
|
||||
engine.camera.commanded.addEventListener(() => commanded++);
|
||||
view.canvas.dispatchEvent(new Event('pointerdown'));
|
||||
view.canvas.dispatchEvent(new Event('wheel'));
|
||||
assert.deepEqual(outcome, ['cancel']);
|
||||
assert.equal(engine.camera.flightActive(), false);
|
||||
assert.deepEqual(outcome, []);
|
||||
assert.equal(engine.camera.flightActive(), true);
|
||||
assert.equal(commanded, 0, 'a gesture is the user, not a new camera owner');
|
||||
});
|
||||
|
||||
@@ -630,17 +703,39 @@ test('the floor stands aside while the camera inputs are off (the cockpit drives
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('the floor stands aside while the camera inputs are suspended (the cockpit holds them)', () => {
|
||||
const { engine, view } = setup();
|
||||
view.sampleTerrainHeight = () => 100;
|
||||
const resume = engine.input.suspendCameraInputs();
|
||||
engine.camera.setView({
|
||||
destination: cartesian3.fromDegrees(2.35, 48.85, 112),
|
||||
test('ground picks use the visible surface and fall back to the globe', async () => {
|
||||
const { normalizeGroundItem } = await import('../ground.js');
|
||||
const view = fakeView();
|
||||
// Right after a click Navara's depth read answers with its near plane.
|
||||
view.pickDepthPosition = () => cartesian3.fromDegrees(10.5, 10, 45900);
|
||||
const options = { id: 'rooftop', kind: 'disc', pickable: true, order: 0 };
|
||||
const item = normalizeGroundItem(
|
||||
'disc',
|
||||
{ center: [10, 10], radiusM: 100, fill: [1, 0, 0, 1], pickId: 'roof' },
|
||||
0,
|
||||
);
|
||||
const engine = createNavaraEngine(view, {
|
||||
...ports,
|
||||
hooks,
|
||||
ground: {
|
||||
...ports.ground,
|
||||
pickables: () => [{ options, items: [item], shown: true }],
|
||||
},
|
||||
});
|
||||
view.emit('preRender', 1);
|
||||
near(heightOf(engine), 112, 1e-6, 'the cockpit eye 12 m up is kept');
|
||||
resume();
|
||||
view.emit('preRender', 2);
|
||||
near(heightOf(engine), 130, 1e-6, 'lifted once the inputs are back');
|
||||
const at = { x: 640, y: 400 };
|
||||
let globe = cartesian3.fromDegrees(10, 10, 0);
|
||||
engine.picker.pickGlobe = () => globe;
|
||||
let tiles = null;
|
||||
engine.surface.raycast = () => (tiles ? { position: tiles } : undefined);
|
||||
assert.equal(engine.picker.pick(at)?.id, 'roof', 'the globe, not the depth');
|
||||
// Under 3D tiles a tilted view meets the roof before the terrain.
|
||||
engine.maps.photorealActive = () => true;
|
||||
globe = cartesian3.fromDegrees(10.01, 10, 0);
|
||||
tiles = cartesian3.fromDegrees(10, 10, 40);
|
||||
assert.equal(engine.picker.pick(at)?.id, 'roof', 'the tiles shown');
|
||||
tiles = null;
|
||||
assert.equal(engine.picker.pick(at), undefined, 'a tile miss: the globe');
|
||||
globe = cartesian3.fromDegrees(10, 10, 0);
|
||||
assert.equal(engine.picker.pick(at)?.id, 'roof');
|
||||
engine.destroy();
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { assertGlobeEngine, engineCapabilities } from '../contract.js';
|
||||
import { cesiumFovy, orientationVectors } from '../cameraMath.js';
|
||||
import { createNavaraEngine } from './createNavaraEngine.js';
|
||||
|
||||
const { cartesian2, cartesian3, math } = geo;
|
||||
|
||||
// The parts of a Navara ThreeView the engine uses.
|
||||
function fakeView() {
|
||||
const handlers = new Map();
|
||||
const canvas = new EventTarget();
|
||||
Object.assign(canvas, {
|
||||
clientWidth: 1280,
|
||||
clientHeight: 800,
|
||||
getBoundingClientRect: () => ({ left: 10, top: 20 }),
|
||||
parentElement: { id: 'container' },
|
||||
});
|
||||
const position = cartesian3.fromDegrees(0, 0, 1e7);
|
||||
const { direction, up } = orientationVectors(
|
||||
position,
|
||||
0,
|
||||
-math.PI_OVER_TWO,
|
||||
0,
|
||||
);
|
||||
// three's camera.matrixWorld: columns right, up, back (−direction), position.
|
||||
const right = cartesian3.cross(direction, up, cartesian3.create());
|
||||
const elements = [
|
||||
right.x,
|
||||
right.y,
|
||||
right.z,
|
||||
0,
|
||||
up.x,
|
||||
up.y,
|
||||
up.z,
|
||||
0,
|
||||
-direction.x,
|
||||
-direction.y,
|
||||
-direction.z,
|
||||
0,
|
||||
position.x,
|
||||
position.y,
|
||||
position.z,
|
||||
1,
|
||||
];
|
||||
const view = {
|
||||
canvas,
|
||||
animation: false,
|
||||
calls: [],
|
||||
flights: [],
|
||||
on(name, fn) {
|
||||
if (!handlers.has(name)) handlers.set(name, new Set());
|
||||
handlers.get(name).add(fn);
|
||||
},
|
||||
off(name, fn) {
|
||||
handlers.get(name)?.delete(fn);
|
||||
},
|
||||
emit(name, ...args) {
|
||||
for (const fn of [...(handlers.get(name) ?? [])]) fn(...args);
|
||||
},
|
||||
listenerCount: () =>
|
||||
[...handlers.values()].reduce((count, set) => count + set.size, 0),
|
||||
camera: {
|
||||
raw: { matrixWorld: { elements }, updateMatrixWorld() {} },
|
||||
fovs: [],
|
||||
set fov(value) {
|
||||
view.camera.fovs.push(value);
|
||||
},
|
||||
set options(value) {
|
||||
view.calls.push(['options', value]);
|
||||
},
|
||||
},
|
||||
setCamera(pose) {
|
||||
view.calls.push(['setCamera', pose]);
|
||||
},
|
||||
flyTo(pose, options) {
|
||||
return new Promise((resolve) =>
|
||||
view.flights.push({ pose, options, resolve }),
|
||||
);
|
||||
},
|
||||
forceUpdate() {
|
||||
view.calls.push(['forceUpdate']);
|
||||
},
|
||||
pickDepthPosition(x, y) {
|
||||
view.calls.push(['pickDepthPosition', x, y]);
|
||||
return x > 100 ? { x: 1, y: 2, z: 3, isVector3: true } : null;
|
||||
},
|
||||
sampleTerrainHeight: () => undefined,
|
||||
addSource: (desc) => ({ id: 's', desc, delete: () => true }),
|
||||
addLayer: (desc) => ({ id: 'l', desc, delete() {} }),
|
||||
attribution: { add() {}, remove() {} },
|
||||
};
|
||||
return view;
|
||||
}
|
||||
|
||||
const hooks = {
|
||||
tileRoots: () => [],
|
||||
isIdle: () => true,
|
||||
retainTileGeometry() {},
|
||||
};
|
||||
|
||||
// Primitive ports for tests of engine orchestration.
|
||||
const STUB_MOVERS = Object.freeze({
|
||||
createSet() {
|
||||
throw new Error("Navara movers need the view's three runtime (movers/)");
|
||||
},
|
||||
list: () => [],
|
||||
});
|
||||
const STUB_LINES = Object.freeze({
|
||||
createSegments() {
|
||||
throw new Error("Navara lines need the view's three runtime (lines/)");
|
||||
},
|
||||
createLine() {
|
||||
throw new Error("Navara lines need the view's three runtime (lines/)");
|
||||
},
|
||||
list: () => [],
|
||||
});
|
||||
const STUB_MESHES = Object.freeze({
|
||||
createMesh() {
|
||||
throw new Error('Navara meshes need the view runtime');
|
||||
},
|
||||
list: () => [],
|
||||
});
|
||||
const STUB_GROUND = Object.freeze({
|
||||
createPulseField() {
|
||||
throw new Error('Navara ground needs the view runtime');
|
||||
},
|
||||
createSet() {
|
||||
throw new Error("Navara ground needs the view's three runtime (ground/)");
|
||||
},
|
||||
list: () => [],
|
||||
});
|
||||
const STUB_IMAGERY = Object.freeze({
|
||||
createLayer() {
|
||||
throw new Error("Navara imagery needs the view's three runtime (imagery/)");
|
||||
},
|
||||
list: () => [],
|
||||
setSplitPosition() {},
|
||||
splitPosition: () => 0.5,
|
||||
surface: () => 'globe',
|
||||
});
|
||||
|
||||
const ports = {
|
||||
movers: { movers: STUB_MOVERS, destroy() {} },
|
||||
lines: { lines: STUB_LINES, destroy() {} },
|
||||
ground: { ground: STUB_GROUND, destroy() {} },
|
||||
imagery: () => ({ imagery: STUB_IMAGERY, destroy() {} }),
|
||||
meshes: () => ({ meshes: STUB_MESHES, destroy() {} }),
|
||||
};
|
||||
|
||||
const setup = () => {
|
||||
const view = fakeView();
|
||||
const engine = createNavaraEngine(view, { ...ports, hooks });
|
||||
return { view, engine };
|
||||
};
|
||||
|
||||
// Cesium's CameraFlightPath turns the camera inputs off for the flight, so a
|
||||
// gesture never cancels it; layers/infrastructure suspends the inputs for the
|
||||
// same reason ("Camera input would cancel the flight").
|
||||
test('a wheel during a flight with the camera inputs suspended does not cancel it', async () => {
|
||||
const { engine, view } = setup();
|
||||
const outcome = [];
|
||||
const restore = engine.input.suspendCameraInputs();
|
||||
engine.camera.flyTo({
|
||||
destination: cartesian3.fromDegrees(100, 0, 5e6),
|
||||
duration: 1.5,
|
||||
complete: () => outcome.push('complete'),
|
||||
cancel: () => outcome.push('cancel'),
|
||||
});
|
||||
view.canvas.dispatchEvent(new Event('wheel'));
|
||||
view.canvas.dispatchEvent(new Event('pointerdown'));
|
||||
assert.deepEqual(outcome, [], 'the flight goes on');
|
||||
assert.equal(engine.camera.flightActive(), true);
|
||||
restore();
|
||||
assert.equal(
|
||||
engine.input.cameraInputsEnabled(),
|
||||
false,
|
||||
'the flight keeps its own suspension',
|
||||
);
|
||||
view.flights[0].resolve(true);
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(outcome, ['complete']);
|
||||
assert.equal(engine.input.cameraInputsEnabled(), true);
|
||||
engine.destroy();
|
||||
});
|
||||
@@ -9,7 +9,9 @@
|
||||
// window ratio uses Cesium's maximumMovementRatio cap; a drag
|
||||
// right turns the heading clockwise;
|
||||
// - right drag: a dolly by dy / height (down closes in);
|
||||
// - wheel: one notch (deltaY 100) is 20 % of the range.
|
||||
// - wheel: one notch (deltaY 100) is 20 % of the range;
|
||||
// - two-finger pinch: the range scales by the fingers' distance ratio
|
||||
// (pointers are told apart by pointerId).
|
||||
|
||||
const WHEEL_STEP = 1.2;
|
||||
const ROTATE_RATE = 1.77;
|
||||
@@ -29,16 +31,32 @@ export function navaraFollowGestures(
|
||||
) {
|
||||
return ({ orbit, zoom, dolly }) => {
|
||||
const resume = suspendCameraInputs();
|
||||
let last = null;
|
||||
const pointers = new Map();
|
||||
const distance = () => {
|
||||
const [a, b] = pointers.values();
|
||||
return Math.hypot(a.x - b.x, a.y - b.y);
|
||||
};
|
||||
const down = (event) => {
|
||||
if (event.button !== 0 && event.button !== 2) return;
|
||||
last = { x: event.clientX, y: event.clientY, button: event.button };
|
||||
pointers.set(event.pointerId, {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
button: event.button,
|
||||
});
|
||||
};
|
||||
const move = (event) => {
|
||||
const last = pointers.get(event.pointerId);
|
||||
if (!last) return;
|
||||
const before = pointers.size === 2 ? distance() : 0;
|
||||
const dx = event.clientX - last.x;
|
||||
const dy = event.clientY - last.y;
|
||||
last = { ...last, x: event.clientX, y: event.clientY };
|
||||
last.x = event.clientX;
|
||||
last.y = event.clientY;
|
||||
if (pointers.size > 1) {
|
||||
const after = pointers.size === 2 ? distance() : 0;
|
||||
if (before > 0 && after > 0) zoom(before / after);
|
||||
return;
|
||||
}
|
||||
const width = canvas.clientWidth || 1;
|
||||
const height = canvas.clientHeight || 1;
|
||||
if (last.button === 2) {
|
||||
@@ -50,8 +68,8 @@ export function navaraFollowGestures(
|
||||
ROTATE_RATE * Math.min(-dy / height, MAX_MOVEMENT_RATIO) * Math.PI,
|
||||
);
|
||||
};
|
||||
const up = () => {
|
||||
last = null;
|
||||
const up = (event) => {
|
||||
pointers.delete(event.pointerId);
|
||||
};
|
||||
const wheel = (event) => {
|
||||
if (!Number.isFinite(event.deltaY) || event.deltaY === 0) return;
|
||||
@@ -63,6 +81,7 @@ export function navaraFollowGestures(
|
||||
canvas.addEventListener('pointerdown', down);
|
||||
windowTarget.addEventListener('pointermove', move);
|
||||
windowTarget.addEventListener('pointerup', up);
|
||||
windowTarget.addEventListener('pointercancel', up);
|
||||
canvas.addEventListener('wheel', wheel, { passive: false });
|
||||
canvas.addEventListener('contextmenu', contextMenu);
|
||||
return () => {
|
||||
@@ -70,6 +89,8 @@ export function navaraFollowGestures(
|
||||
canvas.removeEventListener('pointerdown', down);
|
||||
windowTarget.removeEventListener('pointermove', move);
|
||||
windowTarget.removeEventListener('pointerup', up);
|
||||
windowTarget.removeEventListener('pointercancel', up);
|
||||
pointers.clear();
|
||||
canvas.removeEventListener('wheel', wheel, { passive: false });
|
||||
resume();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { navaraFollowGestures } from './followGestures.js';
|
||||
|
||||
const event = (type, fields = {}) =>
|
||||
Object.assign(new Event(type, { cancelable: true }), fields);
|
||||
|
||||
test('a two-finger pinch while following zooms and does not jerk the heading', () => {
|
||||
const canvas = new EventTarget();
|
||||
canvas.clientWidth = 400;
|
||||
canvas.clientHeight = 800;
|
||||
const win = new EventTarget();
|
||||
const gestures = navaraFollowGestures(canvas, () => () => {}, win);
|
||||
const calls = [];
|
||||
const release = gestures({
|
||||
orbit: (h, p) => calls.push(['orbit', h, p]),
|
||||
zoom: (f) => calls.push(['zoom', f]),
|
||||
dolly: (r) => calls.push(['dolly', r]),
|
||||
});
|
||||
const touch = (type, pointerId, x, y, target = win) =>
|
||||
target.dispatchEvent(
|
||||
event(type, {
|
||||
pointerId,
|
||||
pointerType: 'touch',
|
||||
isPrimary: pointerId === 1,
|
||||
button: type === 'pointermove' ? -1 : 0,
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
}),
|
||||
);
|
||||
// Two fingers 200 px apart spread out symmetrically (a pinch-out).
|
||||
touch('pointerdown', 1, 100, 400, canvas);
|
||||
touch('pointerdown', 2, 300, 400, canvas);
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
touch('pointermove', 1, 100 - 5 * i, 400);
|
||||
touch('pointermove', 2, 300 + 5 * i, 400);
|
||||
}
|
||||
const turn = calls
|
||||
.filter(([kind]) => kind === 'orbit')
|
||||
.reduce((most, [, h]) => Math.max(most, Math.abs(h)), 0);
|
||||
assert.ok(
|
||||
turn < 0.2,
|
||||
`a pinch turned the heading by up to ${turn.toFixed(2)} rad in one move`,
|
||||
);
|
||||
assert.ok(
|
||||
calls.some(([kind]) => kind === 'zoom' || kind === 'dolly'),
|
||||
'a pinch changes the range',
|
||||
);
|
||||
touch('pointercancel', 2, 320, 400);
|
||||
const count = calls.length;
|
||||
touch('pointermove', 2, 350, 400);
|
||||
assert.equal(
|
||||
calls.length,
|
||||
count,
|
||||
'a cancelled finger no longer moves the camera',
|
||||
);
|
||||
touch('pointermove', 1, 75, 400);
|
||||
assert.equal(
|
||||
calls.at(-1)[0],
|
||||
'orbit',
|
||||
'the remaining finger resumes dragging',
|
||||
);
|
||||
touch('pointerup', 1, 75, 400);
|
||||
const ended = calls.length;
|
||||
touch('pointermove', 1, 90, 400);
|
||||
assert.equal(calls.length, ended);
|
||||
release();
|
||||
});
|
||||
@@ -61,6 +61,7 @@ export function createNavaraGround(
|
||||
};
|
||||
const pack = (entry) => {
|
||||
entry.pack = packSet(entry.options.kind, entry.items, { terrainHeight });
|
||||
entry.pack.drape = entry.options.drape;
|
||||
for (
|
||||
let at = REVEAL_OFFSET;
|
||||
at < entry.pack.items.length;
|
||||
|
||||
@@ -274,3 +274,22 @@ test('destroying a revealed corridor leaves the next ground set with fresh pass
|
||||
}
|
||||
port.destroy();
|
||||
});
|
||||
|
||||
test('ground sets carry their surface classification into the frame texture', async () => {
|
||||
const { matrix4 } = await import('../../../geo/index.js');
|
||||
const pass = fakePass();
|
||||
const port = createNavaraGround(fakeView(), { createPass: () => pass });
|
||||
for (const [drape, expected] of [
|
||||
['terrain', 1],
|
||||
['tiles', 2],
|
||||
['both', 0],
|
||||
]) {
|
||||
const set = port.ground.createSet({ id: drape, kind: 'polygon', drape });
|
||||
set.replace([square(0)]);
|
||||
set.commit();
|
||||
const state = pass.owner.state;
|
||||
state.update(matrix4.IDENTITY, matrix4.IDENTITY, 800, 600);
|
||||
assert.equal(state.frames.data[(state.count - 1) * 16 + 15], expected);
|
||||
}
|
||||
port.destroy();
|
||||
});
|
||||
@@ -524,6 +524,7 @@ export function composeGround(packs) {
|
||||
0,
|
||||
);
|
||||
const frames64 = new Float64Array(count * 13);
|
||||
const drapes = new Uint8Array(count);
|
||||
const volumes = new Float64Array(count * 4);
|
||||
const heights = new Float64Array(count * 2);
|
||||
const styles = texelStorage(count * STYLE_TEXELS);
|
||||
@@ -543,6 +544,11 @@ export function composeGround(packs) {
|
||||
let run = 0;
|
||||
let look = 0;
|
||||
for (const pack of packs) {
|
||||
drapes.fill(
|
||||
pack.drape === 'terrain' ? 1 : pack.drape === 'tiles' ? 2 : 0,
|
||||
item,
|
||||
item + pack.count,
|
||||
);
|
||||
frames64.set(pack.frames, item * 13);
|
||||
volumes.set(pack.volumes, item * 4);
|
||||
heights.set(pack.heights, item * 2);
|
||||
@@ -585,6 +591,7 @@ export function composeGround(packs) {
|
||||
const box = new Float64Array(4);
|
||||
const lastView = new Float64Array(16).fill(Number.NaN);
|
||||
const lastProjection = new Float64Array(16).fill(Number.NaN);
|
||||
let lastPixelRatio = 1;
|
||||
let lastWidth = 0;
|
||||
let lastHeight = 0;
|
||||
const clampTo = (value, max) => Math.min(max - 1, Math.max(0, value));
|
||||
@@ -602,8 +609,11 @@ export function composeGround(packs) {
|
||||
return candidates;
|
||||
},
|
||||
/** True when the frames, grid or candidates changed (upload them). */
|
||||
update(view, projection, width, height) {
|
||||
let changed = width !== lastWidth || height !== lastHeight;
|
||||
update(view, projection, width, height, pixelRatio = 1) {
|
||||
let changed =
|
||||
width !== lastWidth ||
|
||||
height !== lastHeight ||
|
||||
pixelRatio !== lastPixelRatio;
|
||||
for (let index = 0; index < 16 && !changed; index++)
|
||||
changed =
|
||||
view[index] !== lastView[index] ||
|
||||
@@ -613,6 +623,7 @@ export function composeGround(packs) {
|
||||
lastProjection.set(projection);
|
||||
lastWidth = width;
|
||||
lastHeight = height;
|
||||
lastPixelRatio = pixelRatio;
|
||||
const m = view;
|
||||
counts.fill(0);
|
||||
for (let index = 0; index < count; index++) {
|
||||
@@ -636,11 +647,12 @@ export function composeGround(packs) {
|
||||
frames.data.set(viewFrame.subarray(3, 6), t + 4);
|
||||
frames.data.set(viewFrame.subarray(6, 9), t + 8);
|
||||
frames.data.set(viewFrame.subarray(9, 12), t + 12);
|
||||
frames.data[t + 15] = drapes[index];
|
||||
const v = index * 4;
|
||||
// The item's extent in its plane and its padding in pixels, for
|
||||
// the shader's early rejection.
|
||||
frames.data[t + 7] = volumes[v];
|
||||
frames.data[t + 11] = volumes[v + 3];
|
||||
frames.data[t + 11] = volumes[v + 3] * pixelRatio;
|
||||
const distance = Math.hypot(viewFrame[0], viewFrame[1], viewFrame[2]);
|
||||
// Heights relative to the plane's origin on the ellipsoid; the
|
||||
// plane dips under the curve by r²/2R at the item's edge.
|
||||
@@ -665,8 +677,8 @@ export function composeGround(packs) {
|
||||
ranges[r] = -1;
|
||||
continue;
|
||||
}
|
||||
const padX = (2 * volumes[v + 3]) / Math.max(1, width);
|
||||
const padY = (2 * volumes[v + 3]) / Math.max(1, height);
|
||||
const padX = (2 * volumes[v + 3] * pixelRatio) / Math.max(1, width);
|
||||
const padY = (2 * volumes[v + 3] * pixelRatio) / Math.max(1, height);
|
||||
ranges[r] = clampTo(
|
||||
Math.floor(((box[0] - padX) * 0.5 + 0.5) * GRID_COLS),
|
||||
GRID_COLS,
|
||||
|
||||
@@ -502,3 +502,22 @@ test('radial discs pack both transitions, alpha and emission without segment dat
|
||||
);
|
||||
assert.equal(pack.segments.length, 0);
|
||||
});
|
||||
|
||||
test('screen padding follows the render pixel ratio', () => {
|
||||
const pack = packSet(
|
||||
'disc',
|
||||
items('disc', [
|
||||
{
|
||||
center: [0, 0],
|
||||
radiusM: 100,
|
||||
outline: { color: [1, 1, 1, 1], widthPx: 8 },
|
||||
},
|
||||
]),
|
||||
);
|
||||
const state = composeGround([pack]);
|
||||
const identity = geo.matrix4.IDENTITY;
|
||||
state.update(identity, identity, 800, 600, 1);
|
||||
const padding = state.frames.data[11];
|
||||
assert.equal(state.update(identity, identity, 800, 600, 2), true);
|
||||
assert.equal(state.frames.data[11], padding * 2);
|
||||
});
|
||||
@@ -44,6 +44,7 @@ const float = (value) => (Number.isInteger(value) ? `${value}.0` : `${value}`);
|
||||
const fragmentShader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth;
|
||||
uniform sampler2D tSurfaceDepth;
|
||||
uniform sampler2D tGlobeDepth;
|
||||
uniform highp sampler2D tFrames;
|
||||
uniform highp sampler2D tStyles;
|
||||
uniform highp sampler2D tSegments;
|
||||
@@ -73,7 +74,7 @@ vec3 blendCorridor(vec3 color, int item, float nearest, vec2 normal, float along
|
||||
// Metres a pixel spans across the line (the screen gradient of the
|
||||
// distance to it): its width in pixels the same at any angle, as Cesium's.
|
||||
float pixel = max(length(vec2(dot(normal, localDx), dot(normal, localDy))), 1e-4);
|
||||
float halfWidth = shape.x > 0.0 ? shape.x * 0.5 * pixel : shape.y * 0.5;
|
||||
float halfWidth = shape.x > 0.0 ? shape.x * uPixelRatio * 0.5 * pixel : shape.y * 0.5;
|
||||
float cover = clamp((halfWidth - nearest) / pixel + 0.5, 0.0, 1.0);
|
||||
if (cover <= 0.0) return color;
|
||||
vec4 fill = atSlot(tItems, at);
|
||||
@@ -137,6 +138,8 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
float surface = texture2D(tSurfaceDepth, uv).r;
|
||||
// The packed depth also holds forward meshes, which are not ground.
|
||||
if (depth < surface - 2e-7) return;
|
||||
float globeDepth = unpackRGBAToDepth(texture2D(tGlobeDepth, uv));
|
||||
bool onTiles = surface < globeDepth - 2e-7;
|
||||
vec3 color = toDisplay(inputColor.rgb);
|
||||
// The pixel's ground in world space, once: every corridor tile tests the
|
||||
// same value, so exactly one tile of a set holds it.
|
||||
@@ -150,7 +153,9 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
vec4 origin = atSlot(tFrames, id * ${TEXELS});
|
||||
vec4 east = atSlot(tFrames, id * ${TEXELS} + 1);
|
||||
vec4 north = atSlot(tFrames, id * ${TEXELS} + 2);
|
||||
vec3 up = atSlot(tFrames, id * ${TEXELS} + 3).xyz;
|
||||
vec4 surfaceFrame = atSlot(tFrames, id * ${TEXELS} + 3);
|
||||
if ((surfaceFrame.w == 1.0 && onTiles) || (surfaceFrame.w == 2.0 && !onTiles)) continue;
|
||||
vec3 up = surfaceFrame.xyz;
|
||||
vec4 span = atSlot(tStyles, id * ${STYLE_TEXELS} + 3);
|
||||
vec3 delta = point - origin.xyz;
|
||||
float height = dot(delta, up);
|
||||
@@ -190,7 +195,7 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
// A pixel past the bins (beyond an open side) takes the bin nearest
|
||||
// it, with a margin that reaches it too.
|
||||
float past = length(max(vec2(0.0), max(place.xy - local, local - open.zw)));
|
||||
float need = (lineColor.z * pixelMax + past) / (${float(MARGIN_RATIO)} * shape.y);
|
||||
float need = (lineColor.z * uPixelRatio * pixelMax + past) / (${float(MARGIN_RATIO)} * shape.y);
|
||||
int level = need <= 1.0 ? 0 : min(int(lineColor.w + 0.5), int(ceil(log2(need))));
|
||||
int columns = int(shape.z + 0.5);
|
||||
int rows = int(shape.w + 0.5);
|
||||
@@ -264,7 +269,7 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
vec2 centre = vec2(0.0);
|
||||
vec4 grid = atSlot(tStyles, id * ${STYLE_TEXELS} + 4);
|
||||
if (grid.x > 0.5 &&
|
||||
(length(localDx) + length(localDy)) * (shape.y * 0.5 + 1.5) <= grid.z * 0.5) {
|
||||
(length(localDx) + length(localDy)) * (shape.y * uPixelRatio * 0.5 + 1.5) <= grid.z * 0.5) {
|
||||
vec2 origin = atSlot(tStyles, id * ${STYLE_TEXELS} + 5).xy;
|
||||
ivec2 cell = ivec2(floor((local - origin) / grid.z));
|
||||
// Off the grid: outside the area, beyond any edge's reach.
|
||||
@@ -317,7 +322,7 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
if (fillColor.a > 0.0)
|
||||
color = mix(color, fillColor.rgb, fillColor.a * clamp(inward / pixel + 0.5, 0.0, 1.0));
|
||||
if (lineColor.a > 0.0 && shape.y > 0.0)
|
||||
color = mix(color, lineColor.rgb, lineColor.a * clamp(shape.y * 0.5 - nearest / pixel + 0.5, 0.0, 1.0));
|
||||
color = mix(color, lineColor.rgb, lineColor.a * clamp(shape.y * uPixelRatio * 0.5 - nearest / pixel + 0.5, 0.0, 1.0));
|
||||
}
|
||||
outputColor = vec4(toLinear(color), inputColor.a);
|
||||
}
|
||||
@@ -401,6 +406,7 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['tGlobeDepth', new Uniform(null)],
|
||||
['tFrames', new Uniform(null)],
|
||||
['tStyles', new Uniform(null)],
|
||||
['tSegments', new Uniform(null)],
|
||||
@@ -425,12 +431,15 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
updateGroundSurface(this.effect, camera, this.ctx, mrt);
|
||||
const input = this.ctx.getInputBuffer();
|
||||
const { state } = owner;
|
||||
const cssWidth = this.view.canvas?.clientWidth;
|
||||
const pixelRatio = cssWidth > 0 ? input.width / cssWidth : 1;
|
||||
if (
|
||||
state.update(
|
||||
camera.matrixWorldInverse.elements,
|
||||
camera.projectionMatrix.elements,
|
||||
input.width,
|
||||
input.height,
|
||||
pixelRatio,
|
||||
)
|
||||
) {
|
||||
const textures = owner.textures;
|
||||
@@ -444,10 +453,10 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
textures.candidates.needsUpdate = true;
|
||||
}
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tGlobeDepth').value = mrt.globeDepthBuffer;
|
||||
u.get('uViewToWorld').value.copy(camera.matrixWorld);
|
||||
u.get('uTime').value = groundSeconds();
|
||||
const cssWidth = this.view.canvas?.clientWidth;
|
||||
u.get('uPixelRatio').value = cssWidth > 0 ? input.width / cssWidth : 1;
|
||||
u.get('uPixelRatio').value = pixelRatio;
|
||||
u.get('tFrames').value = owner.textures.frames;
|
||||
u.get('tStyles').value = owner.textures.styles;
|
||||
u.get('tSegments').value = owner.textures.segments;
|
||||
|
||||
@@ -345,14 +345,13 @@ export function createNavaraImagery(
|
||||
current.canvas.width = current.canvas.height = 0;
|
||||
queue.prune();
|
||||
};
|
||||
// The source's rectangle within the tiling's latitudes; across the
|
||||
// antimeridian the atlas covers every longitude.
|
||||
// The source's rectangle within the tiling's latitudes.
|
||||
const limit = scheme === 'geographic' ? 90 : WEB_MERCATOR_LIMIT;
|
||||
const box = () => {
|
||||
const { west, south, east, north } = source.rectangle;
|
||||
return {
|
||||
west: west < east ? west : -180,
|
||||
east: west < east ? east : 180,
|
||||
west,
|
||||
east,
|
||||
south: Math.max(south, -limit),
|
||||
north: Math.min(north, limit),
|
||||
};
|
||||
@@ -416,7 +415,8 @@ export function createNavaraImagery(
|
||||
tasks.push({
|
||||
url: imageryTileUrl(
|
||||
source.url,
|
||||
plan.x + x,
|
||||
(plan.x + x) %
|
||||
2 ** (plan.z + (scheme === 'geographic' ? 1 : 0)),
|
||||
plan.y + y,
|
||||
plan.z,
|
||||
source.subdomains,
|
||||
@@ -625,7 +625,7 @@ export function createNavaraImagery(
|
||||
},
|
||||
);
|
||||
|
||||
const offCamera = camera.changed.addEventListener(() => {
|
||||
const viewChanged = () => {
|
||||
let changed = false;
|
||||
for (const entry of entries.values()) {
|
||||
changed = entry.drawing.cameraChanged() || changed;
|
||||
@@ -633,12 +633,15 @@ export function createNavaraImagery(
|
||||
}
|
||||
// Raised layers rise with the camera.
|
||||
if (changed || liftNow() !== lift) compose();
|
||||
});
|
||||
};
|
||||
const offCamera = camera.changed.addEventListener(viewChanged);
|
||||
view.on?.('resize', viewChanged);
|
||||
|
||||
return {
|
||||
imagery: registry.imagery,
|
||||
destroy() {
|
||||
offCamera();
|
||||
view.off?.('resize', viewChanged);
|
||||
registry.destroyAll();
|
||||
pass.destroy();
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@ import { MAX_IMAGERY_SLOTS, createNavaraImagery } from './index.js';
|
||||
const BOX = { west: -97.77, south: 30.25, east: -97.71, north: 30.29 };
|
||||
const tick = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
function fixture() {
|
||||
function fixture(rectangle = null) {
|
||||
const canvases = [];
|
||||
const draws = [];
|
||||
const jobs = [];
|
||||
@@ -15,7 +15,11 @@ function fixture() {
|
||||
const changed = createEngineEvent();
|
||||
let photoreal = false;
|
||||
let frames = 0;
|
||||
let height = 800;
|
||||
const events = new Map();
|
||||
const view = {
|
||||
on: (name, run) => events.set(name, run),
|
||||
off: (name) => events.delete(name),
|
||||
forceUpdate: () => frames++,
|
||||
};
|
||||
const { imagery, destroy } = createNavaraImagery(view, {
|
||||
@@ -25,9 +29,9 @@ function fixture() {
|
||||
cartographic: { height: 12_000, latitude: 0.53 },
|
||||
fovy: 0.7,
|
||||
}),
|
||||
viewRectangle: () => null,
|
||||
viewRectangle: () => rectangle,
|
||||
},
|
||||
size: () => ({ width: 1280, height: 800 }),
|
||||
size: () => ({ width: 1280, height }),
|
||||
credits: {
|
||||
addStatic(html) {
|
||||
credits.set(html, (credits.get(html) ?? 0) + 1);
|
||||
@@ -52,6 +56,10 @@ function fixture() {
|
||||
},
|
||||
});
|
||||
return {
|
||||
resize: (next) => {
|
||||
height = next;
|
||||
events.get('resize')?.();
|
||||
},
|
||||
imagery,
|
||||
destroy,
|
||||
canvases,
|
||||
@@ -300,3 +308,43 @@ test('a raised image is lifted with the camera; its detail is a slot over it', a
|
||||
assert.equal(f.last().slots.length, 1);
|
||||
assert.equal(f.last().slots[0].look[3], 0);
|
||||
});
|
||||
|
||||
test('resizing replans a tile atlas without a camera change', async () => {
|
||||
const f = fixture();
|
||||
f.imagery.createLayer({ id: 'resize', source: tiles({ maxLevel: 20 }) });
|
||||
await tick();
|
||||
const before = f.canvases.length;
|
||||
f.resize(1600);
|
||||
await tick();
|
||||
assert.ok(f.canvases.length > before);
|
||||
f.destroy();
|
||||
});
|
||||
|
||||
test('an atlas crossing the antimeridian requests valid columns on both sides', async () => {
|
||||
const r = Math.PI / 180;
|
||||
const f = fixture({
|
||||
west: 179.5 * r,
|
||||
east: -179.5 * r,
|
||||
south: -17 * r,
|
||||
north: -16 * r,
|
||||
});
|
||||
f.imagery.createLayer({
|
||||
id: 'seam',
|
||||
source: tiles({
|
||||
minLevel: 10,
|
||||
maxLevel: 10,
|
||||
rectangle: { west: -180, east: 180, south: -85, north: 85 },
|
||||
}),
|
||||
});
|
||||
let loaded = 0;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
await tick();
|
||||
while (loaded < f.jobs.length) f.jobs[loaded++].resolve({});
|
||||
}
|
||||
const columns = f.jobs.map(({ url }) =>
|
||||
Number(url.match(/\/(\d+)\.png$/)[1]),
|
||||
);
|
||||
assert.ok(columns.includes(0) && columns.includes(1023));
|
||||
assert.ok(columns.every((x) => x >= 0 && x < 1024));
|
||||
f.destroy();
|
||||
});
|
||||
@@ -91,17 +91,17 @@ vec3 paint(vec3 color, sampler2D image, vec4 rect, vec4 bounds, vec4 look, vec4
|
||||
if ((look.y < 0.0 && x > uSplit) || (look.y > 0.0 && x < uSplit)) return color;
|
||||
if (!inRect(geo, rect)) return color;
|
||||
if (look.w > 0.5 && inRect(geo, cut)) return color;
|
||||
float lon = geo.x < rect.x ? geo.x + 360.0 : geo.x;
|
||||
vec2 at;
|
||||
vec2 dx;
|
||||
vec2 dy;
|
||||
if (look.z > 0.5) {
|
||||
vec2 m = vec2(merc.x + (lon - geo.x) / 360.0, merc.y);
|
||||
vec2 m = vec2(merc.x < bounds.x ? merc.x + 1.0 : merc.x, merc.y);
|
||||
at = (m - bounds.xy) / bounds.zw;
|
||||
dx = mercDx / bounds.zw;
|
||||
dy = mercDy / bounds.zw;
|
||||
} else {
|
||||
vec2 span = vec2(bounds.z - bounds.x, bounds.y - bounds.w);
|
||||
float lon = geo.x < bounds.x ? geo.x + 360.0 : geo.x;
|
||||
at = vec2(lon - bounds.x, geo.y - bounds.w) / span;
|
||||
dx = geoDx / span;
|
||||
dy = geoDy / span;
|
||||
|
||||
+26
-23
@@ -6,15 +6,19 @@ import { createExclusivePointer } from '../exclusivePointer.js';
|
||||
// that key is held (shift over ctrl over alt), one without only while none is.
|
||||
//
|
||||
// Camera inputs map to Navara's controller flags (view.camera.options).
|
||||
// Navara 0.2.1 lets a flyTo run on under user input, where Cesium cancels it;
|
||||
// `onCameraInput` reports user camera input so the engine can do the same.
|
||||
// Flights suspend camera inputs, matching Cesium's flight controller.
|
||||
|
||||
import { INPUT_TYPES, normalizeInputOptions } from '../contract.js';
|
||||
import { createPickDelivery } from '../pickDelivery.js';
|
||||
|
||||
const CLICK_PIXEL_TOLERANCE = 5; // Cesium's _clickPixelTolerance
|
||||
const SCREEN_EVENTS = ['pointerdown', 'pointerup', 'pointermove', 'dblclick'];
|
||||
const CAMERA_EVENTS = ['pointerdown', 'wheel', 'touchstart'];
|
||||
const SCREEN_EVENTS = [
|
||||
'pointerdown',
|
||||
'pointerup',
|
||||
'pointermove',
|
||||
'pointercancel',
|
||||
'dblclick',
|
||||
];
|
||||
|
||||
function modifierOf(event) {
|
||||
if (event.shiftKey) return 'shift';
|
||||
@@ -25,8 +29,7 @@ function modifierOf(event) {
|
||||
|
||||
/**
|
||||
* @param {{ canvas: HTMLCanvasElement, camera: { options: object } }} view
|
||||
* @param {{ onCameraInput?: (type: string) => void,
|
||||
* picker?: { clickPick: Function, pick: Function, drillPick: Function },
|
||||
* @param {{ picker?: { clickPick: Function, pick: Function, drillPick: Function },
|
||||
* scheduleFrame?: (run: () => void) => void }} [options] `picker`
|
||||
* answers listeners with { pick, drill } (picking.js): clicks from the
|
||||
* GPU pick of the gesture, moves from the CPU pick once a frame.
|
||||
@@ -34,11 +37,7 @@ function modifierOf(event) {
|
||||
*/
|
||||
export function createNavaraInput(
|
||||
view,
|
||||
{
|
||||
onCameraInput = () => {},
|
||||
picker = null,
|
||||
scheduleFrame = (run) => requestAnimationFrame(run),
|
||||
} = {},
|
||||
{ picker = null, scheduleFrame = (run) => requestAnimationFrame(run) } = {},
|
||||
) {
|
||||
const { canvas } = view;
|
||||
const listeners = new Map(INPUT_TYPES.map((type) => [type, new Set()]));
|
||||
@@ -46,6 +45,7 @@ export function createNavaraInput(
|
||||
let destroyed = false;
|
||||
let cameraOptions = {};
|
||||
let downAt = null;
|
||||
const activePointers = new Set();
|
||||
let last = null;
|
||||
|
||||
const pointer = createExclusivePointer();
|
||||
@@ -92,23 +92,37 @@ export function createNavaraInput(
|
||||
const position = positionOf(event);
|
||||
switch (event.type) {
|
||||
case 'pointerdown':
|
||||
// A primary pointer starts a new gesture: pointers released off the
|
||||
// canvas cannot hold its click back.
|
||||
if (event.isPrimary === true) activePointers.clear();
|
||||
activePointers.add(event.pointerId);
|
||||
if (activePointers.size > 1 || event.isPrimary === false) {
|
||||
downAt = null;
|
||||
break;
|
||||
}
|
||||
if (event.button !== 0) break;
|
||||
downAt = position;
|
||||
downAt = { ...position, pointerId: event.pointerId };
|
||||
emit('down', event, { position });
|
||||
break;
|
||||
case 'pointerup': {
|
||||
activePointers.delete(event.pointerId);
|
||||
if (event.button !== 0) break;
|
||||
emit('up', event, { position });
|
||||
const start = downAt;
|
||||
downAt = null;
|
||||
if (
|
||||
start &&
|
||||
start.pointerId === event.pointerId &&
|
||||
Math.hypot(position.x - start.x, position.y - start.y) <
|
||||
CLICK_PIXEL_TOLERANCE
|
||||
)
|
||||
emit('click', event, { position });
|
||||
break;
|
||||
}
|
||||
case 'pointercancel':
|
||||
activePointers.delete(event.pointerId);
|
||||
downAt = null;
|
||||
break;
|
||||
case 'pointermove':
|
||||
emit('move', event, {
|
||||
startPosition: last ?? position,
|
||||
@@ -121,15 +135,6 @@ export function createNavaraInput(
|
||||
}
|
||||
last = position;
|
||||
};
|
||||
const onCameraEvent = (event) => {
|
||||
onCameraInput(event.type);
|
||||
};
|
||||
for (const type of CAMERA_EVENTS)
|
||||
canvas.addEventListener(type, onCameraEvent, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
|
||||
let suspended = 0;
|
||||
const sendCameraInputs = () => {
|
||||
const enabled = suspended === 0;
|
||||
@@ -199,8 +204,6 @@ export function createNavaraInput(
|
||||
if (destroyed) return;
|
||||
pointer.destroy();
|
||||
destroyed = true;
|
||||
for (const type of CAMERA_EVENTS)
|
||||
canvas.removeEventListener(type, onCameraEvent, { capture: true });
|
||||
if (attached)
|
||||
for (const name of SCREEN_EVENTS)
|
||||
canvas.removeEventListener(name, onScreenEvent);
|
||||
|
||||
@@ -33,7 +33,6 @@ const pointer = (type, x, y, extra = {}) =>
|
||||
function setup() {
|
||||
const canvas = fakeCanvas();
|
||||
const cameraOptions = [];
|
||||
const cameraInputs = [];
|
||||
const view = {
|
||||
canvas,
|
||||
camera: {
|
||||
@@ -42,10 +41,8 @@ function setup() {
|
||||
},
|
||||
},
|
||||
};
|
||||
const { input, destroy } = createNavaraInput(view, {
|
||||
onCameraInput: (type) => cameraInputs.push(type),
|
||||
});
|
||||
return { canvas, input, destroy, cameraOptions, cameraInputs };
|
||||
const { input, destroy } = createNavaraInput(view);
|
||||
return { canvas, input, destroy, cameraOptions };
|
||||
}
|
||||
|
||||
test('down, up and click carry canvas-relative positions', () => {
|
||||
@@ -119,14 +116,9 @@ test('on validates its arguments and returns an idempotent remover', () => {
|
||||
assert.equal(count, 0);
|
||||
});
|
||||
|
||||
test('suspending Navara controls preserves user input notifications', () => {
|
||||
const { canvas, input, cameraOptions, cameraInputs } = setup();
|
||||
canvas.dispatchEvent(pointer('pointerdown', 1, 1));
|
||||
canvas.dispatchEvent(new Event('wheel'));
|
||||
assert.deepEqual(cameraInputs, ['pointerdown', 'wheel']);
|
||||
test("suspending turns Navara's controls off until the resume", () => {
|
||||
const { input, cameraOptions } = setup();
|
||||
const resume = input.suspendCameraInputs();
|
||||
canvas.dispatchEvent(pointer('pointerdown', 1, 1));
|
||||
assert.deepEqual(cameraInputs, ['pointerdown', 'wheel', 'pointerdown']);
|
||||
resume();
|
||||
assert.deepEqual(cameraOptions, [
|
||||
{ enableSpin: false, enableZoom: false, enableTilt: false },
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createNavaraInput } from './input.js';
|
||||
|
||||
function fakeCanvas() {
|
||||
const canvas = new EventTarget();
|
||||
canvas.getBoundingClientRect = () => ({ left: 100, top: 50 });
|
||||
canvas.listenerCount = 0;
|
||||
const add = canvas.addEventListener.bind(canvas);
|
||||
const remove = canvas.removeEventListener.bind(canvas);
|
||||
canvas.addEventListener = (...args) => {
|
||||
canvas.listenerCount++;
|
||||
add(...args);
|
||||
};
|
||||
canvas.removeEventListener = (...args) => {
|
||||
canvas.listenerCount--;
|
||||
remove(...args);
|
||||
};
|
||||
return canvas;
|
||||
}
|
||||
|
||||
const pointer = (type, x, y, extra = {}) =>
|
||||
Object.assign(new Event(type), {
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
button: 0,
|
||||
shiftKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
...extra,
|
||||
});
|
||||
|
||||
function setup() {
|
||||
const canvas = fakeCanvas();
|
||||
const cameraOptions = [];
|
||||
const view = {
|
||||
canvas,
|
||||
camera: {
|
||||
set options(value) {
|
||||
cameraOptions.push(value);
|
||||
},
|
||||
},
|
||||
};
|
||||
const { input, destroy } = createNavaraInput(view);
|
||||
return { canvas, input, destroy, cameraOptions };
|
||||
}
|
||||
|
||||
test('a pinch whose still finger lifts first is not a click', async () => {
|
||||
const { canvas, input, destroy } = setup();
|
||||
let clicks = 0;
|
||||
input.on('click', () => clicks++);
|
||||
const touch = (type, id, x, y) =>
|
||||
pointer(type, x, y, {
|
||||
pointerId: id,
|
||||
pointerType: 'touch',
|
||||
isPrimary: id === 1,
|
||||
});
|
||||
canvas.dispatchEvent(touch('pointerdown', 1, 100, 300));
|
||||
canvas.dispatchEvent(touch('pointerdown', 2, 300, 300));
|
||||
// Only the first finger moves (a one-sided pinch).
|
||||
for (let i = 1; i <= 5; i++)
|
||||
canvas.dispatchEvent(touch('pointermove', 1, 100 - 20 * i, 300));
|
||||
canvas.dispatchEvent(touch('pointerup', 2, 300, 300));
|
||||
canvas.dispatchEvent(touch('pointerup', 1, 0, 300));
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
assert.equal(clicks, 0);
|
||||
canvas.dispatchEvent(touch('pointerdown', 1, 100, 300));
|
||||
canvas.dispatchEvent(touch('pointercancel', 1, 100, 300));
|
||||
canvas.dispatchEvent(touch('pointerup', 1, 100, 300));
|
||||
await Promise.resolve();
|
||||
assert.equal(clicks, 0, 'a cancelled pointer cannot click');
|
||||
canvas.dispatchEvent(touch('pointerdown', 1, 100, 300));
|
||||
canvas.dispatchEvent(touch('pointerup', 1, 100, 300));
|
||||
await Promise.resolve();
|
||||
assert.equal(clicks, 1, 'the next single tap still clicks');
|
||||
destroy();
|
||||
});
|
||||
|
||||
test('a mouse released off the canvas does not hold back the next tap', async () => {
|
||||
const { canvas, input, destroy } = setup();
|
||||
let clicks = 0;
|
||||
input.on('click', () => clicks++);
|
||||
// The mouse goes down on the globe and up outside it.
|
||||
canvas.dispatchEvent(
|
||||
pointer('pointerdown', 100, 300, { pointerId: 1, isPrimary: true }),
|
||||
);
|
||||
canvas.dispatchEvent(
|
||||
pointer('pointerdown', 100, 300, {
|
||||
pointerId: 7,
|
||||
pointerType: 'touch',
|
||||
isPrimary: true,
|
||||
}),
|
||||
);
|
||||
canvas.dispatchEvent(
|
||||
pointer('pointerup', 100, 300, {
|
||||
pointerId: 7,
|
||||
pointerType: 'touch',
|
||||
isPrimary: true,
|
||||
}),
|
||||
);
|
||||
await Promise.resolve();
|
||||
assert.equal(clicks, 1);
|
||||
destroy();
|
||||
});
|
||||
@@ -13,9 +13,9 @@
|
||||
// - photoreal: Google 3D tiles with a browser key only (no server proxy),
|
||||
// with Google's logo and the tiles' own
|
||||
// copyright lines (creditLayerId) on screen. Showing them hides the base
|
||||
// imagery, as MapSourceController removes it; clearing them does not bring
|
||||
// it back until setBaseImagery. Hidden, not deleted: deleting the last
|
||||
// raster layer stops Navara 0.2.1 loading terrain at the current view.
|
||||
// imagery; clearing them restores the last base imagery and its credit.
|
||||
// Hidden, not deleted: deleting the last raster layer stops Navara 0.2.1
|
||||
// loading terrain at the current view.
|
||||
|
||||
import {
|
||||
SENTINEL2_CREDIT,
|
||||
@@ -124,6 +124,8 @@ export function createNavaraMaps(
|
||||
// call made last decides what shows.
|
||||
const generations = { display: 0, terrain: 0 };
|
||||
let destroyed = false;
|
||||
// maps.terrainRevision: one more for every terrain shown or cleared.
|
||||
let terrainRevision = 0;
|
||||
|
||||
function retire(slot) {
|
||||
if (!slot) return;
|
||||
@@ -137,6 +139,7 @@ export function createNavaraMaps(
|
||||
const slot = slots[name];
|
||||
slots[name] = null;
|
||||
retire(slot);
|
||||
if (name === 'terrain' && slot) terrainRevision++;
|
||||
}
|
||||
|
||||
// The new layer goes in before the old one goes: deleting the last raster
|
||||
@@ -150,6 +153,7 @@ export function createNavaraMaps(
|
||||
typeof credit === 'function' ? credit(layer) : credit,
|
||||
);
|
||||
retire(previous);
|
||||
if (name === 'terrain') terrainRevision++;
|
||||
if (shown.length) view.attribution?.add(shown);
|
||||
slots[name] = {
|
||||
key,
|
||||
@@ -204,6 +208,7 @@ export function createNavaraMaps(
|
||||
type: 'quantized-mesh',
|
||||
url: `${endpoint.url}{z}/{x}/{y}.terrain?v=1.2.0`,
|
||||
token: endpoint.accessToken,
|
||||
attributions: endpoint.attributions ?? [],
|
||||
};
|
||||
}
|
||||
default:
|
||||
@@ -249,7 +254,16 @@ export function createNavaraMaps(
|
||||
return;
|
||||
}
|
||||
if (slots.terrain?.key === description.url) return;
|
||||
show('terrain', description.url, description, { type: 'terrain' });
|
||||
const { attributions = [], ...sourceDesc } = description;
|
||||
show(
|
||||
'terrain',
|
||||
description.url,
|
||||
sourceDesc,
|
||||
{ type: 'terrain' },
|
||||
attributions.map(({ html }) => ({ attributionHtml: html })),
|
||||
);
|
||||
if (attributions.some(({ collapsible }) => collapsible === false))
|
||||
view.attribution?.show();
|
||||
},
|
||||
async setPhotorealTiles(source) {
|
||||
const generation = ++generations.display;
|
||||
@@ -329,10 +343,29 @@ export function createNavaraMaps(
|
||||
};
|
||||
},
|
||||
current: () => ({ baseImagery: currentBase, photoreal: tilesSource }),
|
||||
terrainRevision: () => terrainRevision,
|
||||
};
|
||||
|
||||
return {
|
||||
maps,
|
||||
/**
|
||||
* surface.sampleTerrainMostDetailed: the terrain shown sampled at its
|
||||
* finest level (Navara fetches the tiles); 0 on the ellipsoid.
|
||||
*/
|
||||
async sampleTerrain(positions) {
|
||||
const source = slots.terrain?.source;
|
||||
if (!source) return positions.map(() => 0);
|
||||
const sampled = await view.sampleTerrainMostDetailed(
|
||||
source,
|
||||
positions.map((place) => ({
|
||||
lat: (place.latitude * 180) / Math.PI,
|
||||
lng: (place.longitude * 180) / Math.PI,
|
||||
})),
|
||||
);
|
||||
return sampled.map(({ height }) =>
|
||||
Number.isFinite(height) ? height : undefined,
|
||||
);
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
|
||||
@@ -392,3 +392,49 @@ test('a tile overlay stays above the base imagery across map switches and credit
|
||||
remove();
|
||||
destroy();
|
||||
});
|
||||
|
||||
test('world terrain publishes endpoint credits and removes them on replacement', async () => {
|
||||
const view = fakeView();
|
||||
const { maps, destroy } = createNavaraMaps(view, {
|
||||
fetch: async () => ({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
url: 'https://terrain.example/',
|
||||
accessToken: 'temporary',
|
||||
attributions: [{ html: 'Terrain provider', collapsible: false }],
|
||||
}),
|
||||
}),
|
||||
});
|
||||
await maps.setTerrain({ kind: 'world', accessToken: 'configured' });
|
||||
assert.ok(
|
||||
view.shown.some((credit) => credit.attributionHtml === 'Terrain provider'),
|
||||
);
|
||||
assert.ok(view.opened > 0);
|
||||
await maps.setTerrain({ kind: 'ellipsoid' });
|
||||
assert.deepEqual(view.shown, []);
|
||||
destroy();
|
||||
});
|
||||
|
||||
test('terrainRevision counts terrain shown or cleared; sampling reads the shown source', async () => {
|
||||
const view = fakeView();
|
||||
const sampled = [];
|
||||
view.sampleTerrainMostDetailed = async (source, positions) => {
|
||||
sampled.push({ source, positions });
|
||||
return positions.map(({ lat, lng }) => ({ lat, lng, height: lat + lng }));
|
||||
};
|
||||
const navara = createNavaraMaps(view);
|
||||
const { maps } = navara;
|
||||
const place = { longitude: Math.PI / 4, latitude: Math.PI / 6, height: 0 };
|
||||
assert.deepEqual(await navara.sampleTerrain([place]), [0], 'the ellipsoid');
|
||||
await maps.setTerrain({ kind: 'keyless' });
|
||||
assert.equal(maps.terrainRevision(), 1);
|
||||
const [height] = await navara.sampleTerrain([place]);
|
||||
assert.ok(Math.abs(height - 75) < 1e-9);
|
||||
assert.equal(sampled[0].source, layersOf(view, 'terrain')[0].desc.source);
|
||||
await maps.setTerrain({ kind: 'keyless' });
|
||||
assert.equal(maps.terrainRevision(), 1, 'the same terrain again');
|
||||
await maps.setTerrain({ kind: 'ellipsoid' });
|
||||
assert.equal(maps.terrainRevision(), 2);
|
||||
await maps.setTerrain({ kind: 'ellipsoid' });
|
||||
assert.equal(maps.terrainRevision(), 2, 'nothing to clear');
|
||||
});
|
||||
@@ -130,6 +130,7 @@ export function createNavaraMovers(view, { overlay, aces = false }) {
|
||||
);
|
||||
return {
|
||||
ready: mover.ready,
|
||||
failed: mover.failed,
|
||||
commit() {
|
||||
mover.commit(store.dirty());
|
||||
request();
|
||||
@@ -168,6 +169,7 @@ export function createNavaraMovers(view, { overlay, aces = false }) {
|
||||
});
|
||||
return {
|
||||
ready: mover.ready,
|
||||
failed: mover.failed,
|
||||
pickRadiusPx: mover.pickRadiusPx,
|
||||
commit() {
|
||||
mover.commit(store.dirty());
|
||||
|
||||
@@ -199,10 +199,14 @@ export function createModelMover(
|
||||
};
|
||||
|
||||
const group = { meshes: [], pickMeshes: [], ready: null };
|
||||
let failed = false;
|
||||
const asset = load(model.url).catch(() => {
|
||||
// A missing asset keeps the layer's glyph fallback. Do not leak the
|
||||
// rejected loader promise (or its URL) through descriptor creation.
|
||||
if (!disposed) console.warn('[globe] Model asset unavailable');
|
||||
if (!disposed) {
|
||||
failed = true;
|
||||
console.warn('[globe] Model asset unavailable');
|
||||
}
|
||||
return null;
|
||||
});
|
||||
group.ready = asset.then((gltf) => {
|
||||
@@ -259,7 +263,6 @@ export function createModelMover(
|
||||
overlay.add(tint);
|
||||
}
|
||||
materials.push(material);
|
||||
if (tint) materials.push(tint.material);
|
||||
parts.push({ mesh, tint, local: child.matrixWorld.clone() });
|
||||
group.meshes.push(mesh);
|
||||
group.pickMeshes.push(tint ?? mesh);
|
||||
@@ -288,6 +291,7 @@ export function createModelMover(
|
||||
group,
|
||||
uniforms,
|
||||
ready: () => loaded,
|
||||
failed: () => failed,
|
||||
origin: () => origin,
|
||||
/**
|
||||
* The drawn radius (px) of an instance at its last write, or null when
|
||||
|
||||
@@ -204,6 +204,7 @@ test('a failed model load stays not-ready without an unhandled rejection or leak
|
||||
});
|
||||
await mover.group.ready;
|
||||
assert.equal(mover.ready(), false);
|
||||
assert.equal(mover.failed(), true);
|
||||
assert.equal(mover.group.meshes.length, 0);
|
||||
assert.deepEqual(warnings, ['[globe] Model asset unavailable']);
|
||||
mover.dispose();
|
||||
@@ -278,12 +279,21 @@ test('display tint shares transforms, preserves fade opacity and leaves no overl
|
||||
shader.fragmentShader,
|
||||
/mix\(gevLitSrgb, vGevColor.rgb, uGevBlend\)/,
|
||||
);
|
||||
assert.match(shader.vertexShader, /vGevSonarFactor = gevSonarFactor/);
|
||||
assert.match(shader.fragmentShader, /gevSonarColor\(vec4\(mix/);
|
||||
assert.equal(base.material.colorWrite, false);
|
||||
assert.equal(
|
||||
mover.group.pickMeshes[0],
|
||||
tint,
|
||||
'GPU picking keeps its color-writing material',
|
||||
);
|
||||
store.set(0, { color: [1, 1, 1, 1] });
|
||||
mover.commit(store.dirty());
|
||||
assert.equal(
|
||||
tint.material.transparent,
|
||||
true,
|
||||
'sonar can fade an opaque model',
|
||||
);
|
||||
store.setCount(0);
|
||||
mover.commit(store.dirty());
|
||||
assert.equal(tint.count, 0);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// the view's HDR effects. This keeps MSAA from spreading HDR tint into edges.
|
||||
import { InstancedMesh } from 'three';
|
||||
import { OVERLAY_DEPTH_FRAGMENT } from '../overlayDepth.js';
|
||||
import { DETACHED_SONAR, SONAR_VERTEX } from '../sonar.js';
|
||||
|
||||
// three's pinned ACESFilmicToneMapping, with the view's public exposure.
|
||||
const ACES = `
|
||||
@@ -18,6 +19,7 @@ vec3 gevModelAces(vec3 color) {
|
||||
|
||||
export function createModelTint(mesh, uniforms, overlayUniforms) {
|
||||
const material = mesh.material.clone();
|
||||
material.transparent = true;
|
||||
material.depthTest = false;
|
||||
material.depthWrite = false;
|
||||
material.toneMapped = false;
|
||||
@@ -25,22 +27,22 @@ export function createModelTint(mesh, uniforms, overlayUniforms) {
|
||||
? 'gl_FragColor.rgb'
|
||||
: 'gevModelAces(gl_FragColor.rgb)';
|
||||
material.onBeforeCompile = (shader) => {
|
||||
Object.assign(shader.uniforms, uniforms, overlayUniforms, {
|
||||
Object.assign(shader.uniforms, DETACHED_SONAR, uniforms, overlayUniforms, {
|
||||
uGevDepthMode: { value: 1 },
|
||||
});
|
||||
shader.vertexShader = shader.vertexShader
|
||||
.replace(
|
||||
'void main() {',
|
||||
'attribute vec4 gevColor;\nvarying vec4 vGevColor;\nvarying float vGevDepthFree;\nvoid main() {',
|
||||
`attribute vec4 gevColor;\nvarying vec4 vGevColor;\nvarying float vGevDepthFree;\nvarying float vGevSonarFactor;\nuniform vec2 uGevResolution;\n${SONAR_VERTEX}\nvoid main() {`,
|
||||
)
|
||||
.replace(
|
||||
'#include <begin_vertex>',
|
||||
'#include <begin_vertex>\nvGevColor = gevColor;\nvGevDepthFree = 0.0;',
|
||||
'#include <begin_vertex>\nvGevColor = gevColor;\nvGevDepthFree = 0.0;\nvGevSonarFactor = gevSonarFactor(projectionMatrix * modelViewMatrix * instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0), uGevResolution);',
|
||||
);
|
||||
shader.fragmentShader = shader.fragmentShader
|
||||
.replace(
|
||||
'void main() {',
|
||||
`uniform float uGevBlend;\nuniform float uGevAmbient;\nvarying vec4 vGevColor;\n${ACES}\n${OVERLAY_DEPTH_FRAGMENT}\nvoid main() {`,
|
||||
`uniform float uGevBlend;\nuniform float uGevAmbient;\nvarying vec4 vGevColor;\n${ACES}\nvarying float vGevSonarFactor;\n${SONAR_VERTEX}\n${OVERLAY_DEPTH_FRAGMENT}\nvoid main() {`,
|
||||
)
|
||||
.replace(
|
||||
'#include <logdepthbuf_fragment>',
|
||||
@@ -56,7 +58,7 @@ export function createModelTint(mesh, uniforms, overlayUniforms) {
|
||||
)
|
||||
.replace(
|
||||
'#include <opaque_fragment>',
|
||||
`#include <opaque_fragment>\nvec3 gevLitSrgb = sRGBTransferOETF(vec4(${lit}, 1.0)).rgb;\ngl_FragColor.rgb = sRGBTransferEOTF(vec4(mix(gevLitSrgb, vGevColor.rgb, uGevBlend), 1.0)).rgb;`,
|
||||
`#include <opaque_fragment>\nvec3 gevLitSrgb = sRGBTransferOETF(vec4(${lit}, 1.0)).rgb;\nvec4 gevContact = gevSonarColor(vec4(mix(gevLitSrgb, vGevColor.rgb, uGevBlend), gl_FragColor.a), vGevSonarFactor);\ngl_FragColor = vec4(sRGBTransferEOTF(gevContact).rgb, gevContact.a);`,
|
||||
);
|
||||
};
|
||||
material.customProgramCacheKey = () => 'gev-model-lit-display-color';
|
||||
|
||||
@@ -227,24 +227,28 @@ function cesiumSampling(texture, encoded = false) {
|
||||
}
|
||||
|
||||
/** The atlas as a three texture (a canvas at once, a URL once loaded). */
|
||||
function atlasTexture(atlas, encoded, onLoad) {
|
||||
function atlasTexture(atlas, encoded, onLoad, onError) {
|
||||
if (atlas.canvas)
|
||||
return cesiumSampling(new CanvasTexture(atlas.canvas), encoded);
|
||||
const texture = cesiumSampling(new Texture(), encoded);
|
||||
const image = new Image();
|
||||
image.crossOrigin = 'anonymous';
|
||||
const release = () => {
|
||||
image.onload = null;
|
||||
image.onload = image.onerror = null;
|
||||
texture.image = null;
|
||||
texture.removeEventListener('dispose', release);
|
||||
};
|
||||
texture.addEventListener('dispose', release);
|
||||
image.onload = () => {
|
||||
image.onload = null;
|
||||
image.onload = image.onerror = null;
|
||||
texture.image = image;
|
||||
texture.needsUpdate = true;
|
||||
onLoad();
|
||||
};
|
||||
image.onerror = () => {
|
||||
image.onload = image.onerror = null;
|
||||
onError();
|
||||
};
|
||||
image.src = atlas.url;
|
||||
return texture;
|
||||
}
|
||||
@@ -313,14 +317,22 @@ export function createMoverMesh(
|
||||
};
|
||||
// A canvas atlas is there at once; a URL one once its image loads.
|
||||
let textureReady = point || Boolean(options.sprite.atlas.canvas);
|
||||
let textureFailed = false;
|
||||
const encodedAtlas = !point && options.sharpen === true;
|
||||
const material = new MeshBasicMaterial({
|
||||
map: point
|
||||
? null
|
||||
: atlasTexture(options.sprite.atlas, encodedAtlas, () => {
|
||||
textureReady = true;
|
||||
onTextureLoad();
|
||||
}),
|
||||
: atlasTexture(
|
||||
options.sprite.atlas,
|
||||
encodedAtlas,
|
||||
() => {
|
||||
textureReady = true;
|
||||
onTextureLoad();
|
||||
},
|
||||
() => {
|
||||
textureFailed = true;
|
||||
},
|
||||
),
|
||||
transparent: true,
|
||||
alphaTest: point || encodedAtlas ? 0.005 : 0.02,
|
||||
// Drawn after tone mapping, with no depth buffer: the shader tests the
|
||||
@@ -382,6 +394,7 @@ export function createMoverMesh(
|
||||
mesh,
|
||||
uniforms,
|
||||
ready: () => textureReady,
|
||||
failed: () => textureFailed,
|
||||
origin: () => origin,
|
||||
/** Writes the changed instances; the origin starts at the first one. */
|
||||
commit(range) {
|
||||
|
||||
@@ -165,6 +165,17 @@ export class GevOverlayPass extends Pass {
|
||||
resolution[0],
|
||||
resolution[1],
|
||||
);
|
||||
if (signature) {
|
||||
// The sonar's uniforms change the glyphs only while it applies; its
|
||||
// angle moves every frame even then, so it is left out otherwise.
|
||||
const uniforms = this.overlay.uniforms;
|
||||
const enabled = uniforms.uGevSonarEnabled?.value >= 0.5;
|
||||
const [angle, range, floor, active] = uniforms.uGevSonar?.value ?? [];
|
||||
signature.push(enabled);
|
||||
if (enabled) signature.push(floor, active);
|
||||
if (enabled && active >= 0.5)
|
||||
signature.push(angle, range, uniforms.uGevSonarSector?.value);
|
||||
}
|
||||
const targetWidth = resolution[0];
|
||||
const targetHeight = resolution[1];
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
Scene,
|
||||
PerspectiveCamera,
|
||||
HalfFloatType,
|
||||
NoColorSpace,
|
||||
SRGBColorSpace,
|
||||
InstancedMesh,
|
||||
MeshBasicMaterial,
|
||||
PlaneGeometry,
|
||||
Texture,
|
||||
} from 'three';
|
||||
import { GevOverlayPass } from './overlayPass.js';
|
||||
|
||||
function harness() {
|
||||
let active = false,
|
||||
target = null,
|
||||
clearColor = 0x123456,
|
||||
clearAlpha = 1;
|
||||
const overlay = {
|
||||
displayBlend: true,
|
||||
hasDrawables: () => active,
|
||||
uniforms: {
|
||||
uGevResolution: { value: [0, 0] },
|
||||
uGevDisplayBlend: { value: 0 },
|
||||
uGevSonar: { value: [0, 1, 0.84, 1] },
|
||||
uGevSonarSector: { value: 24 },
|
||||
uGevSonarEnabled: { value: 1 },
|
||||
},
|
||||
};
|
||||
const scene = new Scene(),
|
||||
pass = new GevOverlayPass(scene, new PerspectiveCamera(), overlay),
|
||||
draws = [];
|
||||
const renderer = {
|
||||
domElement: new EventTarget(),
|
||||
autoClear: true,
|
||||
outputColorSpace: SRGBColorSpace,
|
||||
getPixelRatio: () => 1,
|
||||
getClearColor(color) {
|
||||
return color.set(clearColor);
|
||||
},
|
||||
getClearAlpha() {
|
||||
return clearAlpha;
|
||||
},
|
||||
setClearColor(color, alpha) {
|
||||
clearColor = color.isColor ? color.getHex() : color;
|
||||
clearAlpha = alpha;
|
||||
},
|
||||
clear() {},
|
||||
get clearAlpha() {
|
||||
return clearAlpha;
|
||||
},
|
||||
setRenderTarget(value) {
|
||||
target = value;
|
||||
},
|
||||
render(object) {
|
||||
draws.push({
|
||||
object,
|
||||
target,
|
||||
displayBlend: overlay.uniforms.uGevDisplayBlend.value,
|
||||
});
|
||||
},
|
||||
};
|
||||
return {
|
||||
overlay,
|
||||
scene,
|
||||
pass,
|
||||
draws,
|
||||
renderer,
|
||||
setActive(value) {
|
||||
active = value;
|
||||
},
|
||||
get target() {
|
||||
return target;
|
||||
},
|
||||
};
|
||||
}
|
||||
test('static sprite glyphs are drawn again when the Cyber sonar moves', () => {
|
||||
const h = harness(),
|
||||
input = { width: 1280, height: 800, texture: {} },
|
||||
output = {},
|
||||
mesh = new InstancedMesh(
|
||||
new PlaneGeometry(1, 1),
|
||||
new MeshBasicMaterial({ map: new Texture() }),
|
||||
1,
|
||||
);
|
||||
mesh.userData.gevStaticSprite = true;
|
||||
mesh.count = 1;
|
||||
h.scene.add(mesh);
|
||||
h.setActive(true);
|
||||
h.pass.render(h.renderer, input, output);
|
||||
const drawn = () => h.draws.filter((draw) => draw.object === h.scene).length;
|
||||
assert.equal(drawn(), 1);
|
||||
// The sweep turns (sonar.js writes the shared uniform each frame).
|
||||
h.overlay.uniforms.uGevSonar.value[0] = 90;
|
||||
h.pass.render(h.renderer, input, output);
|
||||
assert.equal(drawn(), 2, 'a new sonar angle draws the glyphs again');
|
||||
h.overlay.uniforms.uGevSonarSector.value = 60;
|
||||
h.pass.render(h.renderer, input, output);
|
||||
assert.equal(drawn(), 3, 'a new sector draws the glyphs again');
|
||||
// The Cyber treatment is turned off.
|
||||
h.overlay.uniforms.uGevSonarEnabled.value = 0;
|
||||
h.pass.render(h.renderer, input, output);
|
||||
assert.equal(drawn(), 4, 'sonar off draws the glyphs again');
|
||||
// Off, the angle still moves every frame; the glyphs stay cached.
|
||||
h.overlay.uniforms.uGevSonar.value[0] = 180;
|
||||
h.pass.render(h.renderer, input, output);
|
||||
assert.equal(drawn(), 4, 'the angle of an unused sonar draws nothing');
|
||||
});
|
||||
@@ -9,7 +9,7 @@
|
||||
// colour pulled toward the scanner tint by that factor and its alpha scaled
|
||||
// by it.
|
||||
// Positions, picks and the instance data stay as the layers set them.
|
||||
// Models keep their colours (Cesium tints them on the CPU).
|
||||
// Models apply the same treatment after lighting (movers/modelTint.js).
|
||||
|
||||
const views = new WeakMap();
|
||||
|
||||
|
||||
@@ -234,9 +234,15 @@ const tileSizeOf = (root) => {
|
||||
* isIdle: () => boolean,
|
||||
* retainTileGeometry: () => void,
|
||||
* }} hooks Navara internals (internals.js).
|
||||
* @param {(positions: object[]) => Promise<(number | undefined)[]>} [sampleTerrain]
|
||||
* The maps' sampling of the terrain shown (maps.js).
|
||||
* @returns {{ surface: import('../contract.js').GlobeSurface }}
|
||||
*/
|
||||
export function createNavaraSurface(view, hooks) {
|
||||
export function createNavaraSurface(
|
||||
view,
|
||||
hooks,
|
||||
sampleTerrain = async (positions) => positions.map(() => 0),
|
||||
) {
|
||||
let supported = true;
|
||||
try {
|
||||
hooks.retainTileGeometry();
|
||||
@@ -342,6 +348,7 @@ export function createNavaraSurface(view, hooks) {
|
||||
supported,
|
||||
terrainHeight,
|
||||
terrainHeightSupported: true,
|
||||
sampleTerrainMostDetailed: (positions) => sampleTerrain(positions),
|
||||
clampToHeight(position, exclude) {
|
||||
const place = cartographic.fromCartesian(position, WGS84);
|
||||
if (!place) return undefined;
|
||||
|
||||
Reference in new issue
Block a user