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

+12 -3
View File
@@ -2569,12 +2569,15 @@
"src/geo/vector.js", "src/geo/vector.js",
"src/render/cesium/internals.js", "src/render/cesium/internals.js",
"src/render/cesium/common.js", "src/render/cesium/common.js",
"src/layers/submarineCables/pickState.js", "src/layers/submarineCables/pin.js",
"src/data/entityRecords.js", "src/data/entityRecords.js",
"src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/lifecycle.js",
"src/layers/submarineCables/overlay.js", "src/layers/submarineCables/overlay.js",
"src/layers/submarineCables/policy.js", "src/layers/submarineCables/policy.js",
"src/layers/submarineCables/rendering.js", "src/layers/submarineCables/rendering.js",
"src/geo/rhumb.js",
"src/render/color.js",
"src/geo/horizon.js",
"src/layers/submarineCables/state.js", "src/layers/submarineCables/state.js",
"src/layers/submarineCables/surface.js", "src/layers/submarineCables/surface.js",
"src/data/inputOwnership.js", "src/data/inputOwnership.js",
@@ -3212,11 +3215,13 @@
"src/layers/submarineCables/index.js", "src/layers/submarineCables/index.js",
"src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/ingestion.js",
"src/layers/submarineCables/interaction.js", "src/layers/submarineCables/interaction.js",
"src/layers/submarineCables/pickState.js", "src/layers/submarineCables/pin.js",
"src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/lifecycle.js",
"src/layers/submarineCables/overlay.js", "src/layers/submarineCables/overlay.js",
"src/layers/submarineCables/policy.js", "src/layers/submarineCables/policy.js",
"src/layers/submarineCables/rendering.js", "src/layers/submarineCables/rendering.js",
"src/geo/rhumb.js",
"src/geo/horizon.js",
"src/layers/submarineCables/state.js", "src/layers/submarineCables/state.js",
"src/layers/submarineCables/surface.js", "src/layers/submarineCables/surface.js",
"src/layers/traffic/animation.js", "src/layers/traffic/animation.js",
@@ -4150,11 +4155,13 @@
"src/layers/submarineCables/index.js", "src/layers/submarineCables/index.js",
"src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/ingestion.js",
"src/layers/submarineCables/interaction.js", "src/layers/submarineCables/interaction.js",
"src/layers/submarineCables/pickState.js", "src/layers/submarineCables/pin.js",
"src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/lifecycle.js",
"src/layers/submarineCables/overlay.js", "src/layers/submarineCables/overlay.js",
"src/layers/submarineCables/policy.js", "src/layers/submarineCables/policy.js",
"src/layers/submarineCables/rendering.js", "src/layers/submarineCables/rendering.js",
"src/geo/rhumb.js",
"src/geo/horizon.js",
"src/layers/submarineCables/state.js", "src/layers/submarineCables/state.js",
"src/layers/submarineCables/surface.js", "src/layers/submarineCables/surface.js",
"src/layers/traffic/animation.js", "src/layers/traffic/animation.js",
@@ -5783,6 +5790,7 @@
"modules": [ "modules": [
"src/render/contract/index.js", "src/render/contract/index.js",
"src/render/stub/index.js", "src/render/stub/index.js",
"src/geo/horizon.js",
"src/render/conformance/index.js", "src/render/conformance/index.js",
"src/render/conformance/scenes.js", "src/render/conformance/scenes.js",
"src/render/conformance/cameraScripts.js", "src/render/conformance/cameraScripts.js",
@@ -5799,6 +5807,7 @@
"src/geo/quaternion.js", "src/geo/quaternion.js",
"src/render/stub/motion.js", "src/render/stub/motion.js",
"src/render/stub/camera.js", "src/render/stub/camera.js",
"src/geo/geodesic.js",
"src/render/camera/events.js", "src/render/camera/events.js",
"src/render/stub/geodesic.js", "src/render/stub/geodesic.js",
"src/render/stub/viewRectangle.js", "src/render/stub/viewRectangle.js",
-1
View File
@@ -24,7 +24,6 @@ export {
createCableOverlayEntry, createCableOverlayEntry,
cableClassificationTypeForStack, cableClassificationTypeForStack,
cableClassificationTypeForScene, cableClassificationTypeForScene,
applyTranslucentMarkerBlend,
createCableReferenceSweepGate, createCableReferenceSweepGate,
updateCableReferenceStem, updateCableReferenceStem,
} from '../layers/submarineCables/index.js'; } from '../layers/submarineCables/index.js';
File diff suppressed because it is too large. Load diff
+150
View File
@@ -0,0 +1,150 @@
/**
* @module geo/geodesic
* @description Surface distance along the WGS84 geodesic between two
* points, by the default renderer's own method (`EllipsoidGeodesic`,
* Vincenty's inverse formula): the same series in the same order, so the
* distance agrees with the renderer's to floating-point noise. Angles in
* radians, distances in metres.
*/
import { WGS84 } from './ellipsoid.js';
const MAJOR = WGS84.radii.x;
const MINOR = WGS84.radii.z;
const FLATTENING = (MAJOR - MINOR) / MAJOR;
const EPSILON12 = 1e-12;
/**
* Vincenty converges in a handful of steps except between nearly antipodal
* points, where it may not converge at all; stop there instead of hanging.
*/
const MAX_ITERATIONS = 200;
/** Vincenty's longitude correction, shared with the direct series. */
export function deltaLambda(
sineAlpha,
cosineSquaredAlpha,
sigma,
sineSigma,
cosineSigma,
cosineTwiceSigmaMidpoint,
) {
const f = FLATTENING;
const C =
(f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha))) /
16.0;
return (
(1.0 - C) *
f *
sineAlpha *
(sigma +
C *
sineSigma *
(cosineTwiceSigmaMidpoint +
C *
cosineSigma *
(2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0)))
);
}
/**
* Vincenty's inverse: the geodesic from (lon1, lat1) to (lon2, lat2),
* radians, as its length in metres, its start heading and its u².
*/
export function geodesicInverse(lon1, lat1, lon2, lat2) {
const l = lon2 - lon1;
const u1 = Math.atan((1 - FLATTENING) * Math.tan(lat1));
const u2 = Math.atan((1 - FLATTENING) * Math.tan(lat2));
const cosineU1 = Math.cos(u1);
const sineU1 = Math.sin(u1);
const cosineU2 = Math.cos(u2);
const sineU2 = Math.sin(u2);
const cc = cosineU1 * cosineU2;
const cs = cosineU1 * sineU2;
const ss = sineU1 * sineU2;
const sc = sineU1 * cosineU2;
let lambda = l;
let lambdaDot;
let cosineLambda;
let sineLambda;
let sigma;
let cosineSigma;
let sineSigma;
let cosineSquaredAlpha;
let cosineTwiceSigmaMidpoint;
let iterations = 0;
do {
cosineLambda = Math.cos(lambda);
sineLambda = Math.sin(lambda);
const temp = cs - sc * cosineLambda;
sineSigma = Math.sqrt(
cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp,
);
cosineSigma = ss + cc * cosineLambda;
sigma = Math.atan2(sineSigma, cosineSigma);
let sineAlpha;
if (sineSigma === 0.0) {
sineAlpha = 0.0;
cosineSquaredAlpha = 1.0;
} else {
sineAlpha = (cc * sineLambda) / sineSigma;
cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha;
}
lambdaDot = lambda;
cosineTwiceSigmaMidpoint = cosineSigma - (2.0 * ss) / cosineSquaredAlpha;
if (!isFinite(cosineTwiceSigmaMidpoint)) cosineTwiceSigmaMidpoint = 0.0;
lambda =
l +
deltaLambda(
sineAlpha,
cosineSquaredAlpha,
sigma,
sineSigma,
cosineSigma,
cosineTwiceSigmaMidpoint,
);
} while (
Math.abs(lambda - lambdaDot) > EPSILON12 &&
++iterations < MAX_ITERATIONS
);
const uSquared =
(cosineSquaredAlpha * (MAJOR * MAJOR - MINOR * MINOR)) / (MINOR * MINOR);
const A =
1.0 +
(uSquared *
(4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0))) /
16384.0;
const B =
(uSquared *
(256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0))) /
1024.0;
const cosineSquaredTwiceSigmaMidpoint =
cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
const deltaSigma =
B *
sineSigma *
(cosineTwiceSigmaMidpoint +
(B *
(cosineSigma * (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) -
(B *
cosineTwiceSigmaMidpoint *
(4.0 * sineSigma * sineSigma - 3.0) *
(4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0)) /
6.0)) /
4.0);
return {
distance: MINOR * A * (sigma - deltaSigma),
startHeading: Math.atan2(cosineU2 * sineLambda, cs - sc * cosineLambda),
uSquared,
};
}
/**
* Geodesic surface distance between two points; heights are ignored.
* @param {{lon: number, lat: number}} start Radians.
* @param {{lon: number, lat: number}} end Radians.
* @returns {number} Metres.
*/
export function surfaceDistance(start, end) {
return geodesicInverse(start.lon, start.lat, end.lon, end.lat).distance;
}
+47
View File
@@ -0,0 +1,47 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import { surfaceDistance } from './geodesic.js';
test('surface distance matches the default renderer’s geodesic', () => {
let seed = 11;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const d = Math.PI / 180;
const geodesic = new Cesium.EllipsoidGeodesic();
for (let i = 0; i < 400; i++) {
const start = {
lon: (random() * 360 - 180) * d,
lat: (random() * 170 - 85) * d,
};
// Near pairs, as a nearby-sites query asks, and far ones short of antipodal.
const reach = i % 2 ? 2 : 120;
const end = {
lon: start.lon + (random() * 2 - 1) * reach * d,
lat:
Math.max(
-89,
Math.min(89, start.lat / d + (random() * 2 - 1) * reach),
) * d,
};
geodesic.setEndPoints(
new Cesium.Cartographic(start.lon, start.lat, 0),
new Cesium.Cartographic(end.lon, end.lat, 0),
);
const expected = geodesic.surfaceDistance;
assert.ok(
Math.abs(surfaceDistance(start, end) - expected) <=
1e-9 * Math.max(1, expected),
`${i}: ${surfaceDistance(start, end)} vs ${expected}`,
);
}
});
test('the same point is no distance away, and nearly antipodal points still answer', () => {
const p = { lon: 0.3, lat: 0.7 };
assert.equal(surfaceDistance(p, p), 0);
const far = surfaceDistance(
{ lon: 0, lat: 0 },
{ lon: Math.PI - 1e-9, lat: 0 },
);
assert.ok(Number.isFinite(far) && far > 1.9e7);
});
+34
View File
@@ -0,0 +1,34 @@
/**
* @module geo/horizon
* @description Whether a point is beyond the WGS84 ellipsoid's horizon from
* an eye, by the default renderer's own test (`EllipsoidalOccluder`), so
* code that culls by it agrees with what the renderer culls.
*/
import { WGS84 } from './ellipsoid.js';
/**
* A horizon test from `eye` (ECEF): `isPointVisible(p)` is false for a
* point the ellipsoid hides from it.
*/
export function horizonFrom(eye) {
const o = WGS84.oneOverRadii;
const cx = eye.x * o.x;
const cy = eye.y * o.y;
const cz = eye.z * o.z;
const limbSquared = cx * cx + cy * cy + cz * cz - 1;
return {
isPointVisible(p) {
const tx = p.x * o.x - cx;
const ty = p.y * o.y - cy;
const tz = p.z * o.z - cz;
const along = -(tx * cx + ty * cy + tz * cz);
// Inside the ellipsoid the plane through the eye culls instead.
const occluded =
limbSquared < 0
? along > 0
: along > limbSquared &&
(along * along) / (tx * tx + ty * ty + tz * tz) > limbSquared;
return !occluded;
},
};
}
+33
View File
@@ -0,0 +1,33 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import { fromDegrees } from './ellipsoid.js';
import { horizonFrom } from './horizon.js';
test('the horizon hides what the default renderer’s occluder hides', () => {
let seed = 3;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
for (let i = 0; i < 30; i++) {
const eye = fromDegrees(
random() * 360 - 180,
random() * 170 - 85,
i === 0 ? -100 : random() * 2e7,
);
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
new Cesium.Cartesian3(eye.x, eye.y, eye.z),
);
const horizon = horizonFrom(eye);
for (let k = 0; k < 50; k++) {
const p = fromDegrees(
random() * 360 - 180,
random() * 180 - 90,
random() * 1e5,
);
assert.equal(
horizon.isPointVisible(p),
occluder.isPointVisible(new Cesium.Cartesian3(p.x, p.y, p.z)),
);
}
}
});
+221
View File
@@ -0,0 +1,221 @@
/**
* @module geo/rhumb
* @description Rhumb lines on the WGS84 ellipsoid, by the default
* renderer's own method (`EllipsoidRhumbLine`): the same series in the same
* order, so points along one land where the renderer put them. Angles in
* radians, distances in metres.
*/
import { WGS84 } from './ellipsoid.js';
import { negativePiToPi } from './vector.js';
const MAJOR = WGS84.radii.x;
const MINOR = WGS84.radii.z;
const E2 = (MAJOR * MAJOR - MINOR * MINOR) / (MAJOR * MAJOR);
const E = Math.sqrt(E2);
const HALF_PI = Math.PI / 2;
const EPSILON8 = 1e-8;
const EPSILON10 = 1e-10;
/** Meridian distance from the equator to `phi`. */
function meridian(phi) {
const e2 = E2;
const e4 = e2 * e2;
const e6 = e4 * e2;
const e8 = e6 * e2;
const e10 = e8 * e2;
const e12 = e10 * e2;
return (
MAJOR *
((1 -
e2 / 4 -
(3 * e4) / 64 -
(5 * e6) / 256 -
(175 * e8) / 16384 -
(441 * e10) / 65536 -
(4851 * e12) / 1048576) *
phi -
((3 * e2) / 8 +
(3 * e4) / 32 +
(45 * e6) / 1024 +
(105 * e8) / 4096 +
(2205 * e10) / 131072 +
(6237 * e12) / 524288) *
Math.sin(2 * phi) +
((15 * e4) / 256 +
(45 * e6) / 1024 +
(525 * e8) / 16384 +
(1575 * e10) / 65536 +
(155925 * e12) / 8388608) *
Math.sin(4 * phi) -
((35 * e6) / 3072 +
(175 * e8) / 12288 +
(3675 * e10) / 262144 +
(13475 * e12) / 1048576) *
Math.sin(6 * phi) +
((315 * e8) / 131072 + (2205 * e10) / 524288 + (43659 * e12) / 8388608) *
Math.sin(8 * phi) -
((693 * e10) / 1310720 + (6237 * e12) / 5242880) * Math.sin(10 * phi) +
((1001 * e12) / 8388608) * Math.sin(12 * phi))
);
}
/** The latitude a meridian distance `m` reaches. */
function inverseMeridian(m) {
const d = m / MAJOR;
const d2 = d * d;
const d3 = d2 * d;
const d4 = d3 * d;
const e2 = E2;
const e4 = e2 * e2;
const e6 = e4 * e2;
const e8 = e6 * e2;
const e10 = e8 * e2;
const e12 = e10 * e2;
return (
d +
(d * e2) / 4 +
(7 * d * e4) / 64 +
(15 * d * e6) / 256 +
(579 * d * e8) / 16384 +
(1515 * d * e10) / 65536 +
(16837 * d * e12) / 1048576 +
((3 * d * e4) / 16 +
(45 * d * e6) / 256 -
(d * (32 * d2 - 561) * e8) / 4096 -
(d * (232 * d2 - 1677) * e10) / 16384 +
(d * (399985 - 90560 * d2 + 512 * d4) * e12) / 5242880) *
Math.cos(2 * d) +
((21 * d * e6) / 256 +
(483 * d * e8) / 4096 -
(d * (224 * d2 - 1969) * e10) / 16384 -
(d * (33152 * d2 - 112599) * e12) / 1048576) *
Math.cos(4 * d) +
((151 * d * e8) / 4096 +
(4681 * d * e10) / 65536 +
(1479 * d * e12) / 16384 -
(453 * d3 * e12) / 32768) *
Math.cos(6 * d) +
((1097 * d * e10) / 65536 + (42783 * d * e12) / 1048576) * Math.cos(8 * d) +
((8011 * d * e12) / 1048576) * Math.cos(10 * d) +
((3 * e2) / 8 +
(3 * e4) / 16 +
(213 * e6) / 2048 -
(3 * d2 * e6) / 64 +
(255 * e8) / 4096 -
(33 * d2 * e8) / 512 +
(20861 * e10) / 524288 -
(33 * d2 * e10) / 512 +
(d4 * e10) / 1024 +
(28273 * e12) / 1048576 -
(471 * d2 * e12) / 8192 +
(9 * d4 * e12) / 4096) *
Math.sin(2 * d) +
((21 * e4) / 256 +
(21 * e6) / 256 +
(533 * e8) / 8192 -
(21 * d2 * e8) / 512 +
(197 * e10) / 4096 -
(315 * d2 * e10) / 4096 +
(584039 * e12) / 16777216 -
(12517 * d2 * e12) / 131072 +
(7 * d4 * e12) / 2048) *
Math.sin(4 * d) +
((151 * e6) / 6144 +
(151 * e8) / 4096 +
(5019 * e10) / 131072 -
(453 * d2 * e10) / 16384 +
(26965 * e12) / 786432 -
(8607 * d2 * e12) / 131072) *
Math.sin(6 * d) +
((1097 * e8) / 131072 +
(1097 * e10) / 65536 +
(225797 * e12) / 10485760 -
(1097 * d2 * e12) / 65536) *
Math.sin(8 * d) +
((8011 * e10) / 2621440 + (8011 * e12) / 1048576) * Math.sin(10 * d) +
((293393 * e12) / 251658240) * Math.sin(12 * d)
);
}
/** Isometric latitude. */
function sigma(latitude) {
const eSinL = E * Math.sin(latitude);
return (
Math.log(Math.tan(0.5 * (HALF_PI + latitude))) -
(E / 2) * Math.log((1 + eSinL) / (1 - eSinL))
);
}
/** Radius of the parallel at `latitude`. */
function parallelRadius(latitude) {
const sinPhi = Math.sin(latitude);
return (MAJOR * Math.cos(latitude)) / Math.sqrt(1 - E2 * sinPhi * sinPhi);
}
/**
* The rhumb line from `start` to `end` (`{lon, lat}` radians): its heading
* (radians from north), its length, and the point a distance along it.
*/
export function rhumbLine(start, end) {
const heading = Math.atan2(
negativePiToPi(end.lon - start.lon),
sigma(end.lat) - sigma(start.lat),
);
// Near due east or west the series diverge: such a line follows its
// parallel. Its length and its points decide that as the renderer does.
const offEast = Math.abs(Math.abs(heading) - HALF_PI);
const measuredAlongParallel =
offEast <= Math.max(EPSILON8, EPSILON8 * HALF_PI);
const alongParallel = !(offEast > EPSILON8);
const distance = Math.abs(
measuredAlongParallel
? parallelRadius(start.lat) * negativePiToPi(end.lon - start.lon)
: (meridian(end.lat) - meridian(start.lat)) / Math.cos(heading),
);
return {
heading,
distance,
/** The point `metres` along the line from its start. */
at(metres) {
if (metres === 0) return { lon: start.lon, lat: start.lat };
if (alongParallel) {
const delta = metres / parallelRadius(start.lat);
return {
lon: negativePiToPi(start.lon + (heading > 0 ? delta : -delta)),
lat: start.lat,
};
}
const lat = inverseMeridian(
meridian(start.lat) + metres * Math.cos(heading),
);
const lon =
Math.abs(heading) < EPSILON10
? negativePiToPi(start.lon)
: negativePiToPi(
start.lon + Math.tan(heading) * (sigma(lat) - sigma(start.lat)),
);
return { lon, lat };
},
};
}
/**
* The points along a path's rhumb lines no more than `granularity` metres
* apart, as a renderer drawing the path along rhumb lines places them: each
* leg of `distance` split into `ceil(distance / granularity)` equal parts.
* Takes and gives `{lon, lat}` in radians; the path's own points are kept.
*/
export function densifyRhumb(points, granularity = 9999) {
if (points.length < 2) return points.slice();
const out = [points[0]];
for (let i = 1; i < points.length; i++) {
const line = rhumbLine(points[i - 1], points[i]);
if (line.distance >= granularity) {
const parts = Math.ceil(line.distance / granularity);
const step = line.distance / parts;
for (let k = 1; k < parts; k++) out.push(line.at(step * k));
}
out.push(points[i]);
}
return out;
}
+79
View File
@@ -0,0 +1,79 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import { densifyRhumb, rhumbLine } from './rhumb.js';
const d = Math.PI / 180;
test('a rhumb line is the default renderer’s, length and points', () => {
let seed = 11;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const cases = [
[
[-40, 35],
[-30, 40],
],
[
[170, -10],
[-170, 12],
],
[
[10, 20],
[60, 20],
],
[
[5, -60],
[5, 70],
],
];
for (let i = 0; i < 40; i++)
cases.push([
[random() * 360 - 180, random() * 160 - 80],
[random() * 360 - 180, random() * 160 - 80],
]);
for (const [[lonA, latA], [lonB, latB]] of cases) {
const start = { lon: lonA * d, lat: latA * d };
const end = { lon: lonB * d, lat: latB * d };
let cesium;
try {
cesium = new Cesium.EllipsoidRhumbLine(
new Cesium.Cartographic(start.lon, start.lat),
new Cesium.Cartographic(end.lon, end.lat),
);
} catch {
continue; // antipodal: the renderer refuses it too
}
const line = rhumbLine(start, end);
assert.ok(
Math.abs(line.distance - cesium.surfaceDistance) <=
1e-9 * cesium.surfaceDistance + 1e-6,
`${lonA},${latA} → ${lonB},${latB}`,
);
assert.ok(Math.abs(line.heading - cesium.heading) < 1e-12);
for (const f of [0.1, 0.5, 0.9]) {
const ours = line.at(line.distance * f);
const theirs = cesium.interpolateUsingSurfaceDistance(
cesium.surfaceDistance * f,
);
assert.ok(Math.abs(ours.lon - theirs.longitude) < 1e-12);
assert.ok(Math.abs(ours.lat - theirs.latitude) < 1e-12);
}
}
});
test('a densified path keeps its points and spaces the rest under the granularity', () => {
const path = [
{ lon: -40 * d, lat: 35 * d },
{ lon: -39.95 * d, lat: 35 * d },
{ lon: -30 * d, lat: 40 * d },
];
const dense = densifyRhumb(path, 9999);
assert.equal(dense[0], path[0]);
assert.equal(dense[1], path[1], 'a short leg adds nothing');
assert.equal(dense.at(-1), path[2]);
const leg = rhumbLine(path[1], path[2]);
assert.equal(dense.length, 2 + Math.ceil(leg.distance / 9999));
for (let i = 2; i < dense.length; i++)
assert.ok(rhumbLine(dense[i - 1], dense[i]).distance < 9999);
assert.deepEqual(densifyRhumb([path[0]]), [path[0]]);
});
+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 { export {
cableClassificationTypeForStack, cableClassificationTypeForStack,
cableClassificationTypeForScene, cableClassificationTypeForScene,
applyTranslucentMarkerBlend,
} from './surface.js'; } from './surface.js';
export { export {
CABLE_REFERENCE_LABEL_WINNER_CAP, CABLE_REFERENCE_LABEL_WINNER_CAP,
+8 -164
View File
@@ -1,25 +1,5 @@
import { msg, t } from '../../i18n/index.js'; import { msg, t } from '../../i18n/index.js';
import { import { normalizeFeatures } from './geometry.js';
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,
},
})),
};
}
export function createIngestion({ state, parts, source }) { export function createIngestion({ state, parts, source }) {
async function load(viewer) { async function load(viewer) {
@@ -31,9 +11,9 @@ export function createIngestion({ state, parts, source }) {
// Ownership token (the militaryAwareness activationId pattern): a // Ownership token (the militaryAwareness activationId pattern): a
// disable/abort followed by a fresh enable starts a NEWER load while this // 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 // 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 // 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 generation = ++state._loadGeneration;
const abort = new AbortController(); const abort = new AbortController();
state._abort = abort; state._abort = abort;
@@ -63,146 +43,10 @@ export function createIngestion({ state, parts, source }) {
const cableFeatures = normalizeFeatures(cableJson, 'cable'); const cableFeatures = normalizeFeatures(cableJson, 'cable');
const landingFeatures = normalizeFeatures(landingJson, 'landing'); const landingFeatures = normalizeFeatures(landingJson, 'landing');
const cableDataSource = await Cesium.GeoJsonDataSource.load( // Await-free from here: this load still owns the lifecycle, and the
indexedCollection(cableFeatures), // items go into the layer's own sets in one pass.
{ parts.rendering.attach(viewer);
clampToGround: true, parts.rendering.drawFeatures(cableFeatures, landingFeatures);
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,
});
});
state._count = cableFeatures.length + landingFeatures.length; state._count = cableFeatures.length + landingFeatures.length;
state._loaded = true; state._loaded = true;
@@ -210,7 +54,7 @@ export function createIngestion({ state, parts, source }) {
state._loadingLabel = ''; state._loadingLabel = '';
parts.rendering.updateVisibility(); parts.rendering.updateVisibility();
state._referenceSweepGate.markDirty(); state._referenceSweepGate.markDirty();
viewer.scene.requestRender?.(); viewer?.scene?.requestRender?.();
} catch (error) { } catch (error) {
// A stale or aborted load reports nothing: its failure belongs to a // A stale or aborted load reports nothing: its failure belongs to a
// lifecycle the user already left. // lifecycle the user already left.
+12 -36
View File
@@ -1,47 +1,24 @@
import * as Cesium from 'cesium'; import { toRadians } from '../../geo/vector.js';
import { cablePicks } from './pickState.js'; import { cameraOf } from '../../render/rendererOf.js';
import { cameraOf } from '../../render/cesium/camera.js';
export function createInteraction({ state, inputFor }) {
function registerPickEntity(entity, info) {
cablePicks.write(entity).info = info;
}
export function createInteraction({ state, parts, inputFor }) {
function beginInteraction(viewer) { function beginInteraction(viewer) {
if (state._clickSubscription) return; if (state._clickSubscription) return;
state._clickSubscription = inputFor(viewer).onClick((event) => { state._clickSubscription = inputFor(viewer).onClick((event) => {
if (!state._enabled) return; if (!state._enabled) return;
const record = resolvePickRecord(event.pick); const record = resolvePickRecord(event.drawHit);
if (!record?.reference) return; if (!record?.reference) return;
flyToReference(viewer, record.reference); flyToReference(viewer, record.reference);
}); });
} }
function resolvePickRecord(picked) { /**
if (!picked) return null; * What a click's draw hit names: a cable, landing point or reference of
const primitive = picked.primitive; * this layer's current items, as `{ label, kind, featureId, reference }`,
if (primitive) { * or null.
const primitiveInfo = cablePicks.read(primitive)?.info; */
if (primitiveInfo) return primitiveInfo; function resolvePickRecord(hit) {
if ( return parts.rendering.pickInfo(hit);
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;
} }
function flyToReference(viewer, reference) { function flyToReference(viewer, reference) {
@@ -53,7 +30,7 @@ export function createInteraction({ state, inputFor }) {
{ {
orientation: { orientation: {
heading: camera.pose().heading || 0, heading: camera.pose().heading || 0,
pitch: Cesium.Math.toRadians(-52), pitch: toRadians(-52),
roll: 0, roll: 0,
}, },
durationS: 1.35, durationS: 1.35,
@@ -62,7 +39,6 @@ export function createInteraction({ state, inputFor }) {
); );
} }
return { return {
registerPickEntity,
beginInteraction, beginInteraction,
resolvePickRecord, resolvePickRecord,
flyToReference, flyToReference,
+19 -16
View File
@@ -1,3 +1,4 @@
import { cameraOf } from '../../render/rendererOf.js';
import { import {
cableClassificationTypeForScene, cableClassificationTypeForScene,
cableClassificationTypeForStack, cableClassificationTypeForStack,
@@ -14,9 +15,8 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
init(viewer) { init(viewer) {
state._viewer = viewer; state._viewer = viewer;
state._classificationType = cableClassificationTypeForScene( state._clampTo = cableClassificationTypeForScene(viewer?.scene);
viewer?.scene, parts.rendering.attach(viewer);
);
if (!state._mapStackListener && mapStackEventTarget?.addEventListener) { if (!state._mapStackListener && mapStackEventTarget?.addEventListener) {
state._mapStackListener = (event) => { state._mapStackListener = (event) => {
parts.rendering.applyCableClassification( parts.rendering.applyCableClassification(
@@ -31,6 +31,12 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
); );
} }
parts.interaction.beginInteraction(viewer); 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) { if (!state._preRenderRemover) {
state._preRenderRemover = viewer.scene.preRender.addEventListener( state._preRenderRemover = viewer.scene.preRender.addEventListener(
() => { () => {
@@ -41,7 +47,7 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
if ( if (
!state._enabled || !state._enabled ||
!state._loaded || !state._loaded ||
!state._referenceSweepGate.shouldRun(viewer.camera) !state._referenceSweepGate.shouldRun(eye)
) )
return; return;
parts.rendering.updateReferenceVisibility(); parts.rendering.updateReferenceVisibility();
@@ -49,7 +55,7 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
); );
} }
if (!state._moveEndRemover) { if (!state._moveEndRemover) {
state._moveEndRemover = viewer.camera.moveEnd.addEventListener(() => { state._moveEndRemover = cameraOf(viewer).on('moveEnd', () => {
if (!state._enabled) return; if (!state._enabled) return;
state._referenceSweepGate.markDirty(); state._referenceSweepGate.markDirty();
viewer.scene.requestRender?.(); viewer.scene.requestRender?.();
@@ -80,19 +86,21 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
state._loading = false; state._loading = false;
state._loadingLabel = ''; 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 // cached JSON. An in-flight load's own post-await ownership check
// removes whatever that stale generation adds later. // keeps that stale generation from drawing anything later.
parts.rendering.releaseDataSources(state._viewer); parts.rendering.releaseDrawing();
parts.rendering.updateVisibility();
}, },
update(viewer) { update(viewer) {
return parts.ingestion.load(viewer || state._viewer); return parts.ingestion.load(viewer || state._viewer);
}, },
destroy(viewer) { destroy() {
if (state._abort) state._abort.abort(); if (state._abort) state._abort.abort();
parts.rendering.releaseDataSources(viewer || state._viewer); parts.rendering.releaseDrawing({ clearSets: false });
parts.rendering.detach();
state._cachedCableJson = null; state._cachedCableJson = null;
state._cachedLandingJson = null; state._cachedLandingJson = null;
// hide() clears every published host entry and goes invisible while // 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._error = null;
state._lastUpdate = null; state._lastUpdate = null;
state._loadingLabel = ''; state._loadingLabel = '';
state._cableDataSource = null;
state._landingDataSource = null;
state._referenceDataSource = null;
state._referenceRecords = []; state._referenceRecords = [];
state._surfaceRecords = []; state._surfaceItems = [];
state._referenceLabelCount = 0; state._referenceLabelCount = 0;
state._publishScratch.length = 0; state._publishScratch.length = 0;
state._markerBlendDone = false;
state._markerBlendInvariantWarned = false;
parts.rendering.resetPublishSignature(); parts.rendering.resetPublishSignature();
state._referenceSweepGate.reset(); 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 { import {
CABLE_REFERENCE_LABEL_WINNER_CAP, CABLE_REFERENCE_LABEL_WINNER_CAP,
CABLE_REFERENCE_LABEL_MAX_DISTANCE_M, CABLE_REFERENCE_LABEL_MAX_DISTANCE_M,
@@ -41,7 +42,7 @@ export function selectCableReferenceLabelWinners(
.sort( .sort(
(a, b) => (a, b) =>
a.distanceM - b.distanceM || a.distanceM - b.distanceM ||
String(a.entity?.id || '').localeCompare(String(b.entity?.id || '')), String(a.id || '').localeCompare(String(b.id || '')),
) )
.slice(0, cap); .slice(0, cap);
} }
@@ -191,9 +192,9 @@ export function createCableReferenceSweepGate({
motionEpsilonM = CABLE_SWEEP_MOTION_EPSILON_M, motionEpsilonM = CABLE_SWEEP_MOTION_EPSILON_M,
} = {}) { } = {}) {
const motionEpsilonSq = motionEpsilonM ** 2; 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. // nothing per frame.
const lastSweptPosition = new Cesium.Cartesian3(); const lastSweptPosition = { x: 0, y: 0, z: 0 };
let hasSweptPosition = false; let hasSweptPosition = false;
let dirty = true; let dirty = true;
let lastProbeAt = -Infinity; let lastProbeAt = -Infinity;
@@ -203,7 +204,7 @@ export function createCableReferenceSweepGate({
lastProbeAt = time; lastProbeAt = time;
const position = camera?.positionWC; const position = camera?.positionWC;
hasSweptPosition = Boolean(position); hasSweptPosition = Boolean(position);
if (position) Cesium.Cartesian3.clone(position, lastSweptPosition); if (position) copyInto(position, lastSweptPosition);
return true; return true;
} }
@@ -212,7 +213,8 @@ export function createCableReferenceSweepGate({
dirty = true; 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). * fallback entirely (pure dirty-only gate).
* @returns {boolean} * @returns {boolean}
*/ */
@@ -232,8 +234,7 @@ export function createCableReferenceSweepGate({
if (!position) return false; if (!position) return false;
if ( if (
hasSweptPosition && hasSweptPosition &&
Cesium.Cartesian3.distanceSquared(position, lastSweptPosition) <= distanceSquared(position, lastSweptPosition) <= motionEpsilonSq
motionEpsilonSq
) { ) {
return false; return false;
} }
@@ -248,16 +249,17 @@ export function createCableReferenceSweepGate({
} }
/** /**
* Recompute one staticized stem on the sweep cadence. Replaces the former * Recompute one stem on the sweep cadence: its tip rises with the camera's
* per-frame `CallbackProperty` pair: constant properties are redefined only * distance so the stem keeps about `STEM_TARGET_PX` on screen. The tip is
* when the camera-scaled tip moved beyond the settle epsilon, and the two * moved in place (the overlay entry anchors to the same object) only when it
* preallocated position buffers alternate so each real change raises exactly * moved beyond the settle epsilon, so the caller redraws only stems that
* one geometry notification (the localGeojson double-buffer pattern). * really changed.
* @param {object} record Reference record with entity/base/tip/nextTip/buffers. * @param {object} record Reference record with base/tip/reference.
* @param {Cesium.Cartesian3} cameraPositionWC * @param {{x: number, y: number, z: number}} cameraPositionWC ECEF eye.
* @param {number} canvasHeight CSS-pixel canvas height. * @param {number} canvasHeight CSS-pixel canvas height.
* @param {number} fov Camera frustum field of view (radians). * @param {number} fov Camera field of view (radians): horizontal on a wide
* @returns {boolean} True when the stem geometry was redefined. * canvas, vertical on a tall one.
* @returns {boolean} True when the tip moved.
*/ */
export function updateCableReferenceStem( export function updateCableReferenceStem(
@@ -266,8 +268,8 @@ export function updateCableReferenceStem(
canvasHeight, canvasHeight,
fov, fov,
) { ) {
const distance = Cesium.Cartesian3.distance(cameraPositionWC, record.base); const range = distance(cameraPositionWC, record.base);
const effectiveDistance = Math.max(distance, 5000); const effectiveDistance = Math.max(range, 5000);
const height = canvasHeight || 1080; const height = canvasHeight || 1080;
const fieldOfView = fov || Math.PI / 3; const fieldOfView = fov || Math.PI / 3;
const metersPerPixelFactor = (2 * Math.tan(fieldOfView / 2)) / height; const metersPerPixelFactor = (2 * Math.tan(fieldOfView / 2)) / height;
@@ -275,30 +277,21 @@ export function updateCableReferenceStem(
700, 700,
Math.min(85000, effectiveDistance * metersPerPixelFactor * STEM_TARGET_PX), Math.min(85000, effectiveDistance * metersPerPixelFactor * STEM_TARGET_PX),
); );
Cesium.Cartesian3.fromDegrees( const nextTip = fromDegrees(
record.reference.lon, record.reference.lon,
record.reference.lat, record.reference.lat,
tipHeight, tipHeight,
Cesium.Ellipsoid.WGS84,
record.nextTip,
); );
if ( if (distanceSquared(record.tip, nextTip) <= CABLE_STEM_TIP_EPSILON_SQ) {
Cesium.Cartesian3.distanceSquared(record.tip, record.nextTip) <=
CABLE_STEM_TIP_EPSILON_SQ
) {
return false; return false;
} }
Cesium.Cartesian3.clone(record.nextTip, record.tip); copyInto(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);
return true; 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) { export function clampLabel(value, maxLength = 34) {
const text = String(value || '') const text = String(value || '')
.replace(/\s+/g, ' ') .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_CABLE_COLOR = '#39d5ff';
export const BASE_LANDING_COLOR = '#8fffd2'; 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 * trades away (photoreal tiles occluding label TEXT at low, city-level
* cameras) matches the sibling dams/datacenters sources, which shipped * cameras) matches the sibling dams/datacenters sources, which shipped
* host-composited under the same ruling; the anchor points/stems remain * 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 * the world-overlay consolidation design notes ("Depth-testing
* decision") for both dated decisions. * 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']), 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([ export const CABLE_PIN_SIZE_PX = 6;
Object.freeze({
key: '_billboardCollection', /**
type: Cesium.BillboardCollection, * Pin sizes a GeoJSON feature may ask for (`marker-size`), the simplestyle
}), * names the map pins have always honoured.
Object.freeze({ */
key: '_pointCollection',
type: Cesium.PointPrimitiveCollection, 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: * 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 { fromDegrees, fromRadians } from '../../geo/ellipsoid.js';
import { import { horizonFrom } from '../../geo/horizon.js';
probeTranslucentMarkerBlend, import { densifyRhumb } from '../../geo/rhumb.js';
commitTranslucentMarkerBlend, import { distance, toRadians } from '../../geo/vector.js';
} from './surface.js'; import { cssColor } from '../../render/color.js';
import { cameraOf, drawOf } from '../../render/rendererOf.js';
import { import {
clampLabel, clampLabel,
createCableOverlayEntry, createCableOverlayEntry,
@@ -10,9 +11,149 @@ import {
selectCableReferenceLabelWinners, selectCableReferenceLabelWinners,
cableReferencePriority, cableReferencePriority,
} from './overlay.js'; } 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 }) { 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() { function resetPublishSignature() {
state._lastPublishedIds.length = 0; state._lastPublishedIds.length = 0;
state._lastPublishedPriorities.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 * Clear the draw sets and forget the built items. Hiding them is NOT
* entities. Hiding them (`show = false`) is NOT enough: Cesium's * enough: thousands of hidden lines and markers keep costing memory long
* DataSourceDisplay still walks every visualizer of a hidden source on * after the user toggled the layer off — that is the "everything gets
* every frame, and the thousands of hidden polylines/billboards keep * sluggish after I turn layers off" report. The fetched JSON stays
* costing CPU and GC pressure long after the user toggled the layer off — * cached, so the next enable rebuilds without a network round trip or a
* that is the "everything gets sluggish after I turn layers off" report. * re-parse.
* The fetched JSON stays cached, so the next enable rebuilds without a
* network round trip or a re-parse.
*/ */
function releaseDataSources(viewer) { /**
const sources = [ * Forget what was drawn; `clearSets: false` (destroy, where `detach`
state._cableDataSource, * disposes the sets next) leaves the sets alone.
state._landingDataSource, */
state._referenceDataSource, function releaseDrawing({ clearSets = true } = {}) {
];
state._cableDataSource = null;
state._landingDataSource = null;
state._referenceDataSource = null;
state._referenceRecords = []; state._referenceRecords = [];
state._surfaceRecords = []; state._surfaceItems = [];
state._referenceLabelCount = 0; state._referenceLabelCount = 0;
state._publishScratch.length = 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._loaded = false;
state._referenceSweepGate.reset(); state._referenceSweepGate.reset();
for (const source of sources) { if (!state._sets) return;
if (!source) continue; if (clearSets) for (const set of Object.values(state._sets)) set.clear();
try { for (const picks of state._picks.values()) picks.clear();
viewer?.dataSources?.remove(source, true);
} catch {
/* collection gone */
}
}
} }
function updateVisibility() { function updateVisibility() {
if (state._cableDataSource) state._cableDataSource.show = state._enabled; if (!state._sets) return;
if (state._landingDataSource) for (const set of Object.values(state._sets)) set.show = state._enabled;
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 * Re-drape every cable ground line for the active surface. One ground
* reference-point collections. Landing entities carry only billboards and * rebuild per stack switch — never per frame.
* reference entities only points, so completion is one applied collection * @param {'tiles'|'terrain'|'both'} next
* 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
*/ */
function applyCableClassification(next) { function applyCableClassification(next) {
if (next === undefined || next === state._classificationType) return; if (next === undefined || next === state._clampTo) return;
state._classificationType = next; state._clampTo = next;
if (!state._cableDataSource) return; state._sets?.lines.setOptions({ clampTo: next });
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; * The items one source's features draw, by set: lines, fills and pins,
entity.point.color = state.landingColor.withAlpha(0.92); * each culled by its feature's reference, and a reference stem and point
entity.point.pixelSize = feature?.properties?.is_tbd ? 6 : 7; * per feature. `kind` is `cable` or `landing-point`.
entity.point.outlineColor = state.cableOutline; */
entity.point.outlineWidth = 1; function buildFeatures(features, kind, out) {
entity.point.disableDepthTestDistance = 0; const cable = kind === 'cable';
entity.show = true; const baseColor = cssColor(cable ? state.cableColor : state.landingColor);
} features.forEach((feature, index) => {
// A feature with no reference still draws, as the GeoJSON loader drew
function addReferenceStem({ reference, label, kind, color, feature }) { // it: unstyled, not picked and never culled.
if (!state._referenceDataSource || !reference) return; const reference = featureReference(feature);
const label = featureLabel(feature);
const base = Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0); const info = reference && {
const tip = Cesium.Cartesian3.fromDegrees( kind,
reference.lon, reference,
reference.lat, label,
2500, featureId: feature?.id || feature?.properties?.id || null,
); };
const info = { const base = reference && fromDegrees(reference.lon, reference.lat, 0);
kind, const keep = (set, item) => {
reference, if (!reference) return;
label, out.picks[set].set(item.id, info);
featureId: feature?.id || feature?.properties?.id || null, if (set !== 'pins') out.surface.push({ set, item, base });
}; };
const pointColor = color.withAlpha(kind === 'cable' ? 0.84 : 0.94); const props = feature?.properties || {};
const stemColor = color.withAlpha(kind === 'cable' ? 0.58 : 0.68); const parts = geometryParts(feature.geometry);
// Constant properties on the sweep cadence, never per-frame callbacks: const key = `${kind}:${index}`;
// the sweep redefines them through the alternating buffers below. parts.lines.forEach((coordinates, part) => {
const stemPositionBuffers = [ const positions = rhumbPath(coordinates);
[base, tip], if (positions.length < 2) return;
[base, tip], const item = {
]; id: `${key}:line:${part}`,
positions,
const entity = state._referenceDataSource.entities.add({ mode: 'draped',
id: `${kind}-reference-${state._referenceRecords.length}-${info.featureId || 'feature'}`, ...lineStyle(props, cable, Boolean(reference), baseColor),
position: tip, show: true,
polyline: { };
positions: stemPositionBuffers[0], out.lines.push(item);
width: kind === 'cable' ? 2 : 2.4, keep('lines', item);
material: new Cesium.ColorMaterialProperty(stemColor), });
}, parts.polygons.forEach((rings, part) => {
point: { const fill = polygonFill(props, cable, baseColor);
pixelSize: kind === 'cable' ? 7 : 8, // Polygons with heights stand at them, outlined, as the GeoJSON
color: pointColor, // loader drew them; flat ones lie on the surface, edges along
outlineColor: Cesium.Color.BLACK.withAlpha(0.65), // rhumb lines.
outlineWidth: 1, const raised = rings[0]?.[0]?.length > 2;
disableDepthTestDistance: 0, 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 = { const record = {
id: entity.id, id,
entity,
base, base,
// Moved in place: the overlay entry anchors to this object.
tip, tip,
nextTip: Cesium.Cartesian3.clone(tip),
stemPositionBuffers,
stemPositionBufferIndex: 0,
reference, reference,
kind, kind,
label: clampLabel(label), label: clampLabel(label),
visible: false, visible: true,
distanceM: Infinity, distanceM: Infinity,
entry: null, 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); 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() { function updateReferenceVisibility() {
if (!state._enabled || !state._viewer?.camera) return; if (!state._enabled || !state._viewer) return;
const cameraPos = state._viewer.camera.positionWC; if (!sweep()) return;
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;
}
}
const winners = selectCableReferenceLabelWinners(state._referenceRecords); const winners = selectCableReferenceLabelWinners(state._referenceRecords);
let changed = winners.length !== state._lastPublishedCount; let changed = winners.length !== state._lastPublishedCount;
for (let i = 0; i < winners.length; i++) { for (let i = 0; i < winners.length; i++) {
@@ -246,9 +481,6 @@ export function createRendering({ state }) {
} }
state._publishScratch.length = winners.length; state._publishScratch.length = winners.length;
state._referenceLabelCount = 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; if (!changed) return;
state._overlayPublisher.publish(state._publishScratch); state._overlayPublisher.publish(state._publishScratch);
state._lastPublishedCount = winners.length; state._lastPublishedCount = winners.length;
@@ -260,14 +492,14 @@ export function createRendering({ state }) {
state._lastPublishedPriorities.length = winners.length; state._lastPublishedPriorities.length = winners.length;
} }
return { return {
attach,
detach,
resetPublishSignature, resetPublishSignature,
releaseDataSources, releaseDrawing,
updateVisibility, updateVisibility,
styleCableEntity,
applyMarkerBlendOnce,
applyCableClassification, applyCableClassification,
styleLandingEntity, drawFeatures,
addReferenceStem, pickInfo,
updateReferenceVisibility, updateReferenceVisibility,
}; };
} }
+24 -22
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { import {
createCableReferenceSweepGate, createCableReferenceSweepGate,
createCableOverlayPublisher, createCableOverlayPublisher,
@@ -30,17 +29,30 @@ export function createState({ sweepClock, overlayHost }) {
state._loadGeneration = 0; 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 * Fetched cable/landing JSON kept across disable/enable. A disable CLEARS
* the three data sources (see releaseDataSources) instead of hiding them, * the draw sets (see releaseDrawing) instead of hiding them, so a
* so a re-enable has to rebuild the entities; the network/parse half of * re-enable has to rebuild the items; the network/parse half of that
* that rebuild is the expensive part users would notice, so it is cached. * rebuild is the expensive part users would notice, so it is cached.
*/ */
state._cachedCableJson = null; state._cachedCableJson = null;
@@ -49,8 +61,6 @@ export function createState({ sweepClock, overlayHost }) {
state._referenceRecords = []; state._referenceRecords = [];
state._surfaceRecords = [];
state._clickSubscription = null; state._clickSubscription = null;
state._preRenderRemover = null; state._preRenderRemover = null;
@@ -59,15 +69,9 @@ export function createState({ sweepClock, overlayHost }) {
state._mapStackListener = null; 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; state._clampTo = 'both';
/** True once both marker collections blend translucent (or the shape probe failed). */
state._markerBlendDone = false;
state._markerBlendInvariantWarned = false;
state._referenceLabelCount = 0; state._referenceLabelCount = 0;
@@ -96,10 +100,8 @@ export function createState({ sweepClock, overlayHost }) {
state._lastPublishedCount = -1; 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 = BASE_LANDING_COLOR;
state.landingColor = Cesium.Color.fromCssColorString(BASE_LANDING_COLOR);
return state; return state;
} }
+19 -111
View File
@@ -1,126 +1,34 @@
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 * What cable ground lines drape on for one map stack. The photoreal stack
* Google 3D tiles with the Cesium globe HIDDEN, so cable ground lines only * renders Google 3D tiles with the globe HIDDEN, so cable ground lines only
* need the 3D-tile classification pass there; every other known stack (the * need to drape on the tiles there; every other known stack (the bing
* bing stacks and osm) renders imagery on the shown globe, so only the * stacks and osm) renders imagery on the shown globe, so only the terrain
* terrain pass applies. * applies.
* Classifying against just the active surface halves the batched * Draping on just the active surface halves the ground lines' draw
* GroundPolylinePrimitive's emitted command sets. BOTH is the safe fallback * commands. `both` is the safe fallback for an unknown stack — it renders
* for an unknown stack — it renders on every surface, exactly the shipped * on every surface, exactly the shipped pre-optimization behavior.
* pre-optimization behavior.
* @param {string|null|undefined} activeId MapStackController stack id. * @param {string|null|undefined} activeId MapStackController stack id.
* @returns {Cesium.ClassificationType} * @returns {'tiles'|'terrain'|'both'} The draw sets' `clampTo`.
*/ */
export function cableClassificationTypeForStack(activeId) { export function cableClassificationTypeForStack(activeId) {
if (activeId === 'photoreal') return Cesium.ClassificationType.CESIUM_3D_TILE; if (activeId === 'photoreal') return 'tiles';
if (CABLE_GLOBE_STACK_IDS.has(activeId)) if (CABLE_GLOBE_STACK_IDS.has(activeId)) return 'terrain';
return Cesium.ClassificationType.TERRAIN; return 'both';
return Cesium.ClassificationType.BOTH;
} }
/** /**
* Derive the active surface from live scene state. The boot-time * Derive the active surface from live scene state. The boot-time
* `setStack(..., { silent: true })` fires no 'gev:map-stack-changed' event, * `setStack(..., { silent: true })` fires no 'gev:map-stack-changed' event,
* so the initial classification reads the scene the way the height-datum * so the initial surface is read the way the height-datum listeners do: the
* listeners do: the photoreal regime is exactly "globe hidden". * photoreal regime is exactly "globe hidden".
* @param {Cesium.Scene|null|undefined} scene * @param {{globe?: {show?: boolean}}|null|undefined} scene
* @returns {Cesium.ClassificationType} * @returns {'tiles'|'terrain'|'both'}
*/ */
export function cableClassificationTypeForScene(scene) { export function cableClassificationTypeForScene(scene) {
if (!scene?.globe) return Cesium.ClassificationType.BOTH; if (!scene?.globe) return 'both';
return scene.globe.show === false return scene.globe.show === false ? 'tiles' : 'terrain';
? 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);
} }
+122 -15
View File
@@ -148,6 +148,7 @@ export function createCesiumDraw({ scene, report }) {
record.pickIds = []; record.pickIds = [];
record.placed = []; record.placed = [];
record.patchable = null; record.patchable = null;
record.lineParts = null;
build(record); build(record);
setsVersion += 1; setsVersion += 1;
}; };
@@ -162,7 +163,7 @@ export function createCesiumDraw({ scene, report }) {
}, },
upsert(list) { upsert(list) {
// Items that only change how they look are changed where they are. // Items that only change how they look are changed where they are.
if (patchPoints(record, list)) { if (patchPoints(record, list) || patchLines(record, list)) {
for (const item of list) items.set(item.id, item); for (const item of list) items.set(item.id, item);
setsVersion += 1; setsVersion += 1;
requestRender(); requestRender();
@@ -190,12 +191,12 @@ export function createCesiumDraw({ scene, report }) {
Object.assign(spec, options); Object.assign(spec, options);
// What clamped items clamp to, how points blend, and whether ground // What clamped items clamp to, how points blend, and whether ground
// primitives pick, are built into them. Models clamp nothing, only // primitives pick, are built into them. Models clamp nothing, only
// points build in the blend, and only shapes and lines have ground // points and icons build in the blend, and only shapes and lines have ground
// primitives: other kinds are not rebuilt for those (models would // primitives: other kinds are not rebuilt for those (models would
// load again). // load again).
if ( if (
(kind !== 'models' && spec.clampTo !== clampTo) || (kind !== 'models' && spec.clampTo !== clampTo) ||
(kind === 'points' && spec.blend !== blend) || ((kind === 'points' || kind === 'icons') && spec.blend !== blend) ||
((kind === 'shapes' || kind === 'lines') && ((kind === 'shapes' || kind === 'lines') &&
(spec.pickable !== false) !== pickable) (spec.pickable !== false) !== pickable)
) )
@@ -322,6 +323,7 @@ export function createCesiumDraw({ scene, report }) {
for (const record of sets.values()) { for (const record of sets.values()) {
const ground = record.pending; const ground = record.pending;
if (!ground || ground.some((p) => !p.isDestroyed() && !p.ready)) continue; if (!ground || ground.some((p) => !p.isDestroyed() && !p.ready)) continue;
showPending(record);
for (const primitive of ground) primitive.show = true; for (const primitive of ground) primitive.show = true;
record.pending = null; record.pending = null;
retire(record); retire(record);
@@ -381,7 +383,10 @@ export function createCesiumDraw({ scene, report }) {
} }
function buildIcons(record) { function buildIcons(record) {
const host = new Cesium.BillboardCollection({ scene }); const host = new Cesium.BillboardCollection({
scene,
blendOption: pointBlendOf(record.spec.blend),
});
record.atlases = new Set(); record.atlases = new Set();
for (const item of record.items.values()) { for (const item of record.items.values()) {
const image = iconImage(record, item.image); const image = iconImage(record, item.image);
@@ -629,12 +634,23 @@ export function createCesiumDraw({ scene, report }) {
function buildLines(record) { function buildLines(record) {
const host = new Cesium.PolylineCollection(); const host = new Cesium.PolylineCollection();
const draped = new Map(); const draped = new Map();
// Each line as drawn, for upserts that change it in place.
const parts = new Map();
record.lineParts = parts;
for (const item of record.items.values()) { for (const item of record.items.values()) {
if (item.mode === 'draped') { if (item.mode === 'draped') {
if (item.style.kind !== 'solid') if (item.style.kind !== 'solid')
throw new Error('the Cesium renderer drapes solid lines only'); throw new Error('the Cesium renderer drapes solid lines only');
const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both';
if (!draped.has(clampTo)) draped.set(clampTo, []); if (!draped.has(clampTo)) draped.set(clampTo, []);
const id = pickId(record, item);
parts.set(item.id, {
look: lineLook(item),
positions: flatPositions(item.positions),
clampTo,
id,
ground: null,
});
draped.get(clampTo).push( draped.get(clampTo).push(
new Cesium.GeometryInstance({ new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({ geometry: new Cesium.GroundPolylineGeometry({
@@ -650,33 +666,124 @@ export function createCesiumDraw({ scene, report }) {
item.show !== false, item.show !== false,
), ),
}, },
id: pickId(record, item), id,
}), }),
); );
continue; continue;
} }
host.add({ const polyline = host.add({
positions: linePositions(item), positions: linePositions(item),
width: item.widthPx, width: item.widthPx,
material: lineMaterial(item.style), material: lineMaterial(item.style),
show: item.show !== false, show: item.show !== false,
id: pickId(record, item), id: pickId(record, item),
}); });
parts.set(item.id, { look: lineLook(item), polyline });
} }
if (!draped.size) return replaceHost(record, host); if (!draped.size) return replaceHost(record, host);
// Draped lines drape as the entities' clamped polylines do. // Draped lines drape as the entities' clamped polylines do.
const ground = [...draped].map( const byClamp = new Map();
([clampTo, geometryInstances]) => const ground = [...draped].map(([clampTo, geometryInstances]) => {
new Cesium.GroundPolylinePrimitive({ const primitive = new Cesium.GroundPolylinePrimitive({
geometryInstances, geometryInstances,
appearance: new Cesium.PolylineColorAppearance(), appearance: new Cesium.PolylineColorAppearance(),
classificationType: classificationOf(clampTo), classificationType: classificationOf(clampTo),
allowPicking: record.spec.pickable !== false, allowPicking: record.spec.pickable !== false,
}), });
); byClamp.set(clampTo, primitive);
return primitive;
});
for (const part of parts.values())
if (part.clampTo) part.ground = byClamp.get(part.clampTo);
replaceHost(record, collect(host, ground), ground, host); replaceHost(record, collect(host, ground), ground, host);
} }
/**
* How a line draws, but for where it runs and whether it shows: lines
* that keep it can be changed in place.
*/
const lineLook = (item) =>
JSON.stringify([
item.mode,
item.widthPx,
item.clampTo,
item.style,
item.depthFailColor,
item.segmentColors,
item.segmentShow,
item.revealFraction,
item.frame,
]);
/** A line's positions as one flat array of numbers, to compare. */
function flatPositions(positions) {
if (positions instanceof Float64Array) return Array.from(positions);
const flat = [];
for (const p of positions)
if ('x' in p) flat.push(p.x, p.y, p.z);
else flat.push(p.lon, p.lat, p.height ?? 0, NaN);
return flat;
}
const samePositions = (a, b) =>
a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
/**
* Upsert lines in place, without a rebuild, when every item is drawn now
* and looks the same: then only whether it shows, its `meta`, and where
* a line not draped runs change. A draped line keeps its positions, and
* its ground primitive must be ready. False, changing nothing, otherwise.
*/
function patchLines(record, list) {
const parts = record.lineParts;
if (record.kind !== 'lines' || !parts) return false;
for (const item of list) {
const was = parts.get(item.id);
if (!was || was.look !== lineLook(item)) return false;
if (
was.ground &&
(was.ground.isDestroyed() ||
(!was.ground.ready && !record.pending?.includes(was.ground)) ||
!samePositions(flatPositions(item.positions), was.positions))
)
return false;
}
for (const item of list) {
const was = parts.get(item.id);
const show = item.show !== false;
if (was.polyline) {
was.polyline.positions = linePositions(item);
was.polyline.show = show;
was.polyline.id.meta = item.meta;
continue;
}
was.id.meta = item.meta;
// A ground primitive still building takes its show once it is ready
// (`swapReady`), so a show change never restarts the build.
if (was.ground.ready) showPart(was, show);
else was.pendingShow = show;
}
return true;
}
/** A draped line part's show, on its ready ground primitive. */
function showPart(part, show) {
const attributes = part.ground.getGeometryInstanceAttributes(part.id);
attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
/** The shows patched in while a set's ground primitives were building. */
function showPending(record) {
for (const part of record.lineParts?.values() ?? [])
if (part.pendingShow !== undefined && !part.ground.isDestroyed()) {
showPart(part, part.pendingShow);
part.pendingShow = undefined;
}
}
/** One host for a set's own collection and its ground primitives. */ /** One host for a set's own collection and its ground primitives. */
function collect(own, ground) { function collect(own, ground) {
const host = new Cesium.PrimitiveCollection(); const host = new Cesium.PrimitiveCollection();
+130
View File
@@ -1097,3 +1097,133 @@ test('the context layer draws its rim as an outlined ellipse on a viewer of its
rendering.disposeVisual(); rendering.disposeVisual();
assert.equal(other.added.length, 0); assert.equal(other.added.length, 0);
}); });
/** Run `fn` with the image classes Cesium's materials test uniforms against. */
function withImageClasses(fn) {
const names = [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
];
const real = names.map((name) => globalThis[name]);
for (const name of names) globalThis[name] ??= class {};
try {
return fn();
} finally {
names.forEach((name, i) => (globalThis[name] = real[i]));
}
}
test('lines that change only whether they show, or where an undraped one runs, change in place', () =>
withImageClasses(() => {
const { scene, draw, frame } = drawOver();
const set = draw.lines({ id: 'patched' });
const draped = (id, show = true, meta) => ({
id,
positions: [
{ lon: 0, lat: 0 },
{ lon: 1, lat: 1 },
],
widthPx: 2.5,
mode: 'draped',
style: { kind: 'solid', color: '#7fe6ed' },
show,
meta,
});
const stem = (id, height, show = true) => ({
id,
positions: [
Cesium.Cartesian3.fromDegrees(0, 0, 0),
Cesium.Cartesian3.fromDegrees(0, 0, height),
],
widthPx: 2,
mode: '3d',
style: { kind: 'solid', color: [1, 1, 1, 0.5] },
show,
meta: height,
});
const attributes = new Map();
const fakeAttributes = (ground) => {
ground.getGeometryInstanceAttributes = (id) => {
if (!attributes.has(id.id))
attributes.set(id.id, { show: new Uint8Array([1]) });
return attributes.get(id.id);
};
};
set.set([draped('a'), draped('b'), stem('s', 100)]);
const host = scene.added[0];
const ground = host.get(1);
fakeAttributes(ground);
// Still building: the show waits for the ground, and the build goes on.
set.upsert([draped('a', false)]);
assert.equal(scene.added[0], host, 'not rebuilt while its ground builds');
assert.equal(attributes.size, 0);
Object.defineProperty(ground, 'ready', { value: true });
frame();
assert.deepEqual([...attributes.get('a').show], [0], 'shown once ready');
set.upsert([draped('b', false)]);
assert.equal(scene.added[0], host, 'changed in place once ready');
assert.deepEqual([...attributes.get('b').show], [0]);
set.upsert([draped('b', true, 'new')]);
assert.deepEqual([...attributes.get('b').show], [1]);
const [, idB] = ground.geometryInstances.map((instance) => instance.id);
assert.equal(idB.meta, 'new', 'picks read the new meta');
// An undraped line moves and hides in place, and keeps its new meta.
const line = host.get(0).get(0);
set.upsert([stem('s', 2500, false)]);
assert.equal(scene.added[0], host);
assert.equal(host.get(0).get(0), line);
assert.equal(line.show, false);
assert.equal(line.id.meta, 2500);
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
line.positions[1],
Cesium.Cartesian3.fromDegrees(0, 0, 2500),
1e-6,
),
);
// One item that cannot change in place rebuilds them all, and patches
// none of the others first.
set.upsert([
draped('a'),
{
...draped('b'),
positions: [
{ lon: 0, lat: 0 },
{ lon: 2, lat: 2 },
],
},
]);
assert.deepEqual([...attributes.get('a').show], [0], 'not patched');
assert.notEqual(scene.added.at(-1), host, 'a draped line that moves');
const moved = scene.added.at(-1);
set.upsert([{ ...stem('s', 2500), widthPx: 3 }]);
assert.notEqual(scene.added.at(-1), moved, 'a line that looks different');
// A ground primitive gone from under the set rebuilds too.
const third = scene.added.at(-1);
third.get(1).destroy();
set.upsert([draped('a', false)]);
assert.notEqual(scene.added.at(-1), third, 'its ground destroyed');
set.dispose();
}));
test('icons blend as their set says', () => {
const { scene, draw } = drawOver();
const set = draw.icons({ id: 'pins', blend: 'translucent' });
set.set([
{
id: 'a',
pos: { lon: 0, lat: 0 },
image: 'pin.png',
size: [6, 6],
},
]);
assert.equal(scene.added[0].blendOption, Cesium.BlendOption.TRANSLUCENT);
set.setOptions({ blend: undefined });
assert.equal(
scene.added[0].blendOption,
Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT,
);
set.dispose();
});
-7
View File
@@ -126,13 +126,6 @@
"src/layers/streetLevel/selection.js", "src/layers/streetLevel/selection.js",
"src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/view.js", "src/layers/streetLevel/view.js",
"src/layers/submarineCables/ingestion.js",
"src/layers/submarineCables/interaction.js",
"src/layers/submarineCables/overlay.js",
"src/layers/submarineCables/policy.js",
"src/layers/submarineCables/rendering.js",
"src/layers/submarineCables/state.js",
"src/layers/submarineCables/surface.js",
"src/layers/traffic/animation.js", "src/layers/traffic/animation.js",
"src/layers/traffic/flow.js", "src/layers/traffic/flow.js",
"src/layers/traffic/footprint.js", "src/layers/traffic/footprint.js",
+71
View File
@@ -13,3 +13,74 @@ export function hexColor(hex, alpha = 1) {
alpha, alpha,
]; ];
} }
// The default renderer's own patterns, so a colour reads as it read there.
const SHORT_HEX = /^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i;
const LONG_HEX = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;
const RGB =
/^rgba?\s*\(\s*([0-9.]+%?)\s*[,\s]+\s*([0-9.]+%?)\s*[,\s]+\s*([0-9.]+%?)(?:\s*[,\s/]+\s*([0-9.]+))?\s*\)$/i;
const HSL =
/^hsla?\s*\(\s*([0-9.]+)\s*[,\s]+\s*([0-9.]+%)\s*[,\s]+\s*([0-9.]+%)(?:\s*[,\s/]+\s*([0-9.]+))?\s*\)$/i;
function hueToRgb(m1, m2, h) {
if (h < 0) h += 1;
if (h > 1) h -= 1;
if (h * 6 < 1) return m1 + (m2 - m1) * 6 * h;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6;
return m1;
}
const rgbChannel = (text) =>
Number.parseFloat(text) / (text.endsWith('%') ? 100 : 255);
/**
* A CSS colour (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()`,
* `hsl()`, `hsla()`) as a renderer colour, read as the default renderer
* reads it; null for anything else (named colours included).
*/
export function cssColor(text) {
const css = String(text ?? '').trim();
let m = SHORT_HEX.exec(css);
if (m)
return [
Number.parseInt(m[1], 16) / 15,
Number.parseInt(m[2], 16) / 15,
Number.parseInt(m[3], 16) / 15,
Number.parseInt(m[4] ?? 'f', 16) / 15,
];
m = LONG_HEX.exec(css);
if (m)
return [
Number.parseInt(m[1], 16) / 255,
Number.parseInt(m[2], 16) / 255,
Number.parseInt(m[3], 16) / 255,
Number.parseInt(m[4] ?? 'ff', 16) / 255,
];
m = RGB.exec(css);
if (m)
return [
rgbChannel(m[1]),
rgbChannel(m[2]),
rgbChannel(m[3]),
Number.parseFloat(m[4] ?? '1.0'),
];
m = HSL.exec(css);
if (!m) return null;
const hue = (Number.parseFloat(m[1]) / 360) % 1;
const saturation = Number.parseFloat(m[2]) / 100;
const lightness = Number.parseFloat(m[3]) / 100;
const alpha = Number.parseFloat(m[4] ?? '1.0');
if (saturation === 0) return [lightness, lightness, lightness, alpha];
const m2 =
lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const m1 = 2 * lightness - m2;
return [
hueToRgb(m1, m2, hue + 1 / 3),
hueToRgb(m1, m2, hue),
hueToRgb(m1, m2, hue - 1 / 3),
alpha,
];
}
+23
View File
@@ -6,3 +6,26 @@ test('hex colours become renderer colours at the given alpha', () => {
assert.deepEqual(hexColor('#ff8000'), [1, 128 / 255, 0, 1]); assert.deepEqual(hexColor('#ff8000'), [1, 128 / 255, 0, 1]);
assert.deepEqual(hexColor('#000000', 0.25), [0, 0, 0, 0.25]); assert.deepEqual(hexColor('#000000', 0.25), [0, 0, 0, 0.25]);
}); });
test('CSS colours read as the default renderer reads them', async () => {
const Cesium = await import('cesium');
const { cssColor } = await import('./color.js');
for (const css of [
'#39d5ff',
' #8fffd2 ',
'#abc',
'#abcd',
'#11223344',
'rgb(10, 20, 30)',
'rgba(10,20,30,0.5)',
'rgb(10% 20% 30% / 0.25)',
'hsl(120, 50%, 25%)',
'hsla(300, 100%, 75%, 0.4)',
'hsl(30, 0%, 40%)',
]) {
const c = Cesium.Color.fromCssColorString(css);
assert.deepEqual(cssColor(css), [c.red, c.green, c.blue, c.alpha], css);
}
assert.equal(cssColor('not a colour'), null);
assert.equal(cssColor(undefined), null);
});
+5 -83
View File
@@ -1,95 +1,17 @@
/** /**
* @module render/stub/geodesic * @module render/stub/geodesic
* @description The point a fraction of the way along the WGS84 geodesic * @description The point a fraction of the way along the WGS84 geodesic
* between two places: Vincenty's inverse formula, then the series the * between two places: Vincenty's inverse formula (`geo/geodesic`), then
* default renderer interpolates with, term for term, so a rectangle's * the series the default renderer interpolates with, term for term, so a
* centre matches its to floating-point noise. * rectangle's centre matches its to floating-point noise.
*/ */
import { TWO_PI, WGS84 } from './math.js'; import { deltaLambda, geodesicInverse as inverse } from '../../geo/geodesic.js';
import { WGS84 } from './math.js';
const EPSILON12 = 1e-12;
const A = WGS84.radii.x; const A = WGS84.radii.x;
const B = WGS84.radii.z; const B = WGS84.radii.z;
const F = (A - B) / A; const F = (A - B) / A;
function deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm) {
const C = (F * cos2Alpha * (4 + F * (4 - 3 * cos2Alpha))) / 16;
return (
(1 - C) *
F *
sineAlpha *
(sigma + C * sinSigma * (cos2Sm + C * cosSigma * (2 * cos2Sm * cos2Sm - 1)))
);
}
/** Distance, start heading and u² of the geodesic from (lon1, lat1) to (lon2, lat2), radians. */
function inverse(lon1, lat1, lon2, lat2) {
const l = lon2 - lon1;
const u1 = Math.atan((1 - F) * Math.tan(lat1));
const u2 = Math.atan((1 - F) * Math.tan(lat2));
const cosU1 = Math.cos(u1);
const sinU1 = Math.sin(u1);
const cosU2 = Math.cos(u2);
const sinU2 = Math.sin(u2);
const cc = cosU1 * cosU2;
const cs = cosU1 * sinU2;
const ss = sinU1 * sinU2;
const sc = sinU1 * cosU2;
let lambda = l;
let lambdaDot = TWO_PI;
let cosLambda;
let sinLambda;
let sigma;
let cosSigma;
let sinSigma;
let cos2Alpha;
let cos2Sm;
do {
cosLambda = Math.cos(lambda);
sinLambda = Math.sin(lambda);
const temp = cs - sc * cosLambda;
sinSigma = Math.sqrt(cosU2 * cosU2 * sinLambda * sinLambda + temp * temp);
cosSigma = ss + cc * cosLambda;
sigma = Math.atan2(sinSigma, cosSigma);
let sineAlpha;
if (sinSigma === 0) {
sineAlpha = 0;
cos2Alpha = 1;
} else {
sineAlpha = (cc * sinLambda) / sinSigma;
cos2Alpha = 1 - sineAlpha * sineAlpha;
}
lambdaDot = lambda;
cos2Sm = cosSigma - (2 * ss) / cos2Alpha;
if (!isFinite(cos2Sm)) cos2Sm = 0;
lambda =
l + deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm);
} while (Math.abs(lambda - lambdaDot) > EPSILON12);
const uSquared = (cos2Alpha * (A * A - B * B)) / (B * B);
const bigA =
1 +
(uSquared * (4096 + uSquared * (uSquared * (320 - 175 * uSquared) - 768))) /
16384;
const bigB =
(uSquared * (256 + uSquared * (uSquared * (74 - 47 * uSquared) - 128))) /
1024;
const cos2Sm2 = cos2Sm * cos2Sm;
const deltaSigma =
bigB *
sinSigma *
(cos2Sm +
(bigB *
(cosSigma * (2 * cos2Sm2 - 1) -
(bigB * cos2Sm * (4 * sinSigma * sinSigma - 3) * (4 * cos2Sm2 - 3)) /
6)) /
4);
return {
distance: B * bigA * (sigma - deltaSigma),
startHeading: Math.atan2(cosU2 * sinLambda, cs - sc * cosLambda),
uSquared,
};
}
/** /**
* The longitude and latitude (radians) `fraction` of the way along the * The longitude and latitude (radians) `fraction` of the way along the
* geodesic from (lon1, lat1) to (lon2, lat2). * geodesic from (lon1, lat1) to (lon2, lat2).
+2 -10
View File
@@ -9,6 +9,7 @@
* Nothing runs on its own: `testing.tick()` and `testing.advance()` drive the * Nothing runs on its own: `testing.tick()` and `testing.advance()` drive the
* loop on a virtual clock, one frame at a time, in the contract's order. * loop on a virtual clock, one frame at a time, in the contract's order.
*/ */
import { horizonFrom } from '../../geo/horizon.js';
import { createInputRouter } from '../input/router.js'; import { createInputRouter } from '../input/router.js';
import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js'; import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js';
import { createStubCamera } from './camera.js'; import { createStubCamera } from './camera.js';
@@ -27,7 +28,6 @@ import {
toDegrees, toDegrees,
toEcef, toEcef,
vec, vec,
WGS84,
} from './math.js'; } from './math.js';
const FRAME_MS = 1000 / 60; const FRAME_MS = 1000 / 60;
@@ -504,15 +504,7 @@ export function createStubRenderer(options = {}) {
} }
function isOccluded(position) { function isOccluded(position) {
const e = eye(); return !horizonFrom(eye().position).isPointVisible(position);
const r = WGS84.oneOverRadii;
const cv = vec(e.position.x * r.x, e.position.y * r.y, e.position.z * r.z);
const vh = dot(cv, cv) - 1;
const t = vec(position.x * r.x, position.y * r.y, position.z * r.z);
const vt = sub(t, cv);
const vtDotVc = -dot(vt, cv);
if (vh < 0) return vtDotVc > 0;
return vtDotVc > vh && (vtDotVc * vtDotVc) / dot(vt, vt) > vh;
} }
let scriptedPicks = null; let scriptedPicks = null;
+1
View File
@@ -70,6 +70,7 @@ const DRAW_FROM_CALLER = new Set([
'./layers/gnss', './layers/gnss',
'./layers/perimeters', './layers/perimeters',
'./layers/awareness', './layers/awareness',
'./layers/submarine-cables',
]); ]);
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));