Draw submarine cables through the renderer's draw and camera ports

Cable lines, landing pins, polygon fills, reference stems and reference
points are now five draw sets per layer (submarine-cables:N:lines and so
on) instead of GeoJSON data sources and entities. Clicks resolve through
the draw hit; flights and the sweep's eye go through the camera port.
The layer keeps the styling the GeoJSON loader gave it: cable colours,
widths and alphas, simplestyle stroke, fill and marker properties, fills
that keep the source's alpha, raised polygons at their heights, the
default pin image, and features without a reference drawn but neither
picked nor culled. Lines are densified along rhumb lines at the
renderer's own granularity, so the draped geodesic arcs land on the same
vertices the rhumb-line polylines did.

Supporting pieces:
- geo/rhumb, geo/horizon and geo/geodesic port the default renderer's
  rhumb line, ellipsoidal occluder and Vincenty inverse; the stub
  renderer now uses the shared horizon test and Vincenty inverse
  instead of its own copies. render/color gains cssColor, which reads
  CSS colours as the renderer does (hex, rgb, hsl; not named colours).
- The Cesium draw port changes a line in place when only whether it
  shows changes (draped, on its ground primitive, waiting for it to be
  ready rather than restarting its build) or where an undraped line
  runs; anything else still rebuilds. Icon sets honour their blend.

Ingestion, interaction, overlay, policy, rendering, state and surface no
longer import Cesium and leave the allow-list. Pins are culled at the
horizon each frame by the draw port instead of on the sweep, and
marker-symbol glyphs are not drawn inside pins.
This commit is contained in:
Sameh Khamis committed 2026-11-06 22:10:53 -08:00
1 parent f24b66d80d
commit e74c7c1f44
29 files changed
+2260 -2064

No files matched your search

+40
View File
@@ -77,3 +77,43 @@ export function normalizeFeatures(json, kind) {
};
});
}
/**
* A GeoJSON geometry's drawable parts, as GeoJSON sources have always been
* drawn: each line string, point and polygon on its own (multi-geometries
* and collections split into their members). Coordinates stay
* `[lon, lat, height?]` degrees.
* @returns {{lines: number[][][], points: number[][], polygons: number[][][][]}}
*/
export function geometryParts(
geometry,
out = { lines: [], points: [], polygons: [] },
) {
if (!geometry) return out;
const coords = geometry.coordinates;
switch (geometry.type) {
case 'Point':
out.points.push(coords);
break;
case 'MultiPoint':
for (const point of coords) out.points.push(point);
break;
case 'LineString':
out.lines.push(coords);
break;
case 'MultiLineString':
for (const line of coords) out.lines.push(line);
break;
case 'Polygon':
out.polygons.push(coords);
break;
case 'MultiPolygon':
for (const polygon of coords) out.polygons.push(polygon);
break;
case 'GeometryCollection':
for (const member of geometry.geometries ?? [])
geometryParts(member, out);
break;
}
return out;
}
-1
View File
@@ -41,7 +41,6 @@ export {
export {
cableClassificationTypeForStack,
cableClassificationTypeForScene,
applyTranslucentMarkerBlend,
} from './surface.js';
export {
CABLE_REFERENCE_LABEL_WINNER_CAP,
+8 -164
View File
@@ -1,25 +1,5 @@
import { msg, t } from '../../i18n/index.js';
import {
featureLabel,
featureReference,
normalizeFeatures,
} from './geometry.js';
import * as Cesium from 'cesium';
const SOURCE_FEATURE_INDEX = '__gevSourceFeatureIndex';
function indexedCollection(features) {
return {
type: 'FeatureCollection',
features: features.map((feature, index) => ({
...feature,
properties: {
...feature.properties,
[SOURCE_FEATURE_INDEX]: index,
},
})),
};
}
import { normalizeFeatures } from './geometry.js';
export function createIngestion({ state, parts, source }) {
async function load(viewer) {
@@ -31,9 +11,9 @@ export function createIngestion({ state, parts, source }) {
// 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 every await and
// must never touch shared lifecycle state or the viewer it no longer
// must never touch shared lifecycle state or the sets it no longer
// owns — clearing `_loading`/`_abort` for the successor is how duplicate
// or post-destroy data sources got added.
// loads got drawn.
const generation = ++state._loadGeneration;
const abort = new AbortController();
state._abort = abort;
@@ -63,146 +43,10 @@ export function createIngestion({ state, parts, source }) {
const cableFeatures = normalizeFeatures(cableJson, 'cable');
const landingFeatures = normalizeFeatures(landingJson, 'landing');
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._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,
});
});
// Await-free from here: this load still owns the lifecycle, and the
// items go into the layer's own sets in one pass.
parts.rendering.attach(viewer);
parts.rendering.drawFeatures(cableFeatures, landingFeatures);
state._count = cableFeatures.length + landingFeatures.length;
state._loaded = true;
@@ -210,7 +54,7 @@ export function createIngestion({ state, parts, source }) {
state._loadingLabel = '';
parts.rendering.updateVisibility();
state._referenceSweepGate.markDirty();
viewer.scene.requestRender?.();
viewer?.scene?.requestRender?.();
} catch (error) {
// A stale or aborted load reports nothing: its failure belongs to a
// lifecycle the user already left.
+12 -36
View File
@@ -1,47 +1,24 @@
import * as Cesium from 'cesium';
import { cablePicks } from './pickState.js';
import { cameraOf } from '../../render/cesium/camera.js';
export function createInteraction({ state, inputFor }) {
function registerPickEntity(entity, info) {
cablePicks.write(entity).info = info;
}
import { toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createInteraction({ state, parts, inputFor }) {
function beginInteraction(viewer) {
if (state._clickSubscription) return;
state._clickSubscription = inputFor(viewer).onClick((event) => {
if (!state._enabled) return;
const record = resolvePickRecord(event.pick);
const record = resolvePickRecord(event.drawHit);
if (!record?.reference) return;
flyToReference(viewer, record.reference);
});
}
function resolvePickRecord(picked) {
if (!picked) return null;
const primitive = picked.primitive;
if (primitive) {
const primitiveInfo = cablePicks.read(primitive)?.info;
if (primitiveInfo) return primitiveInfo;
if (
primitive.id &&
typeof primitive.id === 'object' &&
primitive.id.reference
) {
return primitive.id;
}
}
const entity = picked.id;
if (entity) {
const entityInfo = cablePicks.read(entity)?.info;
if (entityInfo) return entityInfo;
if (entity.id && typeof entity.id === 'object' && entity.id.reference) {
return entity.id;
}
}
return null;
/**
* What a click's draw hit names: a cable, landing point or reference of
* this layer's current items, as `{ label, kind, featureId, reference }`,
* or null.
*/
function resolvePickRecord(hit) {
return parts.rendering.pickInfo(hit);
}
function flyToReference(viewer, reference) {
@@ -53,7 +30,7 @@ export function createInteraction({ state, inputFor }) {
{
orientation: {
heading: camera.pose().heading || 0,
pitch: Cesium.Math.toRadians(-52),
pitch: toRadians(-52),
roll: 0,
},
durationS: 1.35,
@@ -62,7 +39,6 @@ export function createInteraction({ state, inputFor }) {
);
}
return {
registerPickEntity,
beginInteraction,
resolvePickRecord,
flyToReference,
+19 -16
View File
@@ -1,3 +1,4 @@
import { cameraOf } from '../../render/rendererOf.js';
import {
cableClassificationTypeForScene,
cableClassificationTypeForStack,
@@ -14,9 +15,8 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
init(viewer) {
state._viewer = viewer;
state._classificationType = cableClassificationTypeForScene(
viewer?.scene,
);
state._clampTo = cableClassificationTypeForScene(viewer?.scene);
parts.rendering.attach(viewer);
if (!state._mapStackListener && mapStackEventTarget?.addEventListener) {
state._mapStackListener = (event) => {
parts.rendering.applyCableClassification(
@@ -31,6 +31,12 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
);
}
parts.interaction.beginInteraction(viewer);
// The eye the sweep gate's motion probe reads, only when it probes.
const eye = {
get positionWC() {
return cameraOf(viewer).pose()?.position ?? null;
},
};
if (!state._preRenderRemover) {
state._preRenderRemover = viewer.scene.preRender.addEventListener(
() => {
@@ -41,7 +47,7 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
if (
!state._enabled ||
!state._loaded ||
!state._referenceSweepGate.shouldRun(viewer.camera)
!state._referenceSweepGate.shouldRun(eye)
)
return;
parts.rendering.updateReferenceVisibility();
@@ -49,7 +55,7 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
);
}
if (!state._moveEndRemover) {
state._moveEndRemover = viewer.camera.moveEnd.addEventListener(() => {
state._moveEndRemover = cameraOf(viewer).on('moveEnd', () => {
if (!state._enabled) return;
state._referenceSweepGate.markDirty();
viewer.scene.requestRender?.();
@@ -80,19 +86,21 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
state._loading = false;
state._loadingLabel = '';
}
// Free the entities rather than hide them; enable() rebuilds from the
// Free the items 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);
// keeps that stale generation from drawing anything later.
parts.rendering.releaseDrawing();
parts.rendering.updateVisibility();
},
update(viewer) {
return parts.ingestion.load(viewer || state._viewer);
},
destroy(viewer) {
destroy() {
if (state._abort) state._abort.abort();
parts.rendering.releaseDataSources(viewer || state._viewer);
parts.rendering.releaseDrawing({ clearSets: false });
parts.rendering.detach();
state._cachedCableJson = null;
state._cachedLandingJson = null;
// hide() clears every published host entry and goes invisible while
@@ -126,15 +134,10 @@ 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._surfaceItems = [];
state._referenceLabelCount = 0;
state._publishScratch.length = 0;
state._markerBlendDone = false;
state._markerBlendInvariantWarned = false;
parts.rendering.resetPublishSignature();
state._referenceSweepGate.reset();
},
+27 -34
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { clone, distance } from '../../geo/vector.js';
import {
CABLE_REFERENCE_LABEL_WINNER_CAP,
CABLE_REFERENCE_LABEL_MAX_DISTANCE_M,
@@ -41,7 +42,7 @@ export function selectCableReferenceLabelWinners(
.sort(
(a, b) =>
a.distanceM - b.distanceM ||
String(a.entity?.id || '').localeCompare(String(b.entity?.id || '')),
String(a.id || '').localeCompare(String(b.id || '')),
)
.slice(0, cap);
}
@@ -191,9 +192,9 @@ export function createCableReferenceSweepGate({
motionEpsilonM = CABLE_SWEEP_MOTION_EPSILON_M,
} = {}) {
const motionEpsilonSq = motionEpsilonM ** 2;
// Preallocated: the probe clones into it, so a moving camera allocates
// Preallocated: the probe copies into it, so a moving camera allocates
// nothing per frame.
const lastSweptPosition = new Cesium.Cartesian3();
const lastSweptPosition = { x: 0, y: 0, z: 0 };
let hasSweptPosition = false;
let dirty = true;
let lastProbeAt = -Infinity;
@@ -203,7 +204,7 @@ export function createCableReferenceSweepGate({
lastProbeAt = time;
const position = camera?.positionWC;
hasSweptPosition = Boolean(position);
if (position) Cesium.Cartesian3.clone(position, lastSweptPosition);
if (position) copyInto(position, lastSweptPosition);
return true;
}
@@ -212,7 +213,8 @@ export function createCableReferenceSweepGate({
dirty = true;
},
/**
* @param {Cesium.Camera} [camera] Live camera; omit to disable the motion
* @param {{positionWC?: {x: number, y: number, z: number}}} [camera]
* Live camera (its ECEF eye as `positionWC`); omit to disable the motion
* fallback entirely (pure dirty-only gate).
* @returns {boolean}
*/
@@ -232,8 +234,7 @@ export function createCableReferenceSweepGate({
if (!position) return false;
if (
hasSweptPosition &&
Cesium.Cartesian3.distanceSquared(position, lastSweptPosition) <=
motionEpsilonSq
distanceSquared(position, lastSweptPosition) <= motionEpsilonSq
) {
return false;
}
@@ -248,16 +249,17 @@ export function createCableReferenceSweepGate({
}
/**
* 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
* Recompute one stem on the sweep cadence: its tip rises with the camera's
* distance so the stem keeps about `STEM_TARGET_PX` on screen. The tip is
* moved in place (the overlay entry anchors to the same object) only when it
* moved beyond the settle epsilon, so the caller redraws only stems that
* really changed.
* @param {object} record Reference record with base/tip/reference.
* @param {{x: number, y: number, z: number}} cameraPositionWC ECEF eye.
* @param {number} canvasHeight CSS-pixel canvas height.
* @param {number} fov Camera frustum field of view (radians).
* @returns {boolean} True when the stem geometry was redefined.
* @param {number} fov Camera field of view (radians): horizontal on a wide
* canvas, vertical on a tall one.
* @returns {boolean} True when the tip moved.
*/
export function updateCableReferenceStem(
@@ -266,8 +268,8 @@ export function updateCableReferenceStem(
canvasHeight,
fov,
) {
const distance = Cesium.Cartesian3.distance(cameraPositionWC, record.base);
const effectiveDistance = Math.max(distance, 5000);
const range = distance(cameraPositionWC, record.base);
const effectiveDistance = Math.max(range, 5000);
const height = canvasHeight || 1080;
const fieldOfView = fov || Math.PI / 3;
const metersPerPixelFactor = (2 * Math.tan(fieldOfView / 2)) / height;
@@ -275,30 +277,21 @@ export function updateCableReferenceStem(
700,
Math.min(85000, effectiveDistance * metersPerPixelFactor * STEM_TARGET_PX),
);
Cesium.Cartesian3.fromDegrees(
const nextTip = fromDegrees(
record.reference.lon,
record.reference.lat,
tipHeight,
Cesium.Ellipsoid.WGS84,
record.nextTip,
);
if (
Cesium.Cartesian3.distanceSquared(record.tip, record.nextTip) <=
CABLE_STEM_TIP_EPSILON_SQ
) {
if (distanceSquared(record.tip, nextTip) <= CABLE_STEM_TIP_EPSILON_SQ) {
return false;
}
Cesium.Cartesian3.clone(record.nextTip, 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);
copyInto(nextTip, record.tip);
return true;
}
const distanceSquared = (a, b) => distance(a, b) ** 2;
const copyInto = (from, to) => Object.assign(to, clone(from));
export function clampLabel(value, maxLength = 34) {
const text = String(value || '')
.replace(/\s+/g, ' ')
-7
View File
@@ -1,7 +0,0 @@
import { createEntityStore } from '../../data/entityRecords.js';
/**
* The reference a picked cable, landing point or reference marker flies to:
* `info` is `{ label, kind, featureId, reference: { lon, lat } }`.
*/
export const cablePicks = createEntityStore();
+71
View File
@@ -0,0 +1,71 @@
/**
* The map pin GeoJSON points have always been drawn with: a rounded box on
* a pointed stem, filled with the pin's colour and stroked a brighter
* shade, drawn the way the default renderer's pin builder draws it (its
* path, scaled from a 24-pixel design).
*/
/** A colour byte as the default renderer writes it into CSS. */
const byte = (value) => (value === 1 ? 255 : (value * 256) | 0);
/** A renderer colour `[r, g, b, a]` as the default renderer writes it in CSS. */
function css([r, g, b, a = 1]) {
return a === 1
? `rgb(${byte(r)},${byte(g)},${byte(b)})`
: `rgba(${byte(r)},${byte(g)},${byte(b)},${a})`;
}
/** The colour brightened by `amount` (0..1) toward white, alpha kept. */
function brighten([r, g, b, a = 1], amount) {
const keep = 1 - amount;
return [1 - (1 - r) * keep, 1 - (1 - g) * keep, 1 - (1 - b) * keep, a];
}
/** The default renderer's pin outline (`PinBuilder`), on a 24 px square. */
const PIN_PATH =
'M6.72 0.422L17.28 0.422C18.553 0.422 19.577 1.758 19.577 3.415' +
'L19.577 10.973C19.577 12.63 18.553 13.966 17.282 13.966L14.386 14.008' +
'L11.826 23.578L9.614 14.008L6.719 13.965' +
'C5.446 13.983 4.422 12.629 4.422 10.972L4.422 3.416' +
'C4.423 1.76 5.447 0.423 6.718 0.423Z';
const pins = new Map();
/**
* The pin image for a colour and size (pixels square), one per look: a
* canvas where there is a document, else the same pin as SVG.
* @param {[number, number, number, number]} color Renderer colour.
* @param {number} size
* @returns {import('../../render/contract/draw').ImageRef}
*/
export function cablePinImage(color, size) {
const fill = css(color);
const stroke = css(brighten(color, 0.6));
const key = `cable-pin:${fill}:${stroke}:${size}`;
let image = pins.get(key);
if (image) return image;
if (typeof document !== 'undefined' && document.createElement) {
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const context = canvas.getContext('2d');
context.save();
context.scale(size / 24, size / 24);
context.fillStyle = fill;
context.strokeStyle = stroke;
context.lineWidth = 0.846;
const path = new Path2D(PIN_PATH);
context.fill(path);
context.stroke(path);
context.restore();
image = { canvas, key };
} else {
image = {
svg:
`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24">` +
`<path d="${PIN_PATH}" fill="${fill}" stroke="${stroke}" stroke-width="0.846"/></svg>`,
};
}
pins.set(key, image);
return image;
}
+21 -14
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export const BASE_CABLE_COLOR = '#39d5ff';
export const BASE_LANDING_COLOR = '#8fffd2';
@@ -54,7 +52,7 @@ export const CABLE_SWEEP_MOTION_EPSILON_M = 250;
* trades away (photoreal tiles occluding label TEXT at low, city-level
* cameras) matches the sibling dams/datacenters sources, which shipped
* host-composited under the same ruling; the anchor points/stems remain
* Cesium-native and depth-tested. See
* drawn by the renderer and depth-tested. See
* the world-overlay consolidation design notes ("Depth-testing
* decision") for both dated decisions.
*/
@@ -81,18 +79,27 @@ 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. */
/** Landing-point pins: CSS pixels square, anchored at the bottom tip. */
export const MARKER_COLLECTION_EXPECTATIONS = Object.freeze([
Object.freeze({
key: '_billboardCollection',
type: Cesium.BillboardCollection,
}),
Object.freeze({
key: '_pointCollection',
type: Cesium.PointPrimitiveCollection,
}),
]);
export const CABLE_PIN_SIZE_PX = 6;
/**
* Pin sizes a GeoJSON feature may ask for (`marker-size`), the simplestyle
* names the map pins have always honoured.
*/
export const CABLE_PIN_SIZES = Object.freeze({
small: 24,
medium: 48,
large: 64,
});
/**
* Lines are placed along rhumb lines, as GeoJSON lines always were, at
* points no farther apart than this (metres); the renderer joins them.
*/
export const CABLE_LINE_GRANULARITY_M = 9999;
/**
* Monotonic clock for the sweep gate's motion probe. A hoisted declaration:
+422 -190
View File
@@ -1,8 +1,9 @@
import * as Cesium from 'cesium';
import {
probeTranslucentMarkerBlend,
commitTranslucentMarkerBlend,
} from './surface.js';
import { fromDegrees, fromRadians } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { densifyRhumb } from '../../geo/rhumb.js';
import { distance, toRadians } from '../../geo/vector.js';
import { cssColor } from '../../render/color.js';
import { cameraOf, drawOf } from '../../render/rendererOf.js';
import {
clampLabel,
createCableOverlayEntry,
@@ -10,9 +11,149 @@ import {
selectCableReferenceLabelWinners,
cableReferencePriority,
} from './overlay.js';
import { cablePicks } from './pickState.js';
import { featureLabel, featureReference, geometryParts } from './geometry.js';
import { cablePinImage } from './pin.js';
import {
CABLE_LINE_GRANULARITY_M,
CABLE_PIN_SIZE_PX,
CABLE_PIN_SIZES,
} from './policy.js';
/**
* The layer's draw sets start with this; each layer has its own
* (`submarine-cables:1:lines`, …), so several can share a renderer. Picks
* name them as `Hit.set`.
*/
export const CABLE_SET_PREFIX = 'submarine-cables';
let layers = 0;
const BLACK_OUTLINE = [0, 0, 0, 0.65];
/** A polygon's edges are placed along rhumb lines a degree apart at most. */
const POLYGON_GRANULARITY_M = (6378137 * Math.PI) / 180;
/** A renderer colour with its alpha replaced. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
/** A feature's CSS colour property, or null when absent or unreadable. */
const propColor = (value) =>
value === undefined || value === null ? null : cssColor(String(value));
/** Whether a GeoJSON property is set, as the GeoJSON loader asked. */
const given = (value) => value !== undefined && value !== null;
/**
* How a line draws. A cable with a reference takes the cable's own colour
* (or the base colour) and one width, whatever the feature asks; every other
* line keeps the GeoJSON styling it always had: the source's colour,
* overridable by the feature's simplestyle `stroke`, `stroke-opacity` and
* `stroke-width`, draped on every surface.
*/
function lineStyle(props, cable, styled, baseColor) {
if (cable && styled) {
const color = propColor(props.color) ?? baseColor;
return {
widthPx: 2.5,
style: { kind: 'solid', color: withAlpha(color, 0.92) },
};
}
return {
widthPx: props['stroke-width'] ?? 2,
clampTo: 'both',
style: { kind: 'solid', color: strokeColor(props, cable, baseColor) },
};
}
/** A line's or raised polygon's simplestyle stroke colour. */
function strokeColor(props, cable, baseColor) {
let color = given(props.stroke) ? propColor(props.stroke) : null;
const opacity = props['stroke-opacity'];
if (given(opacity) && opacity !== 1)
color = withAlpha(
color ?? withAlpha(baseColor, cable ? 0.95 : 0.9),
opacity,
);
return color ?? withAlpha(baseColor, cable ? 0.95 : 0.9);
}
/**
* A polygon's fill, as GeoJSON polygons were filled: simplestyle `fill`
* takes the source's fill alpha, and `fill-opacity` replaces it.
*/
function polygonFill(props, cable, baseColor) {
const alpha = cable ? 0.18 : 0.35;
let color = given(props.fill) ? propColor(props.fill) : null;
if (color) color = withAlpha(color, alpha);
const opacity = props['fill-opacity'];
if (given(opacity) && opacity !== alpha)
color = withAlpha(color ?? withAlpha(baseColor, alpha), opacity);
return color ?? withAlpha(baseColor, alpha);
}
/** A finite `[lon, lat, height?]`, or null. */
function lonLat(coordinate) {
if (!Array.isArray(coordinate) || coordinate.length < 2) return null;
const lon = Number(coordinate[0]);
const lat = Number(coordinate[1]);
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
return { lon: toRadians(lon), lat: toRadians(lat) };
}
/** A path's points along rhumb lines, as ECEF, the way GeoJSON drew them. */
function rhumbPath(coordinates, granularity = CABLE_LINE_GRANULARITY_M) {
const points = [];
for (const coordinate of coordinates ?? []) {
const point = lonLat(coordinate);
if (point) points.push(point);
}
return densifyRhumb(points, granularity).map((p) =>
fromRadians(p.lon, p.lat),
);
}
export function createRendering({ state }) {
/** Make the layer's draw sets on the viewer's renderer (once). */
function attach(viewer) {
if (state._sets || !viewer) return;
const draw = drawOf(viewer);
const prefix = `${CABLE_SET_PREFIX}:${++layers}`;
const show = state._enabled;
state._sets = {
lines: draw.lines({
id: `${prefix}:lines`,
clampTo: state._clampTo,
show,
}),
fills: draw.shapes({ id: `${prefix}:fills`, clampTo: 'both', show }),
// Pins cull past the horizon each frame, as the sweep culled them;
// the globe hides them there anyway.
pins: draw.icons({
id: `${prefix}:pins`,
clampTo: 'both',
blend: 'translucent',
horizonCull: true,
show,
}),
stems: draw.lines({ id: `${prefix}:stems`, show }),
references: draw.points({
id: `${prefix}:references`,
blend: 'translucent',
show,
}),
};
state._setIds = new Set(Object.values(state._sets).map((set) => set.id));
state._picks = new Map([...state._setIds].map((id) => [id, new Map()]));
}
/** Dispose the draw sets (destroy); `attach` makes new ones. */
function detach() {
if (!state._sets) return;
for (const set of Object.values(state._sets)) set.dispose();
state._sets = null;
state._setIds = new Set();
state._picks = new Map();
}
function resetPublishSignature() {
state._lastPublishedIds.length = 0;
state._lastPublishedPriorities.length = 0;
@@ -20,215 +161,309 @@ export function createRendering({ state }) {
}
/**
* 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.
* Clear the draw sets and forget the built items. Hiding them is NOT
* enough: thousands of hidden lines and markers keep costing memory 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 releaseDataSources(viewer) {
const sources = [
state._cableDataSource,
state._landingDataSource,
state._referenceDataSource,
];
state._cableDataSource = null;
state._landingDataSource = null;
state._referenceDataSource = null;
/**
* Forget what was drawn; `clearSets: false` (destroy, where `detach`
* disposes the sets next) leaves the sets alone.
*/
function releaseDrawing({ clearSets = true } = {}) {
state._referenceRecords = [];
state._surfaceRecords = [];
state._surfaceItems = [];
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 (!state._sets) return;
if (clearSets) for (const set of Object.values(state._sets)) set.clear();
for (const picks of state._picks.values()) picks.clear();
}
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;
if (!state._sets) return;
for (const set of Object.values(state._sets)) set.show = state._enabled;
}
/**
* 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;
}
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
* Re-drape every cable ground line for the active surface. One ground
* rebuild per stack switch — never per frame.
* @param {'tiles'|'terrain'|'both'} 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?.();
if (next === undefined || next === state._clampTo) return;
state._clampTo = next;
state._sets?.lines.setOptions({ clampTo: next });
}
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,
reference.lat,
2500,
);
const info = {
kind,
reference,
label,
featureId: feature?.id || feature?.properties?.id || null,
};
const pointColor = color.withAlpha(kind === 'cable' ? 0.84 : 0.94);
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'}`,
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,
},
/**
* The items one source's features draw, by set: lines, fills and pins,
* each culled by its feature's reference, and a reference stem and point
* per feature. `kind` is `cable` or `landing-point`.
*/
function buildFeatures(features, kind, out) {
const cable = kind === 'cable';
const baseColor = cssColor(cable ? state.cableColor : state.landingColor);
features.forEach((feature, index) => {
// A feature with no reference still draws, as the GeoJSON loader drew
// it: unstyled, not picked and never culled.
const reference = featureReference(feature);
const label = featureLabel(feature);
const info = reference && {
kind,
reference,
label,
featureId: feature?.id || feature?.properties?.id || null,
};
const base = reference && fromDegrees(reference.lon, reference.lat, 0);
const keep = (set, item) => {
if (!reference) return;
out.picks[set].set(item.id, info);
if (set !== 'pins') out.surface.push({ set, item, base });
};
const props = feature?.properties || {};
const parts = geometryParts(feature.geometry);
const key = `${kind}:${index}`;
parts.lines.forEach((coordinates, part) => {
const positions = rhumbPath(coordinates);
if (positions.length < 2) return;
const item = {
id: `${key}:line:${part}`,
positions,
mode: 'draped',
...lineStyle(props, cable, Boolean(reference), baseColor),
show: true,
};
out.lines.push(item);
keep('lines', item);
});
parts.polygons.forEach((rings, part) => {
const fill = polygonFill(props, cable, baseColor);
// Polygons with heights stand at them, outlined, as the GeoJSON
// loader drew them; flat ones lie on the surface, edges along
// rhumb lines.
const raised = rings[0]?.[0]?.length > 2;
const drawn = rings
.map((ring) =>
raised
? ring
.filter((coordinate) => lonLat(coordinate))
.map(([lon, lat, height]) =>
fromDegrees(Number(lon), Number(lat), Number(height) || 0),
)
: rhumbPath(ring, POLYGON_GRANULARITY_M).map((p) => ({
x: p.x,
y: p.y,
z: p.z,
})),
)
.filter((ring) => ring.length >= 3);
if (!drawn.length) return;
const item = {
id: `${key}:fill:${part}`,
geometry: raised
? { kind: 'polygon', rings: drawn, perPositionHeight: true }
: { kind: 'polygon', rings: drawn },
fill,
...(raised
? {
height: 'absolute',
// WebGL draws the loader's outline one pixel wide.
outline: strokeColor(props, cable, baseColor),
outlineWidth: 1,
}
: { height: 'clampGround' }),
show: true,
};
out.fills.push(item);
keep('fills', item);
});
parts.points.forEach((coordinate, part) => {
const point = lonLat(coordinate);
if (!point) return;
const color =
(given(props['marker-color']) && cssColor(props['marker-color'])) ||
baseColor;
const size = CABLE_PIN_SIZES[props['marker-size']] ?? CABLE_PIN_SIZE_PX;
const raised =
coordinate.length > 2 && Number.isFinite(Number(coordinate[2]));
const item = {
id: `${key}:pin:${part}`,
pos: {
lon: Number(coordinate[0]),
lat: Number(coordinate[1]),
height: raised ? Number(coordinate[2]) : 0,
},
height: raised ? 'absolute' : 'clampGround',
image: cablePinImage(color, size),
size: [size, size],
anchor: 'bottom',
};
out.pins.push(item);
keep('pins', item);
});
if (!reference) return;
addReference(out, {
reference,
label,
kind,
color: baseColor,
info,
base,
});
});
}
cablePicks.write(entity).info = info;
function addReference(out, { reference, label, kind, color, info, base }) {
const cable = kind === 'cable';
const tip = fromDegrees(reference.lon, reference.lat, 2500);
const id = `${kind}-reference-${out.references.length}-${info.featureId || 'feature'}`;
const record = {
id: entity.id,
entity,
id,
base,
// Moved in place: the overlay entry anchors to this object.
tip,
nextTip: Cesium.Cartesian3.clone(tip),
stemPositionBuffers,
stemPositionBufferIndex: 0,
reference,
kind,
label: clampLabel(label),
visible: false,
visible: true,
distanceM: Infinity,
entry: null,
stem: {
id,
positions: [base, { ...tip }],
widthPx: cable ? 2 : 2.4,
mode: '3d',
style: {
kind: 'solid',
color: withAlpha(color, cable ? 0.58 : 0.68),
},
show: true,
},
point: {
id,
pos: { ...tip },
pixelSize: cable ? 7 : 8,
color: withAlpha(color, cable ? 0.84 : 0.94),
outlineColor: BLACK_OUTLINE,
outlineWidth: 1,
show: true,
},
};
record.entry = createCableOverlayEntry(record);
state._referenceRecords.push(record);
out.references.push(record);
out.picks.stems.set(id, info);
out.picks.references.set(id, info);
}
/**
* Draw both sources' features, replacing what was drawn. Items start
* culled for the camera as it is, so the first sweep has nothing to redo.
*/
function drawFeatures(cableFeatures, landingFeatures) {
const out = {
lines: [],
fills: [],
pins: [],
references: [],
surface: [],
picks: {
lines: new Map(),
fills: new Map(),
pins: new Map(),
stems: new Map(),
references: new Map(),
},
};
buildFeatures(cableFeatures, 'cable', out);
buildFeatures(landingFeatures, 'landing-point', out);
state._referenceRecords = out.references;
state._surfaceItems = out.surface;
sweep({ draw: false });
if (!state._sets) return;
const sets = state._sets;
for (const [name, picks] of Object.entries(out.picks)) {
const map = state._picks.get(sets[name].id);
map.clear();
for (const [id, info] of picks) map.set(id, info);
}
sets.lines.set(out.lines);
sets.fills.set(out.fills);
sets.pins.set(out.pins);
sets.stems.set(out.references.map((record) => record.stem));
sets.references.set(out.references.map((record) => record.point));
}
/** What a pick on one of the layer's sets names, or null. */
function pickInfo(hit) {
if (!hit || !state._setIds.has(hit.set)) return null;
return state._picks.get(hit.set)?.get(hit.id) ?? null;
}
/**
* One sweep: cull references and surface items by whether their
* reference is past the horizon, re-size visible stems, and redraw only
* what changed (`draw: false` changes the items without drawing them).
* Returns false when there is no camera to sweep from.
*/
function sweep({ draw = true } = {}) {
const viewer = state._viewer;
if (!viewer) return false;
const pose = cameraOf(viewer).pose();
const cameraPos = pose?.position;
if (!cameraPos) return false;
const canvasHeight = viewer.scene?.canvas?.clientHeight || 1080;
// The field of view along the canvas's longer side.
const fov =
pose.aspectRatio > 1
? 2 * Math.atan(Math.tan(pose.fovy / 2) * pose.aspectRatio)
: pose.fovy;
const horizon = horizonFrom(cameraPos);
const stems = [];
const points = [];
for (const record of state._referenceRecords) {
const visible = horizon.isPointVisible(record.base);
const flipped = record.visible !== visible;
record.visible = visible;
record.distanceM = distance(cameraPos, record.base);
// Hidden stems keep their last geometry; this same sweep refreshes them
// in the pass where they turn visible again.
const moved =
visible &&
updateCableReferenceStem(record, cameraPos, canvasHeight, fov);
if (!flipped && !moved) continue;
record.stem.positions = [record.base, { ...record.tip }];
record.stem.show = visible;
record.point.pos = { ...record.tip };
record.point.show = visible;
stems.push(record.stem);
points.push(record.point);
}
const surface = { lines: [], fills: [] };
for (const entry of state._surfaceItems) {
const visible = horizon.isPointVisible(entry.base);
if (entry.item.show === visible) continue;
entry.item.show = visible;
surface[entry.set].push(entry.item);
}
if (draw && state._sets) {
if (stems.length) state._sets.stems.upsert(stems);
if (points.length) state._sets.references.upsert(points);
if (surface.lines.length) state._sets.lines.upsert(surface.lines);
if (surface.fills.length) state._sets.fills.upsert(surface.fills);
}
return true;
}
function updateReferenceVisibility() {
if (!state._enabled || !state._viewer?.camera) return;
const cameraPos = state._viewer.camera.positionWC;
if (!cameraPos) return;
const canvasHeight = state._viewer.scene?.canvas?.clientHeight || 1080;
const fov = state._viewer.camera.frustum?.fov || Math.PI / 3;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
cameraPos,
);
for (const record of state._referenceRecords) {
const visible = occluder.isPointVisible(record.base);
record.visible = visible;
record.distanceM = Cesium.Cartesian3.distance(cameraPos, record.base);
if (record.entity.show !== visible) {
record.entity.show = visible;
}
// 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);
}
for (const record of state._surfaceRecords) {
const visible = occluder.isPointVisible(record.base);
if (record.entity.show !== visible) {
record.entity.show = visible;
}
}
if (!state._enabled || !state._viewer) return;
if (!sweep()) return;
const winners = selectCableReferenceLabelWinners(state._referenceRecords);
let changed = winners.length !== state._lastPublishedCount;
for (let i = 0; i < winners.length; i++) {
@@ -246,9 +481,6 @@ export function createRendering({ state }) {
}
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;
@@ -260,14 +492,14 @@ export function createRendering({ state }) {
state._lastPublishedPriorities.length = winners.length;
}
return {
attach,
detach,
resetPublishSignature,
releaseDataSources,
releaseDrawing,
updateVisibility,
styleCableEntity,
applyMarkerBlendOnce,
applyCableClassification,
styleLandingEntity,
addReferenceStem,
drawFeatures,
pickInfo,
updateReferenceVisibility,
};
}
+24 -22
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
createCableReferenceSweepGate,
createCableOverlayPublisher,
@@ -30,17 +29,30 @@ export function createState({ sweepClock, overlayHost }) {
state._loadGeneration = 0;
state._cableDataSource = null;
/**
* The layer's draw sets, made at init: cable and landing lines (draped),
* pins (landing points), fills (polygons), stems and reference points.
*/
state._landingDataSource = null;
state._sets = null;
state._referenceDataSource = null;
/** Set ids this layer made, for matching picks. */
state._setIds = new Set();
/** What each drawn item is, by set id then item id (picks fly to it). */
state._picks = new Map();
/** Drawn surface items, culled by their feature's reference each sweep. */
state._surfaceItems = [];
/**
* 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.
* Fetched cable/landing JSON kept across disable/enable. A disable CLEARS
* the draw sets (see releaseDrawing) instead of hiding them, so a
* re-enable has to rebuild the items; the network/parse half of that
* rebuild is the expensive part users would notice, so it is cached.
*/
state._cachedCableJson = null;
@@ -49,8 +61,6 @@ export function createState({ sweepClock, overlayHost }) {
state._referenceRecords = [];
state._surfaceRecords = [];
state._clickSubscription = null;
state._preRenderRemover = null;
@@ -59,15 +69,9 @@ export function createState({ sweepClock, overlayHost }) {
state._mapStackListener = null;
/** Active ground-line classification; refined from live scene state at init. */
/** What ground lines drape on; refined from live scene state at init. */
state._classificationType = Cesium.ClassificationType.BOTH;
/** True once both marker collections blend translucent (or the shape probe failed). */
state._markerBlendDone = false;
state._markerBlendInvariantWarned = false;
state._clampTo = 'both';
state._referenceLabelCount = 0;
@@ -96,10 +100,8 @@ export function createState({ sweepClock, overlayHost }) {
state._lastPublishedCount = -1;
state.cableColor = Cesium.Color.fromCssColorString(BASE_CABLE_COLOR);
state.cableColor = BASE_CABLE_COLOR;
state.cableOutline = Cesium.Color.BLACK.withAlpha(0.45);
state.landingColor = Cesium.Color.fromCssColorString(BASE_LANDING_COLOR);
state.landingColor = BASE_LANDING_COLOR;
return state;
}
+19 -111
View File
@@ -1,126 +1,34 @@
import * as Cesium from 'cesium';
import {
CABLE_GLOBE_STACK_IDS,
MARKER_COLLECTION_EXPECTATIONS,
} from './policy.js';
import { CABLE_GLOBE_STACK_IDS } from './policy.js';
/**
* Ground-line classification for one map stack. The photoreal stack renders
* Google 3D tiles with the Cesium globe HIDDEN, so cable ground lines only
* 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 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.
* What cable ground lines drape on for one map stack. The photoreal stack
* renders Google 3D tiles with the globe HIDDEN, so cable ground lines only
* need to drape on the tiles there; every other known stack (the bing
* stacks and osm) renders imagery on the shown globe, so only the terrain
* applies.
* Draping on just the active surface halves the ground lines' draw
* commands. `both` is the safe fallback for an unknown stack — it renders
* on every surface, exactly the shipped pre-optimization behavior.
* @param {string|null|undefined} activeId MapStackController stack id.
* @returns {Cesium.ClassificationType}
* @returns {'tiles'|'terrain'|'both'} The draw sets' `clampTo`.
*/
export function cableClassificationTypeForStack(activeId) {
if (activeId === 'photoreal') return Cesium.ClassificationType.CESIUM_3D_TILE;
if (CABLE_GLOBE_STACK_IDS.has(activeId))
return Cesium.ClassificationType.TERRAIN;
return Cesium.ClassificationType.BOTH;
if (activeId === 'photoreal') return 'tiles';
if (CABLE_GLOBE_STACK_IDS.has(activeId)) return 'terrain';
return 'both';
}
/**
* Derive the active surface from live scene state. The boot-time
* `setStack(..., { silent: true })` fires no 'gev:map-stack-changed' event,
* so the initial classification reads the scene the way the height-datum
* listeners do: the photoreal regime is exactly "globe hidden".
* @param {Cesium.Scene|null|undefined} scene
* @returns {Cesium.ClassificationType}
* so the initial surface is read the way the height-datum listeners do: the
* photoreal regime is exactly "globe hidden".
* @param {{globe?: {show?: boolean}}|null|undefined} scene
* @returns {'tiles'|'terrain'|'both'}
*/
export function cableClassificationTypeForScene(scene) {
if (!scene?.globe) return Cesium.ClassificationType.BOTH;
return scene.globe.show === false
? 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);
if (!scene?.globe) return 'both';
return scene.globe.show === false ? 'tiles' : 'terrain';
}