mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-14 23:32:20 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72d9f91ad6 | ||
|
|
fda54f6611 | ||
|
|
0760733780 | ||
|
|
6b4b9e43c8 | ||
|
|
c16bfa5abd | ||
|
|
22bdf14be1 | ||
|
|
5aed9ce064 | ||
|
|
96847d5856 | ||
|
|
5eb6515f44 |
No files matched your search
@@ -1,3 +0,0 @@
|
||||
- Shorten the freeze when Submarine cables is switched on from about 1.4 s to
|
||||
about 0.2 s. Landing markers are now shown a few dozen per frame instead of
|
||||
all at once (mazy1998, #1707).
|
||||
@@ -1,4 +0,0 @@
|
||||
- Submarine cables draw from a few batched primitives instead of thousands of
|
||||
entities. Switching the layer off and back on, and zooming with it on, no
|
||||
longer stall the page, and it holds about 900 MB less memory. Double-click
|
||||
no longer starts Cesium's entity tracking on a cable (mazy1998, #1722).
|
||||
+9
-31
@@ -1541,14 +1541,12 @@ query. Movement within an accepted or pending query reuses it. Markers retain
|
||||
their Cesium identity while their geometry is unchanged; refreshes preserve
|
||||
selection without replaying a click event.
|
||||
|
||||
Data Centers and Dams release their built Cesium data sources
|
||||
Data Centers, Dams and Submarine Cables release their built Cesium data sources
|
||||
and record references when disabled. Parsed datasets remain cached for the layer
|
||||
lifetime, so re-enable rebuilds entities without downloading or parsing again;
|
||||
this can take longer than simply revealing hidden entities. Destruction clears
|
||||
the parsed cache as well. A disable during loading cannot leave a completed
|
||||
build hidden in the scene. Submarine Cables draws with its own primitives
|
||||
instead of entities and only hides them when disabled (see "Bundled geography
|
||||
and submarine cable components").
|
||||
build hidden in the scene.
|
||||
|
||||
CCTV exposes a factory through `./layers/cctv`. Catalog and health requests,
|
||||
frame/media URLs, camera records, ground placement, geometry queues, playback,
|
||||
@@ -8149,37 +8147,17 @@ an error. Without feeds it keeps the WebUSB statuses. See
|
||||
Submarine cables use separate source, geometry, rendering, interaction and
|
||||
lifecycle modules. The layer factory accepts cable and landing-point GeoJSON
|
||||
collections from a source with `fetch(signal)` and a display label. The default
|
||||
source loads the same bundled TeleGeography files. Load ownership prevents
|
||||
cancelled work from adding anything to the scene after teardown: the fetch is
|
||||
the load's only await, and everything is built in the turn after it.
|
||||
source loads the same bundled TeleGeography files. Disabling still removes all
|
||||
three Cesium data sources; enabling rebuilds from the accepted parsed cache,
|
||||
and destroying clears it. Load ownership prevents cancelled work from adding
|
||||
entities after teardown.
|
||||
|
||||
The layer draws with four Cesium primitives of its own and creates no entity
|
||||
or data source. Every line is one instance of a single
|
||||
`GroundPolylinePrimitive` (per-line colour and show flag, rhumb lines,
|
||||
tessellated in a worker; a map-stack change re-classifies it in place). Every
|
||||
point is a billboard in one `BillboardCollection`. Reference tips are one
|
||||
`PointPrimitiveCollection`, and the stems of the references in view are one
|
||||
static polyline `Primitive`: a horizon sweep that moved a tip or changed which
|
||||
references are in view builds a replacement in a worker, and it replaces the
|
||||
shown stems once it is ready. Disabling hides the lines, markers and tips and
|
||||
keeps them, so enabling again neither fetches nor builds them (only the stems
|
||||
are redrawn, for the new view); destroying removes everything. These are
|
||||
the same primitives Cesium built from the layer's entities, so the layer looks
|
||||
the same. Polygon geometry in a custom source is not drawn, and GeoJSON
|
||||
simplestyle properties (`marker-color`, `stroke` and the like) are not read.
|
||||
|
||||
Every line and marker from multipart cable or landing-point geometry stays tied
|
||||
to its source feature. Each part gets its own feature's styling, click
|
||||
Every Cesium entity from multipart cable or landing-point geometry stays tied
|
||||
to its source feature, including generated IDs and IDs that collide with
|
||||
Cesium's multipart suffixes. Each segment gets its own feature's styling, click
|
||||
destination and horizon-culling reference, and each source feature has one
|
||||
reference stem. The source collections are not modified.
|
||||
|
||||
Landing markers are ground-clamped billboards. A marker starts hidden and
|
||||
unclamped; the horizon sweep clamps and shows the visible ones 48 per rendered
|
||||
frame (`CABLE_LANDING_REVEALS_PER_FRAME`), so the terrain height reads are
|
||||
never one task. A marker is clamped once: Cesium then keeps it on the surface
|
||||
as terrain loads, and hiding or showing it again reads nothing; hiding is
|
||||
immediate.
|
||||
|
||||
Natural Earth regions and neighborhood polygon lookup are package exports.
|
||||
Their existing lazy loaders, retry behavior, bundled datasets and attribution
|
||||
are unchanged. The cable dataset remains CC BY-NC-SA 3.0 and is not covered by
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
# Slowdown audit, November 2026
|
||||
|
||||
A sweep of `main` (`c02ede3bb`, 13 November 2026) for bugs that freeze the page
|
||||
or hold the frame rate down. This page lists what was found, why it happens and
|
||||
how to fix it, and names the pull request that carries each fix.
|
||||
|
||||
[PERFORMANCE.md](PERFORMANCE.md) is the measured baseline of a healthy build;
|
||||
this page is the list of things that fall outside it.
|
||||
|
||||
## How it was measured
|
||||
|
||||
- Keyless dev server, headless Chrome at 1440 x 900 on Apple silicon (Metal
|
||||
through ANGLE), default globe map.
|
||||
- Per scenario: load, a spell at rest, scripted drags and wheel zooms, then a
|
||||
settle. Long tasks were counted with a `PerformanceObserver`, the hot function
|
||||
named from a CPU profile, and `globe.getHeight`, `scene.sampleHeight`,
|
||||
`scene.pick` and friends wrapped to count calls and time.
|
||||
- A long task is one main-thread task over 50 ms. With no layers on, the
|
||||
baseline is two at load (longest about 240 ms) and none afterwards, with zero
|
||||
frames rendered while the camera is still.
|
||||
- Four profiling sessions ran on one machine at the same time, so absolute
|
||||
timings carry some noise. Ratios against the baseline are what to read.
|
||||
|
||||
Nothing here was measured on Google Photorealistic 3D Tiles, on a discrete or
|
||||
integrated PC GPU, or with keyed feeds (AISStream, FIRMS, TomTom). Those rows
|
||||
are marked "read in code".
|
||||
|
||||
## Findings and fixes
|
||||
|
||||
Worst first. "Fix" names the pull request that carries the fix.
|
||||
|
||||
### Measured
|
||||
|
||||
| # | Where | What happens | Fix |
|
||||
| ---: | --- | --- | --- |
|
||||
| 1 | Bike Share, local data layers, Transit, Rail | 18 s freeze switching Bike Share on over New York (2,519 stations); 2.7 s on Data Centers; multi-second freezes with Transit while zooming | #1688, #1689 |
|
||||
| 2 | Shipwrecks | 3 to 5 s freeze when the markers are built over loaded terrain; a share link with the layer on held the loading screen for 22.9 s in one run | #1703 |
|
||||
| 3 | Camera | Rendering stops until reload: at a whole-globe view looking straight down, pan a few times, then scroll one notch | #1704 |
|
||||
| 4 | Street Traffic | Zooming at 250 m over Manhattan: 25 long tasks in 24 s, longest 746 ms, 6.6 s in total | #1705 |
|
||||
| 5 | ALPR cameras | Depth samples inside the overlay paint, repeated on every re-enable: 240 samples and about 1 s across eight toggles. A first-sample freeze of up to 1.9 s was seen in the sweep but not on a second day | #1706 |
|
||||
| 6 | Wind | First zoom after load: up to 14 long tasks (longest 414 ms). Re-measured as one-off shader links, not a standing cost: see below | none proposed |
|
||||
| 7 | Submarine cables | About 2 s of long tasks on load, heap briefly at 1 GB, about 0.5 s again on each re-enable | #1707 (first step), #1722 (batched primitives) |
|
||||
| 8 | Live Flights at whole-globe view with detection labels | Fine on the test machine; at 4x CPU throttle, 8 fps with 143 long tasks in 15 s | #1708 (fleet pass), #1719 (overlay) |
|
||||
| 9 | Radio | 7 to 10 long tasks when the directory loads, longest 447 ms | #1709 |
|
||||
| 10 | Pointer pick | Not reproduced on a second look: see below | none needed |
|
||||
| 11 | CCTV | A still-image camera holds continuous rendering at 60 frames a second although its picture changes about every 10 s | #1710 |
|
||||
|
||||
### Read in code
|
||||
|
||||
| # | Where | What happens | Fix |
|
||||
| ---: | --- | --- | --- |
|
||||
| 12 | `/api/firms` | The whole fire set is filtered, serialised and sent uncompressed on every request; 15 to 55 MB estimated in a heavy season | #1711 |
|
||||
| 13 | AIS store | Both vessel maps are walked on every position message, and sorted whole once past the cap | #1712 |
|
||||
| 14 | Satellite clouds on the 3D Tiles map | A CPU pass over a 4096 x 2048 image, 90 to 180 ms measured on a synthetic canvas, twice in a row | #1713 (canvas path), #1721 (shader) |
|
||||
| 15 | NVG and FLIR styles | Over 100 texture reads per pixel, and 60 renders a second while the style is on. Measured afterwards: the reads cost 0.4 ms a frame at 1440 x 900 and 1.2 ms at 2560 x 1440 | #1718 |
|
||||
| 16 | Wind server | Full 0.25 degree GRIB fields decoded on the event loop. Measured afterwards: 68 ms blocked per warm refresh, about 250 ms on the first, about 400 ms when all six keys refresh together | #1717 |
|
||||
| 17 | Imported geo files and other per-feature ground clamps | Measured afterwards: imported files do not freeze; see below | none needed |
|
||||
|
||||
## Cause and fix, per finding
|
||||
|
||||
### 1. Terrain height reads
|
||||
|
||||
`globe.getHeight` casts a ray against the mesh of the tile under the point, and
|
||||
`scene.sampleHeight` renders a depth pass. Transit asked for every trail fix of
|
||||
every vehicle several times per poll; Bike Share sampled every station in one
|
||||
go. The fix keeps heights per point in one shared reader with a read budget
|
||||
(`src/services/terrainSurface.js`) and spreads the depth samples across frames.
|
||||
|
||||
### 2. Shipwrecks
|
||||
|
||||
`rebuild()` in `src/layers/shipwrecks/index.js` adds 7,958 billboards with
|
||||
`heightReference: CLAMP_TO_GROUND`. Each constructor runs
|
||||
`Billboard._updateClamping`, which intersects a ray with the terrain mesh,
|
||||
synchronously: 4.8 of the 4.9 s. The cost is only paid when terrain is loaded
|
||||
at the time the markers are built, so a cold start with the layer in the URL
|
||||
sometimes escapes it.
|
||||
|
||||
Fix: do not clamp. Wrecks are at sea and the markers already ignore the depth
|
||||
test, so place them on the ellipsoid with `HeightReference.NONE`.
|
||||
|
||||
### 3. Camera: rendering stops after pan then zoom
|
||||
|
||||
Pure Cesium; no application code is involved. Above 1,000 km,
|
||||
`ScreenSpaceCameraController` `handleZoom` rotates the camera about the cross
|
||||
product of the picked point's normal and the screen centre's normal whenever
|
||||
their dot product is between 0 and 1. With the pointer on the exact centre pixel
|
||||
the two are the same vector, yet `n · n` often rounds to `0.9999999999999999`,
|
||||
so the check passes with a zero axis. `Camera.rotate` then throws
|
||||
`DeveloperError: normalized result is not a number` from
|
||||
`Scene.initializeFrame`, outside the scene's own try/catch, so
|
||||
`scene.renderError` never fires and Cesium stops its render loop for good. The
|
||||
pans in the first reproduction only moved the camera to a pose where the
|
||||
rounding goes that way.
|
||||
|
||||
Fix: make `camera.rotate` ignore a zero or non-finite axis, and recover from any
|
||||
stopped loop by restoring the last drawn camera pose and restarting it a bounded
|
||||
number of times before showing Cesium's error panel.
|
||||
|
||||
### 4. Street Traffic road loading
|
||||
|
||||
Three costs in one task after the detail tiles arrive, in
|
||||
`src/layers/traffic/source.js`:
|
||||
|
||||
- `outsideDetailTiles` clips every coarse z12 road against every loaded detail
|
||||
tile (up to 16) for four regions.
|
||||
- The composed set is then handed on with `replace: true`, so
|
||||
`ingestion.js` parses every road again although each tile was parsed as it
|
||||
streamed.
|
||||
- `parseRoads` (`model.js`) asks `cachedGroundFloor` once per coordinate, and
|
||||
each call builds several string keys.
|
||||
|
||||
Fix: clip once per coarse tile against the detail tiles' union box and slice the
|
||||
work across frames (or do it in the vector-tile worker); reuse the roads parsed
|
||||
while streaming and parse only the clipped coarse remainder; look the floor up
|
||||
once per floor cell within a parse.
|
||||
|
||||
This is separate from the one-viewport-tile-at-a-time loading recorded in
|
||||
[KNOWN-ISSUES.md](KNOWN-ISSUES.md).
|
||||
|
||||
### 5. ALPR cameras
|
||||
|
||||
`refineAnchors` and `anchorFor` in `src/layers/alpr/overlay.js` call
|
||||
`scene.sampleHeight` from the overlay's paint, four per paint. Each is a depth
|
||||
render and a `readPixels`; the first one also compiles the pick shader. Results
|
||||
are kept on the entity, so a rebuild or a re-enable samples everything again.
|
||||
|
||||
Fix: on a terrain globe read `globe.getHeight` through the shared terrain reader
|
||||
instead of sampling; keep the answers in a map keyed by camera that outlives the
|
||||
entities; move what sampling remains out of the paint into a queue of one per
|
||||
frame.
|
||||
|
||||
### 6. Wind
|
||||
|
||||
The first reading blamed the layer's 916,476 vertices for slow depth reads
|
||||
during zoom. Measuring again did not support that: depth reads cost the same
|
||||
with and without Wind, hiding every wind primitive left pick time unchanged, and
|
||||
the stalls appear on the first zoom only, as shader programs link (seven
|
||||
programs, about 0.5 s, long tasks up to 166 ms). Later zooms had none.
|
||||
|
||||
The roughly 30 renders a second are the animation itself. It is already capped
|
||||
at 30 Hz and stops when paused, hidden, out of view or under reduced motion;
|
||||
lowering the rate would change how the layer looks. `disable()` releases the
|
||||
baked geometry on purpose, at the price of one task of about 130 ms on
|
||||
re-enable.
|
||||
|
||||
A third look, timing every program link on a preview build, settled it: Wind
|
||||
owns two shader programs, both link during load in 9 to 18 ms, and none ever
|
||||
linked during a zoom. The programs that do link on a zoom are Cesium's own
|
||||
globe-surface variants, with Wind on or off, and Cesium links them
|
||||
synchronously. No fix is proposed.
|
||||
|
||||
### 7. Submarine cables
|
||||
|
||||
`src/layers/submarineCables/ingestion.js` loads both collections through
|
||||
`Cesium.GeoJsonDataSource` with `clampToGround`. Switching the layer on is one
|
||||
task of about 1.4 s, and 1.2 s of it is Cesium reading the terrain height for
|
||||
the 1,917 ground-clamped landing markers, all created in the first frame,
|
||||
including the ones behind the globe.
|
||||
|
||||
Fix, first step: start the landing markers hidden and let the existing horizon
|
||||
sweep show the visible ones a few dozen per frame.
|
||||
|
||||
Fix, second step: draw from batched primitives in place of the entity data
|
||||
sources: one ground polyline primitive for the lines, one billboard collection
|
||||
for the landing markers, one point collection and one static polyline primitive
|
||||
for the reference stems, all kept while the layer is off. That removes the
|
||||
visualiser tasks, the stall on switch-off and on re-enable, and about 900 MB of
|
||||
heap. The first switch-on still links shaders and builds the ground-line
|
||||
geometry once.
|
||||
|
||||
### 8. Live Flights at whole-globe view
|
||||
|
||||
Two costs that scale with the 7,500 aircraft of a full poll:
|
||||
|
||||
- The fleet pass (`src/layers/flights/rendering.js`, every 80 ms) dead-reckons
|
||||
each visible aircraft and asks `cachedGroundFloor` for it, including aircraft
|
||||
at cruise altitude that can never touch the floor. Each lookup formats numbers
|
||||
to strings several times and rewrites a cache entry: 40% of the busy time.
|
||||
- The detection overlay (`src/data/detection.js` `_drawOverlay`) collects every
|
||||
detectable object and strokes every bracket on every frame.
|
||||
|
||||
Fix for the first: skip the floor path for a contact clearly above any terrain,
|
||||
make the floor-cell key a number, and stop promoting the cache entry on every
|
||||
read.
|
||||
|
||||
The second turned out smaller than it looked. The bracket strokes are already
|
||||
one path per colour, and collecting the objects is about 3 ms of a 56 ms frame
|
||||
at 4x throttle once the first fix is in. What costs is the per-object loop in
|
||||
`_drawOverlay` (projection, occlusion, alpha, twelve path calls per bracket).
|
||||
|
||||
Fix for the second: keep what a sweep built and reuse it on the next paint when
|
||||
the view and every contact are exactly what it was built from, compared value
|
||||
by value so no layer has to announce a change. Between two fleet passes most
|
||||
paints qualify, which cuts frame work by a fifth to a third on a still camera
|
||||
at full speed. At 4x throttle a frame outlasts a fleet pass, no paint
|
||||
qualifies, and the gain is a few milliseconds; the fleet pass is what
|
||||
dominates there.
|
||||
|
||||
### 9. Radio
|
||||
|
||||
`stationTags()` in `src/layers/radio/categories.js` splits and normalises a
|
||||
station's tags on every `hasTag` call, and `buildRadioCategories` runs that for
|
||||
every station against every category, twice.
|
||||
|
||||
Fix: normalise once per station at ingest and count categories from that.
|
||||
|
||||
### 10. Pointer pick
|
||||
|
||||
Three sessions saw a single `scene.pick` of 207 to 342 ms during a gesture and
|
||||
attributed it to `pickPointer` in `src/voice/pointerPick.js`. Timing every pick
|
||||
across pointer rests, drags and wheel bursts did not bear that out: of 78 picks
|
||||
with CCTV on over London all but two took 3 to 8 ms, and with five heavy layers
|
||||
on, 81 picks took 5 to 30 ms apart from the first (135 ms). `pickPointer` picks
|
||||
at most once per pointer rest.
|
||||
|
||||
The slow pick is the first pick after a layer appears, once per page load, most
|
||||
likely the pick shader compiling, and its stack is CCTV's own hover pick
|
||||
(`src/layers/cctv/hover.js`). No fix is proposed: removing the dwell pick would
|
||||
only move the one-off cost to the next click.
|
||||
|
||||
### 11. CCTV still-image cameras
|
||||
|
||||
`src/layers/cctv/projection.js` holds continuous rendering for as long as any
|
||||
projected camera is active and redraws the projection every frame.
|
||||
|
||||
Fix: hold only for video. For a still image, request one render when a new image
|
||||
lands or while a focus fade runs.
|
||||
|
||||
### 12. `/api/firms`
|
||||
|
||||
`server/providers/firms.js` builds the payload and calls `JSON.stringify` per
|
||||
request, with no kept body and no compression, and the client refetches every
|
||||
ten minutes.
|
||||
|
||||
Fix: keep the response bytes and their gzip and serve those, as the OpenSky
|
||||
provider does. The route filters to the trailing 24 hours at serve time, so the
|
||||
bytes can only be reused while that filter keeps the same records (about a
|
||||
minute at a time): bursts and several clients gain most, and every response is
|
||||
about seven times smaller.
|
||||
|
||||
### 13. AIS store
|
||||
|
||||
`server/providers/vessels/ais-store.js` calls `pruneAisStreamCache()` for every
|
||||
message; the static-data map is never pruned.
|
||||
|
||||
Fix: prune on a timer, evict in insertion order, and drop a vessel's static
|
||||
entry with the vessel.
|
||||
|
||||
### 14. Satellite clouds on the 3D Tiles map
|
||||
|
||||
`src/layers/weather/infraredImage.js` runs `getImageData`, a per-pixel power
|
||||
curve and `putImageData` over the whole canvas.
|
||||
|
||||
Fix: a 256-entry lookup table applied in place for the canvas path, which
|
||||
halves it; then, for the shell on the 3D Tiles map, the same curve in its
|
||||
fragment shader from a strength uniform, so the image is never read back and a
|
||||
strength change builds no new image.
|
||||
|
||||
### 15. NVG and FLIR styles
|
||||
|
||||
`src/styles/surveillance.js` loops 11 x 11 texture reads per pixel and
|
||||
`src/styles/thermal.js` totals 106. Timed on the GPU, those loops cost about
|
||||
0.4 ms a frame at 1440 x 900 and 1.2 ms at 2560 x 1440 on the test machine:
|
||||
real, but small there. The standing cost is that a style with animated grain
|
||||
holds continuous rendering at 60 frames a second.
|
||||
|
||||
Fix: split the bloom into a row pass and a column pass, which gives the same
|
||||
picture from a fifth to a half of the reads, and step the grain's clock at
|
||||
15 Hz, asking for one frame per step instead of holding the render loop. The
|
||||
grain then changes 15 times a second, which is visible in motion.
|
||||
|
||||
Switching on any style stage at all costs more than the bloom did (1.8 ms a
|
||||
frame at 1440 x 900 for the one-line noir style). That was not looked into.
|
||||
|
||||
### 16. Wind server
|
||||
|
||||
`server/providers/wind/decode.js` decodes about a million doubles per message
|
||||
synchronously, hourly, for six keys.
|
||||
|
||||
Fix: decode on a worker thread, and keep the sampled U and V of the last
|
||||
forecast file per model so that choosing an overlay fetches only its field.
|
||||
|
||||
### 17. Per-feature ground clamps
|
||||
|
||||
`heightReference: CLAMP_TO_GROUND` per feature is also set in
|
||||
`installations/rendering.js`, `alpr/presentation.js`, `ghostMaps/index.js`,
|
||||
`earthquakes/index.js`, `airQuality/index.js`, `news/index.js` and
|
||||
`osmPlaces/index.js`. Their counts were small in these runs (30 to 1,500) and
|
||||
none froze.
|
||||
|
||||
Imported geo files were the one unbounded case, and measuring them cleared
|
||||
them: 20,000 generated points (the import cap) finish in about 1.5 s with a
|
||||
longest task near 0.5 s, because `settleGroundPins` in
|
||||
`src/data/geoFileImport.js` already places pins with `HeightReference.NONE` and
|
||||
resolves heights 256 at a time with a yield between batches. No fix is needed.
|
||||
|
||||
## Checked and fine
|
||||
|
||||
- Start-up of a production build: viewer ready in about 0.5 s, loading screen
|
||||
gone at 1.6 s, three long tasks totalling about 300 ms.
|
||||
- Idle: no frames rendered with no layers on; every render hold was released
|
||||
when its layer went off.
|
||||
- Leaks: all 41 layers toggled three times and ten of them eight times; no
|
||||
timer, scene listener, primitive or data source grew per cycle. The heap
|
||||
levelled off near 320 MB over 7.5 minutes of toggling eleven layers.
|
||||
- At most one long task after load: Military, Satellites (including 11,903
|
||||
Starlink points), Earthquakes, News, Wildlife, GNSS, Drone Airspace, Military
|
||||
Installations, Fire Perimeters, rain radar, lightning, and satellite clouds on
|
||||
the globe map.
|
||||
- Live Flights at city scale with the same 7,500 aircraft loaded: 60 fps, no
|
||||
long tasks.
|
||||
|
||||
## Not covered
|
||||
|
||||
- Google Photorealistic 3D Tiles: nothing was run there. Depth sampling is the
|
||||
only height source on that map, so findings 4, 5 and 17 may be worse.
|
||||
- Live Vessels, FIRMS with data, TomTom traffic, Local ADS-B.
|
||||
- Frame rate on anything but one Apple silicon machine.
|
||||
- One all-layers run over Manhattan grew the heap from 346 to 638 MB in 60 s;
|
||||
whether that is retained was not established.
|
||||
- One Satellites load showed a 5.2 s long task once and never again in four more
|
||||
loads.
|
||||
@@ -6,6 +6,9 @@ specification and should not be used to predict performance on untested systems.
|
||||
The original capture artifacts are not included here, so this page records
|
||||
results rather than defining a runnable benchmark.
|
||||
|
||||
For slowdowns found since, with their causes and fixes, see
|
||||
[PERFORMANCE-AUDIT-2026-11.md](PERFORMANCE-AUDIT-2026-11.md).
|
||||
|
||||
## Test context
|
||||
|
||||
The baseline was captured on 22 August 2026 with these conditions:
|
||||
|
||||
@@ -24,6 +24,7 @@ export {
|
||||
createCableOverlayEntry,
|
||||
cableClassificationTypeForStack,
|
||||
cableClassificationTypeForScene,
|
||||
applyTranslucentMarkerBlend,
|
||||
createCableReferenceSweepGate,
|
||||
updateCableReferenceStem,
|
||||
} from '../layers/submarineCables/index.js';
|
||||
File diff suppressed because it is too large.
Load diff
@@ -77,58 +77,3 @@ export function normalizeFeatures(json, kind) {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function partPosition(value) {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const lon = Number(value[0]);
|
||||
const lat = Number(value[1]);
|
||||
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
|
||||
const height = Number(value[2]);
|
||||
return Number.isFinite(height) ? [lon, lat, height] : [lon, lat];
|
||||
}
|
||||
|
||||
function collectParts(geometry, out) {
|
||||
const coordinates = geometry?.coordinates;
|
||||
switch (geometry?.type) {
|
||||
case 'Point': {
|
||||
const point = partPosition(coordinates);
|
||||
if (point) out.points.push(point);
|
||||
break;
|
||||
}
|
||||
case 'MultiPoint':
|
||||
for (const value of coordinates || []) {
|
||||
const point = partPosition(value);
|
||||
if (point) out.points.push(point);
|
||||
}
|
||||
break;
|
||||
case 'LineString': {
|
||||
const line = (coordinates || []).map(partPosition).filter(Boolean);
|
||||
if (line.length >= 2) out.lines.push(line);
|
||||
break;
|
||||
}
|
||||
case 'MultiLineString':
|
||||
for (const part of coordinates || []) {
|
||||
const line = (part || []).map(partPosition).filter(Boolean);
|
||||
if (line.length >= 2) out.lines.push(line);
|
||||
}
|
||||
break;
|
||||
case 'GeometryCollection':
|
||||
for (const child of geometry.geometries || []) collectParts(child, out);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The parts of a feature the layer draws: every line of a LineString or
|
||||
* MultiLineString and every point of a Point or MultiPoint, also inside a
|
||||
* GeometryCollection. Each is [lon, lat] or [lon, lat, height] in degrees
|
||||
* and metres. Polygons are not drawn.
|
||||
* @returns {{lines:number[][][],points:number[][]}}
|
||||
*/
|
||||
export function featureParts(feature) {
|
||||
const out = { lines: [], points: [] };
|
||||
collectParts(feature?.geometry, out);
|
||||
return out;
|
||||
}
|
||||
@@ -10,7 +10,6 @@ export function createSubmarineCableLayer({
|
||||
screenSpaceEventHandlerFactory,
|
||||
mapStackEventTarget = null,
|
||||
sweepClock = defaultSweepClock,
|
||||
createMarkerImage,
|
||||
}) {
|
||||
if (!source?.fetch || !source.label)
|
||||
throw new TypeError(
|
||||
@@ -24,7 +23,6 @@ export function createSubmarineCableLayer({
|
||||
source,
|
||||
screenSpaceEventHandlerFactory,
|
||||
mapStackEventTarget,
|
||||
createMarkerImage,
|
||||
};
|
||||
parts.rendering = createRendering(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
@@ -42,6 +40,7 @@ export {
|
||||
export {
|
||||
cableClassificationTypeForStack,
|
||||
cableClassificationTypeForScene,
|
||||
applyTranslucentMarkerBlend,
|
||||
} from './surface.js';
|
||||
export {
|
||||
CABLE_REFERENCE_LABEL_WINNER_CAP,
|
||||
|
||||
@@ -1,82 +1,27 @@
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import {
|
||||
featureLabel,
|
||||
featureParts,
|
||||
featureReference,
|
||||
normalizeFeatures,
|
||||
} from './geometry.js';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
const toCartesian = ([lon, lat, height]) =>
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, height ?? 0);
|
||||
const SOURCE_FEATURE_INDEX = '__gevSourceFeatureIndex';
|
||||
|
||||
function indexedCollection(features) {
|
||||
return {
|
||||
type: 'FeatureCollection',
|
||||
features: features.map((feature, index) => ({
|
||||
...feature,
|
||||
properties: {
|
||||
...feature.properties,
|
||||
[SOURCE_FEATURE_INDEX]: index,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function createIngestion({ state, parts, source }) {
|
||||
/**
|
||||
* Turn the two feature collections into what rendering draws. Every part
|
||||
* of a multipart feature is its own line or marker with its own pick
|
||||
* record, all sharing the feature's reference; a feature gets one
|
||||
* reference stem however many parts it has.
|
||||
*/
|
||||
function describeScene(cableFeatures, landingFeatures) {
|
||||
const lines = [];
|
||||
const markers = [];
|
||||
const references = [];
|
||||
const add = (features, kind, style) => {
|
||||
for (const feature of features) {
|
||||
const reference = featureReference(feature);
|
||||
if (!reference) continue;
|
||||
const label = featureLabel(feature);
|
||||
const base = Cesium.Cartesian3.fromDegrees(
|
||||
reference.lon,
|
||||
reference.lat,
|
||||
0,
|
||||
);
|
||||
const drawn = featureParts(feature);
|
||||
const pick = () =>
|
||||
parts.interaction.registerPick({ kind, reference, label });
|
||||
for (const line of drawn.lines)
|
||||
lines.push({
|
||||
info: pick(),
|
||||
base,
|
||||
positions: line.map(toCartesian),
|
||||
color: style.lineColor(feature),
|
||||
width: style.lineWidth,
|
||||
});
|
||||
for (const point of drawn.points)
|
||||
markers.push({
|
||||
info: pick(),
|
||||
base,
|
||||
position: toCartesian(point),
|
||||
hasHeight: point.length > 2,
|
||||
color: style.color,
|
||||
});
|
||||
references.push({
|
||||
reference,
|
||||
label,
|
||||
kind,
|
||||
color: style.color,
|
||||
feature,
|
||||
});
|
||||
}
|
||||
};
|
||||
add(cableFeatures, 'cable', {
|
||||
color: state.cableColor,
|
||||
lineWidth: 2.5,
|
||||
lineColor: (feature) => {
|
||||
const css = feature?.properties?.color;
|
||||
const color = css && Cesium.Color.fromCssColorString(String(css));
|
||||
return (color || state.cableColor).withAlpha(0.92);
|
||||
},
|
||||
});
|
||||
const landingLine = state.landingColor.withAlpha(0.9);
|
||||
add(landingFeatures, 'landing-point', {
|
||||
color: state.landingColor,
|
||||
lineWidth: 2,
|
||||
lineColor: () => landingLine,
|
||||
});
|
||||
return { lines, markers, references };
|
||||
}
|
||||
|
||||
async function load(viewer) {
|
||||
if (state._loading || state._loaded) return;
|
||||
|
||||
@@ -85,10 +30,10 @@ export function createIngestion({ state, parts, source }) {
|
||||
state._loadingLabel = t('loading...');
|
||||
// Ownership token (the militaryAwareness activationId pattern): a
|
||||
// disable/abort followed by a fresh enable starts a NEWER load while this
|
||||
// one is still settling. The stale load must bail after its await and
|
||||
// one is still settling. The stale load must bail after every await and
|
||||
// must never touch shared lifecycle state or the viewer it no longer
|
||||
// owns — clearing `_loading`/`_abort` for the successor is how duplicate
|
||||
// or post-destroy primitives would get added.
|
||||
// or post-destroy data sources got added.
|
||||
const generation = ++state._loadGeneration;
|
||||
const abort = new AbortController();
|
||||
state._abort = abort;
|
||||
@@ -96,34 +41,170 @@ export function createIngestion({ state, parts, source }) {
|
||||
generation === state._loadGeneration && !abort.signal.aborted;
|
||||
|
||||
try {
|
||||
const { cables: cableJson, landingPoints: landingJson } =
|
||||
await source.fetch(abort.signal);
|
||||
// The fetch is the only await: everything after it runs in this one
|
||||
// turn, so no disable or destroy can land between the ownership check
|
||||
// and the primitives reaching the scene.
|
||||
if (!owns()) return;
|
||||
if (
|
||||
!Array.isArray(cableJson?.features) ||
|
||||
!Array.isArray(landingJson?.features)
|
||||
) {
|
||||
throw new TypeError(
|
||||
'A cable source must return cables and landingPoints GeoJSON collections',
|
||||
);
|
||||
let cableJson = state._cachedCableJson;
|
||||
let landingJson = state._cachedLandingJson;
|
||||
if (!cableJson || !landingJson) {
|
||||
({ cables: cableJson, landingPoints: landingJson } = await source.fetch(
|
||||
abort.signal,
|
||||
));
|
||||
if (!owns()) return;
|
||||
if (
|
||||
!Array.isArray(cableJson?.features) ||
|
||||
!Array.isArray(landingJson?.features)
|
||||
) {
|
||||
throw new TypeError(
|
||||
'A cable source must return cables and landingPoints GeoJSON collections',
|
||||
);
|
||||
}
|
||||
state._cachedCableJson = cableJson;
|
||||
state._cachedLandingJson = landingJson;
|
||||
}
|
||||
|
||||
const cableFeatures = normalizeFeatures(cableJson, 'cable');
|
||||
const landingFeatures = normalizeFeatures(landingJson, 'landing');
|
||||
try {
|
||||
parts.rendering.buildScene(
|
||||
viewer,
|
||||
describeScene(cableFeatures, landingFeatures),
|
||||
);
|
||||
} catch (error) {
|
||||
// Leave nothing half built in the scene.
|
||||
parts.rendering.destroyScene(viewer);
|
||||
throw error;
|
||||
|
||||
const cableDataSource = await Cesium.GeoJsonDataSource.load(
|
||||
indexedCollection(cableFeatures),
|
||||
{
|
||||
clampToGround: true,
|
||||
stroke: state.cableColor.withAlpha(0.95),
|
||||
fill: state.cableColor.withAlpha(0.18),
|
||||
strokeWidth: 2,
|
||||
markerColor: state.cableColor,
|
||||
markerSize: 6,
|
||||
},
|
||||
);
|
||||
if (!owns()) return;
|
||||
const landingDataSource = await Cesium.GeoJsonDataSource.load(
|
||||
indexedCollection(landingFeatures),
|
||||
{
|
||||
clampToGround: true,
|
||||
stroke: state.landingColor.withAlpha(0.9),
|
||||
fill: state.landingColor.withAlpha(0.35),
|
||||
strokeWidth: 2,
|
||||
markerColor: state.landingColor,
|
||||
markerSize: 6,
|
||||
},
|
||||
);
|
||||
if (!owns()) return;
|
||||
|
||||
cableDataSource.name = `${source.label} Submarine Cables`;
|
||||
landingDataSource.name = `${source.label} Landing Points`;
|
||||
const referenceDataSource = new Cesium.CustomDataSource(
|
||||
`${source.label} Cable References`,
|
||||
);
|
||||
const addedSources = [
|
||||
cableDataSource,
|
||||
landingDataSource,
|
||||
referenceDataSource,
|
||||
];
|
||||
|
||||
// dataSources.add() is itself an await point: Cesium mutates the
|
||||
// collection on a DEFERRED tick, so a disable/destroy racing this
|
||||
// window finds nothing to remove and the adds still materialize
|
||||
// afterwards. Await every add to settlement (allSettled so a partial
|
||||
// failure cannot leave an unawaited add materializing later), then
|
||||
// re-check ownership. Pinned teardown mechanism: disable/destroy never
|
||||
// wait for in-flight adds — the stale generation's own post-await
|
||||
// check here guarantees cleanup by removing exactly the sources THIS
|
||||
// generation added.
|
||||
const addResults = await Promise.allSettled([
|
||||
viewer.dataSources.add(cableDataSource),
|
||||
viewer.dataSources.add(landingDataSource),
|
||||
viewer.dataSources.add(referenceDataSource),
|
||||
]);
|
||||
const rejectedAdd = addResults.find(
|
||||
(result) => result.status === 'rejected',
|
||||
);
|
||||
if (!owns() || rejectedAdd) {
|
||||
// Compensate: every add has settled by now, so removal is effective
|
||||
// (a remove inside the deferred window would have been a no-op).
|
||||
// Remove EVERY generation-local source regardless of settle status:
|
||||
// Cesium's add() pushes into the collection BEFORE raising
|
||||
// dataSourceAdded, so a REJECTED add may still have landed its
|
||||
// mutation. remove() of a never-added source is a harmless no-op.
|
||||
for (const source of addedSources) {
|
||||
try {
|
||||
viewer.dataSources.remove(source, true);
|
||||
} catch {
|
||||
/* collection gone */
|
||||
}
|
||||
}
|
||||
if (owns() && rejectedAdd) throw rejectedAdd.reason;
|
||||
return;
|
||||
}
|
||||
|
||||
// Await-free commit: the viewer accepted all three sources and this
|
||||
// load still owns the lifecycle.
|
||||
state._cableDataSource = cableDataSource;
|
||||
state._landingDataSource = landingDataSource;
|
||||
state._referenceDataSource = referenceDataSource;
|
||||
|
||||
const cableEntities = state._cableDataSource.entities.values;
|
||||
const landingEntities = state._landingDataSource.entities.values;
|
||||
state._pickByEntity = new WeakMap();
|
||||
state._referenceRecords = [];
|
||||
state._surfaceRecords = [];
|
||||
|
||||
// Cesium expands multipart geometry into several entities and suffixes
|
||||
// colliding IDs. Its copied properties retain this source index even
|
||||
// when a provider has no ID, so every segment keeps the right owner.
|
||||
const cableReferences = new Set();
|
||||
cableEntities.forEach((entity) => {
|
||||
const index = entity.properties?.[SOURCE_FEATURE_INDEX]?.getValue();
|
||||
const feature = cableFeatures[index];
|
||||
const reference = featureReference(feature);
|
||||
if (!reference) return;
|
||||
|
||||
parts.rendering.styleCableEntity(entity, feature);
|
||||
parts.interaction.registerPickEntity(entity, {
|
||||
kind: 'cable',
|
||||
reference,
|
||||
label: featureLabel(feature),
|
||||
});
|
||||
state._surfaceRecords.push({
|
||||
entity,
|
||||
base: Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0),
|
||||
});
|
||||
if (cableReferences.has(index)) return;
|
||||
cableReferences.add(index);
|
||||
parts.rendering.addReferenceStem({
|
||||
reference,
|
||||
label: featureLabel(feature),
|
||||
kind: 'cable',
|
||||
color: state.cableColor,
|
||||
feature,
|
||||
});
|
||||
});
|
||||
|
||||
const landingReferences = new Set();
|
||||
landingEntities.forEach((entity) => {
|
||||
const index = entity.properties?.[SOURCE_FEATURE_INDEX]?.getValue();
|
||||
const feature = landingFeatures[index];
|
||||
const reference = featureReference(feature);
|
||||
if (!reference) return;
|
||||
|
||||
parts.rendering.styleLandingEntity(entity, feature);
|
||||
parts.interaction.registerPickEntity(entity, {
|
||||
kind: 'landing-point',
|
||||
reference,
|
||||
label: featureLabel(feature),
|
||||
});
|
||||
state._surfaceRecords.push({
|
||||
entity,
|
||||
base: Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0),
|
||||
});
|
||||
if (landingReferences.has(index)) return;
|
||||
landingReferences.add(index);
|
||||
parts.rendering.addReferenceStem({
|
||||
reference,
|
||||
label: featureLabel(feature),
|
||||
kind: 'landing-point',
|
||||
color: state.landingColor,
|
||||
feature,
|
||||
});
|
||||
});
|
||||
|
||||
state._count = cableFeatures.length + landingFeatures.length;
|
||||
state._loaded = true;
|
||||
state._lastUpdate = Date.now();
|
||||
|
||||
@@ -2,10 +2,9 @@ import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
export function createInteraction({ state, screenSpaceEventHandlerFactory }) {
|
||||
/** Every drawn part carries its own record as the Cesium pick id. */
|
||||
function registerPick(info) {
|
||||
state._pickRecords.add(info);
|
||||
return info;
|
||||
function registerPickEntity(entity, info) {
|
||||
entity.__gevTeleGeography = info;
|
||||
state._pickByEntity.set(entity, info);
|
||||
}
|
||||
|
||||
function beginInteraction(viewer) {
|
||||
@@ -23,8 +22,32 @@ export function createInteraction({ state, screenSpaceEventHandlerFactory }) {
|
||||
}
|
||||
|
||||
function resolvePickRecord(picked) {
|
||||
const info = picked?.id;
|
||||
return info && state._pickRecords.has(info) ? info : null;
|
||||
if (!picked) return null;
|
||||
const primitive = picked.primitive;
|
||||
if (primitive) {
|
||||
const primitiveInfo = state._pickByEntity.get(primitive);
|
||||
if (primitiveInfo) return primitiveInfo;
|
||||
if (primitive.__gevTeleGeography) return primitive.__gevTeleGeography;
|
||||
if (
|
||||
primitive.id &&
|
||||
typeof primitive.id === 'object' &&
|
||||
primitive.id.reference
|
||||
) {
|
||||
return primitive.id;
|
||||
}
|
||||
}
|
||||
|
||||
const entity = picked.id;
|
||||
if (entity) {
|
||||
const entityInfo = state._pickByEntity.get(entity);
|
||||
if (entityInfo) return entityInfo;
|
||||
if (entity.__gevTeleGeography) return entity.__gevTeleGeography;
|
||||
if (entity.id && typeof entity.id === 'object' && entity.id.reference) {
|
||||
return entity.id;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function flyToReference(viewer, reference) {
|
||||
@@ -47,7 +70,7 @@ export function createInteraction({ state, screenSpaceEventHandlerFactory }) {
|
||||
});
|
||||
}
|
||||
return {
|
||||
registerPick,
|
||||
registerPickEntity,
|
||||
beginInteraction,
|
||||
resolvePickRecord,
|
||||
flyToReference,
|
||||
|
||||
@@ -38,13 +38,12 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
|
||||
// never emit moveEnd — reach the motion fallback. No render is
|
||||
// requested for a fallback sweep: it only fires while the camera is
|
||||
// already moving, so frames are flowing by construction.
|
||||
if (!state._enabled || !state._loaded) return;
|
||||
// Markers left over from the last sweep, a few per frame; line
|
||||
// shows and rebuilt stems waiting for their geometry.
|
||||
parts.rendering.revealLandingMarkers();
|
||||
parts.rendering.syncLineShow();
|
||||
parts.rendering.settleStems();
|
||||
if (!state._referenceSweepGate.shouldRun(viewer.camera)) return;
|
||||
if (
|
||||
!state._enabled ||
|
||||
!state._loaded ||
|
||||
!state._referenceSweepGate.shouldRun(viewer.camera)
|
||||
)
|
||||
return;
|
||||
parts.rendering.updateReferenceVisibility();
|
||||
},
|
||||
);
|
||||
@@ -81,15 +80,10 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
|
||||
state._loading = false;
|
||||
state._loadingLabel = '';
|
||||
}
|
||||
// Hide what is built and keep it: a hidden primitive is skipped by
|
||||
// the scene, so it costs nothing per frame, and the next enable shows
|
||||
// it again without a rebuild. Only the stems go: they are sized for
|
||||
// the view and the next sweep redraws them in a worker. An in-flight load's own post-await
|
||||
// ownership check stops that stale generation from building anything.
|
||||
state._pendingLandingReveals.length = 0;
|
||||
parts.rendering.dropStems();
|
||||
parts.rendering.updateVisibility();
|
||||
state._viewer?.scene?.requestRender?.();
|
||||
// Free the entities rather than hide them; enable() rebuilds from the
|
||||
// cached JSON. An in-flight load's own post-await ownership check
|
||||
// removes whatever that stale generation adds later.
|
||||
parts.rendering.releaseDataSources(state._viewer);
|
||||
},
|
||||
|
||||
update(viewer) {
|
||||
@@ -98,7 +92,9 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
|
||||
|
||||
destroy(viewer) {
|
||||
if (state._abort) state._abort.abort();
|
||||
parts.rendering.destroyScene(viewer || state._viewer);
|
||||
parts.rendering.releaseDataSources(viewer || state._viewer);
|
||||
state._cachedCableJson = null;
|
||||
state._cachedLandingJson = null;
|
||||
// hide() clears every published host entry and goes invisible while
|
||||
// keeping the publisher reusable — the legacy layer supported re-init
|
||||
// after destroy, and hidden publishers already drop late publishes.
|
||||
@@ -132,6 +128,16 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
|
||||
state._error = null;
|
||||
state._lastUpdate = null;
|
||||
state._loadingLabel = '';
|
||||
state._cableDataSource = null;
|
||||
state._landingDataSource = null;
|
||||
state._referenceDataSource = null;
|
||||
state._referenceRecords = [];
|
||||
state._surfaceRecords = [];
|
||||
state._pickByEntity = new WeakMap();
|
||||
state._referenceLabelCount = 0;
|
||||
state._publishScratch.length = 0;
|
||||
state._markerBlendDone = false;
|
||||
state._markerBlendInvariantWarned = false;
|
||||
parts.rendering.resetPublishSignature();
|
||||
state._referenceSweepGate.reset();
|
||||
},
|
||||
|
||||
@@ -41,7 +41,7 @@ export function selectCableReferenceLabelWinners(
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.distanceM - b.distanceM ||
|
||||
String(a.id || '').localeCompare(String(b.id || '')),
|
||||
String(a.entity?.id || '').localeCompare(String(b.entity?.id || '')),
|
||||
)
|
||||
.slice(0, cap);
|
||||
}
|
||||
@@ -248,15 +248,16 @@ export function createCableReferenceSweepGate({
|
||||
}
|
||||
|
||||
/**
|
||||
* Recompute one stem tip on the sweep cadence. The tip is moved in place, so
|
||||
* the label entry keeps pointing at it, and only when the camera-scaled tip
|
||||
* moved beyond the settle epsilon; the tip point follows with one buffer
|
||||
* write, and the caller redraws the stems when any tip moved.
|
||||
* @param {object} record Reference record with point/base/tip/nextTip.
|
||||
* Recompute one staticized stem on the sweep cadence. Replaces the former
|
||||
* per-frame `CallbackProperty` pair: constant properties are redefined only
|
||||
* when the camera-scaled tip moved beyond the settle epsilon, and the two
|
||||
* preallocated position buffers alternate so each real change raises exactly
|
||||
* one geometry notification (the localGeojson double-buffer pattern).
|
||||
* @param {object} record Reference record with entity/base/tip/nextTip/buffers.
|
||||
* @param {Cesium.Cartesian3} cameraPositionWC
|
||||
* @param {number} canvasHeight CSS-pixel canvas height.
|
||||
* @param {number} fov Camera frustum field of view (radians).
|
||||
* @returns {boolean} True when the tip moved.
|
||||
* @returns {boolean} True when the stem geometry was redefined.
|
||||
*/
|
||||
|
||||
export function updateCableReferenceStem(
|
||||
@@ -288,7 +289,13 @@ export function updateCableReferenceStem(
|
||||
return false;
|
||||
}
|
||||
Cesium.Cartesian3.clone(record.nextTip, record.tip);
|
||||
record.point.position = record.tip;
|
||||
record.stemPositionBufferIndex = 1 - record.stemPositionBufferIndex;
|
||||
const stemPositions =
|
||||
record.stemPositionBuffers[record.stemPositionBufferIndex];
|
||||
stemPositions[0] = record.base;
|
||||
stemPositions[1] = record.tip;
|
||||
record.entity.position.setValue(record.tip);
|
||||
record.entity.polyline.positions.setValue(stemPositions);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export const BASE_CABLE_COLOR = '#39d5ff';
|
||||
|
||||
export const BASE_LANDING_COLOR = '#8fffd2';
|
||||
@@ -64,22 +66,6 @@ export const CABLE_LABEL_DEPTH_DECISION = Object.freeze({
|
||||
depthTested: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* Landing markers clamped to the ground per rendered frame. A marker is put
|
||||
* on the surface the first time it comes into view, and that reads the
|
||||
* terrain height under it. Doing it for all 1,917 in the frame after the
|
||||
* layer was switched on was a single task (measured 1.2 s on a loaded
|
||||
* globe); a few dozen per frame keeps each frame short and the markers still
|
||||
* fill in within a second. A marker is clamped once: after that Cesium moves
|
||||
* it as terrain loads, and hiding or showing it reads nothing.
|
||||
*/
|
||||
|
||||
export const CABLE_LANDING_REVEALS_PER_FRAME = 48;
|
||||
|
||||
/** Pixel size of the marker drawn for point geometry (GeoJSON's small pin). */
|
||||
|
||||
export const CABLE_MARKER_SIZE = 6;
|
||||
|
||||
/**
|
||||
* `MAP_STACKS` ids that render imagery on the SHOWN Cesium globe (the ion
|
||||
* Bing stacks + OSM). Deliberately an explicit allowlist, not "anything that
|
||||
@@ -95,6 +81,19 @@ export const CABLE_GLOBE_STACK_IDS = Object.freeze(
|
||||
new Set(['bing-aerial', 'bing-labels', 'esri-imagery', 'osm']),
|
||||
);
|
||||
|
||||
/** EntityCluster's private marker collections and their required types. */
|
||||
|
||||
export const MARKER_COLLECTION_EXPECTATIONS = Object.freeze([
|
||||
Object.freeze({
|
||||
key: '_billboardCollection',
|
||||
type: Cesium.BillboardCollection,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: '_pointCollection',
|
||||
type: Cesium.PointPrimitiveCollection,
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Monotonic clock for the sweep gate's motion probe. A hoisted declaration:
|
||||
* the module's `export default createTeleGeographySubmarineCableLayer()`
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
CABLE_LANDING_REVEALS_PER_FRAME,
|
||||
CABLE_MARKER_SIZE,
|
||||
} from './policy.js';
|
||||
probeTranslucentMarkerBlend,
|
||||
commitTranslucentMarkerBlend,
|
||||
} from './surface.js';
|
||||
import {
|
||||
clampLabel,
|
||||
createCableOverlayEntry,
|
||||
@@ -11,13 +11,7 @@ import {
|
||||
cableReferencePriority,
|
||||
} from './overlay.js';
|
||||
|
||||
const defaultMarkerImage = (color) =>
|
||||
new Cesium.PinBuilder().fromColor(color, CABLE_MARKER_SIZE);
|
||||
|
||||
export function createRendering({
|
||||
state,
|
||||
createMarkerImage = defaultMarkerImage,
|
||||
}) {
|
||||
export function createRendering({ state }) {
|
||||
function resetPublishSignature() {
|
||||
state._lastPublishedIds.length = 0;
|
||||
state._lastPublishedPriorities.length = 0;
|
||||
@@ -25,131 +19,129 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/**
|
||||
* Build everything the layer draws, in one synchronous pass with no entity
|
||||
* per feature. The layer used to load two GeoJsonDataSources and a
|
||||
* CustomDataSource: 6,459 entities whose creation held about 1 GB of
|
||||
* short-lived heap, whose visualizers ran 100–250 ms tasks whenever shows
|
||||
* or stems changed, and whose removal on disable was a 150 ms task. These
|
||||
* are the primitives Cesium built from those entities, made directly:
|
||||
*
|
||||
* - lines: one GroundPolylinePrimitive, a colour and a show flag per line
|
||||
* (Cesium's own batch for clamped colour polylines), tessellated in a
|
||||
* worker;
|
||||
* - point markers: one BillboardCollection, each billboard hidden and
|
||||
* unclamped until revealLandingMarkers puts it on the ground;
|
||||
* - references: one PointPrimitiveCollection for the tips, whose positions
|
||||
* and shows are plain buffer writes, and one Primitive of polylines for
|
||||
* the stems (see rebuildStems).
|
||||
*
|
||||
* `lines`, `markers` and `references` come from ingestion; each line and
|
||||
* marker carries the pick record Cesium returns as the pick id.
|
||||
* Remove the three data sources from the viewer and forget the built
|
||||
* entities. Hiding them (`show = false`) is NOT enough: Cesium's
|
||||
* DataSourceDisplay still walks every visualizer of a hidden source on
|
||||
* every frame, and the thousands of hidden polylines/billboards keep
|
||||
* costing CPU and GC pressure long after the user toggled the layer off —
|
||||
* that is the "everything gets sluggish after I turn layers off" report.
|
||||
* The fetched JSON stays cached, so the next enable rebuilds without a
|
||||
* network round trip or a re-parse.
|
||||
*/
|
||||
|
||||
function buildScene(viewer, { lines, markers, references }) {
|
||||
const scene = viewer.scene;
|
||||
state._lineRecords = [];
|
||||
state._markerRecords = [];
|
||||
function releaseDataSources(viewer) {
|
||||
const sources = [
|
||||
state._cableDataSource,
|
||||
state._landingDataSource,
|
||||
state._referenceDataSource,
|
||||
];
|
||||
state._cableDataSource = null;
|
||||
state._landingDataSource = null;
|
||||
state._referenceDataSource = null;
|
||||
state._referenceRecords = [];
|
||||
state._pendingLandingReveals.length = 0;
|
||||
|
||||
if (lines.length) {
|
||||
// The entity display gave every line this attribute too. It is a float
|
||||
// attribute, and with one present Cesium keeps the per-line width as a
|
||||
// float; without it the 2.5 px width is stored as a byte and draws 2 px.
|
||||
const always =
|
||||
Cesium.DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
|
||||
new Cesium.DistanceDisplayCondition(),
|
||||
);
|
||||
const instances = lines.map(
|
||||
(line) =>
|
||||
new Cesium.GeometryInstance({
|
||||
id: line.info,
|
||||
geometry: new Cesium.GroundPolylineGeometry({
|
||||
positions: line.positions,
|
||||
width: line.width,
|
||||
// GeoJSON lines are rhumb lines (GeoJsonDataSource's choice).
|
||||
arcType: Cesium.ArcType.RHUMB,
|
||||
}),
|
||||
attributes: {
|
||||
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
|
||||
line.color,
|
||||
),
|
||||
show: new Cesium.ShowGeometryInstanceAttribute(true),
|
||||
distanceDisplayCondition: always,
|
||||
},
|
||||
}),
|
||||
);
|
||||
state._cablePrimitive = scene.groundPrimitives.add(
|
||||
new Cesium.GroundPolylinePrimitive({
|
||||
geometryInstances: instances,
|
||||
appearance: new Cesium.PolylineColorAppearance(),
|
||||
classificationType: state._classificationType,
|
||||
asynchronous: true,
|
||||
show: state._enabled,
|
||||
}),
|
||||
);
|
||||
for (const line of lines)
|
||||
state._lineRecords.push({
|
||||
info: line.info,
|
||||
base: line.base,
|
||||
visible: true,
|
||||
shown: true,
|
||||
attributes: null,
|
||||
});
|
||||
}
|
||||
|
||||
if (markers.length) {
|
||||
// Every marker is translucent, so one blend pass, not Cesium's two.
|
||||
const billboards = scene.primitives.add(
|
||||
new Cesium.BillboardCollection({
|
||||
scene,
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
show: state._enabled,
|
||||
}),
|
||||
);
|
||||
state._markerBillboards = billboards;
|
||||
const images = new Map();
|
||||
for (const marker of markers) {
|
||||
const key = marker.color.toCssHexString();
|
||||
let image = images.get(key);
|
||||
if (!image) {
|
||||
image = {
|
||||
id: `gev-cable-marker-${key}`,
|
||||
source: createMarkerImage(marker.color),
|
||||
};
|
||||
images.set(key, image);
|
||||
}
|
||||
const billboard = billboards.add({
|
||||
id: marker.info,
|
||||
position: marker.position,
|
||||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||||
show: false,
|
||||
});
|
||||
billboard.setImage(image.id, image.source);
|
||||
state._markerRecords.push({
|
||||
info: marker.info,
|
||||
marker: billboard,
|
||||
base: marker.base,
|
||||
// A position with its own height is drawn there, as before.
|
||||
clamped: marker.hasHeight,
|
||||
visible: false,
|
||||
});
|
||||
state._surfaceRecords = [];
|
||||
state._pickByEntity = new WeakMap();
|
||||
state._referenceLabelCount = 0;
|
||||
state._publishScratch.length = 0;
|
||||
// The blend pass targets the collections being dropped; the rebuilt
|
||||
// sources need their own pass.
|
||||
state._markerBlendDone = false;
|
||||
state._loaded = false;
|
||||
state._referenceSweepGate.reset();
|
||||
for (const source of sources) {
|
||||
if (!source) continue;
|
||||
try {
|
||||
viewer?.dataSources?.remove(source, true);
|
||||
} catch {
|
||||
/* collection gone */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (references.length) {
|
||||
state._referencePoints = scene.primitives.add(
|
||||
new Cesium.PointPrimitiveCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
show: state._enabled,
|
||||
}),
|
||||
);
|
||||
for (const reference of references) addReferenceStem(reference);
|
||||
function updateVisibility() {
|
||||
if (state._cableDataSource) state._cableDataSource.show = state._enabled;
|
||||
if (state._landingDataSource)
|
||||
state._landingDataSource.show = state._enabled;
|
||||
if (state._referenceDataSource)
|
||||
state._referenceDataSource.show = state._enabled;
|
||||
}
|
||||
|
||||
function styleCableEntity(entity, feature) {
|
||||
if (!entity?.polyline) return;
|
||||
const color = feature?.properties?.color
|
||||
? Cesium.Color.fromCssColorString(String(feature.properties.color))
|
||||
: state.cableColor;
|
||||
entity.polyline.material = color.withAlpha(0.92);
|
||||
entity.polyline.width = 2.5;
|
||||
entity.polyline.clampToGround = true;
|
||||
entity.polyline.classificationType = state._classificationType;
|
||||
entity.show = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the single translucent blend pass to the landing-billboard and
|
||||
* reference-point collections. Landing entities carry only billboards and
|
||||
* reference entities only points, so completion is one applied collection
|
||||
* per source; a failed shape probe disables the optimization permanently
|
||||
* for this session and says so loudly in dev builds.
|
||||
* Both sources are probed BEFORE either is committed, so the helper's
|
||||
* "defaults untouched on shape drift" fallback holds across the pair too —
|
||||
* a reference-source failure can never leave the landing source already
|
||||
* forced to TRANSLUCENT.
|
||||
*/
|
||||
|
||||
function applyMarkerBlendOnce() {
|
||||
const landing = probeTranslucentMarkerBlend(state._landingDataSource);
|
||||
const reference = probeTranslucentMarkerBlend(state._referenceDataSource);
|
||||
if (landing.invariantFailed || reference.invariantFailed) {
|
||||
state._markerBlendDone = true;
|
||||
if (!state._markerBlendInvariantWarned && import.meta.env?.DEV === true) {
|
||||
state._markerBlendInvariantWarned = true;
|
||||
console.error(
|
||||
'[Data:telegeography-submarine-cables] EntityCluster marker-collection ' +
|
||||
'shape changed — single-pass translucent blend skipped; markers fall ' +
|
||||
"back to Cesium's default two-pass blend.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
state._lineShowDirty = false;
|
||||
const landingBlend = commitTranslucentMarkerBlend(landing);
|
||||
const referenceBlend = commitTranslucentMarkerBlend(reference);
|
||||
if (landingBlend.applied > 0 && referenceBlend.applied > 0)
|
||||
state._markerBlendDone = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-classify every cable ground line for the active surface. One batched
|
||||
* ground-primitive rebuild per stack switch — never per frame.
|
||||
* @param {Cesium.ClassificationType} next
|
||||
*/
|
||||
|
||||
function applyCableClassification(next) {
|
||||
if (next === undefined || next === state._classificationType) return;
|
||||
state._classificationType = next;
|
||||
if (!state._cableDataSource) return;
|
||||
const entities = state._cableDataSource.entities.values;
|
||||
for (let i = 0; i < entities.length; i++) {
|
||||
const polyline = entities[i].polyline;
|
||||
if (polyline) polyline.classificationType = next;
|
||||
}
|
||||
state._viewer?.scene?.requestRender?.();
|
||||
}
|
||||
|
||||
function styleLandingEntity(entity, feature) {
|
||||
if (!entity?.point) return;
|
||||
entity.point.color = state.landingColor.withAlpha(0.92);
|
||||
entity.point.pixelSize = feature?.properties?.is_tbd ? 6 : 7;
|
||||
entity.point.outlineColor = state.cableOutline;
|
||||
entity.point.outlineWidth = 1;
|
||||
entity.point.disableDepthTestDistance = 0;
|
||||
entity.show = true;
|
||||
}
|
||||
|
||||
function addReferenceStem({ reference, label, kind, color, feature }) {
|
||||
if (!state._referenceDataSource || !reference) return;
|
||||
|
||||
const base = Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0);
|
||||
const tip = Cesium.Cartesian3.fromDegrees(
|
||||
reference.lon,
|
||||
@@ -162,31 +154,42 @@ export function createRendering({
|
||||
label,
|
||||
featureId: feature?.id || feature?.properties?.id || null,
|
||||
};
|
||||
state._pickRecords.add(info);
|
||||
const pointColor = color.withAlpha(kind === 'cable' ? 0.84 : 0.94);
|
||||
// The tip is moved in place on the sweep cadence (overlay.js), never by a
|
||||
// per-frame callback.
|
||||
const point = state._referencePoints.add({
|
||||
id: info,
|
||||
position: tip,
|
||||
pixelSize: kind === 'cable' ? 7 : 8,
|
||||
color: pointColor,
|
||||
outlineColor: Cesium.Color.BLACK.withAlpha(0.65),
|
||||
outlineWidth: 1,
|
||||
disableDepthTestDistance: 0,
|
||||
show: false,
|
||||
});
|
||||
const record = {
|
||||
const stemColor = color.withAlpha(kind === 'cable' ? 0.58 : 0.68);
|
||||
// Constant properties on the sweep cadence, never per-frame callbacks:
|
||||
// the sweep redefines them through the alternating buffers below.
|
||||
const stemPositionBuffers = [
|
||||
[base, tip],
|
||||
[base, tip],
|
||||
];
|
||||
|
||||
const entity = state._referenceDataSource.entities.add({
|
||||
id: `${kind}-reference-${state._referenceRecords.length}-${info.featureId || 'feature'}`,
|
||||
info,
|
||||
point,
|
||||
position: tip,
|
||||
polyline: {
|
||||
positions: stemPositionBuffers[0],
|
||||
width: kind === 'cable' ? 2 : 2.4,
|
||||
material: new Cesium.ColorMaterialProperty(stemColor),
|
||||
},
|
||||
point: {
|
||||
pixelSize: kind === 'cable' ? 7 : 8,
|
||||
color: pointColor,
|
||||
outlineColor: Cesium.Color.BLACK.withAlpha(0.65),
|
||||
outlineWidth: 1,
|
||||
disableDepthTestDistance: 0,
|
||||
},
|
||||
});
|
||||
|
||||
entity.__gevTeleGeography = info;
|
||||
state._pickByEntity.set(entity, info);
|
||||
const record = {
|
||||
id: entity.id,
|
||||
entity,
|
||||
base,
|
||||
tip,
|
||||
nextTip: Cesium.Cartesian3.clone(tip),
|
||||
stemColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
|
||||
color.withAlpha(kind === 'cable' ? 0.58 : 0.68),
|
||||
),
|
||||
stemWidth: kind === 'cable' ? 2 : 2.4,
|
||||
stemPositionBuffers,
|
||||
stemPositionBufferIndex: 0,
|
||||
reference,
|
||||
kind,
|
||||
label: clampLabel(label),
|
||||
@@ -198,212 +201,6 @@ export function createRendering({
|
||||
state._referenceRecords.push(record);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the stems of the references now in view, base to tip. Stems are one
|
||||
* static polyline primitive, as the entity display batched them: nothing
|
||||
* runs for it per frame, and a stem's length cannot change without new
|
||||
* geometry. So a sweep that moved a tip or changed which references are
|
||||
* in view builds a replacement in a worker, and settleStems swaps it in
|
||||
* once it is ready; the previous stems stay until then. A sweep that
|
||||
* changed nothing builds nothing.
|
||||
*/
|
||||
|
||||
function rebuildStems() {
|
||||
const primitives = state._viewer?.scene?.primitives;
|
||||
if (!primitives) return;
|
||||
if (state._stemPrimitivePending) {
|
||||
// Superseded before it was ever shown.
|
||||
primitives.remove(state._stemPrimitivePending);
|
||||
state._stemPrimitivePending = null;
|
||||
}
|
||||
const instances = [];
|
||||
for (const record of state._referenceRecords) {
|
||||
if (!record.visible) continue;
|
||||
instances.push(
|
||||
new Cesium.GeometryInstance({
|
||||
id: record.info,
|
||||
geometry: new Cesium.PolylineGeometry({
|
||||
positions: [record.base, record.tip],
|
||||
width: record.stemWidth,
|
||||
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
|
||||
}),
|
||||
attributes: { color: record.stemColor },
|
||||
}),
|
||||
);
|
||||
}
|
||||
state._stemsDirty = false;
|
||||
if (!instances.length) {
|
||||
if (state._stemPrimitive) primitives.remove(state._stemPrimitive);
|
||||
state._stemPrimitive = null;
|
||||
return;
|
||||
}
|
||||
state._stemPrimitivePending = primitives.add(
|
||||
new Cesium.Primitive({
|
||||
geometryInstances: instances,
|
||||
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
|
||||
asynchronous: true,
|
||||
// Hidden while it builds; settleStems shows it.
|
||||
show: false,
|
||||
}),
|
||||
);
|
||||
state._viewer.scene.requestRender?.();
|
||||
}
|
||||
|
||||
/** Swap in rebuilt stems once their geometry is ready; called per frame. */
|
||||
|
||||
function settleStems() {
|
||||
const pending = state._stemPrimitivePending;
|
||||
if (!pending) return;
|
||||
const scene = state._viewer?.scene;
|
||||
if (!pending.ready) {
|
||||
// Keep frames coming until the geometry is in.
|
||||
scene?.requestRender?.();
|
||||
return;
|
||||
}
|
||||
pending.show = state._enabled;
|
||||
if (state._stemPrimitive) scene?.primitives?.remove(state._stemPrimitive);
|
||||
state._stemPrimitive = pending;
|
||||
state._stemPrimitivePending = null;
|
||||
scene?.requestRender?.();
|
||||
}
|
||||
|
||||
/** Remove and destroy everything buildScene made. Only destroy() does this;
|
||||
* a disable hides the primitives and keeps them for the next enable. */
|
||||
|
||||
function destroyScene(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
const owned = [
|
||||
[scene?.groundPrimitives, state._cablePrimitive],
|
||||
[scene?.primitives, state._markerBillboards],
|
||||
[scene?.primitives, state._stemPrimitive],
|
||||
[scene?.primitives, state._stemPrimitivePending],
|
||||
[scene?.primitives, state._referencePoints],
|
||||
];
|
||||
state._cablePrimitive = null;
|
||||
state._markerBillboards = null;
|
||||
state._stemPrimitive = null;
|
||||
state._stemPrimitivePending = null;
|
||||
state._stemsDirty = false;
|
||||
state._referencePoints = null;
|
||||
state._referenceRecords = [];
|
||||
state._lineRecords = [];
|
||||
state._markerRecords = [];
|
||||
state._lineShowDirty = false;
|
||||
state._pendingLandingReveals.length = 0;
|
||||
state._pickRecords = new WeakSet();
|
||||
state._referenceLabelCount = 0;
|
||||
state._publishScratch.length = 0;
|
||||
state._loaded = false;
|
||||
state._referenceSweepGate.reset();
|
||||
for (const [collection, primitive] of owned) {
|
||||
if (!primitive) continue;
|
||||
try {
|
||||
// A collection destroys what it removes; one that is already gone
|
||||
// has destroyed it too.
|
||||
if (!collection?.remove?.(primitive) && !primitive.isDestroyed())
|
||||
primitive.destroy();
|
||||
} catch {
|
||||
/* collection gone */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the stems, shown and building, so the next sweep draws them afresh.
|
||||
* A disable does this: stems kept from the view the layer was switched off
|
||||
* in would show at their old lengths until the rebuild for the new view
|
||||
* was ready.
|
||||
*/
|
||||
|
||||
function dropStems() {
|
||||
const primitives = state._viewer?.scene?.primitives;
|
||||
for (const primitive of [state._stemPrimitive, state._stemPrimitivePending])
|
||||
if (primitive) primitives?.remove(primitive);
|
||||
state._stemPrimitive = null;
|
||||
state._stemPrimitivePending = null;
|
||||
state._stemsDirty = true;
|
||||
}
|
||||
|
||||
function updateVisibility() {
|
||||
for (const primitive of [
|
||||
state._cablePrimitive,
|
||||
state._markerBillboards,
|
||||
state._stemPrimitive,
|
||||
state._referencePoints,
|
||||
])
|
||||
if (primitive) primitive.show = state._enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-classify the cable ground lines for the active surface. The primitive
|
||||
* reads its classification as it queues commands, so this is one
|
||||
* assignment per stack switch and no rebuild.
|
||||
* @param {Cesium.ClassificationType} next
|
||||
*/
|
||||
|
||||
function applyCableClassification(next) {
|
||||
if (next === undefined || next === state._classificationType) return;
|
||||
state._classificationType = next;
|
||||
if (!state._cablePrimitive) return;
|
||||
state._cablePrimitive.classificationType = next;
|
||||
state._viewer?.scene?.requestRender?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the line show states the last sweep worked out. The primitive
|
||||
* builds its geometry in a worker and has no per-line attributes until it
|
||||
* is ready, so the states wait in the records until then.
|
||||
*/
|
||||
|
||||
function syncLineShow() {
|
||||
if (!state._lineShowDirty) return;
|
||||
const primitive = state._cablePrimitive;
|
||||
if (!primitive?.ready) {
|
||||
// Keep frames coming until the geometry is in.
|
||||
if (primitive) state._viewer?.scene?.requestRender?.();
|
||||
return;
|
||||
}
|
||||
for (const record of state._lineRecords) {
|
||||
if (record.shown === record.visible) continue;
|
||||
record.attributes ??= primitive.getGeometryInstanceAttributes(
|
||||
record.info,
|
||||
);
|
||||
if (!record.attributes) continue;
|
||||
record.attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(
|
||||
record.visible,
|
||||
record.attributes.show,
|
||||
);
|
||||
record.shown = record.visible;
|
||||
}
|
||||
state._lineShowDirty = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the next few markers the last sweep found visible on the ground and
|
||||
* show them, and ask for another frame while any are left. Called from the
|
||||
* sweep and then once per rendered frame, so a parked camera costs nothing
|
||||
* once the list is empty. Clamping is what reads the terrain height, once
|
||||
* per marker; Cesium then keeps the marker on the surface as terrain loads,
|
||||
* within its own per-frame time budget.
|
||||
*/
|
||||
|
||||
function revealLandingMarkers() {
|
||||
const pending = state._pendingLandingReveals;
|
||||
if (!pending.length) return;
|
||||
let budget = CABLE_LANDING_REVEALS_PER_FRAME;
|
||||
while (pending.length && budget > 0) {
|
||||
const record = pending.pop();
|
||||
if (!record.visible || record.marker.show) continue;
|
||||
if (!record.clamped) {
|
||||
record.marker.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND;
|
||||
record.clamped = true;
|
||||
budget--;
|
||||
}
|
||||
record.marker.show = true;
|
||||
}
|
||||
if (pending.length) state._viewer?.scene?.requestRender?.();
|
||||
}
|
||||
|
||||
function updateReferenceVisibility() {
|
||||
if (!state._enabled || !state._viewer?.camera) return;
|
||||
const cameraPos = state._viewer.camera.positionWC;
|
||||
@@ -419,35 +216,20 @@ export function createRendering({
|
||||
const visible = occluder.isPointVisible(record.base);
|
||||
record.visible = visible;
|
||||
record.distanceM = Cesium.Cartesian3.distance(cameraPos, record.base);
|
||||
if (record.point.show !== visible) {
|
||||
record.point.show = visible;
|
||||
state._stemsDirty = true;
|
||||
if (record.entity.show !== visible) {
|
||||
record.entity.show = visible;
|
||||
}
|
||||
// Hidden stems keep their last tip; this same sweep refreshes them in
|
||||
// the pass where they turn visible again.
|
||||
if (
|
||||
visible &&
|
||||
updateCableReferenceStem(record, cameraPos, canvasHeight, fov)
|
||||
)
|
||||
state._stemsDirty = true;
|
||||
// Hidden stems keep their last geometry; this same sweep refreshes them
|
||||
// in the pass where they turn visible again.
|
||||
if (visible)
|
||||
updateCableReferenceStem(record, cameraPos, canvasHeight, fov);
|
||||
}
|
||||
if (state._stemsDirty) rebuildStems();
|
||||
for (const record of state._lineRecords) {
|
||||
record.visible = occluder.isPointVisible(record.base);
|
||||
if (record.visible !== record.shown) state._lineShowDirty = true;
|
||||
}
|
||||
syncLineShow();
|
||||
state._pendingLandingReveals.length = 0;
|
||||
for (const record of state._markerRecords) {
|
||||
for (const record of state._surfaceRecords) {
|
||||
const visible = occluder.isPointVisible(record.base);
|
||||
record.visible = visible;
|
||||
if (record.marker.show === visible) continue;
|
||||
// A marker not yet on the ground waits its turn; one that already is
|
||||
// shows at once, and hiding is immediate.
|
||||
if (visible && !record.clamped) state._pendingLandingReveals.push(record);
|
||||
else record.marker.show = visible;
|
||||
if (record.entity.show !== visible) {
|
||||
record.entity.show = visible;
|
||||
}
|
||||
}
|
||||
revealLandingMarkers();
|
||||
const winners = selectCableReferenceLabelWinners(state._referenceRecords);
|
||||
let changed = winners.length !== state._lastPublishedCount;
|
||||
for (let i = 0; i < winners.length; i++) {
|
||||
@@ -465,6 +247,9 @@ export function createRendering({
|
||||
}
|
||||
state._publishScratch.length = winners.length;
|
||||
state._referenceLabelCount = winners.length;
|
||||
// The marker collections are created lazily by the visualizers, so the
|
||||
// single-pass blend is applied on the sweep cadence until both landed.
|
||||
if (!state._markerBlendDone) applyMarkerBlendOnce();
|
||||
if (!changed) return;
|
||||
state._overlayPublisher.publish(state._publishScratch);
|
||||
state._lastPublishedCount = winners.length;
|
||||
@@ -477,14 +262,13 @@ export function createRendering({
|
||||
}
|
||||
return {
|
||||
resetPublishSignature,
|
||||
buildScene,
|
||||
destroyScene,
|
||||
releaseDataSources,
|
||||
updateVisibility,
|
||||
styleCableEntity,
|
||||
applyMarkerBlendOnce,
|
||||
applyCableClassification,
|
||||
syncLineShow,
|
||||
settleStems,
|
||||
dropStems,
|
||||
revealLandingMarkers,
|
||||
styleLandingEntity,
|
||||
addReferenceStem,
|
||||
updateReferenceVisibility,
|
||||
};
|
||||
}
|
||||
@@ -30,50 +30,26 @@ export function createState({ sweepClock, overlayHost }) {
|
||||
|
||||
state._loadGeneration = 0;
|
||||
|
||||
state._cableDataSource = null;
|
||||
|
||||
state._landingDataSource = null;
|
||||
|
||||
state._referenceDataSource = null;
|
||||
|
||||
/**
|
||||
* What the layer draws, built once per load and kept across disable/enable
|
||||
* (a disable only hides them, which costs nothing per frame):
|
||||
* one ground polyline primitive for every line, one billboard collection
|
||||
* for every point marker, a point collection for the reference tips and
|
||||
* one polyline primitive for the reference stems.
|
||||
* Fetched cable/landing JSON kept across disable/enable. A disable RELEASES
|
||||
* the three data sources (see releaseDataSources) instead of hiding them,
|
||||
* so a re-enable has to rebuild the entities; the network/parse half of
|
||||
* that rebuild is the expensive part users would notice, so it is cached.
|
||||
*/
|
||||
|
||||
state._cablePrimitive = null;
|
||||
state._cachedCableJson = null;
|
||||
|
||||
state._markerBillboards = null;
|
||||
|
||||
state._referencePoints = null;
|
||||
|
||||
/** The stems now drawn, and their replacement while it builds. */
|
||||
|
||||
state._stemPrimitive = null;
|
||||
|
||||
state._stemPrimitivePending = null;
|
||||
|
||||
state._stemsDirty = false;
|
||||
state._cachedLandingJson = null;
|
||||
|
||||
state._referenceRecords = [];
|
||||
|
||||
/** One record per drawn line: its pick record, horizon base and show state. */
|
||||
|
||||
state._lineRecords = [];
|
||||
|
||||
/** Line show states still to be written once the primitive is ready. */
|
||||
|
||||
state._lineShowDirty = false;
|
||||
|
||||
/** One record per point marker: its billboard and horizon base. */
|
||||
|
||||
state._markerRecords = [];
|
||||
|
||||
/** Markers the last sweep found visible but not on the ground yet; drained
|
||||
* a few per frame (CABLE_LANDING_REVEALS_PER_FRAME). */
|
||||
|
||||
state._pendingLandingReveals = [];
|
||||
|
||||
/** The pick records handed to Cesium as ids, so a pick is known to be ours. */
|
||||
|
||||
state._pickRecords = new WeakSet();
|
||||
state._surfaceRecords = [];
|
||||
|
||||
state._clickHandler = null;
|
||||
|
||||
@@ -87,6 +63,14 @@ export function createState({ sweepClock, overlayHost }) {
|
||||
|
||||
state._classificationType = Cesium.ClassificationType.BOTH;
|
||||
|
||||
/** True once both marker collections blend translucent (or the shape probe failed). */
|
||||
|
||||
state._markerBlendDone = false;
|
||||
|
||||
state._markerBlendInvariantWarned = false;
|
||||
|
||||
state._pickByEntity = new WeakMap();
|
||||
|
||||
state._referenceLabelCount = 0;
|
||||
|
||||
state._referenceSweepGate = createCableReferenceSweepGate({
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { CABLE_GLOBE_STACK_IDS } from './policy.js';
|
||||
import {
|
||||
CABLE_GLOBE_STACK_IDS,
|
||||
MARKER_COLLECTION_EXPECTATIONS,
|
||||
} from './policy.js';
|
||||
|
||||
/**
|
||||
* Ground-line classification for one map stack. The photoreal stack renders
|
||||
@@ -7,7 +10,7 @@ import { CABLE_GLOBE_STACK_IDS } from './policy.js';
|
||||
* need the 3D-tile classification pass there; every other known stack (the
|
||||
* bing stacks and osm) renders imagery on the shown globe, so only the
|
||||
* terrain pass applies.
|
||||
* Classifying against just the active surface halves the
|
||||
* Classifying against just the active surface halves the batched
|
||||
* GroundPolylinePrimitive's emitted command sets. BOTH is the safe fallback
|
||||
* for an unknown stack — it renders on every surface, exactly the shipped
|
||||
* pre-optimization behavior.
|
||||
@@ -37,3 +40,87 @@ export function cableClassificationTypeForScene(scene) {
|
||||
? Cesium.ClassificationType.CESIUM_3D_TILE
|
||||
: Cesium.ClassificationType.TERRAIN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one data source's marker collections WITHOUT mutating anything.
|
||||
* Splitting validation from mutation is what makes the fallback honest: a
|
||||
* shape failure on the SECOND collection (or the second data source) must
|
||||
* not leave the first one already forced to TRANSLUCENT.
|
||||
* @param {Cesium.DataSource|null|undefined} dataSource
|
||||
* @returns {{ready:object[],pending:number,invariantFailed:boolean}}
|
||||
*/
|
||||
|
||||
export function probeTranslucentMarkerBlend(dataSource) {
|
||||
const cluster = dataSource?.clustering;
|
||||
if (!cluster) return { ready: [], pending: 0, invariantFailed: true };
|
||||
const ready = [];
|
||||
let pending = 0;
|
||||
let invariantFailed = false;
|
||||
for (const { key, type } of MARKER_COLLECTION_EXPECTATIONS) {
|
||||
if (!(key in cluster)) {
|
||||
invariantFailed = true;
|
||||
continue;
|
||||
}
|
||||
const collection = cluster[key];
|
||||
if (collection === undefined || collection === null) {
|
||||
pending++;
|
||||
continue;
|
||||
}
|
||||
if (!(collection instanceof type) || !('blendOption' in collection)) {
|
||||
invariantFailed = true;
|
||||
continue;
|
||||
}
|
||||
ready.push(collection);
|
||||
}
|
||||
// Any failure discards every collected target: nothing is mutated at all.
|
||||
if (invariantFailed) return { ready: [], pending: 0, invariantFailed: true };
|
||||
return { ready, pending, invariantFailed: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit a clean probe. Only ever called once every probe in the batch has
|
||||
* passed, so this cannot land a partial application.
|
||||
* @param {{ready:object[],pending:number}} probe
|
||||
* @returns {{applied:number,pending:number,invariantFailed:boolean}}
|
||||
*/
|
||||
|
||||
export function commitTranslucentMarkerBlend(probe) {
|
||||
for (const collection of probe.ready) {
|
||||
if (collection.blendOption !== Cesium.BlendOption.TRANSLUCENT) {
|
||||
collection.blendOption = Cesium.BlendOption.TRANSLUCENT;
|
||||
}
|
||||
}
|
||||
return {
|
||||
applied: probe.ready.length,
|
||||
pending: probe.pending,
|
||||
invariantFailed: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Force one translucent draw pass for a data source's marker collections.
|
||||
* The default `OPAQUE_AND_TRANSLUCENT` blend emits two draw commands per
|
||||
* collection, and every cable marker is translucent (alpha < 1), so the
|
||||
* opaque pass is pure overhead across 1,917 landing billboards + 2,629
|
||||
* reference points. Cesium has no public accessor for the entity-backed
|
||||
* collections, so this reaches through EntityCluster's private fields under
|
||||
* a SHAPE INVARIANT the caller must honor loudly: the constructor
|
||||
* pre-assigns `_billboardCollection`/`_pointCollection` (= undefined until a
|
||||
* visualizer lazily creates them), so a missing PROPERTY means Cesium's
|
||||
* shape changed — report `invariantFailed` and never touch anything —
|
||||
* while a present-but-undefined value only means "not created yet"
|
||||
* (`pending`). Wrong instance types also fail the invariant. The cables
|
||||
* sources never enable clustering, so created collections persist.
|
||||
* VALIDATE-ALL-THEN-MUTATE-ALL: every field/type check runs before the first
|
||||
* assignment, so a failure anywhere leaves BOTH collections on Cesium's
|
||||
* default blend — the fallback this helper promises.
|
||||
* @param {Cesium.DataSource|null|undefined} dataSource
|
||||
* @returns {{applied:number,pending:number,invariantFailed:boolean}}
|
||||
*/
|
||||
|
||||
export function applyTranslucentMarkerBlend(dataSource) {
|
||||
const probe = probeTranslucentMarkerBlend(dataSource);
|
||||
if (probe.invariantFailed)
|
||||
return { applied: 0, pending: 0, invariantFailed: true };
|
||||
return commitTranslucentMarkerBlend(probe);
|
||||
}
|
||||
Reference in new issue
Block a user