mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 10:12:18 +00:00
Draw transit vehicles through the renderer ports, off the Cesium list
Transit drew its vehicles into two Cesium billboard collections and culled, turned and floored them through the Cesium scene. It now draws them as two draw-port icon sets, still and moving, registered with the sprite order by set id in the same places. Each marker is a plain record; a frame writes the changed ones in one upsert per set, and markers taken out in one task go in one removal. Clicks read the draw-port hit. Visibility uses the query port's horizon test and the frustum planes of the camera port's pose. Icons stay turned in screen space by an exact projection through the query port, the same answer the Cesium helper gave. The flat globe is told from terrain by asking the height service once per surface change; floors are read again when the answer flips. The mesh floor sampler sees through the layer's sets by id. The camera pose and surface version are read once per task. The Cesium draw port now moves and turns an icon without restyling it. The GL upload probe moves to src/render/cesium/uploadProbe.js, which the QA scripts hand to the frame probe; the QA scripts read the billboards drawn for each set.
This commit is contained in:
1 parent
00ae80908c
commit
347427f83d
24 files changed
+1618
-452
No files matched your search
+452
-231
@@ -1,14 +1,16 @@
|
||||
import * as Cesium from 'cesium';
|
||||
// The Cesium camera factory: given a viewer of a caller's own, with no
|
||||
// renderer bound, the layer's camera reads find a camera port.
|
||||
import '../../render/cesium/camera.js';
|
||||
import '../../render/cesium/frame.js';
|
||||
import { webglContext } from '../../render/cesium/internals.js';
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import {
|
||||
cameraPoseSignature,
|
||||
perspectiveProjectedRotation,
|
||||
} from '../../render/cesium/iconOrientation.js';
|
||||
canvasOf,
|
||||
drawOf,
|
||||
findCamera,
|
||||
findFrame,
|
||||
findGlobe,
|
||||
findQuery,
|
||||
} from '../../render/rendererOf.js';
|
||||
import { poseSignature } from '../../render/camera/poseSignature.js';
|
||||
import { heightsOf } from '../../queries/heights.js';
|
||||
import { fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { frustumPlanes } from '../../geo/frustum.js';
|
||||
import { perspectiveCourseRotation } from '../../data/screenRotation.js';
|
||||
import {
|
||||
updatePlayback,
|
||||
applyDisplayCourse,
|
||||
@@ -35,15 +37,22 @@ import {
|
||||
vehicleNearView,
|
||||
} from './policy.js';
|
||||
|
||||
export const MODE_CESIUM_COLORS = Object.fromEntries(
|
||||
Object.entries(TRANSIT_MODE_COLORS).map(([mode, css]) => [
|
||||
mode,
|
||||
Cesium.Color.fromCssColorString(css),
|
||||
]),
|
||||
);
|
||||
/** Layers built so far, so each one's draw sets have ids of their own. */
|
||||
let instances = 0;
|
||||
|
||||
/** Radius, metres, of the sphere a vehicle is culled by. */
|
||||
const CULL_RADIUS_M = 5;
|
||||
|
||||
/**
|
||||
* Billboards and the per-frame glide.
|
||||
* Markers and the per-frame glide.
|
||||
*
|
||||
* Each vehicle's marker is a plain record (`entry.marker`: its position,
|
||||
* whether it shows, its image, size, colour and screen rotation) drawn as
|
||||
* an icon in one of two draw sets: the still one, or the moving one while
|
||||
* it glides or turns, so a fleet at rest is not rewritten with the few
|
||||
* that move. Changed markers are pushed to their sets once per frame (and
|
||||
* once per visibility sweep), each with the one item object it keeps:
|
||||
* a frame pass over a moving fleet allocates nothing per vehicle.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
@@ -56,69 +65,211 @@ export function createRendering({ state, services, parts }) {
|
||||
// The application's rendered-mesh sampler. Optional so a layer built on a
|
||||
// bare floor stub still runs; the application always supplies it.
|
||||
const sampleMeshFloorCells = services.mesh?.sampleMeshFloorCells || null;
|
||||
const instance = (instances += 1);
|
||||
|
||||
/** Markers changed since they were last pushed to their sets. */
|
||||
const dirty = new Set();
|
||||
// Kept between pushes, so a push allocates no lists.
|
||||
const stillUpserts = [];
|
||||
const movingUpserts = [];
|
||||
const stillRemovals = [];
|
||||
const movingRemovals = [];
|
||||
|
||||
/**
|
||||
* The two billboard collections, still and moving, added to the scene and
|
||||
* to the shared sprite order, hidden.
|
||||
* The two icon sets, still and moving, hidden, in the scene now (with no
|
||||
* items) and in the shared sprite order. A viewer of the layer's own
|
||||
* draws through `./render/cesium/unbound`, which its owner loads.
|
||||
* @param {object} viewer
|
||||
*/
|
||||
function createMarkers(viewer) {
|
||||
state._markers = new Cesium.BillboardCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
destroyMarkers(viewer);
|
||||
const draw = drawOf(viewer);
|
||||
state._stillIcons = draw.icons({
|
||||
id: `transit:${instance}:still`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
});
|
||||
viewer.scene.primitives.add(state._markers);
|
||||
services.sprites.registerSpriteCollection('transit', state._markers);
|
||||
state._animatedMarkers = new Cesium.BillboardCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
state._movingIcons = draw.icons({
|
||||
id: `transit:${instance}:moving`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
});
|
||||
viewer.scene.primitives.add(state._animatedMarkers);
|
||||
services.sprites.registerSpriteCollection(
|
||||
// Emptied, they are drawn now: the sprite order finds them at once.
|
||||
state._stillIcons.set([]);
|
||||
state._movingIcons.set([]);
|
||||
const { registerSpriteSet } = services.sprites;
|
||||
state._stillSprite = registerSpriteSet?.('transit', state._stillIcons.id);
|
||||
state._movingSprite = registerSpriteSet?.(
|
||||
'transit-motion',
|
||||
state._animatedMarkers,
|
||||
state._movingIcons.id,
|
||||
);
|
||||
state._animatedMarkers.show = false;
|
||||
state._markers.show = false;
|
||||
state._markersShown = false;
|
||||
}
|
||||
|
||||
/** Show both collections. */
|
||||
/** Show both sets. */
|
||||
function showMarkers() {
|
||||
state._markers.show = true;
|
||||
state._animatedMarkers.show = true;
|
||||
if (!state._stillIcons) return;
|
||||
state._stillIcons.show = true;
|
||||
state._movingIcons.show = true;
|
||||
state._markersShown = true;
|
||||
}
|
||||
|
||||
/** Drop every billboard and hide both collections. */
|
||||
/** Drop every marker and hide both sets. */
|
||||
function clearMarkers() {
|
||||
state._markers?.removeAll();
|
||||
state._animatedMarkers?.removeAll();
|
||||
if (state._animatedMarkers) state._animatedMarkers.show = false;
|
||||
if (state._markers) state._markers.show = false;
|
||||
dirty.clear();
|
||||
stillRemovals.length = 0;
|
||||
movingRemovals.length = 0;
|
||||
state._stillIcons?.clear();
|
||||
state._movingIcons?.clear();
|
||||
if (state._movingIcons) state._movingIcons.show = false;
|
||||
if (state._stillIcons) state._stillIcons.show = false;
|
||||
state._markersShown = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Take both collections off the scene and out of the sprite order.
|
||||
* @param {object|null|undefined} viewer
|
||||
* Let both sets go and take them out of the sprite order.
|
||||
* @param {object|null|undefined} _viewer
|
||||
*/
|
||||
function destroyMarkers(viewer) {
|
||||
if (state._markers) {
|
||||
services.sprites.unregisterSpriteCollection('transit', state._markers);
|
||||
viewer?.scene?.primitives?.remove(state._markers);
|
||||
state._markers = null;
|
||||
function destroyMarkers(_viewer) {
|
||||
dirty.clear();
|
||||
stillRemovals.length = 0;
|
||||
movingRemovals.length = 0;
|
||||
const { unregisterSpriteCollection } = services.sprites;
|
||||
if (state._stillIcons) {
|
||||
if (state._stillSprite)
|
||||
unregisterSpriteCollection?.('transit', state._stillSprite);
|
||||
state._stillIcons.dispose();
|
||||
state._stillIcons = null;
|
||||
state._stillSprite = null;
|
||||
}
|
||||
if (state._animatedMarkers) {
|
||||
services.sprites.unregisterSpriteCollection(
|
||||
'transit-motion',
|
||||
state._animatedMarkers,
|
||||
);
|
||||
viewer?.scene?.primitives?.remove(state._animatedMarkers);
|
||||
state._animatedMarkers = null;
|
||||
if (state._movingIcons) {
|
||||
if (state._movingSprite)
|
||||
unregisterSpriteCollection?.('transit-motion', state._movingSprite);
|
||||
state._movingIcons.dispose();
|
||||
state._movingIcons = null;
|
||||
state._movingSprite = null;
|
||||
}
|
||||
state._markersShown = false;
|
||||
}
|
||||
|
||||
/** Whether a vehicle's billboard is shown. */
|
||||
/** The ids of both sets (for the frame probe and floor sampling). */
|
||||
function setIds() {
|
||||
return [state._stillIcons?.id, state._movingIcons?.id].filter(Boolean);
|
||||
}
|
||||
|
||||
/** Whether `setId` is one of this layer's sets. */
|
||||
function ownsSet(setId) {
|
||||
return (
|
||||
typeof setId === 'string' &&
|
||||
(setId === state._stillIcons?.id || setId === state._movingIcons?.id)
|
||||
);
|
||||
}
|
||||
|
||||
/** Which of the sets a draw set id is: `'moving'`, `'still'` or null. */
|
||||
function setNameOf(setId) {
|
||||
if (setId && setId === state._movingIcons?.id) return 'moving';
|
||||
if (setId && setId === state._stillIcons?.id) return 'still';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether a vehicle's marker is shown. */
|
||||
function markerShown(entry) {
|
||||
return entry.marker?.show === true;
|
||||
}
|
||||
|
||||
/** Note that a marker changed, for the next push. */
|
||||
function markDirty(entry) {
|
||||
if (entry.marker) dirty.add(entry);
|
||||
}
|
||||
|
||||
/** Show or hide a marker. */
|
||||
function setShown(entry, shown) {
|
||||
if (entry.marker.show === shown) return;
|
||||
entry.marker.show = shown;
|
||||
dirty.add(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* The icon item a marker draws as: the one item object the vehicle
|
||||
* keeps, brought up to date. Its position is the marker's own, which the
|
||||
* frame pass moves in place; the renderer reads positions as they are
|
||||
* when pushed.
|
||||
*/
|
||||
function itemOf(entry) {
|
||||
const marker = entry.marker;
|
||||
const item = (entry.iconItem ||= {
|
||||
id: entry.key,
|
||||
pos: marker.position,
|
||||
image: marker.image,
|
||||
size: [0, 0],
|
||||
color: marker.color,
|
||||
rotationMode: 'screen',
|
||||
rotation: 0,
|
||||
show: false,
|
||||
disableDepthTest: Infinity,
|
||||
meta: { layer: 'transit', key: entry.key },
|
||||
});
|
||||
item.pos = marker.position;
|
||||
item.image = marker.image;
|
||||
item.size[0] = marker.width;
|
||||
item.size[1] = marker.height;
|
||||
item.color = marker.color;
|
||||
item.rotation = marker.rotation;
|
||||
item.show = marker.show;
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push the markers changed since the last push to their sets: a marker
|
||||
* that changed set leaves the one it was in first.
|
||||
*/
|
||||
function flushMarkers() {
|
||||
const still = state._stillIcons;
|
||||
const moving = state._movingIcons;
|
||||
if (!still || !moving) return;
|
||||
if (!dirty.size && !stillRemovals.length && !movingRemovals.length) return;
|
||||
for (const entry of dirty) {
|
||||
if (!entry.marker) continue;
|
||||
const target = entry.animated ? moving : still;
|
||||
if (entry.drawnIn && entry.drawnIn !== target)
|
||||
(entry.drawnIn === still ? stillRemovals : movingRemovals).push(
|
||||
entry.key,
|
||||
);
|
||||
entry.drawnIn = target;
|
||||
(target === still ? stillUpserts : movingUpserts).push(itemOf(entry));
|
||||
}
|
||||
dirty.clear();
|
||||
if (stillRemovals.length) still.remove(stillRemovals);
|
||||
if (movingRemovals.length) moving.remove(movingRemovals);
|
||||
if (stillUpserts.length) still.upsert(stillUpserts);
|
||||
if (movingUpserts.length) moving.upsert(movingUpserts);
|
||||
stillRemovals.length = 0;
|
||||
movingRemovals.length = 0;
|
||||
stillUpserts.length = 0;
|
||||
movingUpserts.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Take a vehicle's marker out of the set it is drawn in: with the others
|
||||
* taken out in this task, in one removal (a sweep drops many at once).
|
||||
*/
|
||||
let flushQueued = false;
|
||||
function removeMarker(entry) {
|
||||
dirty.delete(entry);
|
||||
const set = entry.drawnIn;
|
||||
entry.drawnIn = null;
|
||||
if (!set) return;
|
||||
if (set === state._stillIcons) stillRemovals.push(entry.key);
|
||||
else if (set === state._movingIcons) movingRemovals.push(entry.key);
|
||||
else return;
|
||||
if (flushQueued) return;
|
||||
flushQueued = true;
|
||||
queueMicrotask(() => {
|
||||
flushQueued = false;
|
||||
flushMarkers();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for the camera moving, at this layer's own threshold.
|
||||
*
|
||||
@@ -159,7 +310,7 @@ export function createRendering({ state, services, parts }) {
|
||||
function startFrames(viewer) {
|
||||
if (!state._preRenderRemove)
|
||||
state._preRenderRemove =
|
||||
viewer.scene.preRender.addEventListener(onPreRender);
|
||||
findFrame(viewer)?.on('preRender', onPreRender) ?? null;
|
||||
}
|
||||
|
||||
/** Stop the per-frame glide. */
|
||||
@@ -170,23 +321,91 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
}
|
||||
|
||||
// The camera's pose and the globe's surface version, read once in a task:
|
||||
// a sweep, a frame or a poll asks for them per vehicle, and reading them
|
||||
// walks the camera's frames and the scene's primitives. Forgotten when the
|
||||
// task ends, and at the start of every frame and visibility sweep.
|
||||
let viewMemo = null;
|
||||
let viewMemoQueued = false;
|
||||
function forgetView() {
|
||||
viewMemo = null;
|
||||
}
|
||||
function viewOf() {
|
||||
if (viewMemo) return viewMemo;
|
||||
viewMemo = { pose: undefined, surface: undefined };
|
||||
if (!viewMemoQueued) {
|
||||
viewMemoQueued = true;
|
||||
queueMicrotask(() => {
|
||||
viewMemoQueued = false;
|
||||
viewMemo = null;
|
||||
});
|
||||
}
|
||||
return viewMemo;
|
||||
}
|
||||
|
||||
/** The camera port's pose, or null without a camera. */
|
||||
function cameraPose() {
|
||||
const view = viewOf();
|
||||
if (view.pose === undefined)
|
||||
view.pose = findCamera(state._viewer)?.pose() ?? null;
|
||||
return view.pose;
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera's height above the ellipsoid, or Infinity when it has none.
|
||||
* @returns {number}
|
||||
*/
|
||||
function cameraHeightM() {
|
||||
const carto = state._viewer?.camera?.positionCartographic;
|
||||
return carto && Number.isFinite(carto.height) ? carto.height : Infinity;
|
||||
const height = cameraPose()?.height;
|
||||
return Number.isFinite(height) ? height : Infinity;
|
||||
}
|
||||
|
||||
/** The camera's subpoint in degrees, for the sampler's proximity gate. */
|
||||
function viewerSubpoint() {
|
||||
const carto = state._viewer?.camera?.positionCartographic;
|
||||
if (!carto) return { viewerLat: undefined, viewerLon: undefined };
|
||||
return {
|
||||
viewerLat: (carto.latitude * 180) / Math.PI,
|
||||
viewerLon: (carto.longitude * 180) / Math.PI,
|
||||
const pose = cameraPose();
|
||||
if (!pose) return { viewerLat: undefined, viewerLon: undefined };
|
||||
return { viewerLat: pose.lat, viewerLon: pose.lon };
|
||||
}
|
||||
|
||||
// Whether the globe's terrain is the bare ellipsoid, as the height service
|
||||
// last said for the surface `surfaceVersion` names; asked again whenever
|
||||
// that changes, keeping the last answer until the new one comes. A terrain
|
||||
// height that is only the ellipsoid's is one the service counts as a miss
|
||||
// when asked to, so the ellipsoid is the point answered plainly and missed
|
||||
// that way.
|
||||
let flatVersion = null;
|
||||
let flatTerrain = false;
|
||||
function askFlat(globe) {
|
||||
const view = viewOf();
|
||||
if (view.surface === undefined)
|
||||
view.surface = globe.surfaceVersion?.() ?? 0;
|
||||
const version = view.surface;
|
||||
if (version === flatVersion) return;
|
||||
flatVersion = version;
|
||||
const pose = cameraPose();
|
||||
const point = {
|
||||
lon: Number.isFinite(pose?.lon) ? pose.lon : 0,
|
||||
lat: Number.isFinite(pose?.lat) ? pose.lat : 0,
|
||||
};
|
||||
const heights = heightsOf(state._viewer);
|
||||
Promise.all([
|
||||
heights.batch([point], { against: 'terrain' }),
|
||||
heights.batch([point], { against: 'terrain', ellipsoidMisses: true }),
|
||||
]).then(
|
||||
([[answered], [terrain]]) => {
|
||||
if (flatVersion !== version) return;
|
||||
const flat = answered !== null && terrain === null;
|
||||
if (flat === flatTerrain) return;
|
||||
flatTerrain = flat;
|
||||
// Floors read under the last answer are read again under this one,
|
||||
// in a fresh cycle (which replaces the one pending).
|
||||
if (state._enabled) parts.height.anchorFloors?.();
|
||||
},
|
||||
() => {
|
||||
// Asked again at the next read.
|
||||
if (flatVersion === version) flatVersion = null;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,44 +414,36 @@ export function createRendering({ state, services, parts }) {
|
||||
* @returns {'none'|'flat'|'terrain'}
|
||||
*/
|
||||
function globeSurface() {
|
||||
if (state._viewer?.scene?.globe?.show !== true) return 'none';
|
||||
return state._viewer?.terrainProvider instanceof
|
||||
Cesium.EllipsoidTerrainProvider
|
||||
? 'flat'
|
||||
: 'terrain';
|
||||
const globe = findGlobe(state._viewer);
|
||||
if (globe?.isGlobeVisible?.() !== true) return 'none';
|
||||
askFlat(globe);
|
||||
return flatTerrain ? 'flat' : 'terrain';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample the rendered mesh under floor cells, seeing through these
|
||||
* vehicles' billboards.
|
||||
* Sample the rendered mesh under floor cells, seeing through this layer's
|
||||
* own sets.
|
||||
* @param {object[]} cells
|
||||
* @param {object[]} entries
|
||||
*/
|
||||
function sampleMeshFloors(cells, entries) {
|
||||
function sampleMeshFloors(cells) {
|
||||
if (!sampleMeshFloorCells) return;
|
||||
const markers = entries.map((entry) => entry.marker).filter(Boolean);
|
||||
const sets = setIds();
|
||||
for (let i = 0; i < cells.length; i += 8)
|
||||
sampleMeshFloorCells(state._viewer?.scene, cells.slice(i, i + 8), {
|
||||
excludeObjects: markers,
|
||||
sampleMeshFloorCells(state._viewer, cells.slice(i, i + 8), {
|
||||
sets,
|
||||
...viewerSubpoint(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Cartesian position for a lat/lon at a height. Called on POLL, not per
|
||||
* frame: `fromDegrees` runs trigonometry, and doing that for every vehicle on
|
||||
* ECEF position for a lat/lon at a height. Called on POLL, not per frame:
|
||||
* the conversion runs trigonometry, and doing that for every vehicle on
|
||||
* every frame was most of what made this layer heavy.
|
||||
*/
|
||||
function cartesianFor(lat, lon, heightM, out) {
|
||||
function cartesianFor(lat, lon, heightM, out = { x: 0, y: 0, z: 0 }) {
|
||||
// `heightM` already carries the shared floor's own lift, so nothing is
|
||||
// added here: two lifts stacked is a vehicle hovering.
|
||||
return Cesium.Cartesian3.fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
heightM || 0,
|
||||
undefined,
|
||||
out,
|
||||
);
|
||||
return fromDegreesInto(lon, lat, heightM || 0, out);
|
||||
}
|
||||
|
||||
/** Heights are aligned to work with Google 3D tiles. Rebuild both ends. */
|
||||
@@ -244,13 +455,13 @@ export function createRendering({ state, services, parts }) {
|
||||
entry.from.lat,
|
||||
entry.from.lon,
|
||||
entry.from.h,
|
||||
entry.fromCart || new Cesium.Cartesian3(),
|
||||
entry.fromCart || { x: 0, y: 0, z: 0 },
|
||||
);
|
||||
entry.toCart = cartesianFor(
|
||||
entry.to.lat,
|
||||
entry.to.lon,
|
||||
entry.to.h,
|
||||
entry.toCart || new Cesium.Cartesian3(),
|
||||
entry.toCart || { x: 0, y: 0, z: 0 },
|
||||
);
|
||||
entry.endpointRevision = entry.sample.revision;
|
||||
entry.endpointFromSeq = entry.sample.fromSeq;
|
||||
@@ -271,9 +482,16 @@ export function createRendering({ state, services, parts }) {
|
||||
);
|
||||
entry.surfaceReady = !!known;
|
||||
entry.heightPending = !known;
|
||||
entry.marker.show = !!known && vehicleInView(entry);
|
||||
setShown(entry, !!known && vehicleInView(entry));
|
||||
if (known) {
|
||||
entry.marker.position = state._scratchCartesian;
|
||||
const p = entry.marker.position;
|
||||
const s = state._scratchCartesian;
|
||||
if (p.x !== s.x || p.y !== s.y || p.z !== s.z) {
|
||||
p.x = s.x;
|
||||
p.y = s.y;
|
||||
p.z = s.z;
|
||||
dirty.add(entry);
|
||||
}
|
||||
entry.hasRendered = true;
|
||||
}
|
||||
}
|
||||
@@ -288,29 +506,12 @@ export function createRendering({ state, services, parts }) {
|
||||
if (entry.wakeTimer != null) clearTimeout(entry.wakeTimer);
|
||||
entry.wakeTimer = null;
|
||||
}
|
||||
/** Draw a marker in the moving set, or the still one. */
|
||||
function migrateMarker(entry, animated) {
|
||||
const collection = animated ? state._animatedMarkers : state._markers;
|
||||
if (!entry.marker || entry.markerCollection === collection) return;
|
||||
const old = entry.marker;
|
||||
const marker = collection.add({
|
||||
id: entry.key,
|
||||
position: old.position,
|
||||
image: old.image,
|
||||
width: old.width,
|
||||
height: old.height,
|
||||
color: old.color,
|
||||
scaleByDistance: old.scaleByDistance,
|
||||
rotation: old.rotation,
|
||||
alignedAxis: old.alignedAxis,
|
||||
show: old.show,
|
||||
disableDepthTestDistance: old.disableDepthTestDistance,
|
||||
});
|
||||
entry.markerCollection.remove(old);
|
||||
entry.marker = marker;
|
||||
entry.markerCollection = collection;
|
||||
if (!entry.marker || entry.animated === animated) return;
|
||||
entry.animated = animated;
|
||||
entry.markerRevision = (entry.markerRevision || 0) + 1;
|
||||
// Cached contacts and card getters must follow the replacement billboard.
|
||||
if (entry.detectContact) entry.detectContact.position = marker.position;
|
||||
dirty.add(entry);
|
||||
}
|
||||
function schedulePlayback(entry) {
|
||||
cancelWake(entry);
|
||||
@@ -346,6 +547,7 @@ export function createRendering({ state, services, parts }) {
|
||||
updatePlayback(entry, Date.now(), performance.now());
|
||||
placeSample(entry);
|
||||
schedulePlayback(entry);
|
||||
flushMarkers();
|
||||
syncRenderHold();
|
||||
governorRequestRender('transit-motion-boundary');
|
||||
},
|
||||
@@ -365,7 +567,7 @@ export function createRendering({ state, services, parts }) {
|
||||
return state._visible.has(entry);
|
||||
}
|
||||
|
||||
/** Cesium colour for a preset tuple, cached per profile+mode. */
|
||||
/** A preset tuple as a colour (0..1 channels), cached per profile+mode. */
|
||||
const _presetColors = new Map();
|
||||
function presetColor(style, mode) {
|
||||
const rgba = presetSpriteRgba(style, mode);
|
||||
@@ -373,12 +575,12 @@ export function createRendering({ state, services, parts }) {
|
||||
const key = `${transitStyleProfile(style)}:${mode}`;
|
||||
let color = _presetColors.get(key);
|
||||
if (!color) {
|
||||
color = new Cesium.Color(
|
||||
color = Object.freeze([
|
||||
rgba[0] / 255,
|
||||
rgba[1] / 255,
|
||||
rgba[2] / 255,
|
||||
rgba[3],
|
||||
);
|
||||
]);
|
||||
_presetColors.set(key, color);
|
||||
}
|
||||
return color;
|
||||
@@ -416,28 +618,27 @@ export function createRendering({ state, services, parts }) {
|
||||
entry.detectContact.bracketHalfWidth = Math.ceil(px / 2) + 2;
|
||||
entry.detectContact.bracketHalfHeight = Math.ceil(px / 2) + 2;
|
||||
}
|
||||
const preset = presetColor(style, entry.mode);
|
||||
if (preset) marker.color = preset;
|
||||
else
|
||||
marker.color =
|
||||
MODE_CESIUM_COLORS[entry.mode] || MODE_CESIUM_COLORS.unknown;
|
||||
marker.color =
|
||||
presetColor(style, entry.mode) ||
|
||||
TRANSIT_MODE_COLORS[entry.mode] ||
|
||||
TRANSIT_MODE_COLORS.unknown;
|
||||
dirty.add(entry);
|
||||
}
|
||||
|
||||
function addMarker(key, entry) {
|
||||
const marker = state._markers.add({
|
||||
id: key,
|
||||
position: entry.toCart,
|
||||
const at = entry.toCart;
|
||||
const marker = {
|
||||
position: { x: at?.x ?? 0, y: at?.y ?? 0, z: at?.z ?? 0 },
|
||||
show: false,
|
||||
image: transitIcon(entry.mode),
|
||||
width: MARKER_PIXEL_SIZE,
|
||||
height: MARKER_PIXEL_SIZE,
|
||||
color: MODE_CESIUM_COLORS[entry.mode],
|
||||
color: TRANSIT_MODE_COLORS[entry.mode],
|
||||
rotation: 0,
|
||||
alignedAxis: Cesium.Cartesian3.ZERO,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
};
|
||||
entry.marker = marker;
|
||||
entry.markerCollection = state._markers;
|
||||
marker.show = false;
|
||||
entry.animated = false;
|
||||
entry.drawnIn = null;
|
||||
applySpriteStyle(entry);
|
||||
return marker;
|
||||
}
|
||||
@@ -462,14 +663,29 @@ export function createRendering({ state, services, parts }) {
|
||||
if (next === state._stylePreset) return;
|
||||
state._stylePreset = next;
|
||||
for (const entry of state._vehicles.values()) applySpriteStyle(entry);
|
||||
flushMarkers();
|
||||
parts.trails.style();
|
||||
governorRequestRender('transit-style');
|
||||
}
|
||||
|
||||
/**
|
||||
* The screen rotation that points a marker along `course`, projected
|
||||
* exactly through the query port (see `perspectiveCourseRotation`).
|
||||
*/
|
||||
function courseRotation(query, pose, position, course, previous) {
|
||||
return perspectiveCourseRotation(
|
||||
query.project,
|
||||
pose,
|
||||
position,
|
||||
course,
|
||||
previous,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Point every glyph along its reported course.
|
||||
*
|
||||
* Billboards are camera-facing quads, so a course has to be projected into
|
||||
* Icons are camera-facing quads, so a course has to be projected into
|
||||
* screen space — which depends on where the camera is, not only on the
|
||||
* vehicle. Doing that for the whole fleet on every frame is exactly the kind
|
||||
* of cost that made this layer heavy, and it buys nothing: a bus icon whose
|
||||
@@ -478,17 +694,18 @@ export function createRendering({ state, services, parts }) {
|
||||
* changed somebody's heading.
|
||||
*/
|
||||
function refreshRotations(now) {
|
||||
const scene = state._viewer?.scene;
|
||||
if (!scene?.camera) return;
|
||||
if (now - state._rotationAt < ROTATION_REFRESH_MS) return;
|
||||
const pose = cameraPose();
|
||||
const query = findQuery(state._viewer);
|
||||
if (!pose?.position || !query) return;
|
||||
state._rotationAt = now;
|
||||
const pose = cameraPoseSignature(scene.camera);
|
||||
const signature = poseSignature(pose);
|
||||
const cameraChanged =
|
||||
state._rotationPose !== pose ||
|
||||
state._rotationPose !== signature ||
|
||||
state._rotationRevision !== state._cameraRevision;
|
||||
if (!cameraChanged && !state._rotationDirty && state._moving.size === 0)
|
||||
return;
|
||||
state._rotationPose = pose;
|
||||
state._rotationPose = signature;
|
||||
state._rotationRevision = state._cameraRevision;
|
||||
state._rotationDirty = false;
|
||||
const monoNow = performance.now();
|
||||
@@ -496,13 +713,15 @@ export function createRendering({ state, services, parts }) {
|
||||
// Idle contacts still need a course when their first usable bearing arrives.
|
||||
if (!state._moving.has(entry)) applyDisplayCourse(entry, monoNow);
|
||||
if (entry.key === state._selectedKey) continue;
|
||||
const marker = entry.marker;
|
||||
const course = entry.courseDeg;
|
||||
if (!Number.isFinite(course)) {
|
||||
entry.marker.rotation = 0;
|
||||
if (marker.rotation !== 0) dirty.add(entry);
|
||||
marker.rotation = 0;
|
||||
entry.rotationCourse = null;
|
||||
continue;
|
||||
}
|
||||
const position = entry.marker.position;
|
||||
const position = marker.position;
|
||||
if (
|
||||
!cameraChanged &&
|
||||
entry.rotationCourse === course &&
|
||||
@@ -520,12 +739,17 @@ export function createRendering({ state, services, parts }) {
|
||||
// camera-basis helper aircraft use is orthographic — fine at altitude,
|
||||
// and wrong by twenty-odd degrees for a street-level contact away from
|
||||
// the centre of an obliquely pitched view, which is most of them.
|
||||
entry.marker.rotation = perspectiveProjectedRotation(
|
||||
scene,
|
||||
entry.marker.position,
|
||||
const rotation = courseRotation(
|
||||
query,
|
||||
pose,
|
||||
position,
|
||||
course,
|
||||
entry.marker.rotation,
|
||||
marker.rotation,
|
||||
);
|
||||
if (rotation !== marker.rotation) {
|
||||
marker.rotation = rotation;
|
||||
dirty.add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,6 +783,7 @@ export function createRendering({ state, services, parts }) {
|
||||
)
|
||||
return;
|
||||
if (!state._enabled) return;
|
||||
forgetView();
|
||||
const now = Date.now();
|
||||
if (state._vehicles.size === 0) {
|
||||
state._moving.clear();
|
||||
@@ -598,23 +823,31 @@ export function createRendering({ state, services, parts }) {
|
||||
refreshRotations(now);
|
||||
const selected = state._vehicles.get(state._selectedKey);
|
||||
if (selected && state._visible.has(selected)) {
|
||||
selected.marker.rotation = Number.isFinite(selected.courseDeg)
|
||||
? perspectiveProjectedRotation(
|
||||
state._viewer.scene,
|
||||
selected.marker.position,
|
||||
const marker = selected.marker;
|
||||
const pose = Number.isFinite(selected.courseDeg) ? cameraPose() : null;
|
||||
const query = pose?.position ? findQuery(state._viewer) : null;
|
||||
const rotation = query
|
||||
? courseRotation(
|
||||
query,
|
||||
pose,
|
||||
marker.position,
|
||||
selected.courseDeg,
|
||||
selected.marker.rotation,
|
||||
marker.rotation,
|
||||
)
|
||||
: 0;
|
||||
: Number.isFinite(selected.courseDeg)
|
||||
? marker.rotation
|
||||
: 0;
|
||||
if (rotation !== marker.rotation) {
|
||||
marker.rotation = rotation;
|
||||
dirty.add(selected);
|
||||
}
|
||||
}
|
||||
flushMarkers();
|
||||
if (state._heightDirty.size) governorRequestRender('transit-height-batch');
|
||||
syncRenderHold();
|
||||
}
|
||||
|
||||
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84);
|
||||
const sphere = new Cesium.BoundingSphere(undefined, 5);
|
||||
const cameraPosition = new Cesium.Cartesian3();
|
||||
const candidatePosition = new Cesium.Cartesian3();
|
||||
const candidatePosition = { x: 0, y: 0, z: 0 };
|
||||
/** Visibility work runs off the frame path, coalesced at four sweeps/second. */
|
||||
function requestVisibility() {
|
||||
state._visibilityDirty = true;
|
||||
@@ -627,6 +860,24 @@ export function createRendering({ state, services, parts }) {
|
||||
Math.max(0, VISIBILITY_REFRESH_MS - (Date.now() - state._visibilityAt)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The planes of the frustum the camera looks through, as the default
|
||||
* renderer culls with them, or null when the pose does not describe one.
|
||||
*/
|
||||
function viewPlanes(pose) {
|
||||
if (
|
||||
!pose?.position ||
|
||||
!pose.direction ||
|
||||
!pose.up ||
|
||||
!Number.isFinite(pose.fovy) ||
|
||||
!Number.isFinite(pose.aspectRatio) ||
|
||||
!Number.isFinite(pose.near)
|
||||
)
|
||||
return null;
|
||||
return frustumPlanes(pose);
|
||||
}
|
||||
|
||||
function refreshVisibility() {
|
||||
if (!state._enabled) return 0;
|
||||
const now = Date.now();
|
||||
@@ -636,33 +887,22 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
state._visibilityAt = now;
|
||||
state._visibilityDirty = false;
|
||||
const viewer = state._viewer,
|
||||
camera = viewer?.camera;
|
||||
if (!camera) return 0;
|
||||
const position =
|
||||
camera.positionWC ||
|
||||
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
|
||||
camera.positionCartographic,
|
||||
cameraPosition,
|
||||
);
|
||||
occluder.cameraPosition = position;
|
||||
const frustum = camera.frustum?.computeCullingVolume(
|
||||
position,
|
||||
camera.directionWC,
|
||||
camera.upWC,
|
||||
);
|
||||
const planes = frustum?.planes;
|
||||
forgetView();
|
||||
const pose = cameraPose();
|
||||
if (!pose) return 0;
|
||||
const query = findQuery(state._viewer);
|
||||
const planes = viewPlanes(pose);
|
||||
let changed = false;
|
||||
for (const entry of state._vehicles.values()) {
|
||||
if (!entry.marker) continue;
|
||||
// Refresh hidden clocks before testing admission, even if no frame has
|
||||
// ever sampled them. Do not write the billboard until it is admitted.
|
||||
// ever sampled them. Do not write the marker until it is admitted.
|
||||
const noSample = !entry.sample || !Number.isFinite(entry.sample.lat);
|
||||
if (entry.track?.count && (!state._visible.has(entry) || noSample)) {
|
||||
entry.sample ||= {};
|
||||
updatePlayback(entry, now, performance.now());
|
||||
}
|
||||
sphere.center =
|
||||
const center =
|
||||
state._visible.has(entry) || !entry.sample
|
||||
? entry.marker.position
|
||||
: cartesianFor(
|
||||
@@ -675,24 +915,24 @@ export function createRendering({ state, services, parts }) {
|
||||
// view. The current frustum is authoritative; the horizon still rejects
|
||||
// the far side when the rectangle is missing or stale.
|
||||
const bounds = vehicleNearView(state._viewBounds, entry);
|
||||
const horizon = occluder.isPointVisible(sphere.center);
|
||||
const horizon = !(query?.isOccluded(center) ?? false);
|
||||
let inFrustum = true;
|
||||
if (planes) {
|
||||
for (let i = 0; i < planes.length; i++) {
|
||||
const p = planes[i],
|
||||
c = sphere.center;
|
||||
if (p.x * c.x + p.y * c.y + p.z * c.z + p.w < -sphere.radius) {
|
||||
const { normal: n, w } = planes[i];
|
||||
if (
|
||||
n.x * center.x + n.y * center.y + n.z * center.z + w <
|
||||
-CULL_RADIUS_M
|
||||
) {
|
||||
inFrustum = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (frustum)
|
||||
inFrustum =
|
||||
frustum.computeVisibility(sphere) !== Cesium.Intersect.OUTSIDE;
|
||||
const visible = (frustum || bounds) && horizon && inFrustum;
|
||||
}
|
||||
const visible = (planes || bounds) && horizon && inFrustum;
|
||||
const visibility = (entry.visibility ||= {});
|
||||
visibility.bounds = bounds;
|
||||
visibility.boundsApplied = !frustum;
|
||||
visibility.boundsApplied = !planes;
|
||||
visibility.occluder = horizon;
|
||||
visibility.frustum = inFrustum;
|
||||
visibility.noSample = noSample;
|
||||
@@ -713,13 +953,18 @@ export function createRendering({ state, services, parts }) {
|
||||
placeSample(entry);
|
||||
}
|
||||
}
|
||||
entry.marker.show =
|
||||
visible && !entry.heightPending && entry.surfaceReady !== false;
|
||||
setShown(
|
||||
entry,
|
||||
Boolean(
|
||||
visible && !entry.heightPending && entry.surfaceReady !== false,
|
||||
),
|
||||
);
|
||||
visibility.heightPending = !!entry.heightPending;
|
||||
visibility.surfaceReady = entry.surfaceReady ?? null;
|
||||
schedulePlayback(entry);
|
||||
changed ||= visible !== wasVisible || wasShown !== entry.marker.show;
|
||||
}
|
||||
flushMarkers();
|
||||
state._shownCount = state._visible.size;
|
||||
if (changed) state._detectRevision++;
|
||||
syncRenderHold();
|
||||
@@ -740,6 +985,7 @@ export function createRendering({ state, services, parts }) {
|
||||
placeSample(entry);
|
||||
schedulePlayback(entry);
|
||||
}
|
||||
flushMarkers();
|
||||
parts.trails.update();
|
||||
parts.selection.refreshSelectedCard(true);
|
||||
state._detectRevision++;
|
||||
@@ -758,6 +1004,7 @@ export function createRendering({ state, services, parts }) {
|
||||
function paintSelected(entry, selected) {
|
||||
void selected; // decided from state._selectedKey, which the caller has set
|
||||
applySpriteStyle(entry);
|
||||
flushMarkers();
|
||||
}
|
||||
|
||||
let stopProbe = null;
|
||||
@@ -766,60 +1013,30 @@ export function createRendering({ state, services, parts }) {
|
||||
stopProbe?.();
|
||||
}
|
||||
|
||||
/** Measure inside Cesium postRender with fixed typed storage; no sample objects per frame. */
|
||||
function measureFrames(durationMs = 12000) {
|
||||
/**
|
||||
* Measure inside the renderer's frames with fixed typed storage; no sample
|
||||
* objects per frame. `uploads`, when given, counts the bytes the
|
||||
* renderer uploads for this layer's sets each frame (the Cesium one's is
|
||||
* `src/render/cesium/uploadProbe.js`, which QA hands in): `reset()` at
|
||||
* each frame's start, `bytes()` at its end, `stop()` when done.
|
||||
* @param {number} [durationMs]
|
||||
* @param {{reset: () => void, bytes: () => number, stop: () => void}|null} [uploads]
|
||||
*/
|
||||
function measureFrames(durationMs = 12000, uploads = null) {
|
||||
stopProbe?.();
|
||||
const scene = state._viewer.scene;
|
||||
const frame = findFrame(state._viewer);
|
||||
const canvas = canvasOf(state._viewer);
|
||||
const capacity = 20000,
|
||||
stride = 12,
|
||||
data = new Float64Array(capacity * stride);
|
||||
const previousPositions = new Float64Array(state._vehicles.size * 3);
|
||||
const gl = webglContext(scene);
|
||||
let active = false,
|
||||
upload = 0,
|
||||
cpu = 0,
|
||||
let cpu = 0,
|
||||
count = 0,
|
||||
previous = 0;
|
||||
const saved = [];
|
||||
for (const name of ['bufferData', 'bufferSubData']) {
|
||||
const original = gl[name];
|
||||
gl[name] = function (...args) {
|
||||
if (active) {
|
||||
const value = args[name === 'bufferData' ? 1 : 2];
|
||||
const offset = args[name === 'bufferData' ? 3 : 3] || 0;
|
||||
const length = args[4];
|
||||
upload +=
|
||||
typeof value === 'number'
|
||||
? value
|
||||
: value
|
||||
? length !== undefined
|
||||
? length * (value.BYTES_PER_ELEMENT || 1)
|
||||
: value.byteLength - offset * (value.BYTES_PER_ELEMENT || 1)
|
||||
: 0;
|
||||
}
|
||||
return original.apply(this, args);
|
||||
};
|
||||
saved.push(() => {
|
||||
gl[name] = original;
|
||||
});
|
||||
}
|
||||
for (const collection of [state._markers, state._animatedMarkers]) {
|
||||
const original = collection.update;
|
||||
collection.update = function (frame) {
|
||||
active = true;
|
||||
try {
|
||||
return original.call(this, frame);
|
||||
} finally {
|
||||
active = false;
|
||||
}
|
||||
};
|
||||
saved.push(() => {
|
||||
collection.update = original;
|
||||
});
|
||||
}
|
||||
state._preRenderRemove?.();
|
||||
const removePre = scene.preRender.addEventListener(() => {
|
||||
upload = 0;
|
||||
const wasRunning = state._preRenderRemove !== null;
|
||||
stopFrames();
|
||||
const removePre = frame.on('preRender', () => {
|
||||
uploads?.reset();
|
||||
const start = performance.now();
|
||||
onPreRender();
|
||||
cpu = performance.now() - start;
|
||||
@@ -830,10 +1047,8 @@ export function createRendering({ state, services, parts }) {
|
||||
clearTimeout(timer);
|
||||
removePre();
|
||||
removePost?.();
|
||||
for (const restore of saved) restore();
|
||||
if (state._enabled)
|
||||
state._preRenderRemove =
|
||||
scene.preRender.addEventListener(onPreRender);
|
||||
uploads?.stop();
|
||||
if (wasRunning && state._enabled) startFrames(state._viewer);
|
||||
stopProbe = null;
|
||||
const rows = [];
|
||||
for (let i = 1; i < count; i++) {
|
||||
@@ -854,12 +1069,12 @@ export function createRendering({ state, services, parts }) {
|
||||
resolve({
|
||||
rows,
|
||||
dpr: devicePixelRatio,
|
||||
width: scene.canvas.clientWidth,
|
||||
height: scene.canvas.clientHeight,
|
||||
width: canvas?.clientWidth,
|
||||
height: canvas?.clientHeight,
|
||||
});
|
||||
};
|
||||
stopProbe = finish;
|
||||
removePost = scene.postRender.addEventListener(() => {
|
||||
removePost = frame.on('postRender', () => {
|
||||
const now = performance.now();
|
||||
if (count >= capacity) return;
|
||||
const k = count++ * stride;
|
||||
@@ -867,7 +1082,7 @@ export function createRendering({ state, services, parts }) {
|
||||
data[k] = previous ? now - previous : 0;
|
||||
previous = now;
|
||||
data[k + 1] = cpu;
|
||||
data[k + 2] = upload;
|
||||
data[k + 2] = uploads ? uploads.bytes() : 0;
|
||||
let actuallyMoved = 0;
|
||||
for (const vehicle of state._visible) {
|
||||
const p = vehicle.marker.position,
|
||||
@@ -905,7 +1120,13 @@ export function createRendering({ state, services, parts }) {
|
||||
showMarkers,
|
||||
clearMarkers,
|
||||
destroyMarkers,
|
||||
setIds,
|
||||
ownsSet,
|
||||
setNameOf,
|
||||
markerShown,
|
||||
markDirty,
|
||||
flushMarkers,
|
||||
removeMarker,
|
||||
watchCamera,
|
||||
unwatchCamera,
|
||||
startFrames,
|
||||
|
||||
Reference in new issue
Block a user