Merge main into denis/iss-live-telemetry

Conflicts: the locale catalogs, package boundaries and format scope are
three-way merges (entries main removed, such as displayPanelScroll.js,
stay removed); applicationShell.js and ContextView.vue keep main's Space
Missions panel and the STATION and LIVE wiring, moved back into
_initGlobalContextPanel; installations take main's feedback module, and
their label box joins main's card-on-top click rule; ports.test.mjs lists
modelParts and modelNodes; CURRENT-STATE.md keeps both edits.

zh-Hant is regenerated from zh-CN, as main now requires. "Below" keeps
main's translations.
This commit is contained in:
Denis Groshev committed 2026-11-19 17:07:48 +01:00
commit 0620d01140
1526 files changed
+52168 -11320

No files matched your search

+2
View File
@@ -218,6 +218,8 @@ export function createCesiumRendererPlugin({
// Whether an entity is one of the viewer's own (Cockpit asks whether
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// An application drawing with Cesium itself beside the contract.
engine: Object.freeze({ kind: 'cesium', viewer }),
// QA scripts drive and read the viewer itself.
qaHandles: {
viewer,
+2
View File
@@ -156,6 +156,8 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
);
assert.equal(hooks.ownCreditDisplay, true, 'Cesium shows its own credits');
assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer');
assert.equal(hooks.engine.kind, 'cesium', 'the engine says what it is');
assert.equal(hooks.engine.viewer, viewer, 'an application may draw with it');
assert.equal(hooks.viewerDrawsEntity({ own: true }), true);
assert.equal(hooks.viewerDrawsEntity({}), false);
assert.equal(typeof hooks.trimStaleCommands, 'function');
+86 -8
View File
@@ -2,15 +2,93 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { recordCameraGoldens } from './cameraGoldens.js';
import { near, nearAngle } from '../conformance/expect.js';
// The recorder is deterministic, but platforms can differ in the last bits
// of trigonometric arithmetic. Keep structure and discrete values exact.
function compareTrace(actual, expected, path = []) {
const label = path.join('.');
if (typeof expected === 'number') {
const key = path.at(-1);
if (['step', 'frames', 'count'].includes(key) || path[0] === 'viewport') {
assert.equal(actual, expected, label);
return;
}
const metres =
path.at(-2) === 'position' ||
key === 'height' ||
(path.at(-2) === 'view' && Number(key) >= 12 && Number(key) <= 14);
// A few ulps of the value itself, so large untagged values (pick points,
// ray origins, the far plane) are not held below one ulp.
const tolerance = Math.max(
metres ? 1e-8 : 1e-14,
Math.abs(expected) * 4 * Number.EPSILON,
);
// Heading and roll wrap at 2π: a value just under it is one just over 0.
if (key === 'heading' || key === 'roll')
nearAngle(actual, expected, tolerance, label);
else near(actual, expected, tolerance, label);
return;
}
if (expected !== null && typeof expected === 'object') {
assert.ok(actual !== null && typeof actual === 'object', label);
assert.equal(Array.isArray(actual), Array.isArray(expected), label);
assert.deepEqual(Object.keys(actual), Object.keys(expected), label);
if (Array.isArray(expected))
assert.equal(actual.length, expected.length, label);
for (const key of Object.keys(expected))
compareTrace(actual[key], expected[key], [...path, key]);
return;
}
assert.equal(actual, expected, label);
}
test('the committed camera traces are what the installed Cesium records', async () => {
const committed = readFileSync(
new URL('../conformance/goldens/camera.json', import.meta.url),
'utf8',
);
const recorded = `${JSON.stringify(await recordCameraGoldens(), null, 2)}\n`;
assert.ok(
recorded === committed,
'goldens/camera.json is out of date: run node scripts/record-camera-goldens.mjs and review the diff',
const committed = JSON.parse(
readFileSync(
new URL('../conformance/goldens/camera.json', import.meta.url),
'utf8',
),
);
compareTrace(await recordCameraGoldens(), committed);
});
test('trace comparison tolerates only numeric roundoff, preserving structure and counters', () => {
const expected = {
position: { x: 1000 },
pitch: 0.3,
frames: 2,
values: [1],
label: 'pose',
};
compareTrace(
{ ...expected, position: { x: 1000 + 2e-9 }, pitch: 0.3 + 1e-16 },
expected,
);
for (const actual of [
{ ...expected, extra: true },
{ ...expected, values: [] },
{ ...expected, position: { x: 1000 + 2e-8 } },
{ ...expected, pitch: 0.3 + 2e-14 },
{ ...expected, frames: 2 + 1e-15 },
{ ...expected, pitch: NaN },
{ ...expected, pitch: null },
{ ...expected, pitch: '0.3' },
{ ...expected, label: 'other' },
])
assert.throws(() => compareTrace(actual, expected));
const { label, ...missing } = expected;
assert.throws(() => compareTrace(missing, expected));
});
test('trace comparison scales with the value and wraps heading and roll', () => {
// One ulp of a ground pick point (about 5e-10 at 3e6 m) is roundoff.
const far = 3_000_000.123;
compareTrace({ pick: far + 2 * Number.EPSILON * far }, { pick: far });
assert.throws(() => compareTrace({ pick: far + 1e-6 }, { pick: far }));
// A heading just under 2π is one just over 0.
compareTrace({ heading: 2 * Math.PI - 1e-16 }, { heading: 1e-16 });
compareTrace({ roll: 1e-16 }, { roll: 2 * Math.PI - 1e-16 });
assert.throws(() => compareTrace({ heading: 0.1 }, { heading: 0 }));
assert.throws(() => compareTrace({ heading: NaN }, { heading: 0 }));
});
+10 -1
View File
@@ -416,7 +416,16 @@ test('a pose measures heading, pitch and roll as Cesium does, and leaves the cam
const pitch = camera.pitch;
const roll = camera.roll;
assert.equal(pose.heading, heading, `heading ${k}`);
assert.ok(Math.abs(pose.pitch - pitch) < 1e-12, `pitch ${k}`);
assert.ok(
pose.pitch >= -Math.PI / 2 && pose.pitch <= Math.PI / 2,
`canonical pitch ${k}`,
);
// Near vertical, acos amplifies last-bit direction differences. Match
// the conformance suite's well-conditioned pitch comparison.
assert.ok(
Math.abs(Math.sin(pose.pitch) - Math.sin(pitch)) < 1e-12,
`pitch ${k}`,
);
const turn = Math.abs(pose.roll - roll);
assert.ok(Math.min(turn, 2 * Math.PI - turn) < 1e-12, `roll ${k}`);
}
+10 -3
View File
@@ -5312,10 +5312,14 @@ export function createCesiumDraw({
replaceHost,
horizonNow,
requestRender,
parts: capabilities.has('modelParts'),
now,
});
const buildModels = (record) => modelSets.build(record);
// Whether shapes pulsed in the last frame, which draws on in the next.
let pulsing = false;
// Whether a shown model's parts spun in the last frame, likewise.
let spinning = false;
const lineWidth = (px) =>
typeof scene.clampLineWidth === 'function'
? scene.clampLineWidth(px)
@@ -5452,7 +5456,7 @@ export function createCesiumDraw({
turnInertial(record);
record.drapeInertial?.();
}
modelSets.beforeRender(sets.values());
spinning = modelSets.beforeRender(sets.values());
quadSets.beforeRender(sets.values());
},
/** Each frame, after it drew: clamp state, and ground swaps. */
@@ -5483,7 +5487,8 @@ export function createCesiumDraw({
// Rows moving on a live clock, and flowing lines, draw on in the
// frames that follow.
const playing = quadSets.afterRender(sets.values());
if (anySet(animating) || flowing() || pulsing || playing) requestRender();
if (anySet(animating) || flowing() || pulsing || spinning || playing)
requestRender();
},
/**
* Let go of the sets; with `removeHosts`, take what they draw out of
@@ -5494,6 +5499,8 @@ export function createCesiumDraw({
clampListeners.clear();
// Fields go with the port, and their frame listeners with them.
fieldPart.dispose();
// Part shaders and their textures go with it too.
modelSets.dispose();
// Late model loads find no host and destroy themselves.
for (const record of sets.values()) {
if (removeHosts && !scene.isDestroyed?.()) {
@@ -5538,7 +5545,7 @@ provideUnboundDraw((viewer) => {
const part = createCesiumDraw({
scene,
report: uncaught,
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields']),
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
});
unboundParts.set(part.port, part);
const offs = [
+22 -13
View File
@@ -4452,19 +4452,28 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del
}
assert.equal(host._recedeParams().scaleFloor, 0.45);
// Drawn where the layer reads it, between its two fixes.
const t = Date.now() - delayMs;
const tau = set.seconds(julianAt(t));
const drawn = set.position(row, tau);
const read = icons._iconPosition('abc123');
assert.ok(Cesium.Cartesian3.distance(drawn, read) < 0.5, 'same place');
const lon = Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(drawn).longitude,
);
assert.ok(lon > -97 && lon < -96.9, 'interpolating the fixes');
assert.ok(
Math.abs(set.course(row, tau) - icons._iconCourse('abc123')) < 0.01,
);
// Drawn where the layer reads it, between its two fixes. The clock
// holds still while both are read: the contact covers half a metre in
// about a millisecond, so two readings of a moving clock may not agree.
const realNow = Date.now;
const frozen = realNow();
Date.now = () => frozen;
try {
const t = frozen - delayMs;
const tau = set.seconds(julianAt(t));
const drawn = set.position(row, tau);
const read = icons._iconPosition('abc123');
assert.ok(Cesium.Cartesian3.distance(drawn, read) < 0.5, 'same place');
const lon = Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(drawn).longitude,
);
assert.ok(lon > -97 && lon < -96.9, 'interpolating the fixes');
assert.ok(
Math.abs(set.course(row, tau) - icons._iconCourse('abc123')) < 0.01,
);
} finally {
Date.now = realNow;
}
assert.equal(state._icons.expires('abc123'), now - 20_000);
assert.deepEqual(
drawHitOf(host._pickObject('abc123', null, { show: true })),
+629 -6
View File
@@ -26,6 +26,20 @@
* `shading: 'thermal'` draws the model unlit and white-hot (its texture
* left out), then tinted as asked: a hot target, as the thermal views draw
* them. Heights are absolute: models clamp nothing.
*
* An item's `parts` (with `modelParts`) poses the moving parts of a model
* whose mesh carries `_PART` and whose root node carries a part table
* (`render/modelParts.js`): its model then draws with a custom shader of
* its own whose vertex stage moves each vertex by its part's matrix, read
* from a small float texture (`PARTS_VERTEX` says its layout), with the
* item's mask, unlit or thermal look in the same shader; a moved part's
* material normal turns with it. The texture is written again in place
* when the part state changes, and each frame while a part of a model in
* view spins (frames are asked for while one does). Spins keep their angle
* across a change of rate. A model at rest, or without a part table, draws
* exactly as it would without `parts`, on the shared shaders above. Cesium
* culls and picks a model by its bounds as its file draws it, so a part
* moved outside them is drawn only while those bounds are in view.
*/
import * as Cesium from 'cesium';
import {
@@ -34,6 +48,15 @@ import {
recedeParams,
recededAlpha,
} from '../recession.js';
import { customShaderTexture } from './internals.js';
import {
glbJson,
gltfMeshMatrix,
gltfPartTable,
partMatrices,
PART_HIGHLIGHT,
asksHighlight,
} from '../modelParts.js';
const BLEND_MODES = {
highlight: Cesium.ColorBlendMode.HIGHLIGHT,
@@ -200,6 +223,366 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
return undefined;
}
/** The colour a part with `highlight: true` is drawn in. */
const PART_HIGHLIGHT_COLOR = '#ffc400';
/** How much of a highlighted part's colour the highlight replaces. */
const PART_HIGHLIGHT_MIX = 0.6;
/** Texels in a part's row of its texture. */
const PART_TEXELS = 8;
/** Floats in a part's row: `PART_TEXELS` RGBA texels. */
const PART_FLOATS = PART_TEXELS * 4;
/** A texel's centre across a part's row, as a texture coordinate. */
const texelAt = (i) => ((i + 0.5) / PART_TEXELS).toFixed(4);
/**
* The vertex stage of a posed model. A part's row of the texture holds the
* three rows of its matrix in the mesh's own frame (texels 0..2), the three
* rows of that matrix's inverse transpose (3..5; texel 3's alpha is 1 where
* the part is moved, 0 where it is at rest), and its highlight colour (6,
* alpha 0 for none). Each vertex is moved by its part's matrix; the normal
* turn is passed on in eye space, for the fragment stage to turn the
* material's own normal (normal maps and back-face flips kept) by it.
* Positions are the mesh's own (before its node's transform), as are the
* matrices written for it, and as `czm_normal` takes them to eye space.
*/
const PARTS_VERTEX = `
void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
float row = (floor(vsInput.attributes.part + 0.5) + 0.5) / u_partRows;
vec4 r0 = texture(u_partMatrices, vec2(${texelAt(0)}, row));
vec4 r1 = texture(u_partMatrices, vec2(${texelAt(1)}, row));
vec4 r2 = texture(u_partMatrices, vec2(${texelAt(2)}, row));
vec4 n0 = texture(u_partMatrices, vec2(${texelAt(3)}, row));
v_partHighlight = texture(u_partMatrices, vec2(${texelAt(6)}, row));
vec4 p = vec4(vsOutput.positionMC, 1.0);
vsOutput.positionMC = vec3(dot(r0, p), dot(r1, p), dot(r2, p));
v_partMoved = n0.a;
if (n0.a > 0.5) {
vec4 n1 = texture(u_partMatrices, vec2(${texelAt(4)}, row));
vec4 n2 = texture(u_partMatrices, vec2(${texelAt(5)}, row));
mat3 turn = transpose(mat3(n0.xyz, n1.xyz, n2.xyz));
v_partNormalEC = czm_normal * turn * inverse(czm_normal);
} else {
v_partNormalEC = mat3(1.0);
}
}`;
/**
* A posed model's custom shader: its parts moved (`PARTS_VERTEX`), drawn in
* `shading` with `mask` painted where `_TINT` marks the model (not under
* `thermal`), and its highlighted parts in their colour. Lit, a moved
* part's material normal is turned with it; the body and parts at rest keep
* theirs as the material made them. `data` is the part texture's first
* contents, `rows` its parts.
*/
function partShaderOf(shading, mask, data, rows) {
const lit = shading !== 'unlit' && shading !== 'thermal';
const masked = Boolean(mask) && shading !== 'thermal';
return new Cesium.CustomShader({
mode: Cesium.CustomShaderMode.MODIFY_MATERIAL,
...(lit ? {} : { lightingModel: Cesium.LightingModel.UNLIT }),
uniforms: {
u_partMatrices: {
type: Cesium.UniformType.SAMPLER_2D,
value: partTexture(data, rows),
},
u_partRows: { type: Cesium.UniformType.FLOAT, value: rows },
...(masked
? {
u_maskColor: {
type: Cesium.UniformType.VEC3,
value: new Cesium.Cartesian3(mask.red, mask.green, mask.blue),
},
}
: {}),
},
varyings: {
v_partNormalEC: Cesium.VaryingType.MAT3,
v_partMoved: Cesium.VaryingType.FLOAT,
v_partHighlight: Cesium.VaryingType.VEC4,
},
vertexShaderText: PARTS_VERTEX,
fragmentShaderText: `
void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
${
lit
? ` if (v_partMoved > 0.5)
material.normalEC = normalize(v_partNormalEC * material.normalEC);`
: ''
}
${shading === 'thermal' ? ' material.diffuse = vec3(1.0);' : ''}
${
masked
? ` vec3 mask = czm_srgbToLinear(u_maskColor);
material.diffuse *= mix(vec3(1.0), mask, fsInput.attributes.tint);`
: ''
}
if (v_partHighlight.a > 0.0) {
vec3 highlight = czm_srgbToLinear(v_partHighlight.rgb);
material.diffuse = mix(material.diffuse, highlight, ${PART_HIGHLIGHT_MIX.toFixed(2)});
material.emissive = max(material.emissive, highlight * 0.5);
}
}`,
});
}
/** A part texture's contents as a texture uniform: `PART_TEXELS` float texels a row, read unfiltered. */
function partTexture(data, rows) {
return new Cesium.TextureUniform({
typedArray: data,
width: PART_TEXELS,
height: rows,
pixelFormat: Cesium.PixelFormat.RGBA,
pixelDatatype: Cesium.PixelDatatype.FLOAT,
repeat: false,
minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST,
});
}
/** An affine column-major 4×4's inverse. */
function inverseAffine(m) {
const [a, b, c] = [m[0], m[1], m[2]];
const [d, e, f] = [m[4], m[5], m[6]];
const [g, h, i] = [m[8], m[9], m[10]];
const A = e * i - f * h;
const B = -(b * i - c * h);
const C = b * f - c * e;
const det = a * A + d * B + g * C;
if (!(Math.abs(det) > 1e-30)) return null;
const r = 1 / det;
const out = [
A * r,
B * r,
C * r,
0,
-(d * i - f * g) * r,
(a * i - c * g) * r,
-(a * f - c * d) * r,
0,
(d * h - e * g) * r,
-(a * h - b * g) * r,
(a * e - b * d) * r,
0,
0,
0,
0,
1,
];
for (let row = 0; row < 3; row++)
out[12 + row] = -(
out[row] * m[12] +
out[4 + row] * m[13] +
out[8 + row] * m[14]
);
return out;
}
/** What a glTF document (or GLB) says of its parts: its table and mesh frame; null without a table. */
const partInfos = new WeakMap();
/** `source`'s part table and mesh frame, read once; null for a model without moving parts. */
function partInfoOf(source) {
if (partInfos.has(source)) return partInfos.get(source);
let info = null;
try {
const json = source instanceof Uint8Array ? glbJson(source) : source;
const table = gltfPartTable(json);
const mesh = table && gltfMeshMatrix(json);
const meshInverse = mesh && inverseAffine(mesh);
if (table && table.parts.length > 1 && meshInverse)
info = { table, mesh, meshInverse };
} catch {
// A malformed table: the model draws whole.
info = null;
}
partInfos.set(source, info);
return info;
}
/** Whether a part state asks for anything. */
const asksParts = (state) =>
Boolean(state) &&
typeof state === 'object' &&
['spin', 'deploy', 'poses'].some(
(key) => state[key] && Object.keys(state[key]).length > 0,
);
/** Scratch for one model's part matrices and flags, and one matrix's rows. */
let scratchParts = new Float64Array(16 * 32);
let scratchFlags = new Uint8Array(32);
const scratchRow = new Float64Array(4);
const scratchL = new Float64Array(12);
/** How far from the identity a part's matrix may be and still be at rest. */
const AT_REST_EPSILON = 1e-9;
/** Highlight colours by what was asked, read once (a few at most). */
const highlightColors = new Map();
/**
* The colour a part's `highlight` asks for, read once: `true` the
* renderer's own, a colour that parses as itself; null for anything else
* (drawn without a highlight).
*/
export function partHighlightColor(value) {
if (!asksHighlight(value)) return null;
const key = value === true ? PART_HIGHLIGHT_COLOR : String(value);
let color = highlightColors.get(key);
if (color === undefined) {
if (value === true || typeof value === 'string')
color = Cesium.Color.fromCssColorString(key.trim()) ?? null;
else color = new Cesium.Color(value[0], value[1], value[2], 1);
if (highlightColors.size >= 256) highlightColors.clear();
highlightColors.set(key, color);
}
return color;
}
/**
* Write a model's part texture into `data` (`PART_FLOATS` a part, the
* layout `PARTS_VERTEX` reads) for `state` at `timeS`: for each part the
* rows of its matrix in the mesh's own frame, L = meshInverse · X · mesh,
* then the rows of L's inverse transpose (normals turn by it, exact under a
* stretch or a mesh frame that is not a rotation) with whether the part is
* moved, then its highlight colour. Whether any part is not at rest.
*/
export function writePartTexture(info, state, timeS, scale, data) {
const { table, mesh, meshInverse } = info;
const n = table.parts.length;
if (scratchParts.length < n * 16) {
scratchParts = new Float64Array(n * 16);
scratchFlags = new Uint8Array(n);
}
const posed = partMatrices(table, state, timeS, scratchParts, {
flags: scratchFlags,
scale,
});
const poses = state?.poses;
const x = scratchParts;
const ix = scratchRow;
const L = scratchL;
for (let k = 0; k < n; k++) {
const o = k * 16;
const d = k * PART_FLOATS;
let moved = false;
for (let row = 0; row < 3; row++) {
// (meshInverse · X) row `row`, as four column entries.
for (let col = 0; col < 4; col++) {
let sum = 0;
for (let j = 0; j < 4; j++)
sum += meshInverse[j * 4 + row] * x[o + col * 4 + j];
ix[col] = sum;
}
for (let col = 0; col < 4; col++) {
let sum = 0;
for (let j = 0; j < 4; j++) sum += ix[j] * mesh[col * 4 + j];
L[row * 4 + col] = sum;
data[d + row * 4 + col] = sum;
if (Math.abs(sum - (row === col ? 1 : 0)) > AT_REST_EPSILON)
moved = true;
}
}
// The inverse transpose of L's 3×3: its cofactors over its determinant.
const a = L[0];
const b = L[1];
const c = L[2];
const e = L[4];
const f = L[5];
const g = L[6];
const h = L[8];
const i = L[9];
const j = L[10];
const c00 = f * j - g * i;
const c01 = -(e * j - g * h);
const c02 = e * i - f * h;
const c10 = -(b * j - c * i);
const c11 = a * j - c * h;
const c12 = -(a * i - b * h);
const c20 = b * g - c * f;
const c21 = -(a * g - c * e);
const c22 = a * f - b * e;
const det = a * c00 + b * c01 + c * c02;
const nd = d + 12;
// At rest, or hidden (collapsed to a point): normals as they are.
const turned = moved && Math.abs(det) > 1e-12;
const r = turned ? 1 / det : 0;
data[nd] = turned ? c00 * r : 1;
data[nd + 1] = turned ? c01 * r : 0;
data[nd + 2] = turned ? c02 * r : 0;
data[nd + 3] = turned ? 1 : 0;
data[nd + 4] = turned ? c10 * r : 0;
data[nd + 5] = turned ? c11 * r : 1;
data[nd + 6] = turned ? c12 * r : 0;
data[nd + 7] = 0;
data[nd + 8] = turned ? c20 * r : 0;
data[nd + 9] = turned ? c21 * r : 0;
data[nd + 10] = turned ? c22 * r : 1;
data[nd + 11] = 0;
const color =
scratchFlags[k] & PART_HIGHLIGHT
? partHighlightColor(poses?.[table.parts[k].name]?.highlight)
: null;
const hd = d + 24;
data[hd] = color ? color.red : 0;
data[hd + 1] = color ? color.green : 0;
data[hd + 2] = color ? color.blue : 0;
data[hd + 3] = color ? 1 : 0;
}
return posed;
}
/**
* A posed model's spins, turned on to `timeS` (seconds): each spinning
* part's angle moves on at its rate since it last did, so a change of rate
* never makes a part jump. A part that stops spinning keeps its angle.
*/
export function advanceSpins(spins, timeS) {
const dt = timeS - spins.at;
spins.at = timeS;
if (!(dt > 0)) return;
for (const [name, rate] of spins.rates)
spins.angles[name] = (spins.angles[name] + rate * dt) % 360;
}
/**
* Spins at `state`'s rates from `timeS` on, carrying the angles reached; a
* part starting to spin starts at an angle of `startAngle`'s (by default a
* random one, so a fleet posed at once does not turn in step).
*/
export function respin(
spins,
table,
state,
timeS,
startAngle = () => Math.random() * 360,
) {
advanceSpins(spins, timeS);
spins.rates.clear();
for (const [name, rate] of Object.entries(state?.spin ?? {})) {
const index = table.byName.get(name);
if (
index === undefined ||
!table.parts[index].axis ||
typeof rate !== 'number' ||
!Number.isFinite(rate) ||
rate === 0
)
continue;
spins.rates.set(name, rate);
if (!(name in spins.angles)) spins.angles[name] = startAngle();
}
}
/** New spins: none yet, at `timeS`. */
export const newSpins = (timeS) => ({
rates: new Map(),
angles: {},
at: timeS,
});
/** A contract distance curve's value at `distance`: linear, clamped. */
export function nearFarValue(curve, distance) {
if (!curve) return 1;
@@ -284,8 +667,11 @@ const focusOf = (item) =>
* The models part of a Cesium draw port.
* @param {{scene: object, toColor: Function, pickId: Function,
* replaceHost: Function, horizonNow: () => object|null,
* requestRender: () => void}} options From the draw port: its colour
* conversion, pick ids, host swap, horizon and render request.
* requestRender: () => void, parts?: boolean,
* now?: () => number}} options From the draw port: its colour
* conversion, pick ids, host swap, horizon and render request; whether it
* poses models' parts (`modelParts`), and the clock (milliseconds) spins
* are turned by.
*/
export function createModelSets({
scene,
@@ -294,7 +680,238 @@ export function createModelSets({
replaceHost,
horizonNow,
requestRender,
parts: posesParts = false,
now = () => performance.now(),
}) {
/** Each Cesium model drawn posed: its part shader, texture and spins. */
const posings = new Map();
/** The GLB bytes each model was built from, where it was. */
const modelBytes = new WeakMap();
/** Part shaders let go, destroyed once no draw uses them. */
const retired = [];
// Float textures carry the part matrices, and WebGL 2's shading language
// turns the normals: without them models draw whole.
const canPose = () =>
scene.context?.floatingPointTexture !== false &&
scene.context?.webgl2 !== false;
/** A model's part table and mesh frame, or null. */
function partInfoOfModel(model) {
const bytes = modelBytes.get(model);
if (bytes) return partInfoOf(bytes);
const json = model.loader?.gltfJson;
return json ? partInfoOf(json) : null;
}
/** Let go of a model's posing: its shader goes once no draw uses it. */
function unpose(model) {
const posing = posings.get(model);
if (!posing) return;
posings.delete(model);
retired.push({ shader: posing.shader, frames: 0 });
}
/** Write a posing's texture where its shader reads it. */
function upload(posing) {
const texture = customShaderTexture(posing.shader, 'u_partMatrices');
if (
texture &&
!texture.isDestroyed?.() &&
texture.width === PART_TEXELS &&
texture.height === posing.rows
)
texture.copyFrom({
source: {
arrayBufferView: posing.data,
width: PART_TEXELS,
height: posing.rows,
},
});
else
posing.shader.setUniform(
'u_partMatrices',
partTexture(posing.data, posing.rows),
);
}
/**
* The state a posing's texture is written for: its item's deploys and
* poses, its spins as the angles they have reached (written at a time of
* 1 s, each angle given as a rate).
*/
function spunState(posing) {
const drawn = posing.drawn;
drawn.deploy = posing.state.deploy;
drawn.poses = posing.state.poses;
drawn.spin = posing.spins.angles;
return drawn;
}
/** Write a posing's texture for now. Whether any part is not at rest. */
function writePosing(posing, timeS) {
advanceSpins(posing.spins, timeS);
return writePartTexture(
posing.info,
spunState(posing),
1,
posing.scale,
posing.data,
);
}
/**
* The shader `model` draws its entry's item's `parts` with, its texture
* written for them now; undefined when the model draws whole (no `parts`,
* no part table, or every part at rest), its posing let go.
*/
function posedShader(entry, model) {
const item = entry.item;
const state = posesParts ? item.parts : undefined;
const posing = posings.get(model);
const info = asksParts(state) && canPose() ? partInfoOfModel(model) : null;
if (!info) {
unpose(model);
return undefined;
}
const axes = item.axisScale;
const scale =
axes && (axes[0] !== 1 || axes[1] !== 1 || axes[2] !== 1)
? axes
: undefined;
const key = JSON.stringify(state);
const scaleKey = scale ? scale.join(',') : '';
const shading = item.shading;
const sameLook =
posing?.info === info &&
posing.shading === shading &&
posing.mask === entry.mask;
// A fleet re-poses every frame with the same parts: written when they
// change (a spin turns in the frame pass).
if (sameLook && posing.key === key && posing.scaleKey === scaleKey)
return posing.shader;
const timeS = now() / 1000;
// Spins go on from where they were, whatever else changed.
const spins = posing?.info === info ? posing.spins : newSpins(timeS);
respin(spins, info.table, state, timeS);
const spinning = spins.rates.size > 0;
const rows = info.table.parts.length;
const next = {
info,
shader: sameLook ? posing.shader : null,
shading,
mask: entry.mask,
data: sameLook ? posing.data : new Float32Array(rows * PART_FLOATS),
rows,
key,
scaleKey,
scale,
spinning,
state,
spins,
drawn: posing?.drawn ?? {},
};
const posed = writePosing(next, timeS);
if (!posed && !spinning) {
unpose(model);
return undefined;
}
if (sameLook) {
Object.assign(posing, next);
upload(posing);
return posing.shader;
}
unpose(model);
next.shader = partShaderOf(shading, entry.mask, next.data, rows);
posings.set(model, next);
return next.shader;
}
/** Pixels across a model's bounds under which its spins are not turned. */
const MIN_SPIN_PIXELS = 4;
const scratchSpinSphere = new Cesium.BoundingSphere();
/**
* Whether a model is worth turning this frame: shown, in the view, and
* at least `MIN_SPIN_PIXELS` across.
*/
function seen(model, culling, width, height) {
if (!model.show || !model.ready) return false;
const sphere = model.boundingSphere;
if (!sphere || !(sphere.radius > 0)) return false;
if (
culling &&
culling.computeVisibility(sphere) === Cesium.Intersect.OUTSIDE
)
return false;
if (!(width > 0 && height > 0)) return true;
Cesium.BoundingSphere.clone(sphere, scratchSpinSphere);
scratchSpinSphere.radius = 0;
const metresPerPixel = scene.camera.getPixelSize(
scratchSpinSphere,
width,
height,
);
return (
!(metresPerPixel > 0) ||
!Number.isFinite(metresPerPixel) ||
(2 * sphere.radius) / metresPerPixel >= MIN_SPIN_PIXELS
);
}
/**
* Before a frame: turn the spinning parts of each model in view to now,
* sweep the posings of models gone, and destroy part shaders no draw
* uses any more. Whether any model in view spins (frames go on being
* asked for; one out of view or too small to see asks for none).
*/
function turnParts() {
for (let i = retired.length - 1; i >= 0; i--)
if ((retired[i].frames += 1) > 2) {
const [{ shader }] = retired.splice(i, 1);
shader.destroy?.();
}
if (!posings.size) return false;
const timeS = now() / 1000;
const camera = scene.camera;
const culling =
camera?.frustum?.computeCullingVolume && camera.positionWC
? camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC,
)
: null;
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
let spinning = false;
for (const [model, posing] of posings) {
if (model.isDestroyed?.()) {
unpose(model);
continue;
}
if (!posing.spinning || !seen(model, culling, width, height)) continue;
spinning = true;
writePosing(posing, timeS);
upload(posing);
}
return spinning;
}
/**
* Let go of every posing and part shader now, their textures with them:
* the port is done, and no frame comes to retire them. A model still
* drawn is left drawing whole.
*/
function dispose() {
for (const [model, posing] of posings) {
if (!model.isDestroyed?.() && model.customShader === posing.shader)
model.customShader = undefined;
posing.shader.destroy?.();
}
posings.clear();
for (const { shader } of retired.splice(0)) shader.destroy?.();
}
/** The set's host, made once: its models are changed where they are. */
function hostOf(record) {
if (record.host && !record.host.isDestroyed?.()) return record.host;
@@ -393,6 +1010,7 @@ export function createModelSets({
settle(false);
return model.destroy();
}
if (item.gltf) modelBytes.set(model, item.gltf);
entry.next = model;
entry.styled = null;
style(record, entry, model, true);
@@ -469,7 +1087,7 @@ export function createModelSets({
if (model.minimumPixelSize !== minimum) model.minimumPixelSize = minimum;
if (model.maximumScale !== item.maxScale)
model.maximumScale = item.maxScale;
const shader = entryShader(entry);
const shader = posedShader(entry, model) ?? entryShader(entry);
if (model.customShader !== shader) model.customShader = shader;
const clip = item.clip === 'belowOrigin';
if (Boolean(model.clippingPlanes) !== clip)
@@ -640,10 +1258,14 @@ export function createModelSets({
notePickIds(record);
}
/** Each frame, before it draws: distance curves, pixel caps and the cull. */
/**
* Each frame, before it draws: distance curves, pixel caps, the cull and
* spinning parts. Whether any shown model spins.
*/
function beforeRender(sets) {
const spinning = turnParts();
const eye = scene.camera?.positionWC;
if (!eye) return;
if (!eye) return spinning;
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
let horizon;
@@ -734,6 +1356,7 @@ export function createModelSets({
if (m) apply(entry, m, frame, hidden);
}
}
return spinning;
}
/**
@@ -758,5 +1381,5 @@ export function createModelSets({
}
}
return { build, upsert, beforeRender, restyle };
return { build, upsert, beforeRender, restyle, dispose };
}
+180
View File
@@ -0,0 +1,180 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
advanceSpins,
newSpins,
partHighlightColor,
respin,
writePartTexture,
} from './drawModels.js';
import { partsModelGlb } from '../conformance/partsModel.js';
import { glbJson, gltfMeshMatrix, gltfPartTable } from '../modelParts.js';
/** Floats a part's row of the texture holds. */
const ROW = 32;
/** The part info `drawModels.js` reads from a model's GLB. */
function infoOf(glb) {
const json = glbJson(glb);
const mesh = gltfMeshMatrix(json);
// The test models' node transforms are rotations, uniform scales and moves.
const s = Math.hypot(mesh[0], mesh[1], mesh[2]);
const r = (i, j) => mesh[j * 4 + i] / s;
const t = [mesh[12], mesh[13], mesh[14]];
const inv = new Array(16).fill(0);
for (let i = 0; i < 3; i++)
for (let j = 0; j < 3; j++) inv[j * 4 + i] = r(j, i) / s;
for (let i = 0; i < 3; i++)
inv[12 + i] = -(inv[i] * t[0] + inv[4 + i] * t[1] + inv[8 + i] * t[2]);
inv[15] = 1;
return { table: gltfPartTable(json), mesh, meshInverse: inv };
}
const row = (data, k, texel) =>
Array.from(data.slice(k * ROW + texel * 4, k * ROW + texel * 4 + 4));
/** A part's matrix in the mesh frame, as rows of 4. */
const matrixOf = (data, k) => [0, 1, 2].map((t) => row(data, k, t));
/** Its normal matrix, as rows of 3, and whether it is moved. */
const normalsOf = (data, k) => ({
rows: [3, 4, 5].map((t) => row(data, k, t).slice(0, 3)),
moved: row(data, k, 3)[3],
});
const near = (a, b, eps = 1e-5) => a.every((v, i) => Math.abs(v - b[i]) < eps);
test('a part moved writes its matrix in the mesh’s own frame, the rest identity', () => {
for (const node of [{}, { scale: 4, turnDeg: 90, translation: [3, 2, -1] }]) {
const info = infoOf(partsModelGlb(node));
const data = new Float32Array(4 * ROW);
const posed = writePartTexture(
info,
{ poses: { body: { offsetM: [15, 0, 0] } } },
0,
undefined,
data,
);
assert.equal(posed, true);
// The body's vertex at model (10, −10, −10) lands 15 m to its right
// (−Z): back in the model frame through the node's transform.
const m = info.mesh;
const inv = info.meshInverse;
const toMesh = (p) =>
[0, 1, 2].map(
(i) =>
inv[i] * p[0] + inv[4 + i] * p[1] + inv[8 + i] * p[2] + inv[12 + i],
);
const toModel = (p) =>
[0, 1, 2].map(
(i) => m[i] * p[0] + m[4 + i] * p[1] + m[8 + i] * p[2] + m[12 + i],
);
const L = matrixOf(data, 0);
const v = [...toMesh([10, -10, -10]), 1];
const moved = toModel(L.map((r) => r.reduce((s, x, i) => s + x * v[i], 0)));
assert.ok(near(moved, [10, -10, -25], 1e-4), JSON.stringify(moved));
// A move turns no normal, but the part is marked moved.
const n = normalsOf(data, 0);
assert.equal(n.moved, 1);
assert.ok(near(n.rows.flat(), [1, 0, 0, 0, 1, 0, 0, 0, 1]));
}
});
test('normals turn by the inverse transpose, exact under a stretch', () => {
const info = infoOf(partsModelGlb());
const data = new Float32Array(4 * ROW);
writePartTexture(
info,
{ poses: { pod: { yawDeg: 30 } } },
0,
[2, 1, 1],
data,
);
const L = matrixOf(data, 1).map((r) => r.slice(0, 3));
const { rows: N, moved } = normalsOf(data, 1);
assert.equal(moved, 1);
// N = L⁻ᵀ: Nᵀ · L is the identity.
for (let i = 0; i < 3; i++)
for (let j = 0; j < 3; j++) {
let sum = 0;
for (let k = 0; k < 3; k++) sum += N[k][i] * L[k][j];
assert.ok(Math.abs(sum - (i === j ? 1 : 0)) < 1e-4, `${i},${j}: ${sum}`);
}
// A stretched turn is not a rotation: its own 3×3 would turn normals wrong.
assert.ok(!near(N.flat(), L.flat(), 1e-3));
// The body, at rest, is left as it is.
assert.equal(normalsOf(data, 0).moved, 0);
});
test('a highlight that is not true or a colour draws none, and never throws', () => {
const info = infoOf(partsModelGlb());
const data = new Float32Array(4 * ROW);
for (const highlight of ['', 'not a colour', 0, [1, 'x', 0], {}]) {
writePartTexture(
info,
{ poses: { pod: { highlight } } },
0,
undefined,
data,
);
assert.deepEqual(row(data, 1, 6), [0, 0, 0, 0], String(highlight));
}
writePartTexture(
info,
{ poses: { pod: { highlight: true } } },
0,
undefined,
data,
);
assert.equal(row(data, 1, 6)[3], 1);
writePartTexture(
info,
{ poses: { pod: { highlight: [0, 1, 0] } } },
0,
undefined,
data,
);
assert.deepEqual(row(data, 1, 6), [0, 1, 0, 1]);
assert.equal(partHighlightColor('#00f').blue, 1);
assert.equal(partHighlightColor('nope'), null);
assert.equal(partHighlightColor(false), null);
});
test('a hidden part collapses, its normals left alone', () => {
const info = infoOf(partsModelGlb());
const data = new Float32Array(4 * ROW);
writePartTexture(
info,
{ poses: { pod: { hidden: true } } },
0,
undefined,
data,
);
assert.ok(
matrixOf(data, 1)
.flat()
.every((v) => v === 0),
);
assert.equal(normalsOf(data, 1).moved, 0);
assert.ok(data.every(Number.isFinite));
});
test('spins keep their angle when their rate changes, and stop where they are', () => {
const { table } = infoOf(partsModelGlb());
const spins = newSpins(0);
respin(spins, table, { spin: { pod: 90 } }, 0, () => 10);
assert.equal(spins.angles.pod, 10);
advanceSpins(spins, 1);
assert.equal(spins.angles.pod, 100);
// Twice as fast from here: no jump at the change.
respin(spins, table, { spin: { pod: 180 } }, 1.5);
assert.equal(spins.angles.pod, 145);
advanceSpins(spins, 2);
assert.equal(spins.angles.pod, 235);
// Stopped: the angle stays; a name without an axis or a rate of 0 spins nothing.
respin(spins, table, { spin: { body: 50, missing: 5, pod: 0 } }, 3);
assert.equal(spins.angles.pod, (235 + 180) % 360);
assert.equal(spins.rates.size, 0);
advanceSpins(spins, 10);
assert.equal(spins.angles.pod, (235 + 180) % 360);
});
+3
View File
@@ -85,7 +85,9 @@ export const CESIUM_CHECKS = new Set([
'draw.models.nodes',
'draw.models.tint',
'draw.models.blend',
'draw.models.paint',
'draw.models.update',
'draw.models.parts',
'draw.motion',
'draw.motion.arc',
'draw.motion.climb',
@@ -116,6 +118,7 @@ export const CESIUM_CHECKS = new Set([
'frame.time',
'globe.base.vector',
'globe.imagery',
'globe.imagery.decoded',
'globe.imagery.frames',
'globe.imagery.video',
'globe.sky',
+7 -2
View File
@@ -94,7 +94,7 @@ out vec4 v_pickColor;
out float v_proxy;
// The row's anchor in clip space before screen offsets, for effects that wrap
// main() (cyber sonar) and must not change geometry or picks.
// main() (sonar) and must not change geometry or picks.
vec4 iconAnchorClip = vec4(0.0, 0.0, 0.0, -1.0);
${ICON_SEGMENT_GLSL}
@@ -261,7 +261,12 @@ void main() {
if (overDepth && zclip >= -1.0 && zclip <= 1.0) {
gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH
v_depthFromNearPlusOne = 1.0;
// Just past the near plane, not on it: czm_writeLogDepth discards a
// fragment at or below 0.9999999, and 1.0 interpolated across the quad
// can arrive a rounding step or two under that, dropping the icon for a
// frame as it moves (flicker). 1e-4 m past the near plane is still in
// front of everything the scene draws.
v_depthFromNearPlusOne = 1.0001;
#endif
}
+55 -17
View File
@@ -18,13 +18,21 @@
* `prefetch` frames loading unseen at alpha 0. A frame is ready
* (`frameReady`) once the globe's tiles drawn are drawn from its own
* imagery (`imageryFrames.js`).
*
* With `imageryDecoded`, a `decoded` source is drawn the same way, a layer
* a slot: the slot its clock shows, and the next `prefetch` of the slots the
* source holds ahead, each tile the image the source answers for it.
*/
import * as Cesium from 'cesium';
import { vectorBaseProvider } from './vectorBase.js';
import { creditMarkup } from './credits.js';
import { listenerList } from './common.js';
import {
MissingTile,
createTileVideos,
decodedHeld,
decodedProvider,
decodedShownAt,
framesOf,
heldFrames,
layerDrawn,
@@ -41,14 +49,6 @@ export const TILE_RETRY_DELAY_MS = 250;
/** Ion's world imagery assets, by contract style. */
const WORLD_ASSETS = { aerial: 2, aerialLabels: 3 };
/** A tile the source says is not there: Cesium draws the parent's. */
class MissingTile extends Error {
constructor() {
super('No tile here');
this.name = 'MissingTile';
}
}
const rectangleOf = (rect) =>
rect &&
Cesium.Rectangle.fromDegrees(rect.west, rect.south, rect.east, rect.north);
@@ -676,11 +676,21 @@ export function createCesiumImagery(
};
if (capabilities.has('imageryFrames')) {
handle.setFrames = (source, options = {}) => {
const decoded = source?.kind === 'decoded';
if (decoded && !capabilities.has('imageryDecoded'))
throw new TypeError('decoded imagery needs imageryDecoded');
if (
decoded &&
(typeof source.slotAt !== 'function' ||
typeof source.tile !== 'function')
)
throw new TypeError('a decoded source needs slotAt and tile');
const frames = framesOf(source);
if (record.removed) return;
dropFrames(record);
record.timed = {
video: source.kind === 'video',
decoded: decoded ? source : null,
frames,
mode: options.mode === 'blend' ? 'blend' : 'nearest',
prefetch: Math.max(0, Math.floor(options.prefetch ?? 1)),
@@ -723,12 +733,24 @@ export function createCesiumImagery(
function frameLayer(record, frame) {
const timed = record.timed;
const spec = { ...record.spec, url: frame.url };
const entry = { layer: null, host: null, offError: null };
const entry = {
layer: null,
host: null,
offError: null,
signals: new Set(),
};
let made;
try {
made = timed.video
? videoProvider(record.spec, frame, timed.videos)
: providerFor(spec, { worldDataToken: worldDataToken() });
made = timed.decoded
? decodedProvider(record.spec, frame.slot, timed.decoded, {
laterFrame,
signals: entry.signals,
urgency: () =>
timed.at?.nearest === frame.slot ? 'shown' : 'prefetch',
})
: timed.video
? videoProvider(record.spec, frame, timed.videos)
: providerFor(spec, { worldDataToken: worldDataToken() });
} catch (error) {
report(error);
made = Promise.reject(error);
@@ -746,7 +768,9 @@ export function createCesiumImagery(
} else {
entry.offError = record.watchErrors(made);
entry.layer = new Cesium.ImageryLayer(
timed.video ? made : hookProvider(made, spec, record.ctx),
timed.video || timed.decoded
? made
: hookProvider(made, spec, record.ctx),
layerOptions(spec),
);
}
@@ -756,6 +780,9 @@ export function createCesiumImagery(
function dropFrameLayer(entry) {
entry.removed = true;
// A decoded slot's tiles still asked for are not wanted any more.
for (const controller of entry.signals) controller.abort();
entry.signals.clear();
entry.offError?.();
if (usable(entry.host) && entry.host.contains(entry.layer))
entry.host.remove(entry.layer, true);
@@ -785,9 +812,15 @@ export function createCesiumImagery(
const timed = record.timed;
if (!timed || record.removed) continue;
const ms = timed.clock === 'own' ? (timed.own ?? NaN) : sceneMs;
const at = shownAt(timed.frames, ms, timed.mode);
const at = timed.decoded
? decodedShownAt(timed.decoded, ms)
: shownAt(timed.frames, ms, timed.mode);
timed.at = at;
const held = at ? heldFrames(timed.frames, at, timed.prefetch) : [];
const held = !at
? []
: timed.decoded
? decodedHeld(timed.decoded, at, timed.prefetch, ms)
: heldFrames(timed.frames, at, timed.prefetch);
for (const [index, entry] of timed.layers)
if (!held.includes(index) || entry.layer.isDestroyed()) {
dropFrameLayer(entry);
@@ -802,7 +835,10 @@ export function createCesiumImagery(
for (const index of held.sort((a, b) => a - b)) {
let entry = timed.layers.get(index);
if (!entry) {
entry = frameLayer(record, timed.frames[index]);
entry = frameLayer(
record,
timed.decoded ? { slot: index, url: '' } : timed.frames[index],
);
timed.layers.set(index, entry);
}
const layer = entry.layer;
@@ -846,7 +882,9 @@ export function createCesiumImagery(
const timed = record.timed;
// A layer removed by another's listener says nothing.
if (record.removed || !timed?.at || !record.show) continue;
const time = timed.frames[timed.at.nearest].time;
const time = timed.decoded
? timed.at.nearest
: timed.frames[timed.at.nearest].time;
if (time === timed.announced) continue;
if (!timed.at.shown.every((s) => frameDrawn(timed.layers.get(s.index))))
continue;
+84
View File
@@ -11,10 +11,22 @@
* steps a segment): a time is shown by the step nearest it, its offset into
* the segment's videos in proportion; outside every segment, the nearest
* segment end is the nearest frame.
*
* A `decoded` source (`imageryDecoded`) has no list: the slot a time shows
* is the source's `slotAt`, the slots held ahead its `prefetch`, and each
* slot's tiles are the images its `tile` answers.
*/
import * as Cesium from 'cesium';
import { globeTilesDrawn } from './internals.js';
/** A tile the source says is not there: Cesium draws the parent's. */
export class MissingTile extends Error {
constructor() {
super('No tile here');
this.name = 'MissingTile';
}
}
/** How far apart the times a video segment is seen at are, ms. */
export const VIDEO_STEP_MS = 250;
/** The most times one video segment is seen at. */
@@ -61,6 +73,7 @@ export function framesOf(source) {
}
return frames.sort((a, b) => a.time - b.time);
}
if (source?.kind === 'decoded') return [];
if (source?.kind === 'frames')
return (source.frames ?? [])
.filter((f) => Number.isFinite(f?.time) && typeof f?.url === 'string')
@@ -408,3 +421,74 @@ export function layerDrawn(scene, layer) {
}
return true;
}
/**
* What `ms` shows of a `decoded` source: its slot, as `shownAt` answers for
* a list (the slot standing for the index), or null with none.
* @returns {{nearest: number, shown: Array<{index: number, weight: number}>}|null}
*/
export function decodedShownAt(source, ms) {
if (!Number.isFinite(ms)) return null;
const slot = source.slotAt(ms);
if (!Number.isFinite(slot)) return null;
return { nearest: slot, shown: [{ index: slot, weight: 1 }] };
}
/**
* The slots of a `decoded` source to hold for `ms`: the one shown, and the
* first `prefetch` of those the source holds ahead (finite, not shown, each
* once).
* @returns {number[]}
*/
export function decodedHeld(source, at, prefetch, ms) {
const held = [at.nearest];
if (prefetch <= 0 || typeof source.prefetch !== 'function') return held;
for (const slot of source.prefetch(ms) ?? []) {
if (held.length > prefetch) break;
if (Number.isFinite(slot) && !held.includes(slot)) held.push(slot);
}
return held;
}
/**
* A provider drawing one slot of a `decoded` source: each tile the image
* the source answers for it, in the spec's tiling (an `xyz` spec), or one
* image over the layer's rectangle (any other). A deferred tile is asked
* again on a later frame (`laterFrame`); a missing one draws the parent's.
* @param {import('../contract/globe').ImagerySpec} spec
* @param {number} slot
* @param {Extract<import('../contract/globe').TimedSource, {kind: 'decoded'}>} source
* @param {{laterFrame: () => Promise<void>, signals: Set<AbortController>,
* urgency: () => 'shown'|'prefetch'}} ctx
*/
export function decodedProvider(spec, slot, source, ctx) {
// The same tiling and bounds a video frame's provider draws in.
const provider = videoProvider(spec, { url: '', fraction: 0 }, null);
provider.requestImage = async (x, y, level) => {
const controller = new AbortController();
ctx.signals.add(controller);
try {
for (;;) {
const answer = await source.tile({
tile: { x, y, level },
slot,
signal: controller.signal,
urgency: ctx.urgency(),
});
// An image no longer wanted is let go at once.
if (controller.signal.aborted) answer?.image?.close?.();
controller.signal.throwIfAborted();
if (answer?.defer) {
await ctx.laterFrame();
controller.signal.throwIfAborted();
continue;
}
if (!answer?.image) throw new MissingTile();
return answer.image;
}
} finally {
ctx.signals.delete(controller);
}
};
return provider;
}
+99
View File
@@ -2,7 +2,11 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test, { mock } from 'node:test';
import {
MissingTile,
createTileVideos,
decodedHeld,
decodedProvider,
decodedShownAt,
framesOf,
heldFrames,
layerDrawn,
@@ -336,3 +340,98 @@ test('a video’s length is learnt with a longer wait, and a failed one is not l
restore();
}
});
/** A decoded source over slots 0, 100, 200, with what its tiles answer. */
function decodedSource(answers = () => ({ missing: true })) {
const asked = [];
return {
asked,
kind: 'decoded',
slotAt: (ms) => (ms < 0 ? null : Math.min(200, Math.round(ms / 100) * 100)),
prefetch: (ms) => [Math.round(ms / 100) * 100, 300, NaN, 300, 400, 500],
tile: async (request) => {
asked.push(request);
return answers(request);
},
};
}
test('a decoded source shows the slot its clock names and holds the next it prefetches', () => {
const source = decodedSource();
assert.equal(framesOf(source).length, 0, 'no list to step through');
const at = decodedShownAt(source, 140);
assert.deepEqual(at, { nearest: 100, shown: [{ index: 100, weight: 1 }] });
assert.equal(decodedShownAt(source, -5), null, 'no slot: nothing shown');
assert.equal(decodedShownAt(source, NaN), null);
assert.deepEqual(decodedHeld(source, at, 2, 140), [100, 300, 400]);
assert.deepEqual(decodedHeld(source, at, 0, 140), [100]);
assert.deepEqual(
decodedHeld({ slotAt: () => 0 }, at, 3, 140),
[100],
'a source with no prefetch holds the shown slot only',
);
});
test("a decoded slot's tiles are the source's images, asked again when deferred", async () => {
const image = { width: 256, height: 256 };
let defers = 1;
const source = decodedSource(({ tile }) => {
if (tile.level === 9) return { missing: true };
if (defers-- > 0) return { defer: true };
return { image };
});
let frames = 0;
let shown = true;
const signals = new Set();
const provider = decodedProvider(
{ kind: 'xyz', url: '', maxLevel: 10, tiling: 'webmercator' },
100,
source,
{
laterFrame: async () => {
frames += 1;
},
signals,
urgency: () => (shown ? 'shown' : 'prefetch'),
},
);
assert.ok(provider.tilingScheme instanceof Cesium.WebMercatorTilingScheme);
assert.equal(provider.maximumLevel, 10);
assert.equal(provider.hasAlphaChannel, true);
assert.equal(await provider.requestImage(1, 2, 3), image);
assert.equal(frames, 1, 'the deferred tile waited a frame');
assert.deepEqual(
source.asked.map((r) => [r.tile, r.slot, r.urgency]),
[
[{ x: 1, y: 2, level: 3 }, 100, 'shown'],
[{ x: 1, y: 2, level: 3 }, 100, 'shown'],
],
);
shown = false;
await assert.rejects(provider.requestImage(0, 0, 9), MissingTile);
assert.equal(source.asked.at(-1).urgency, 'prefetch');
assert.equal(signals.size, 0, 'no tile left waiting');
});
test('a decoded tile answered after its slot was let go is closed, not drawn', async () => {
let release;
const closed = [];
const image = { close: () => closed.push('image') };
const source = decodedSource(
() => new Promise((resolve) => (release = () => resolve({ image }))),
);
const signals = new Set();
const provider = decodedProvider({ kind: 'single-image' }, 0, source, {
laterFrame: async () => {},
signals,
urgency: () => 'shown',
});
assert.equal(provider.maximumLevel, 0, 'one image over the rectangle');
const pending = provider.requestImage(0, 0, 0);
await Promise.resolve();
assert.ok(source.asked[0].signal instanceof AbortSignal);
for (const controller of signals) controller.abort();
release();
await assert.rejects(pending);
assert.deepEqual(closed, ['image']);
});
+14
View File
@@ -300,3 +300,17 @@ export function creditDisplayContents(display) {
export function materialTexture(material, uniform) {
return material?._textures?.[uniform];
}
/**
* The texture a custom shader holds for a texture uniform, once it has made
* it. A custom shader takes a new texture uniform only as a texture it makes
* (and the old one it destroys) on its next update; `drawModels.js` writes a
* posed model's part matrices into this texture in place instead, each frame
* a part spins.
* @param {object} shader Cesium CustomShader.
* @param {string} uniform The uniform's name.
* @returns {object|undefined} Cesium Texture.
*/
export function customShaderTexture(shader, uniform) {
return shader?._textureManager?.getTexture?.(uniform);
}
+14
View File
@@ -12,6 +12,7 @@ import {
closeRenderLoopLatch,
commandExtents,
creditDisplayContents,
customShaderTexture,
defaultView,
globeTilesDrawn,
lastRenderTime,
@@ -70,6 +71,7 @@ test('every private field the app reaches is still declared by the installed Ces
[ENGINE, 'Scene/CreditDisplay.js', '_currentFrameCredits'],
[ENGINE, 'Scene/CreditDisplay.js', '_currentCesiumCredit'],
[ENGINE, 'Scene/Material.js', '_textures'],
[ENGINE, 'Scene/Model/CustomShader.js', '_textureManager'],
];
const missing = fields.filter(
([root, file, field]) =>
@@ -281,6 +283,18 @@ test('private Cesium fields are reached only through internals.js', () => {
assert.deepEqual([...new Set(offenders)], []);
});
test('customShaderTexture reads the texture a custom shader made for a uniform', () => {
const texture = {};
const shader = {
_textureManager: {
getTexture: (name) => (name === 'u_a' ? texture : undefined),
},
};
assert.equal(customShaderTexture(shader, 'u_a'), texture);
assert.equal(customShaderTexture(shader, 'u_b'), undefined);
assert.equal(customShaderTexture(undefined, 'u_a'), undefined);
});
test('trimGlobeTiles empties the globe cache of what the frame did not draw', () => {
const trims = [];
trimGlobeTiles({
+4
View File
@@ -49,6 +49,8 @@ const GLOBE_CAPABILITIES = [
'imageHooks',
// Timed imagery: a layer a frame, prefetched unseen (`imagery.js`).
'imageryFrames',
// Timed imagery handed over as finished images (`imageryFrames.js`).
'imageryDecoded',
'surfaceIdentity',
'surfaceShading',
// A MapLibre style's vector tiles, painted as imagery (`vectorBase.js`).
@@ -70,6 +72,8 @@ const GLOBE_CAPABILITIES = [
export function cesiumCapabilities(scene, only) {
const all = [
'models',
// Moving parts posed in a custom shader per posed model (`drawModels.js`).
'modelParts',
// Cesium scatters drawn models through the atmosphere wherever the
// scene draws fog (its models' atmosphere stage).
'modelAtmosphere',
+2
View File
@@ -28,6 +28,7 @@ test('capabilities follow what the scene supports', () => {
'splitSwipe',
'imageHooks',
'imageryFrames',
'imageryDecoded',
'surfaceIdentity',
'surfaceShading',
'vectorBase',
@@ -35,6 +36,7 @@ test('capabilities follow what the scene supports', () => {
const globe = { show: true };
const draw = [
'models',
'modelParts',
'modelAtmosphere',
'modelNodes',
'quads',