Define the renderer contract, with a stub renderer and a conformance suite

The renderer contract is what the application asks of a 3D renderer. It is nine ports
(frame, globe, draw, camera, query, input, effects, credits, quality) plus
the renderer itself, one strict .d.ts per port in src/render/contract/.
PORTS lists every member at run time, and a TypeScript-compiler test fails
when the list and the types disagree on one member. An optional member
exists only with its capability; a required one answers null or empty
without it. Nothing in the application uses the contract yet.

The stub renderer (src/render/stub/) implements every port in memory and
draws nothing. Its camera is a port of the default camera's maths: views,
lookAt, flights with their height arc and easing, rectangle framing on the
geodesic midpoint, the view rectangle with its horizon and pole cases,
changed thresholds, follows, and flights that finish inside the call.

The conformance suite (src/render/conformance/) runs 59 checks against
a renderer through the contract alone, in Node or in a browser page. The
camera checks compare traces recorded from Cesium's own Camera, headless on
a virtual clock (scripts/record-camera-goldens.mjs), to 1 mm, 1e-9 and
1e-3 px. The other checks cover listener rules on every subscription, the
frame loop, draw sets, picks, motion clocks, heights, leases, imagery,
styles, credits and quality knobs. The stub passes all of them but the
model check, which needs a glTF asset.

Reference scenes draw one scene per primitive family, a city and a
calibration path from orbit to the street, from contract calls only and
with no network. /dev/conformance/ draws them on the Cesium scene renderer
(src/render/cesium/sceneRenderer.js), records references through a
dev-server-only, loopback-only endpoint, and compares captures with
pixelmatch's antialias detection plus a solid-pixel count. Measured on
Cesium: every MSAA setting passes, and a dropped 4 px point, a dropped 2 px
line and a 1 px shift of the view fail. visual.js states the limits.

The package exports ./render/contract, ./render/stub and
./render/conformance. Documented in docs/RENDERER-CONTRACT.md,
docs/CODE-BOUNDARIES.md and docs/CURRENT-STATE.md.
This commit is contained in:
Sameh Khamis committed 2026-11-04 14:21:48 -08:00
1 parent 464c29a9ed
commit 8db995acfc
65 files changed
+12759 -9

No files matched your search

+245
View File
@@ -0,0 +1,245 @@
/**
* The camera. It belongs to the renderer: the application asks for poses,
* flights and follows, and the renderer reproduces the behaviour below
* exactly.
*
* Behaviour the renderer keeps (the application depends on each one):
* - Camera input is suspended during a flight, by a hold: a flight ending
* gives back only its own hold, never another owner's.
* - `lookAt` orbits the target (the user can still rotate and zoom about it);
* `release` returns to the world frame.
* - `changed` fires when the view has moved by more than the listener's own
* `threshold` (default 0.5) since it last fired, measured per listener:
* heading and roll each by their change over π since they last fired; the
* view by the larger of the direction's turn over half the vertical field
* of view and the eye's travel over its height, since the view last
* fired. A frame can fire it twice, once for each measure.
* - `moveEnd` fires 500 ms after the last change, and never while following.
* - A flight's `onCancel` and `onComplete` run synchronously, inside the call
* or frame that ends it.
* - Axes follow the usual convention: heading clockwise from north, pitch
* negative looking down, roll about the view direction; local frames are
* east-north-up.
*/
import type {
Ecef,
GeoRect,
HeadingPitchRange,
HeadingPitchRoll,
Off,
Position,
Release,
Sphere,
Vec3,
} from './common';
export interface CameraPose {
lon: number;
lat: number;
/** Metres above the ellipsoid. */
height: number;
heading: number;
pitch: number;
roll: number;
position: Ecef;
direction: Vec3;
up: Vec3;
right: Vec3;
/** Vertical field of view, radians. */
fovy: number;
aspectRatio: number;
near: number;
far: number;
/** False while `lookAt` has the camera in a target's frame. */
frameIsIdentity: boolean;
}
export type Orientation =
Partial<HeadingPitchRoll> | { direction: Vec3; up: Vec3 };
/**
* A position, or a rectangle. For a rectangle the eye stands on the surface
* normal at the geodesic midpoint of its central meridian (latitude 0 when it
* spans nearly pole to pole), at the least distance that keeps on screen its
* corners, its edge centres and, when it crosses the equator, its equator
* points. The orientation is then resolved as for any position.
*/
export type Destination = Position | { rect: GeoRect };
/**
* Omitted orientation angles are heading 0, pitch −π/2 (straight down) and
* roll 0, not the current ones; an omitted destination keeps the position.
*/
export interface ViewSpec {
destination?: Destination;
orientation?: Orientation;
}
export type Easing =
'linear' | 'quadraticInOut' | 'cubicInOut' | 'cubicOut' | 'quinticInOut';
/**
* A flight's omitted orientation is the same as `setView`'s. Its omitted
* duration is `min(3, ceil(distance / 1000 km) + 2)` seconds, the distance
* measured from the eye's position in its current frame (the `lookAt` frame
* when one is active). A flight with a duration of 0 or less, or one whose
* eye (its position in its current frame, as above) already stands at the
* destination with the destination's angles (to 1e-10, relative),
* completes inside the call: it places the eye, runs `onComplete`, raises
* `flightEnd` and resolves `done`, and no frame is needed. Starting a
* flight cancels the one in progress.
*
* The path, at eased time `s` (0..1): longitude and latitude linear in `s`
* the short way round; heading, pitch and roll linear in `s` the short way
* round; height on an arc to `maxHeight` when both ends are below it,
* otherwise linear. The reference traces (`conformance/goldens/camera.json`)
* pin the arc and the omitted `maxHeight`.
*/
export interface FlightOptions {
orientation?: Orientation;
durationS?: number;
/**
* Omitted: `cubicOut` when descending from above 11.5 km, otherwise
* `quinticInOut`.
*/
easing?: Easing;
/** Top of the height arc, metres. Omitted: a fifth of what fits both ends on screen. */
maxHeight?: number;
/** When the arc tops this height, pitch turns straight down mid-flight. */
pitchAdjustHeight?: number;
/** End in the world frame even when a target frame is active. */
endFrame?: 'world';
onComplete?: () => void;
onCancel?: () => void;
}
export interface Flight {
done: Promise<'complete' | 'cancelled'>;
cancel(): void;
}
/** Something the camera follows; the application owns it and the renderer reads it each frame. */
export interface FollowTarget {
/** Stable key, e.g. `'flights:a1b2c3'`. */
key: string;
/** Where the target is at scene time `t` (epoch ms), or null when unknown. */
position(t: number): Ecef | null;
/** Where it is drawn, when that differs from `position` (a lifted icon). */
visualPosition?(t: number): Ecef | null;
/**
* The drawn item this target is, when it is one. Where the renderer moves
* items itself (`motionSegments`) follows where it draws the item, so the
* eye and the icon never part; `position` stays the answer elsewhere.
*/
item?: { set: string; id: string };
/**
* `enu`: offset in the target's east-north-up frame;
* `autodetect`: an orbit frame from its motion, north-up when still
* (`followAutodetect`).
*/
frame: 'enu' | 'autodetect';
/** Offset of the eye from the target, metres in `frame`. */
viewFrom: Vec3 | ((t: number) => Vec3);
minRange?: number;
boundingRadius?: number;
}
/**
* A camera command, as an ownership hook sees it before it runs. An owner
* that issues commands itself (a ground guard) recognises its own by
* issuing them inside its own call; any other command is someone else's.
*/
export interface CameraCommand {
kind:
| 'setView'
| 'flyTo'
| 'flyToBounds'
| 'lookAt'
| 'release'
| 'follow'
| 'cancelFlight';
}
export interface CameraControls {
/** False while any hold is out. */
readonly enabled: boolean;
/** Suspend user camera input until released. Holds are counted. */
suspend(reason: string): Release;
enableTilt: boolean;
enableRotate: boolean;
enableZoom: boolean;
minDistance: number;
maxDistance: number;
inertiaSpin: number;
inertiaTranslate: number;
inertiaZoom: number;
/** What the eye cannot pass below. */
collision: 'none' | 'terrain' | 'tiles' | 'both';
zoomFactor: number;
/** Pitch the user may tilt between, radians (−π/2 straight down). */
pitchRange: [min: number, max: number];
/** Input bindings that zoom. */
zoomInputs: Array<'wheel' | 'pinch' | 'rightDrag' | 'ctrlWheel'>;
}
export type CameraEvent =
'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd';
export interface CameraPort {
pose(): CameraPose;
setView(view: ViewSpec): void;
setFov(fov: { vertical: number }): void;
/**
* The geodetic rectangle in view: the bounds of the canvas corners on the
* ellipsoid, a corner that misses it taken where the horizon is, and the
* full longitude span to the pole when the view goes over one. The whole
* globe when fewer than two corners land; null only when the globe is
* wholly outside the view.
*/
viewRectangle(): GeoRect | null;
flyTo(destination: Destination, options?: FlightOptions): Flight;
/**
* Fly to look at a sphere from `offset` in its east-north-up frame
* (default heading 0, pitch −π/4; a range of 0 fits the sphere in view).
*/
flyToBounds(
sphere: Sphere,
options?: { offset?: HeadingPitchRange; durationS?: number } & Pick<
FlightOptions,
'onComplete' | 'onCancel'
>,
): Flight;
cancelFlight(): void;
readonly flying: boolean;
/** Orbit `target` at `offset`; user input orbits it too. */
lookAt(target: Ecef, offset: HeadingPitchRange): void;
/** Leave `lookAt` for the world frame. */
release(): void;
move(
direction: 'forward' | 'back' | 'left' | 'right' | 'up' | 'down',
metres: number,
): void;
look(direction: 'left' | 'right' | 'up' | 'down', radians: number): void;
rotateAround(axis: Vec3, radians: number): void;
zoom(metres: number): void;
follow(target: FollowTarget | null): void;
readonly followed: FollowTarget | null;
/** Whether the follow has placed its first frame. */
readonly followFramed: boolean;
/** The eye's offset from the followed target, in its frame. */
readonly followOffset: {
get(): Vec3 | null;
set(offset: Vec3): void;
};
readonly controls: CameraControls;
on(event: CameraEvent, cb: () => void, options?: { threshold?: number }): Off;
/** Runs before each camera command, so an owner can yield to another. */
onCommand(cb: (command: CameraCommand) => void): Off;
/**
* Column-major, right-handed: `view` takes ECEF to eye space (absolute,
* not eye-relative); `projection` takes eye space to clip space with depth
* in [-1, 1]. A renderer with an infinite far plane returns the
* infinite-far form, and `pose().far` is `Infinity`.
*/
matrices(): { view: Float64Array; projection: Float64Array };
}
+200
View File
@@ -0,0 +1,200 @@
/**
* Shared value types of the renderer contract.
*
* Only plain numbers, strings and typed arrays cross the contract: no engine
* object ever does. Positions are f64 Earth-centred, Earth-fixed metres
* (`Ecef`) or geodetic degrees and metres (`LonLatH`). Angles are radians
* unless a name says degrees. Times are epoch milliseconds. Screen positions
* are CSS pixels from the top left of the renderer's canvas.
*/
/** Earth-centred, Earth-fixed position in metres (WGS84). */
export interface Ecef {
x: number;
y: number;
z: number;
}
/** A direction or offset in metres; the frame is stated where it is used. */
export interface Vec3 {
x: number;
y: number;
z: number;
}
/** Geodetic position: degrees, and metres above the WGS84 ellipsoid. */
export interface LonLatH {
lon: number;
lat: number;
height?: number;
}
/** Geodetic position without a height. */
export interface LonLat {
lon: number;
lat: number;
}
/** Either position form. A value with `lon` and `lat` is geodetic. */
export type Position = Ecef | LonLatH;
/** CSS pixels from the canvas's top left. */
export interface ScreenXY {
x: number;
y: number;
}
/** A screen rectangle in CSS pixels. */
export interface ScreenRect {
x: number;
y: number;
width: number;
height: number;
}
/** A geodetic rectangle in degrees. */
export interface GeoRect {
west: number;
south: number;
east: number;
north: number;
}
/** A ray in ECEF metres; `direction` is a unit vector. */
export interface Ray {
origin: Ecef;
direction: Vec3;
}
/** A bounding sphere. */
export interface Sphere {
center: Ecef;
radius: number;
}
export interface HeadingPitchRoll {
heading: number;
pitch: number;
roll: number;
}
export interface HeadingPitchRange {
heading: number;
pitch: number;
range: number;
}
/** A quaternion `(x, y, z, w)`, unit length. */
export interface Quaternion {
x: number;
y: number;
z: number;
w: number;
}
/** A CSS colour string, or linear `[r, g, b, a]` in 0..1 (`a` defaults to 1). */
export type Color = string | readonly [number, number, number, number?];
/**
* A distance curve: `nearValue` at `near` metres from the eye, `farValue`
* at `far`, linear in between and clamped outside.
*/
export interface NearFar {
near: number;
nearValue: number;
far: number;
farValue: number;
}
/**
* Unsubscribes. Calling it twice is harmless.
*
* Every `on(...)` in the contract keeps these rules: listeners run in the
* order they subscribed; one removed while an event is being delivered does
* not run for it if it has not yet; one added during delivery first runs for
* the next event; a listener that throws is reported (`Renderer` `error`,
* or the platform's `reportError` when nothing listens for errors) and the
* others, and the frame, still run.
*/
export type Off = () => void;
/** Gives back a hold. Calling it twice is harmless. */
export type Release = () => void;
/** A handle on something the renderer draws. */
export interface Handle {
show: boolean;
dispose(): void;
}
/** Opaque data the application attaches to a drawn item and gets back on a pick. */
export type Meta = unknown;
/**
* Optional features. A renderer lists the ones it has in
* `Renderer.capabilities`. A member's documentation names the capability
* it depends on, in backticks, first:
* - on an optional member (`?`), the member exists only with the capability;
* - on a required member, the member always exists, and without the
* capability it answers null, an empty list or a status saying so (a
* query asked for depth on a renderer without `pickPosition` returns null).
* Options guarded by a capability are ignored without it. Quality settings
* are not capabilities: `QualityPort.knobs()` lists the ones a renderer has.
*/
export type Capability =
/** Google photorealistic 3D tiles as the base. */
| 'photoreal'
/** A vector basemap (`BaseSpec.vector`), with its own labels. */
| 'vectorBase'
/** Heights from the finest data available, not only what is drawn. */
| 'finestHeights'
/** Height terrain under the globe. */
| 'terrain'
/** Atmosphere scattering applied to drawn models. */
| 'modelAtmosphere'
/** Imagery draped onto 3D tiles as well as the globe. */
| 'imageryOnTiles'
/** A screen-split comparison between imagery layers. */
| 'splitSwipe'
/** Timed imagery frames with hidden prefetch. */
| 'imageryFrames'
/** Wind-relief and similar shading of the globe surface. */
| 'surfaceShading'
/** A screen-space sector modulation pass (a sweeping sonar band). */
| 'screenModulation'
/** GPU frame timing through timer queries. */
| 'gpuTiming'
/** Depth picks against tiles and terrain. */
| 'pickPosition'
/** Height sampling against tiles and terrain. */
| 'sampleHeight'
/** Ray casts against tiles and terrain. */
| 'rayCast'
/** Columnar draw-set updates with dirty ranges. */
| 'columns'
/** Icon motion segments evaluated on the renderer's clock. */
| 'motionSegments'
/** glTF models. */
| 'models'
/** Image, video and canvas planes. */
| 'quads'
/** Custom meshes in a local east-north-up frame. */
| 'meshes'
/** Wind streamlines, scalar rasters and raised raster shells. */
| 'fields'
/** Stars and orbit rings in an inertial frame. */
| 'celestial'
/** Agents moving along polylines (traffic flow). */
| 'agents'
/** Screen-space clustering of icons. */
| 'cluster'
/** Post-processing styles. */
| 'styles'
/** A bloom pass. */
| 'bloom'
/** A sharpen pass. */
| 'sharpen'
/** Following with an automatically chosen frame (orbit or north-up). */
| 'followAutodetect'
/** A built-in quality benchmark. */
| 'benchmark';
+168
View File
@@ -0,0 +1,168 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
import {
CAPABILITIES,
CONTRACT_VERSION,
FRAME_STEPS,
PORTS,
QUALITY_KEYS,
checkPortShape,
checkRendererShape,
} from './index.js';
const DIR = path.dirname(fileURLToPath(import.meta.url));
const INDEX = path.join(DIR, 'index.d.ts');
const program = ts.createProgram([INDEX], {
strict: true,
noEmit: true,
target: ts.ScriptTarget.ES2022,
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
skipLibCheck: false,
types: [],
});
const checker = program.getTypeChecker();
const contractFiles = program
.getSourceFiles()
.filter((file) => path.dirname(file.fileName) === DIR);
/** The named interface or type alias declared in the contract files. */
function declared(name) {
for (const file of contractFiles)
for (const statement of file.statements)
if (
(ts.isInterfaceDeclaration(statement) ||
ts.isTypeAliasDeclaration(statement)) &&
statement.name.text === name
)
return statement;
throw new Error(`${name} is not declared in the contract`);
}
const PORT_INTERFACES = {
renderer: 'Renderer',
frame: 'FramePort',
globe: 'GlobePort',
draw: 'DrawPort',
camera: 'CameraPort',
query: 'QueryPort',
input: 'InputPort',
effects: 'EffectsPort',
credits: 'CreditsPort',
quality: 'QualityPort',
drawSet: 'DrawSet',
imageryLayer: 'ImageryLayer',
flight: 'Flight',
lease: 'Lease',
};
const PORT_NAMES = new Set(Object.values(PORT_INTERFACES));
/** Whether a property's type is one of the contract's own object shapes to list member by member. */
function nestedShape(type) {
if (type.isUnion() || type.getCallSignatures().length) return null;
const symbol = type.aliasSymbol ?? type.getSymbol();
const declaration = symbol?.declarations?.[0];
if (!declaration) return null;
const inContract = path.dirname(declaration.getSourceFile().fileName) === DIR;
if (!inContract) return null;
if (ts.isTypeLiteralNode(declaration)) return type;
if (ts.isInterfaceDeclaration(declaration))
return PORT_NAMES.has(declaration.name.text) ? null : type;
return null;
}
/** `[member, optional]` for every member, nested shapes dotted. */
function members(type, prefix = '') {
const out = [];
for (const property of checker.getPropertiesOfType(type)) {
const name = `${prefix}${property.name}`;
const optional = Boolean(property.flags & ts.SymbolFlags.Optional);
out.push([name, optional]);
const declaration = property.valueDeclaration ?? property.declarations?.[0];
const propertyType = checker.getTypeOfSymbolAtLocation(
property,
declaration,
);
const nested = nestedShape(propertyType);
if (nested) out.push(...members(nested, `${name}.`));
}
return out;
}
function unionLiterals(name) {
const type = checker.getTypeAtLocation(declared(name).name);
return (type.isUnion() ? type.types : [type]).map((t) => t.value).sort();
}
test('the contract type-checks under strict TypeScript', () => {
const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => {
const where = d.file
? `${path.relative(DIR, d.file.fileName)}:${d.file.getLineAndCharacterOfPosition(d.start).line + 1}`
: '';
return `${where} ${ts.flattenDiagnosticMessageText(d.messageText, '\n')}`;
});
assert.deepEqual(diagnostics, []);
});
test('PORTS lists every member of every port, required exactly when the type requires it', () => {
for (const [port, interfaceName] of Object.entries(PORT_INTERFACES)) {
const type = checker.getTypeAtLocation(declared(interfaceName).name);
const typed = Object.fromEntries(members(type));
const described = PORTS[port];
assert.deepEqual(
Object.keys(described).sort(),
Object.keys(typed).sort(),
`${port} members`,
);
for (const [member, capability] of Object.entries(described))
assert.equal(
capability !== null,
typed[member],
`${port}.${member}: optional in the type exactly when a capability adds it`,
);
}
});
test('the capability and frame-step lists are the types’ own', () => {
assert.deepEqual([...CAPABILITIES].sort(), unionLiterals('Capability'));
assert.deepEqual([...FRAME_STEPS].sort(), unionLiterals('FrameStep'));
for (const port of Object.values(PORTS))
for (const capability of Object.values(port))
if (capability !== null) assert.ok(CAPABILITIES.includes(capability));
assert.equal(CONTRACT_VERSION, '0');
const settings = checker.getTypeAtLocation(declared('QualitySettings').name);
assert.deepEqual(
[...QUALITY_KEYS].sort(),
checker
.getPropertiesOfType(settings)
.map((p) => p.name)
.sort(),
);
});
test('the shape check names what is missing and what a capability does not allow', () => {
assert.deepEqual(checkRendererShape(null), ['renderer is not an object']);
assert.deepEqual(checkRendererShape({}), [
'renderer.capabilities is not a Set',
]);
const problems = checkRendererShape({
capabilities: new Set(['warp']),
contractVersion: '0',
});
assert.ok(problems.includes('unknown capability warp'));
assert.ok(problems.includes('renderer.frame is missing'));
const set = Object.fromEntries(
Object.keys(PORTS.drawSet).map((member) => [member, () => {}]),
);
assert.deepEqual(checkPortShape(set, 'drawSet', new Set()), [
'drawSet.setColumns is present without columns',
]);
delete set.setColumns;
assert.deepEqual(checkPortShape(set, 'drawSet', new Set(['columns'])), [
'drawSet.setColumns is missing with columns',
]);
assert.deepEqual(checkPortShape(set, 'drawSet', new Set()), []);
});
+21
View File
@@ -0,0 +1,21 @@
/**
* Attribution. The renderer reports every credit it owes (its own, each
* base layer's, and per-tile credits as tiles load); the application renders the
* credit DOM, so the credits always look the same.
*/
import type { Off } from './common';
export interface Credit {
/** Sanitised HTML: text, links and images only. */
html: string;
/** Shown on the map itself, rather than in the expanded list. */
inline?: boolean;
}
export interface CreditsPort {
/** Add a credit the application owes (a layer's source). */
addStatic(credit: Credit): Off;
/** Every credit owed now, in display order. */
list(): Credit[];
on(event: 'change', cb: (credits: Credit[]) => void): Off;
}
+477
View File
@@ -0,0 +1,477 @@
/**
* Things to draw: batched sets of items keyed by string id.
*
* The application owns every record; a set is only what it pushed. Each item may carry
* an opaque `meta` that comes back on a pick (`Hit.meta`). There is no world
* text here: every label goes through the application's screen-space label overlay,
* which only needs `query.project`/`projectMany` and `query.isOccluded`.
*
* Moving icons follow a motion segment the renderer evaluates on its own
* clock (`motionSegments`), so the application writes a row only when its motion or
* style changes, not every frame.
*/
import type {
Color,
Ecef,
GeoRect,
Handle,
Meta,
NearFar,
Off,
Position,
Quaternion,
ScreenXY,
Vec3,
} from './common';
/** How an item's height is read. */
export type HeightMode = 'absolute' | 'clampGround' | 'relativeGround';
/** What `clampGround` / `relativeGround` clamp to. */
export type ClampTarget = 'terrain' | 'tiles' | 'both';
export interface ClusterSpec {
/** Screen distance under which icons merge. */
pixelRange: number;
/** Fewest icons that form a cluster. */
minimumSize: number;
/** Draws a cluster's icon from its member count. */
icon?: (count: number) => ImageRef;
}
/** Options of a whole set; the mutable ones can change later through `setOptions`. */
export interface SetSpec {
/**
* Unique among the renderer's live sets (making a second set with a live
* id throws; a disposed set's id can be used again); returned as `Hit.set`.
*/
id: string;
/** Hide items beyond the ellipsoid's horizon, for sets drawn without depth test. */
horizonCull?: boolean;
/** `cluster`: screen-space clustering (icons only). */
cluster?: ClusterSpec | null;
blend?: 'opaque' | 'translucent' | 'additive';
/** Draw order between sets that do not depth-test against each other. */
drawOrder?: number;
/** `false`: the set never takes part in picks. */
pickable?: boolean;
/** Height queries see through this set. */
excludeFromHeightQueries?: boolean;
/** What clamped items clamp to. */
clampTo?: ClampTarget;
/**
* `motionSegments`: the clock motion segments are evaluated on.
* `live` (the default) is wall time minus `delayMs`, as a live feed is
* drawn a little behind real time; `scene` is the frame port's scene time.
*/
motionClock?: { kind: 'live'; delayMs?: number } | { kind: 'scene' };
show?: boolean;
}
/** Common to items placed at one position. */
export interface Placed {
id: string;
pos: Position;
height?: HeightMode;
meta?: Meta;
show?: boolean;
/** `false`: this item never takes part in picks. */
pickable?: boolean;
scaleByDistance?: NearFar;
fadeByDistance?: NearFar;
/** Shown only between these eye distances, metres. */
displayRange?: [near: number, far: number];
/** Draw over depth within this many metres of the eye (`Infinity`: always). */
disableDepthTest?: number;
}
/** An image an icon draws: a URL, a slot in a shared atlas, or generated. */
export type ImageRef =
| string
| { atlas: string; slot: string }
| { svg: string }
| { blob: Blob }
| { canvas: HTMLCanvasElement | OffscreenCanvas; key: string };
/**
* How an icon moves between updates, on its set's `motionClock`. Times are
* epoch ms. Sending an item a new segment replaces its old one, whatever the
* times (an earlier or equal `t0` included).
* - hold: stays at `pos`.
* - lerp: straight in space from `from` (at `t0`) to `to` (at `t1`), holding
* at both ends; the course runs from `course0Deg` by `courseSlopeDeg`
* across the segment.
* - arc: a constant-rate turn in the plane tangent to the ellipsoid at `fix`
* (its east and north axes), at the fix's height, from `fix` at `t0`, at
* `speedMps` along `trackDeg` turning at `turnRateDps` (under 1e-4 rad/s is
* straight). The elapsed time is clamped to `[minDtS, maxDtS]`; a negative
* `minDtS` runs the fix backward before `t0` (a warm-up), `maxDtS` is how
* long it coasts.
* `courseGlide` eases the displayed course onto the segment's at `rateDps`.
*/
export type MotionSegment =
| { kind: 'hold'; courseDeg?: number }
| {
kind: 'lerp';
from: Ecef;
to: Ecef;
t0: number;
t1: number;
course0Deg?: number;
courseSlopeDeg?: number;
}
| {
kind: 'arc';
fix: Ecef;
t0: number;
minDtS: number;
maxDtS: number;
speedMps: number;
trackDeg: number;
turnRateDps: number;
};
export interface CourseGlide {
fromCourseDeg: number;
t0: number;
/** Degrees per second; 0 or less holds `fromCourseDeg`. */
rateDps: number;
}
export interface IconItem extends Placed {
image: ImageRef;
/** Drawn size in CSS pixels. */
size: [width: number, height: number];
color?: Color;
alpha?: number;
scale?: number;
/** `motionSegments`: motion on the renderer's clock. */
motion?: MotionSegment;
courseGlide?: CourseGlide;
/** Degrees clockwise from north. */
course?: number;
/**
* `screen`: upright on screen, rotated by `rotation`;
* `course`: rotated on screen along `course` (or the motion's course);
* `axis`: rotated about `alignedAxis`.
*/
rotationMode?: 'screen' | 'course' | 'axis';
/** Radians counter-clockwise on screen, for `rotationMode: 'screen'`. */
rotation?: number;
/** ECEF axis for `rotationMode: 'axis'`. */
alignedAxis?: Vec3;
pixelOffset?: ScreenXY;
/** Offset toward the eye, metres in eye space. */
eyeOffset?: Vec3;
anchor?: 'center' | 'bottom' | 'top';
/** Swap to `near` when drawn larger than `switchPx`. */
imageLod?: { near: ImageRef; switchPx: number };
/** A larger invisible pick target, CSS pixels. */
pickProxy?: { size: [width: number, height: number] };
/** Fade and shrink toward the globe's limb. */
recede?: boolean;
/** Emphasis factor for a focused item, 1 = none. */
focus?: number;
}
export interface PointItem extends Placed {
pixelSize: number;
color: Color;
outlineColor?: Color;
outlineWidth?: number;
}
export type LineStyle =
| { kind: 'solid'; color: Color }
| { kind: 'glow'; color: Color; power: number; taper?: number }
| {
kind: 'dash';
color: Color;
gapColor?: Color;
length: number;
pattern16?: number;
}
| { kind: 'arrow'; color: Color }
| { kind: 'pattern'; image: ImageRef; repeat: number }
| { kind: 'flow'; color: Color; repeat: number; duty: number; speed: number };
export interface LineItem {
id: string;
/** ECEF positions, or packed `x, y, z` triples. */
positions: Ecef[] | Float64Array;
widthPx: number;
/** `3d`: straight in space; `geodesic`: along the ellipsoid; `draped`: on the surface. */
mode: '3d' | 'geodesic' | 'draped';
clampTo?: ClampTarget;
style: LineStyle;
/** Colour where the line is behind the surface; `null` hides those parts. */
depthFailColor?: Color | null;
/** Per-segment colours; changing them does not rebuild the line. */
segmentColors?: Color[];
segmentShow?: boolean[];
/** Draw only the first fraction of the line, 0..1. */
revealFraction?: number;
/** Positions are in a frame rotating with the sky (orbits). */
frame?: 'fixed' | 'inertial';
meta?: Meta;
show?: boolean;
pickable?: boolean;
}
/** A shape's fill. */
export type Fill =
| Color
| { image: ImageRef; repeat?: [number, number] }
| { preset: 'radialRim'; color: Color; rimColor: Color; rimWidth: number };
/** Declarative animation the renderer runs (no per-frame callbacks). */
export interface Pulse {
property: 'radius' | 'alpha';
from: number;
to: number;
periodMs: number;
/** Repeat count; omitted repeats forever. */
repeat?: number;
}
/** A radius that follows the camera's height above the ground. */
export interface RadiusByCameraHeight {
byCameraHeight: { factor: number; min: number; max: number };
}
export type ShapeGeometry =
| { kind: 'polygon'; rings: Position[][]; perPositionHeight?: boolean }
| {
kind: 'ellipse';
center: Position;
semiMajor: number | RadiusByCameraHeight;
semiMinor: number | RadiusByCameraHeight;
/** Radians counter-clockwise from north to the semi-major axis. */
rotation?: number;
/** Only part of the ellipse, radians from north. */
arc?: { start: number; end: number };
}
/** `height`: metres above the ellipsoid, for a rectangle not clamped. */
| { kind: 'rectangle'; rect: GeoRect; height?: number }
| {
kind: 'box';
center: Position;
dimensions: Vec3;
orientation?: Quaternion;
}
| {
kind: 'wall';
positions: Position[];
minimumHeights?: number[];
maximumHeights?: number[];
};
export interface ShapeItem {
id: string;
geometry: ShapeGeometry;
fill?: Fill | null;
outline?: Color | null;
outlineWidth?: number;
/** Draw the outline only. Clamped outlines are drawn as draped lines. */
outlineOnly?: boolean;
/** Height of the extruded face, metres above the ellipsoid (not above the shape). */
extrudeHeight?: number;
height?: 'absolute' | 'clampGround';
clampTo?: ClampTarget;
/** Classify what is inside the volume (tint the tiles it covers). */
classifyVolume?: boolean;
/** Pull toward the eye, metres, to win depth against coplanar surfaces. */
depthBias?: number;
animate?: Pulse;
meta?: Meta;
show?: boolean;
pickable?: boolean;
}
/**
* A glTF model. The renderer draws one this way: glTF is Y-up and is
* turned to Z-up before `orientation` applies; `minPixelSize` is measured at
* the model's bounding-sphere distance from the eye; `colorBlend` mixes the
* tint into the shaded colour and never changes the model's alpha.
*/
export interface ModelItem extends Placed {
url: string;
orientation: { heading: number; pitch: number; roll: number };
scale?: number;
minPixelSize?: number;
maxPixelSize?: number;
maxScale?: number;
/** Can change live. */
shading?: 'pbr' | 'unlit' | 'thermal';
tint?: Color;
colorBlend?: { mode: 'highlight' | 'replace' | 'mix'; amount?: number };
environmentMap?: boolean;
}
/** A plane showing an image, a video or a canvas. */
export interface QuadItem {
id: string;
center: Position;
orientation: Quaternion;
/** Metres. */
size: [width: number, height: number];
source:
| { image: ImageRef }
| { video: HTMLVideoElement }
| { canvas: HTMLCanvasElement | OffscreenCanvas };
alpha?: number;
outline?: { color: Color; widthPx: number } | null;
meta?: Meta;
show?: boolean;
pickable?: boolean;
}
/** Custom geometry in a local east-north-up frame at `origin`. */
export interface MeshItem {
id: string;
origin: Ecef;
/** Packed `east, north, up` metres. */
positions: Float32Array;
indices: Uint16Array | Uint32Array;
color: Color;
/** Unlit, with back faces drawn. */
flat?: boolean;
meta?: Meta;
show?: boolean;
pickable?: boolean;
}
export type FieldSpec =
| {
kind: 'windStreamlines';
id: string;
/** Row-major `u` and `v` in m/s on a `width × height` grid over `rectangle`. */
u: Float32Array;
v: Float32Array;
width: number;
height: number;
rectangle: GeoRect;
pathBudget: number;
steps: number;
style: { color: Color; widthPx: number; speedFactor?: number };
/** Draw height, metres; omitted drapes on the surface. */
heightM?: number;
}
| {
kind: 'scalarRaster';
id: string;
values: Float32Array;
width: number;
height: number;
rectangle: GeoRect;
/** Colour ramp: value stops in ascending order. */
ramp: Array<{ value: number; color: Color }>;
alpha?: number;
}
| {
kind: 'rasterShell';
id: string;
/** A raster on a sphere raised above the ground. */
image: ImageRef;
rectangle: GeoRect;
heightM: number;
liftM?: number;
/** Full detail inside this rectangle only. */
detailWindow?: GeoRect;
alpha?: number;
};
export interface FieldHandle extends Handle {
update(patch: Partial<FieldSpec>): void;
}
export type CelestialSpec =
| {
kind: 'stars';
id: string;
catalogue: Float32Array;
magnitudeLimit?: number;
}
| {
kind: 'orbitRings';
id: string;
/** Each ring: packed `x, y, z` in the inertial frame, metres. */
rings: Float64Array[];
color: Color;
widthPx: number;
};
/** `agents`: dots moving along polylines (traffic flow). */
export interface AgentPathItem {
id: string;
positions: Ecef[] | Float64Array;
/** Agents on this path. */
count: number;
speedMps: number;
/** 0 flows freely; 1 stopped; between creeps. */
congestion?: number;
color: Color;
pixelSize: number;
fadeByDistance?: NearFar;
meta?: Meta;
}
/**
* Columnar update for large sets (`columns`). Column `i` of each array is
* row `ids[i]`. `dirty` limits the upload to these index runs.
*/
export interface Columns {
ids: readonly string[];
/** Packed ECEF `x, y, z`. */
positions?: Float64Array;
/** Degrees clockwise from north. */
courses?: Float32Array;
shown?: Uint8Array;
scales?: Float32Array;
alphas?: Float32Array;
/** Packed `r, g, b, a`, 0..255. */
colors?: Uint8Array;
meta?: readonly Meta[];
dirty?: ReadonlyArray<{ start: number; end: number }>;
}
export interface DrawSet<T> {
readonly id: string;
/** Replace every item. */
set(items: T[]): void;
/** Add or replace items by id. */
upsert(items: T[]): void;
remove(ids: string[]): void;
clear(): void;
/** `columns`. */
setColumns?(columns: Columns): void;
/** Change the mutable set options. */
setOptions(options: Partial<Omit<SetSpec, 'id'>>): void;
/** Items in the set. */
size(): number;
show: boolean;
/** `models`: a model has loaded and is posed. */
on(event: 'ready', cb: (id: string) => void): Off;
dispose(): void;
}
export interface DrawPort {
icons(spec: SetSpec): DrawSet<IconItem>;
points(spec: SetSpec): DrawSet<PointItem>;
lines(spec: SetSpec): DrawSet<LineItem>;
shapes(spec: SetSpec): DrawSet<ShapeItem>;
/** `models`. */
models?(spec: SetSpec): DrawSet<ModelItem>;
/** `quads`. */
quads?(spec: SetSpec): DrawSet<QuadItem>;
/** `meshes`. */
meshes?(spec: SetSpec): DrawSet<MeshItem>;
/** `fields`. */
field?(spec: FieldSpec): FieldHandle;
/** `celestial`: drawn in an inertial frame rotated by sidereal time. */
celestial?(spec: CelestialSpec): Handle;
/** `agents`. */
agents?(spec: SetSpec): DrawSet<AgentPathItem>;
/** Register an atlas of images icons refer to by slot. */
atlas(id: string, images: Record<string, ImageRef>): void;
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Full-screen effects: visual styles, bloom, sharpen and screen modulation.
* Each style is a plain full-screen pass over the frame's colour, so every
* renderer can provide the same set.
*/
import type { Off } from './common';
export interface StyleDescriptor {
id: string;
/** Parameters and their ranges. */
params: Array<{ key: string; min: number; max: number; default: number }>;
/** Animates, so it needs frames while on. */
animated: boolean;
}
/** A sweeping sector drawn over the frame (a sonar band), or null. */
export interface ModulationSector {
/** Centre of the sweep, CSS pixels. */
center: { x: number; y: number };
/** Current angle, radians clockwise from up. */
angle: number;
/** Width of the band, radians. */
width: number;
/** 0..1. */
strength: number;
color: string;
}
export interface EffectsDiagnostics {
style: string | null;
passes: string[];
}
export interface EffectsPort {
/** `styles`. */
styles(): StyleDescriptor[];
setStyle(id: string | null, params?: Record<string, number>): void;
setStyleIntensity(id: string, intensity: number): void;
setStyleParams(id: string, params: Record<string, number>): void;
/** `bloom`. */
bloom(settings: { enabled: boolean; strength?: number }): void;
/** `sharpen`. */
sharpen(settings: { enabled: boolean; amount?: number }): void;
/** `screenModulation`. */
screenModulation?(sector: ModulationSector | null): void;
diagnostics(): EffectsDiagnostics;
on(event: 'change', cb: (diagnostics: EffectsDiagnostics) => void): Off;
}
+76
View File
@@ -0,0 +1,76 @@
/**
* The frame loop, render on demand and scene time.
*
* A renderer draws on demand: a frame is drawn when something asks for one
* (`requestRender`), while any continuous hold is out, or every frame on an
* engine that cannot idle (it then reports `mode()` as `'continuous'`).
*
* One frame runs in this order, and the renderer keeps it:
* camera flight → input → camera `changed` → follow → `preUpdate` →
* move detection (`moveStart` / `moveEnd`) → `preRender` → render →
* `postRender`. `preUpdate` fires on every frame the loop ticks, including
* frames that end up drawing nothing, so owners that write the camera there
* (a cockpit, a follow clamp) see each one.
*/
import type { Off, Release } from './common';
export type FramePhase = 'preUpdate' | 'preRender' | 'postRender';
/** The order the phases (and the steps between them) run in one frame. */
export type FrameStep =
| 'flight'
| 'input'
| 'changed'
| 'follow'
| 'preUpdate'
| 'moveDetection'
| 'preRender'
| 'render'
| 'postRender';
export interface FrameTime {
/** Frames ticked since creation. */
frame: number;
/** Scene time, epoch ms: what sun, stars and lighting show. */
time: number;
/** The loop's clock, ms (virtual under a test clock). */
now: number;
/** Seconds since the previous tick. */
dt: number;
/** Whether this tick draws. */
rendering: boolean;
}
export interface FrameDiagnostics {
mode: 'demand' | 'continuous';
frames: number;
rendered: number;
/** Reasons given to `requestRender` since the last frame drawn. */
pendingReasons: string[];
/** Reasons of the holds now out. */
holds: string[];
suspended: boolean;
targetFps: number;
}
export interface FramePort {
on(phase: FramePhase, cb: (t: FrameTime) => void): Off;
/** Ask for one frame. The reason shows in diagnostics and signals. */
requestRender(reason: string): void;
/** Keep drawing every frame until released. Holds are counted. */
holdContinuous(reason: string): Release;
mode(): 'demand' | 'continuous';
diagnostics(): FrameDiagnostics;
/** Stop ticking while the page is hidden; resume on `false`. */
suspend(hidden: boolean): void;
/** Draw a frame now, synchronously. */
renderNow(): void;
/** Resolves after the next frame has been drawn and presented. */
renderOnce(options?: { timeoutMs?: number }): Promise<void>;
/** Cap the loop's rate; 0 is the display's rate. */
setTargetFps(fps: number): void;
/** Set scene time, epoch ms. */
setTime(ms: number): void;
/** Scene time, epoch ms. */
time(): number;
}
+210
View File
@@ -0,0 +1,210 @@
/**
* The base world: photorealistic tiles or a globe with terrain and imagery,
* the sky, and what drapes onto them.
*/
import type { Credit } from './credits';
import type { GeoRect, Off } from './common';
export interface PhotorealSpec {
provider: 'google';
key?: string;
/** Renews a session token; called again when the token expires. */
token?: () => Promise<string>;
/** Fall back to an ion-hosted copy when Google refuses. */
ionFallback?: boolean;
}
export interface PhotorealStatus {
/** Which route is drawing, or `'none'` when photoreal is off or failed. */
route: 'google' | 'ion' | 'none';
error?: { code: string; message: string };
}
/**
* Heights everywhere in the contract are physical (metres above the
* ellipsoid, unexaggerated): absolute positions, `HeightSample.height`,
* `clampToSurface`. Only drawing follows the exaggerated surface:
* `clampGround` and `relativeGround` items sit on the ground as drawn.
*/
export type TerrainSpec = (
| { kind: 'ellipsoid' }
| { kind: 'quantizedMesh'; url: string; requestVertexNormals?: boolean }
| { kind: 'ion'; assetId: number }
/** A DEM image pyramid (`{z}/{x}/{y}`), heights encoded in RGB. */
| {
kind: 'heightmap';
url: string;
encoding: 'terrarium' | 'mapbox';
maxLevel?: number;
/** The geoid the encoded heights are relative to; omitted: the ellipsoid. */
geoid?: 'egm96' | 'egm2008';
}
) & {
/** Vertical exaggeration of the drawn terrain; default 1. */
exaggeration?: number;
};
export type TilingScheme = 'webMercator' | 'geographic';
/** One tile request, as an admission hook sees it. */
export interface TileRequest {
x: number;
y: number;
level: number;
}
export interface ImagerySpec {
kind: 'xyz' | 'wmts' | 'arcgis' | 'bing' | 'single-image' | 'canvas';
/** URL or URL template (`{x}`, `{y}`, `{z}`, `{s}`, `{time}`). */
url?: string;
/** `'canvas'`: draws one tile. */
drawTile?: (tile: TileRequest, canvas: HTMLCanvasElement) => void;
/** WMTS: layer, style, tile matrix set and format. */
wmts?: {
layer: string;
style: string;
tileMatrixSetId: string;
format?: string;
};
subdomains?: string[];
tiling?: TilingScheme;
rectangle?: GeoRect;
minLevel?: number;
maxLevel?: number;
tileSize?: number;
credit?: Credit;
/** Requests in flight at once for this layer. */
maxConcurrentRequests?: number;
/** HTTP statuses retried rather than treated as missing. */
retryStatuses?: number[];
/** Changes a tile's image before it is drawn. */
tileTransform?: (
tile: TileRequest,
image: ImageBitmap,
) => ImageBitmap | Promise<ImageBitmap>;
/**
* Decides each tile request: call `issue()` to fetch it, or return
* `undefined` to defer it and be asked again on a later frame.
*/
admit?: (
tile: TileRequest,
issue: () => Promise<unknown> | undefined,
) => Promise<unknown> | undefined;
/** Draw order among imagery layers; higher draws on top. */
zOrder?: number;
}
export interface TimedUrl {
/** Epoch ms the frame shows. */
time: number;
url: string;
}
export interface ImageryLayer {
alpha: number;
show: boolean;
/** Which side of the split this layer shows on. */
split: 'none' | 'left' | 'right';
/** What it drapes onto. `'active'` follows whichever base is showing. */
drapeOn: 'globe' | 'tiles' | 'both' | 'active';
/** `imageryFrames`: a timed sequence, prefetched hidden. */
setFrames?(
frames: TimedUrl[],
options?: { mode?: 'nearest' | 'blend'; prefetch?: number },
): void;
/** `imageryFrames`: which time to show. */
setFrameTime?(ms: number): void;
on(event: 'frameReady', cb: (time: number) => void): Off;
on(
event: 'tileError',
cb: (error: { tile: TileRequest; status?: number }) => void,
): Off;
raise(): void;
lower(): void;
remove(): void;
}
export interface BaseSpec {
photoreal?: PhotorealSpec | null;
/** `vectorBase`: a vector basemap from a style document. */
vector?: { styleUrl: string } | null;
terrain?: TerrainSpec | null;
imagery?: ImagerySpec[];
credit?: Credit;
}
export interface BaseStatus {
photoreal: PhotorealStatus;
imagery: ImageryLayer[];
settled: boolean;
}
/**
* The sky. A renderer whose sun, moon or fog are not separate from its
* atmosphere follows `atmosphere` for them and reports them as it draws them.
*/
export interface SkySettings {
atmosphere: boolean;
atmosphereTuning?: {
brightness?: number;
hueShift?: number;
saturation?: number;
};
stars: boolean;
/** Milky Way brightness, 0..1. */
milkyWay: number;
sun: boolean;
moon: boolean;
/** Distance fog, separate from atmosphere on models. */
fog: boolean;
/** Sun lighting of the globe and models. */
lighting: boolean;
}
export interface SurfaceShading {
kind: 'relief';
/** Elevation-like field to shade, row-major, `width × height`. */
values: Float32Array;
width: number;
height: number;
rectangle: GeoRect;
strength: number;
}
export interface LoadProgress {
tilesPending: number;
imageryPending: number;
terrainPending: number;
}
export type SettleKind = 'base' | 'tiles' | 'terrain' | 'imagery';
export interface GlobePort {
/** Switch the whole base at once; resolves when the new base has settled. */
setBase(base: BaseSpec): Promise<BaseStatus>;
/** `photoreal`: on, off or a new token route. */
setPhotoreal(spec: PhotorealSpec | null): Promise<PhotorealStatus>;
setTerrain(spec: TerrainSpec | null): Promise<void>;
/** Show or hide the globe surface (hidden under photoreal). */
setGlobeVisible(visible: boolean): void;
/** `surfaceShading`. */
setSurfaceShading?(shading: SurfaceShading | null): void;
readonly imagery: {
add(spec: ImagerySpec, index?: number): ImageryLayer;
list(): ImageryLayer[];
/** What imagery drapes onto now. */
host(): 'globe' | 'tiles' | 'both';
onHostChange(cb: (host: 'globe' | 'tiles' | 'both') => void): Off;
/** `splitSwipe`: split position, a fraction of the canvas's CSS width. */
getSplit?(): number;
/** `splitSwipe`: move the split to `x01` of the canvas's CSS width. */
setSplit?(x01: number): void;
};
readonly sky: {
get(): SkySettings;
set(settings: Partial<SkySettings>): void;
};
/** Whether that part of the base has finished loading what is in view. */
isSettled(kind: SettleKind): boolean;
on(event: 'progress', cb: (progress: LoadProgress) => void): Off;
}
+48
View File
@@ -0,0 +1,48 @@
/**
* The renderer contract: what the application asks of a renderer, typed
* than the default one can draw the same application.
*/
export * from './common';
export * from './renderer';
export * from './frame';
export * from './globe';
export * from './draw';
export * from './camera';
export * from './query';
export * from './input';
export * from './effects';
export * from './credits';
export * from './quality';
/** Every capability a renderer may list. */
export declare const CAPABILITIES: readonly import('./common').Capability[];
/** The contract version this module describes. */
export declare const CONTRACT_VERSION: import('./renderer').ContractVersion;
/** One port's members: null when required, else the capability that adds it. */
export type PortDescriptor = Readonly<
Record<string, import('./common').Capability | null>
>;
/** Every port's members, by port name. */
export declare const PORTS: Readonly<Record<string, PortDescriptor>>;
/** Every quality setting a renderer may support. */
export declare const QUALITY_KEYS: readonly import('./quality').QualityKey[];
/** The phases and steps of one frame, in order. */
export declare const FRAME_STEPS: readonly import('./frame').FrameStep[];
/**
* What a renderer is missing against the contract: each required member it
* lacks, and each capability-gated member present without its capability.
*/
export declare function checkRendererShape(renderer: unknown): string[];
/** What one port (or handed-out shape) is missing against its descriptor. */
export declare function checkPortShape(
target: object,
port: string,
capabilities: ReadonlySet<string>,
): string[];
+370
View File
@@ -0,0 +1,370 @@
/**
* @module render/contract
* @description The renderer contract at run time: the capability flags, every
* port's members, and a shape check. The types live beside this file
* (`index.d.ts` and one `.d.ts` per port); `contract.test.mjs` keeps
* {@link PORTS} and those types in step, member for member.
*
* A member is required (`null`) or added by a capability: a renderer without
* that capability leaves the member out.
*/
/** @type {import('./index').ContractVersion} */
export const CONTRACT_VERSION = '0';
/** @type {readonly import('./common').Capability[]} */
export const CAPABILITIES = Object.freeze([
'photoreal',
'vectorBase',
'finestHeights',
'terrain',
'modelAtmosphere',
'imageryOnTiles',
'splitSwipe',
'imageryFrames',
'surfaceShading',
'screenModulation',
'gpuTiming',
'pickPosition',
'sampleHeight',
'rayCast',
'columns',
'motionSegments',
'models',
'quads',
'meshes',
'fields',
'celestial',
'agents',
'cluster',
'styles',
'bloom',
'sharpen',
'followAutodetect',
'benchmark',
]);
/** @type {readonly import('./frame').FrameStep[]} */
export const FRAME_STEPS = Object.freeze([
'flight',
'input',
'changed',
'follow',
'preUpdate',
'moveDetection',
'preRender',
'render',
'postRender',
]);
/** Every quality setting a renderer may support. */
export const QUALITY_KEYS = Object.freeze([
'pixelRatio',
'overlayPixelRatio',
'msaa',
'tiles3dDetail',
'terrainDetail',
'imageryDetail',
'tilesCacheBytes',
'clouds',
'shadows',
'water',
'atmosphere',
'milkyWay',
'particles',
'models',
'postFx',
'animatedStyleFps',
'sonarCadenceHz',
'targetFps',
]);
const required = (...names) => names.map((name) => [name, null]);
/**
* Every port's members. Nested members are dotted (`imagery.add`); the
* instance shapes a port hands out (`drawSet`, `imageryLayer`, `flight`,
* `lease`) are listed as their own entries.
* @type {Readonly<Record<string, Readonly<Record<string, import('./common').Capability|null>>>>}
*/
export const PORTS = deepFreeze({
renderer: Object.fromEntries(
required(
'id',
'contractVersion',
'capabilities',
'canvas',
'frame',
'globe',
'draw',
'camera',
'query',
'input',
'effects',
'credits',
'quality',
'capture',
'readPixels',
'whenSettled',
'resize',
'releaseUnused',
'on',
'destroy',
),
),
frame: Object.fromEntries(
required(
'on',
'requestRender',
'holdContinuous',
'mode',
'diagnostics',
'suspend',
'renderNow',
'renderOnce',
'setTargetFps',
'setTime',
'time',
),
),
globe: Object.fromEntries([
...required(
'setBase',
'setPhotoreal',
'setTerrain',
'setGlobeVisible',
'imagery',
'imagery.add',
'imagery.list',
'imagery.host',
'imagery.onHostChange',
'sky',
'sky.get',
'sky.set',
'isSettled',
'on',
),
['setSurfaceShading', 'surfaceShading'],
['imagery.getSplit', 'splitSwipe'],
['imagery.setSplit', 'splitSwipe'],
]),
draw: Object.fromEntries([
...required('icons', 'points', 'lines', 'shapes', 'atlas'),
['models', 'models'],
['quads', 'quads'],
['meshes', 'meshes'],
['field', 'fields'],
['celestial', 'celestial'],
['agents', 'agents'],
]),
camera: Object.fromEntries(
required(
'pose',
'setView',
'setFov',
'viewRectangle',
'flyTo',
'flyToBounds',
'cancelFlight',
'flying',
'lookAt',
'release',
'move',
'look',
'rotateAround',
'zoom',
'follow',
'followed',
'followFramed',
'followOffset',
'followOffset.get',
'followOffset.set',
'controls',
'controls.enabled',
'controls.suspend',
'controls.enableTilt',
'controls.enableRotate',
'controls.enableZoom',
'controls.minDistance',
'controls.maxDistance',
'controls.inertiaSpin',
'controls.inertiaTranslate',
'controls.inertiaZoom',
'controls.collision',
'controls.zoomFactor',
'controls.pitchRange',
'controls.zoomInputs',
'on',
'onCommand',
'matrices',
),
),
query: Object.fromEntries(
required(
'pick',
'drillPick',
'pickPosition',
'pickEllipsoid',
'pickGlobe',
'pickRay',
'project',
'projectMany',
'isOccluded',
'sampleHeightNow',
'sampleHeightNowMany',
'sampleHeight',
'clampToSurface',
'rayCast',
),
),
input: Object.fromEntries(
required(
'on',
'claimPointer',
'isPointerFree',
'suspendCameraControls',
'behaviours',
'behaviours.select',
'behaviours.select.enabled',
'behaviours.select.suppress',
'behaviours.dblclickFollow',
'behaviours.dblclickFollow.enabled',
'behaviours.dblclickFollow.suppress',
'ctrlWheelZoom',
),
),
effects: Object.fromEntries([
...required(
'styles',
'setStyle',
'setStyleIntensity',
'setStyleParams',
'bloom',
'sharpen',
'diagnostics',
'on',
),
['screenModulation', 'screenModulation'],
]),
credits: Object.fromEntries(required('addStatic', 'list', 'on')),
quality: Object.fromEntries([
...required(
'knobs',
'get',
'set',
'device',
'probe',
'signals',
'signals.gpuTiming',
'signals.on',
),
['benchmark', 'benchmark'],
]),
drawSet: Object.fromEntries([
...required(
'id',
'set',
'upsert',
'remove',
'clear',
'setOptions',
'size',
'show',
'on',
'dispose',
),
['setColumns', 'columns'],
]),
imageryLayer: Object.fromEntries([
...required(
'alpha',
'show',
'split',
'drapeOn',
'on',
'raise',
'lower',
'remove',
),
['setFrames', 'imageryFrames'],
['setFrameTime', 'imageryFrames'],
]),
flight: Object.fromEntries(required('done', 'cancel')),
lease: Object.fromEntries(required('owner', 'current', 'release')),
});
/** The ports a renderer object holds, by the key it holds them under. */
const RENDERER_PORTS = [
'frame',
'globe',
'draw',
'camera',
'query',
'input',
'effects',
'credits',
'quality',
];
function deepFreeze(value) {
for (const inner of Object.values(value))
if (inner && typeof inner === 'object') deepFreeze(inner);
return Object.freeze(value);
}
function has(target, dotted) {
let at = target;
for (const key of dotted.split('.')) {
if (at == null || (typeof at !== 'object' && typeof at !== 'function'))
return false;
if (!(key in at)) return false;
at = at[key];
}
return true;
}
/**
* What `target` is missing against one descriptor, and what it has that its
* capabilities do not allow.
* @param {object} target
* @param {string} port
* @param {ReadonlySet<string>} capabilities
* @returns {string[]}
*/
export function checkPortShape(target, port, capabilities) {
const problems = [];
for (const [member, capability] of Object.entries(PORTS[port])) {
const present = has(target, member);
if (capability === null) {
if (!present) problems.push(`${port}.${member} is missing`);
} else if (capabilities.has(capability) && !present) {
problems.push(`${port}.${member} is missing with ${capability}`);
} else if (!capabilities.has(capability) && present) {
problems.push(`${port}.${member} is present without ${capability}`);
}
}
return problems;
}
/**
* What a renderer is missing against the contract.
* @param {unknown} renderer
* @returns {string[]}
*/
export function checkRendererShape(renderer) {
if (!renderer || typeof renderer !== 'object')
return ['renderer is not an object'];
const r = /** @type {any} */ (renderer);
const capabilities = r.capabilities instanceof Set ? r.capabilities : null;
if (!capabilities) return ['renderer.capabilities is not a Set'];
const problems = [];
for (const capability of capabilities)
if (!CAPABILITIES.includes(capability))
problems.push(`unknown capability ${capability}`);
if (r.contractVersion !== CONTRACT_VERSION)
problems.push(`contractVersion is ${r.contractVersion}`);
problems.push(...checkPortShape(r, 'renderer', capabilities));
for (const port of RENDERER_PORTS)
if (r[port]) problems.push(...checkPortShape(r[port], port, capabilities));
return problems;
}
+93
View File
@@ -0,0 +1,93 @@
/**
* Pointer input over the scene, through one dispatcher.
*
* A tool takes the pointer with a lease; while a lease is out, ambient
* subscribers (those without a lease) get only `move` and `up`: no presses,
* clicks, double-clicks, wheel or pinch. Suspending camera
* input is separate and counted, and takes effect on the same pointerdown
* that asked for it.
*
* A click is delivered with its pick already made, once, and shared by
* every subscriber (`PointerEv.pick`). Where the renderer's picks answer a
* or two late delivers the click that much later rather than answering
* without them; `query.pick` stays synchronous for everything else.
*
* The engine's stock behaviours (select on click, follow on double-click)
* are explicit and removable here, never implicit.
*/
import type { Hit, PickWindow } from './query';
import type { Ecef, Off, Release, ScreenXY } from './common';
export type PointerEventType =
'down' | 'move' | 'up' | 'click' | 'dblclick' | 'wheel' | 'pinch';
export interface Modifiers {
shift: boolean;
ctrl: boolean;
alt: boolean;
meta: boolean;
}
export interface PointerEv {
type: PointerEventType;
position: ScreenXY;
/** For `move`: where the pointer is now (`position` is where it was). */
endPosition?: ScreenXY;
button: 0 | 1 | 2;
modifiers: Modifiers;
/** Event time, ms (`performance.now()` timeline). */
timestamp: number;
pointerType: 'mouse' | 'touch' | 'pen';
/** `click`: how far the pointer travelled and how long the press lasted. */
gesture?: { travelPx: number; durationMs: number };
/** `wheel`: lines scrolled; `pinch`: scale since the last event. */
delta?: number;
/** `click` and `dblclick`: the hit under the pointer, picked once for every subscriber. */
pick?(): Hit | null;
/** `click` and `dblclick`: every hit under the pointer, from the same pick. */
drill?(options?: PickWindow & { limit?: number }): Hit[];
/** `click` and `dblclick`: the surface position under the pointer. */
ground?(): Ecef | null;
}
/** A tool's hold on the pointer. */
export interface Lease {
readonly owner: string;
readonly current: boolean;
release(): void;
}
/** A stock behaviour, on until suppressed. */
export interface StockBehaviour {
readonly enabled: boolean;
/** Turn it off until released. Holds are counted. */
suppress(): Release;
}
export interface InputPort {
on(
type: PointerEventType,
cb: (ev: PointerEv) => void,
options?: { lease?: Lease | (() => Lease | null) },
): Off;
/** Take the pointer for a tool. A new claim ends the previous lease. */
claimPointer(owner: string): Lease;
isPointerFree(): boolean;
/** Suspend user camera input until released. Holds are counted. */
suspendCameraControls(reason: string): Release;
/**
* Every behaviour the renderer does on its own in answer to input, each
* suppressible. `select` and `dblclickFollow` are always listed (a
* renderer without one reports it disabled); any other built-in one (a
* double-click zoom) is listed under its own name.
*/
readonly behaviours: {
/** Select the item under a click. */
readonly select: StockBehaviour;
/** Follow the item under a double-click. */
readonly dblclickFollow: StockBehaviour;
readonly [name: string]: StockBehaviour;
};
/** Ctrl+wheel zooms (rather than the page). */
ctrlWheelZoom: boolean;
}
+116
View File
@@ -0,0 +1,116 @@
/**
* Adaptive quality. A governor above the contract decides a level; each
* renderer reports its frame signals, lists the settings it supports and
* applies them. Nothing here is engine-specific.
*/
import type { Off } from './common';
export interface QualitySettings {
/** Absolute device pixel ratio for the scene; 0 = browser recommended. */
pixelRatio: number;
/** Pixel ratio of screen-space overlays. */
overlayPixelRatio: number;
msaa: 0 | 2 | 4 | 8;
/** 0..1: 3D tile detail (screen-space error, both directions). */
tiles3dDetail: number;
terrainDetail: number;
imageryDetail: number;
tilesCacheBytes: number;
clouds: 'off' | 'low' | 'medium' | 'high' | 'ultra';
shadows: boolean;
water: 'off' | 'low' | 'high';
atmosphere: 'off' | 'low' | 'high';
milkyWay: 'low' | 'high';
/** 0..1 density of particle fields (wind, weather). */
particles: number;
models: { maxInstances: number; maxDistance: number };
postFx: { bloom: boolean; sharpen: boolean; style: 'low' | 'high' };
/** Frame rate of animated styles. */
animatedStyleFps: number;
/** Updates per second of a screen modulation sweep. */
sonarCadenceHz: number;
targetFps: number;
}
export type QualityKey = keyof QualitySettings;
export interface KnobDescriptor {
key: QualityKey;
kind: 'number' | 'boolean' | 'enum' | 'object';
min?: number;
max?: number;
options?: readonly string[] | readonly number[];
default: unknown;
/** Relative cost, 0 (free) to 1 (the heaviest knob). */
cost: number;
/** Changing it recreates the drawing context. */
recreates?: boolean;
/** What else changing it affects (lower tile detail lowers height accuracy). */
couples?: string[];
}
export interface FrameSignals {
cpuMs: number;
/** `gpuTiming`. */
gpuMs?: number;
passes?: Record<string, number>;
drawCalls?: number;
commands?: number;
tilesInFlight?: number;
memory?: { gpuBytes?: number; tilesBytes?: number };
pixelRatio: number;
width: number;
height: number;
mode: 'demand' | 'continuous';
/** This frame was asked for (not continuous). */
requested: boolean;
holds: string[];
/** Spread of present intervals over the last second, ms. */
presentJitterMs?: number;
}
export interface DeviceFacts {
backend: 'webgl1' | 'webgl2' | 'webgpu';
gpuVendor?: string;
gpuRenderer?: string;
maxTextureSize: number;
msaaSamples: number[];
gpuTimer: boolean;
}
export interface ProbeResult {
device: DeviceFacts;
browser: {
devicePixelRatio: number;
screen: { width: number; height: number };
hardwareConcurrency?: number;
deviceMemory?: number;
touchOnly: boolean;
};
knobs: KnobDescriptor[];
}
export interface BenchResult {
frames: number;
cpuMs: { median: number; p95: number };
gpuMs?: { median: number; p95: number };
}
export interface QualityPort {
/** The settings this renderer supports, with ranges, defaults and costs. */
knobs(): KnobDescriptor[];
get(): Partial<QualitySettings>;
/** Applied at the next frame; returns the keys it ignored as unsupported. */
set(settings: Partial<QualitySettings>): QualityKey[];
device(): DeviceFacts;
probe(): ProbeResult;
readonly signals: {
readonly gpuTiming: 'none' | 'frame' | 'perPass';
on(event: 'frame', cb: (signals: FrameSignals) => void): Off;
};
/** `benchmark`: the renderer's own; the governor has a default. */
benchmark?(options: {
durationMs: number;
scene?: 'standard';
}): Promise<BenchResult>;
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Questions about what is on screen.
*
* Picks, projection and rays are synchronous and answer against the last
* presented frame. Heights have a synchronous cache-only form that may
* return null, and asynchronous forms that load what they need.
*/
import type { Ecef, LonLat, Meta, Ray, ScreenXY } from './common';
/** One thing under the pointer. */
export interface Hit {
/** The draw set's id. */
set: string;
/** The item's id. */
id: string;
/** The item's `meta`, as it was given; absent when the item had none. */
meta?: Meta;
/** The map itself (tiles or globe), rather than a drawn item. */
surface: boolean;
/** Where the hit is, when the renderer knows it. */
position?: Ecef;
}
export interface PickWindow {
/** Pick window, CSS pixels; default 3 × 3. */
width?: number;
height?: number;
/**
* What the pick is for. A hover pick may skip costly exact tests (a
* point-in-polygon on a large fill) that a select pick must make.
*/
purpose?: 'hover' | 'select';
}
export interface HeightOptions {
/** `surface`: tiles where they are drawn, otherwise terrain. */
against?: 'surface' | 'terrain' | 'tiles';
/** Set ids to see through. */
exclude?: string[];
}
export interface HeightSample {
/** Metres above the ellipsoid. */
height: number;
/** 1 for the most detailed data, lower for a coarser level. */
confidence: number;
source: 'tiles' | 'terrain' | 'ellipsoid';
/** The detail answered from: what is drawn now, or (`finestHeights`) the finest available. */
lod: 'visible' | 'finest';
/** Edge length of the tile answered from, metres, when known. */
tileSizeM?: number;
}
export interface QueryPort {
pick(x: number, y: number, window?: PickWindow): Hit | null;
drillPick(
x: number,
y: number,
options?: PickWindow & { limit?: number },
): Hit[];
/** `pickPosition`: depth under the pointer, against tiles and terrain. */
pickPosition(x: number, y: number): Ecef | null;
pickEllipsoid(x: number, y: number): Ecef | null;
/** Where a ray meets the globe surface (not tiles). */
pickGlobe(ray: Ray): Ecef | null;
pickRay(x: number, y: number): Ray;
/** Screen position, or null behind the eye (off-screen points still answer). */
project(position: Ecef): ScreenXY | null;
/**
* Packed `x, y, z` in → packed `x, y` out, CSS pixels; NaN for points
* behind the eye. For the label overlay's per-frame pass.
*/
projectMany(source: Float64Array, out: Float32Array): void;
/** Hidden by the ellipsoid's horizon from the current eye. */
isOccluded(position: Ecef): boolean;
/** `sampleHeight`: cached height now, or null when not loaded. */
sampleHeightNow(point: LonLat, options?: HeightOptions): number | null;
/**
* `sampleHeight`: cached heights for many points at once: packed `lon, lat`
* degrees in, one height per point out (NaN when not loaded). The app makes
* its per-frame height reads through this, once a frame.
*/
sampleHeightNowMany(
points: Float64Array,
out: Float64Array,
options?: HeightOptions,
): void;
/**
* `sampleHeight`: heights, loading as needed; null per miss.
* `mostDetailed` (`finestHeights`) waits for the finest data.
*/
sampleHeight(
points: LonLat[],
options?: HeightOptions & { mostDetailed?: boolean },
): Promise<Array<HeightSample | null>>;
/** `sampleHeight`: positions moved onto the surface; null per miss. */
clampToSurface(
positions: Ecef[],
options?: HeightOptions,
): Promise<Array<Ecef | null>>;
/** `rayCast`: first surface hit along a ray. */
rayCast(
ray: Ray,
options?: HeightOptions & { maxDistance?: number },
): Promise<Ecef | null>;
}
+114
View File
@@ -0,0 +1,114 @@
/**
* The renderer itself: what a plugin creates and what the application holds.
*
* A renderer draws the globe and what the application asks it to draw, owns the camera,
* and answers queries about what is on screen. The application keeps every record of
* its own; it never reads a renderer to learn its own state, only what the
* renderer itself measures (picks, depth, heights, readiness).
*/
import type { Capability, Off, ScreenRect } from './common';
import type { CameraPort } from './camera';
import type { CreditsPort } from './credits';
import type { DrawPort } from './draw';
import type { EffectsPort } from './effects';
import type { FramePort } from './frame';
import type { GlobePort, SkySettings } from './globe';
import type { InputPort } from './input';
import type { QualityPort } from './quality';
import type { QueryPort } from './query';
/** The version of the contract this file describes. */
export type ContractVersion = '0';
/** What the application is given to make a renderer. */
export interface RendererPlugin {
/** Stable id, recorded with each session (`'cesium'`, ...). */
id: string;
create(options: CreateOptions): Promise<Renderer>;
}
export interface CreateOptions {
/** The element the renderer fills. It creates its own canvas inside. */
container: HTMLElement;
/** Where the app renders credits, when it has a place for them. */
creditContainer?: HTMLElement;
/** Google Maps Platform key for photorealistic tiles. */
googleApiKey?: string;
/** Short-lived Google session tokens, when the key is held server-side. */
googleTokens?: () => Promise<string>;
/** Cesium ion token, for ion-hosted terrain and fallback tiles. */
ionToken?: string;
/** Initial multisampling; quality can change it later. */
msaa?: 0 | 2 | 4 | 8;
/** Keep the drawing buffer after presenting, for capture. */
preserveDrawingBuffer?: boolean;
/** Sky applied before the first frame, so nothing draws in the wrong sky. */
sky?: Partial<SkySettings>;
/** Scene time in epoch ms. The application passes its boot time. */
time?: number;
/**
* The clocks the renderer reads, for flights, inertia, tweens and
* `FrameTime.now`: `now` on the `performance.now()` timeline, `date` in
* epoch ms. Omitted: the browser's. Tests pass virtual ones.
*/
clock?: { now(): number; date(): number };
/** Aborts creation; the renderer cleans up whatever it had built. */
signal: AbortSignal;
}
export interface CaptureOptions {
type?: 'png' | 'jpeg';
/** JPEG quality, 0..1. */
quality?: number;
/** Output scale relative to the canvas's CSS size. */
scale?: number;
/** Part of the canvas, in CSS pixels. */
crop?: ScreenRect;
}
export interface SettleResult {
state: 'settled' | 'timeout' | 'failed';
blockers: string[];
}
export interface Renderer {
readonly id: string;
readonly contractVersion: ContractVersion;
readonly capabilities: ReadonlySet<Capability>;
readonly canvas: HTMLCanvasElement;
readonly frame: FramePort;
readonly globe: GlobePort;
readonly draw: DrawPort;
readonly camera: CameraPort;
readonly query: QueryPort;
readonly input: InputPort;
readonly effects: EffectsPort;
readonly credits: CreditsPort;
readonly quality: QualityPort;
/** The last presented frame as an encoded image. */
capture(options?: CaptureOptions): Promise<Blob>;
/**
* The last presented frame's pixels, synchronously, for loops that render
* a frame and read it at once (a share clip, a black-frame check). Call it
* right after `frame.renderNow()`.
*/
readPixels(options?: { crop?: ScreenRect; scale?: number }): ImageData;
/**
* Resolves once what is in view has loaded, or the timeout passes, or a
* load failed for good. `blockers` names what was still loading or
* failed (`'tiles'`, `'imagery:<id>'`, `'models'`, ...); empty when settled.
*/
whenSettled(options?: { timeoutMs?: number }): Promise<SettleResult>;
/** Follows the container's size. */
resize(): void;
/** Frees caches and GPU memory nothing in view uses. */
releaseUnused(): void;
on(event: 'error', cb: (error: Error) => void): Off;
/**
* The drawing context was lost, or came back. Where the renderer cannot
* restore its context it never sends `contextRestored`; the application
* a new renderer.
*/
on(event: 'contextLost' | 'contextRestored', cb: () => void): Off;
destroy(): void;
}