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.
No files matched your search
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* @module render/conformance/cameraRunner
|
||||
* @description Runs a camera script ({@link module:render/conformance/cameraScripts})
|
||||
* on a driver and collects what it records, in step order. A driver is
|
||||
* either a renderer through the contract ({@link contractDriver}) or the
|
||||
* reference recorder's own.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} CameraDriver
|
||||
* @property {(name: string, args: unknown[]) => import('../contract/camera').Flight|void} command
|
||||
* @property {() => void|Promise<void>} frame One frame, 1/60 s on the script's clock.
|
||||
* @property {(threshold: number) => () => number} listen Counts `changed`; returns a reader.
|
||||
* @property {() => object} pose
|
||||
* @property {(position: object) => object|null} project
|
||||
* @property {(screen: {x: number, y: number}) => object|null} pickEllipsoid
|
||||
* @property {(screen: {x: number, y: number}) => object} pickRay
|
||||
* @property {(position: object) => boolean} occluded
|
||||
* @property {() => boolean} flying
|
||||
* @property {(position: object) => object} toEcef
|
||||
*/
|
||||
|
||||
/** The parts of a pose a trace keeps. */
|
||||
export function tracePose(pose) {
|
||||
return {
|
||||
position: pick3(pose.position),
|
||||
direction: pick3(pose.direction),
|
||||
up: pick3(pose.up),
|
||||
right: pick3(pose.right),
|
||||
heading: pose.heading,
|
||||
pitch: pose.pitch,
|
||||
roll: pose.roll,
|
||||
height: pose.height,
|
||||
frameIsIdentity: pose.frameIsIdentity,
|
||||
};
|
||||
}
|
||||
|
||||
const pick3 = (v) => (v ? { x: v.x, y: v.y, z: v.z } : null);
|
||||
|
||||
/**
|
||||
* @param {CameraDriver} driver
|
||||
* @param {{name: string, steps: object[]}} script
|
||||
* @returns {Promise<{records: object[], flights: object[]}>}
|
||||
*/
|
||||
export async function runCameraScript(driver, script) {
|
||||
const records = [];
|
||||
const flights = [];
|
||||
const listeners = [];
|
||||
let frame = 0;
|
||||
for (const [index, step] of script.steps.entries()) {
|
||||
if (step.do === 'frames') {
|
||||
for (let i = 0; i < step.count; i++) {
|
||||
frame += 1;
|
||||
await driver.frame();
|
||||
}
|
||||
} else if (step.do === 'listen') {
|
||||
listeners.push({
|
||||
threshold: step.threshold,
|
||||
read: driver.listen(step.threshold),
|
||||
});
|
||||
} else if (step.do) {
|
||||
const args = resolveArgs(driver, step.do, step.args ?? []);
|
||||
const flight = driver.command(step.do, args);
|
||||
if (flight && typeof flight.done?.then === 'function') {
|
||||
const entry = {
|
||||
step: index,
|
||||
startFrame: frame,
|
||||
outcome: null,
|
||||
frames: null,
|
||||
};
|
||||
flights.push(entry);
|
||||
flight.done.then((outcome) => {
|
||||
entry.outcome = outcome;
|
||||
entry.frames = frame - entry.startFrame;
|
||||
});
|
||||
}
|
||||
} else if (step.record) {
|
||||
// Let flight outcomes that settled this frame land first.
|
||||
await Promise.resolve();
|
||||
records.push({
|
||||
step: index,
|
||||
kind: step.record,
|
||||
value: record(driver, step),
|
||||
});
|
||||
}
|
||||
}
|
||||
await Promise.resolve();
|
||||
return { records, flights: flights.map(({ startFrame, ...rest }) => rest) };
|
||||
|
||||
function record(d, step) {
|
||||
switch (step.record) {
|
||||
case 'pose':
|
||||
return tracePose(d.pose());
|
||||
case 'project':
|
||||
return step.points.map((p) => d.project(d.toEcef(p)));
|
||||
case 'pickEllipsoid':
|
||||
return step.screen.map((s) => pick3(d.pickEllipsoid(s)));
|
||||
case 'pickRay':
|
||||
return step.screen.map((s) => {
|
||||
const ray = d.pickRay(s);
|
||||
return { origin: pick3(ray.origin), direction: pick3(ray.direction) };
|
||||
});
|
||||
case 'occluded':
|
||||
return step.points.map((p) => d.occluded(d.toEcef(p)));
|
||||
case 'changed':
|
||||
return listeners.map((l) => ({
|
||||
threshold: l.threshold,
|
||||
count: l.read(),
|
||||
}));
|
||||
case 'flying':
|
||||
return { flying: d.flying(), pose: tracePose(d.pose()) };
|
||||
case 'viewRectangle':
|
||||
return d.viewRectangle();
|
||||
case 'matrices': {
|
||||
const m = d.matrices();
|
||||
const { near, far } = d.pose();
|
||||
return {
|
||||
view: [...m.view],
|
||||
projection: [...m.projection],
|
||||
near,
|
||||
// JSON has no Infinity: an infinite far plane is null. Anything
|
||||
// else that is not a number stays as it is, to fail the check.
|
||||
far: far === Infinity ? null : far,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`unknown record ${step.record}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Geodetic positions in arguments become ECEF where the command takes ECEF. */
|
||||
function resolveArgs(driver, name, args) {
|
||||
if (name === 'lookAt') return [driver.toEcef(args[0]), args[1]];
|
||||
if (name === 'flyToBounds')
|
||||
return [
|
||||
{ ...args[0], center: driver.toEcef(args[0].center) },
|
||||
...args.slice(1),
|
||||
];
|
||||
return args;
|
||||
}
|
||||
|
||||
/**
|
||||
* A driver over a renderer, through the contract only.
|
||||
* @param {import('../contract/renderer').Renderer} renderer
|
||||
* @param {{frame: () => void|Promise<void>, toEcef: (p: object) => object}} hooks
|
||||
* @returns {CameraDriver}
|
||||
*/
|
||||
export function contractDriver(renderer, hooks) {
|
||||
const camera = renderer.camera;
|
||||
return {
|
||||
command(name, args) {
|
||||
return camera[name](...args);
|
||||
},
|
||||
frame: hooks.frame,
|
||||
listen(threshold) {
|
||||
let count = 0;
|
||||
camera.on('changed', () => (count += 1), { threshold });
|
||||
return () => count;
|
||||
},
|
||||
pose: () => camera.pose(),
|
||||
project: (p) => renderer.query.project(p),
|
||||
pickEllipsoid: (s) => renderer.query.pickEllipsoid(s.x, s.y),
|
||||
pickRay: (s) => renderer.query.pickRay(s.x, s.y),
|
||||
occluded: (p) => renderer.query.isOccluded(p),
|
||||
flying: () => camera.flying,
|
||||
matrices: () => camera.matrices(),
|
||||
viewRectangle: () => camera.viewRectangle(),
|
||||
toEcef: hooks.toEcef,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
/**
|
||||
* @module render/conformance/cameraScripts
|
||||
* @description Camera scripts in the contract's own terms, each a list of
|
||||
* steps run from a fixed start: commands, frames (1/60 s each, on a clock
|
||||
* that restarts per script) and records of what the camera reports.
|
||||
*
|
||||
* The same scripts are run on the default renderer to make the reference
|
||||
* traces (`goldens/camera.json`, by `scripts/record-camera-goldens.mjs`) and
|
||||
* on a renderer under test by the conformance suite, which compares the two.
|
||||
*
|
||||
* Step kinds:
|
||||
* - `{ do: 'setView' | 'lookAt' | 'release' | 'move' | 'look' | 'rotateAround' | 'zoom', args }`
|
||||
* - `{ do: 'flyTo' | 'flyToBounds', args }`: starts a flight; its outcome and
|
||||
* the frame it ended on are recorded when it ends.
|
||||
* - `{ do: 'cancelFlight' }`
|
||||
* - `{ do: 'listen', threshold }`: counts `changed` with that threshold.
|
||||
* - `{ do: 'frames', count }`
|
||||
* - `{ record: 'pose' }`, `{ record: 'project', points }`,
|
||||
* `{ record: 'pickEllipsoid', screen }`, `{ record: 'pickRay', screen }`,
|
||||
* `{ record: 'occluded', points }`, `{ record: 'changed' }`,
|
||||
* `{ record: 'flying' }`, `{ record: 'matrices' }`, `{ record: 'viewRectangle' }`.
|
||||
*/
|
||||
|
||||
/** Where the scripts, scenes and checks look: downtown Austin, degrees. */
|
||||
export const AUSTIN = Object.freeze({ lon: -97.7431, lat: 30.2672 });
|
||||
const START = {
|
||||
do: 'setView',
|
||||
args: [
|
||||
{
|
||||
destination: { ...AUSTIN, height: 15000000 },
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const city = (height, heading, pitch, roll = 0) => ({
|
||||
do: 'setView',
|
||||
args: [
|
||||
{
|
||||
destination: { ...AUSTIN, height },
|
||||
orientation: { heading, pitch, roll },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const AUSTIN_GROUND = [
|
||||
{ lon: -97.7431, lat: 30.2672, height: 0 },
|
||||
{ lon: -97.75, lat: 30.27, height: 150 },
|
||||
{ lon: -97.735, lat: 30.26, height: 20 },
|
||||
{ lon: -97.7431, lat: 30.28, height: 0 },
|
||||
{ lon: -97.72, lat: 30.25, height: 300 },
|
||||
];
|
||||
|
||||
const SCREEN_GRID = [
|
||||
{ x: 640, y: 360 },
|
||||
{ x: 10, y: 10 },
|
||||
{ x: 1270, y: 10 },
|
||||
{ x: 10, y: 710 },
|
||||
{ x: 1270, y: 710 },
|
||||
{ x: 320, y: 540 },
|
||||
];
|
||||
|
||||
/** The viewport every script runs in, CSS pixels. */
|
||||
export const SCRIPT_VIEWPORT = Object.freeze({ width: 1280, height: 720 });
|
||||
|
||||
/** @type {ReadonlyArray<{name: string, steps: object[]}>} */
|
||||
export const CAMERA_SCRIPTS = Object.freeze([
|
||||
{
|
||||
name: 'setView angles',
|
||||
steps: [
|
||||
START,
|
||||
{ record: 'pose' },
|
||||
city(600, 0.3, -0.6),
|
||||
{ record: 'pose' },
|
||||
city(600, 5.9, -0.2, 0.15),
|
||||
{ record: 'pose' },
|
||||
city(25000, 3.1, -1.2),
|
||||
{ record: 'pose' },
|
||||
{
|
||||
do: 'setView',
|
||||
args: [
|
||||
{
|
||||
destination: { lon: 12.5, lat: 89.95, height: 40000 },
|
||||
orientation: { heading: 1.0, pitch: -0.7, roll: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ record: 'pose' },
|
||||
{
|
||||
do: 'setView',
|
||||
args: [
|
||||
{
|
||||
destination: { lon: 151.2, lat: -33.87, height: 2000 },
|
||||
orientation: { heading: 0.0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'view rectangles',
|
||||
steps: [
|
||||
START,
|
||||
{ record: 'viewRectangle' },
|
||||
...[
|
||||
[5000, 0, -Math.PI / 2],
|
||||
[2000, 0, -0.3],
|
||||
[600, 0.3, -0.6],
|
||||
[2000, 0, 1.2],
|
||||
[15000000, 0, Math.PI / 2],
|
||||
].flatMap(([height, heading, pitch]) => [
|
||||
city(height, heading, pitch),
|
||||
{ record: 'viewRectangle' },
|
||||
]),
|
||||
...[
|
||||
{ lon: 0, lat: 89.9, height: 1000000 },
|
||||
{ lon: 180, lat: 10, height: 2000000 },
|
||||
].flatMap((destination) => [
|
||||
{ do: 'setView', args: [{ destination }] },
|
||||
{ record: 'viewRectangle' },
|
||||
]),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'view and projection matrices',
|
||||
steps: [
|
||||
START,
|
||||
{ record: 'matrices' },
|
||||
city(600, 0.3, -0.6, 0.1),
|
||||
{ record: 'matrices' },
|
||||
city(25000, 3.1, -1.2),
|
||||
{ record: 'matrices' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'setView keeps the position when only orientation is given',
|
||||
steps: [
|
||||
START,
|
||||
city(800, 1.0, -0.5),
|
||||
{
|
||||
do: 'setView',
|
||||
args: [{ orientation: { heading: 2.0, pitch: -0.3, roll: 0 } }],
|
||||
},
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'lookAt sweep and release',
|
||||
steps: [
|
||||
START,
|
||||
...Array.from({ length: 12 }, (_, i) => [
|
||||
{
|
||||
do: 'lookAt',
|
||||
args: [
|
||||
{ ...AUSTIN, height: 0 },
|
||||
{ heading: (i * Math.PI) / 6, pitch: -0.4, range: 2000 },
|
||||
],
|
||||
},
|
||||
{ record: 'pose' },
|
||||
]).flat(),
|
||||
{ do: 'release' },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'move, look, rotate and zoom',
|
||||
steps: [
|
||||
START,
|
||||
city(600, 0.3, -0.6),
|
||||
{ do: 'move', args: ['forward', 100] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'move', args: ['right', 50] },
|
||||
{ do: 'move', args: ['up', 20] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'look', args: ['left', 0.1] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'look', args: ['up', 0.05] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'rotateAround', args: [{ x: 0, y: 0, z: 1 }, 0.01] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'zoom', args: [200] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'move', args: ['back', 300] },
|
||||
{ do: 'look', args: ['down', 0.2] },
|
||||
{ do: 'look', args: ['right', 0.3] },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'commands inside a lookAt frame',
|
||||
steps: [
|
||||
START,
|
||||
{
|
||||
do: 'lookAt',
|
||||
args: [
|
||||
{ ...AUSTIN, height: 0 },
|
||||
{ heading: 0.7, pitch: -0.5, range: 3000 },
|
||||
],
|
||||
},
|
||||
{ do: 'move', args: ['forward', 500] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'rotateAround', args: [{ x: 0, y: 0, z: 1 }, 0.4] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'zoom', args: [-1000] },
|
||||
{ record: 'pose' },
|
||||
{ do: 'release' },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'flyTo from orbit, default orientation and duration',
|
||||
steps: [
|
||||
START,
|
||||
{ do: 'flyTo', args: [{ ...AUSTIN, height: 600 }] },
|
||||
{ do: 'frames', count: 45 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 60 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 135 },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'flyTo with duration and orientation',
|
||||
steps: [
|
||||
START,
|
||||
city(5000, 0, -1.0),
|
||||
{
|
||||
do: 'flyTo',
|
||||
args: [
|
||||
{ lon: -97.7, lat: 30.3, height: 1200 },
|
||||
{
|
||||
durationS: 2,
|
||||
orientation: { heading: 1.2, pitch: -0.35, roll: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ do: 'frames', count: 40 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 110 },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'flyTo with a height cap, pitch adjustment and named easings',
|
||||
steps: [
|
||||
START,
|
||||
city(3000, 0.5, -0.4),
|
||||
{
|
||||
do: 'flyTo',
|
||||
args: [
|
||||
{ lon: 2.35, lat: 48.86, height: 2000 },
|
||||
{
|
||||
durationS: 3,
|
||||
easing: 'linear',
|
||||
pitchAdjustHeight: 500000,
|
||||
// Not straight down: there heading is ill-conditioned, and the
|
||||
// next flight would start from a last-bit difference in it.
|
||||
orientation: { heading: 0.2, pitch: -0.6, roll: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ do: 'frames', count: 50 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 50 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 100 },
|
||||
{ record: 'pose' },
|
||||
{
|
||||
do: 'flyTo',
|
||||
args: [
|
||||
{ lon: 2.4, lat: 48.9, height: 800 },
|
||||
{ durationS: 1, easing: 'cubicOut', maxHeight: 50000 },
|
||||
],
|
||||
},
|
||||
{ do: 'frames', count: 20 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 50 },
|
||||
{ record: 'pose' },
|
||||
{
|
||||
do: 'flyTo',
|
||||
args: [
|
||||
{ lon: 2.3, lat: 48.8, height: 1500 },
|
||||
{ durationS: 1, easing: 'quadraticInOut' },
|
||||
],
|
||||
},
|
||||
{ do: 'frames', count: 25 },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 50 },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'flyTo with a duration of 0 completes inside the call',
|
||||
steps: [
|
||||
START,
|
||||
{ do: 'flyTo', args: [{ ...AUSTIN, height: 900 }, { durationS: 0 }] },
|
||||
{ record: 'flying' },
|
||||
{ do: 'frames', count: 3 },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'flyTo where the camera already is completes inside the call',
|
||||
steps: [
|
||||
city(600, 0.3, -0.6),
|
||||
{
|
||||
do: 'flyTo',
|
||||
args: [
|
||||
{ ...AUSTIN, height: 600 },
|
||||
{ orientation: { heading: 0.3, pitch: -0.6, roll: 0 } },
|
||||
],
|
||||
},
|
||||
{ record: 'flying' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'rectangle destinations',
|
||||
steps: [
|
||||
START,
|
||||
...[
|
||||
{ west: -98, south: 30, east: -97.5, north: 30.4 },
|
||||
{ west: -10, south: 0, east: 40, north: 60 },
|
||||
{ west: -60, south: -20, east: 10, north: 60 },
|
||||
{ west: 170, south: -50, east: -170, north: -30 },
|
||||
{ west: -30, south: -89.5, east: 30, north: 89.5 },
|
||||
].flatMap((rect) => [
|
||||
{ do: 'setView', args: [{ destination: { rect } }] },
|
||||
{ record: 'pose' },
|
||||
]),
|
||||
{
|
||||
do: 'setView',
|
||||
args: [
|
||||
{
|
||||
destination: { rect: { west: 2, south: 48, east: 3, north: 49 } },
|
||||
orientation: { heading: 0.5, pitch: -0.9, roll: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ record: 'pose' },
|
||||
{
|
||||
do: 'flyTo',
|
||||
args: [
|
||||
{ rect: { west: -10, south: 0, east: 40, north: 60 } },
|
||||
{ durationS: 1 },
|
||||
],
|
||||
},
|
||||
{ do: 'frames', count: 70 },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'flyToBounds default offset and explicit offset',
|
||||
steps: [
|
||||
START,
|
||||
{
|
||||
do: 'flyToBounds',
|
||||
args: [{ center: { ...AUSTIN, height: 0 }, radius: 500 }],
|
||||
},
|
||||
{ do: 'frames', count: 240 },
|
||||
{ record: 'pose' },
|
||||
{
|
||||
do: 'flyToBounds',
|
||||
args: [
|
||||
{ center: { ...AUSTIN, height: 0 }, radius: 500 },
|
||||
{ offset: { heading: 1.0, pitch: -0.3, range: 3000 }, durationS: 1 },
|
||||
],
|
||||
},
|
||||
{ do: 'frames', count: 90 },
|
||||
{ record: 'pose' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'a cancelled flight stops where it was',
|
||||
steps: [
|
||||
START,
|
||||
{ do: 'flyTo', args: [{ ...AUSTIN, height: 600 }, { durationS: 3 }] },
|
||||
{ do: 'frames', count: 30 },
|
||||
{ do: 'cancelFlight' },
|
||||
{ do: 'frames', count: 5 },
|
||||
{ record: 'flying' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'changed fires by each listener’s threshold',
|
||||
steps: [
|
||||
START,
|
||||
city(2000, 0, -0.5),
|
||||
{ do: 'listen', threshold: 0.5 },
|
||||
{ do: 'listen', threshold: 0.1 },
|
||||
{ do: 'frames', count: 1 },
|
||||
...Array.from({ length: 24 }, () => [
|
||||
{ do: 'look', args: ['right', 0.05] },
|
||||
{ do: 'frames', count: 1 },
|
||||
]).flat(),
|
||||
{ record: 'changed' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'projection, picks and the horizon',
|
||||
steps: [
|
||||
START,
|
||||
city(600, 0.3, -0.6),
|
||||
{ record: 'project', points: AUSTIN_GROUND },
|
||||
{ record: 'pickEllipsoid', screen: SCREEN_GRID },
|
||||
{ record: 'pickRay', screen: SCREEN_GRID },
|
||||
START,
|
||||
{
|
||||
record: 'occluded',
|
||||
points: [
|
||||
{ lon: -97.7431, lat: 30.2672, height: 0 },
|
||||
{ lon: 82.26, lat: -30.27, height: 0 },
|
||||
{ lon: -97.7431, lat: -55, height: 0 },
|
||||
{ lon: -10, lat: 30, height: 0 },
|
||||
{ lon: -10, lat: 30, height: 2000000 },
|
||||
{ lon: 170, lat: 10, height: 30000000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,505 @@
|
||||
/**
|
||||
* Camera checks: the reference traces, then flight, hold, event, follow and
|
||||
* view rules the traces cannot show.
|
||||
*/
|
||||
import goldens from '../goldens/camera.json' with { type: 'json' };
|
||||
import { CAMERA_SCRIPTS, SCRIPT_VIEWPORT } from '../cameraScripts.js';
|
||||
import { contractDriver, runCameraScript } from '../cameraRunner.js';
|
||||
import { deepEqual, equal, near, nearAngle, nearVec, ok } from '../expect.js';
|
||||
|
||||
const lonLatToEcef = (h) => h.toEcef;
|
||||
|
||||
function comparePose(actual, expected, tol, where) {
|
||||
nearVec(actual.position, expected.position, tol.metres, `${where} position`);
|
||||
nearVec(actual.direction, expected.direction, tol.unit, `${where} direction`);
|
||||
nearVec(actual.up, expected.up, tol.unit, `${where} up`);
|
||||
nearVec(actual.right, expected.right, tol.unit, `${where} right`);
|
||||
nearAngle(actual.heading, expected.heading, tol.radians, `${where} heading`);
|
||||
// Pitch is compared by its sine: straight up or down, the angle itself
|
||||
// turns a last-bit difference in direction into ~1e-8 rad.
|
||||
near(
|
||||
Math.sin(actual.pitch),
|
||||
Math.sin(expected.pitch),
|
||||
tol.radians,
|
||||
`${where} sin(pitch)`,
|
||||
);
|
||||
nearAngle(actual.roll, expected.roll, tol.radians, `${where} roll`);
|
||||
near(actual.height, expected.height, tol.metres, `${where} height`);
|
||||
equal(
|
||||
actual.frameIsIdentity,
|
||||
expected.frameIsIdentity,
|
||||
`${where} frameIsIdentity`,
|
||||
);
|
||||
}
|
||||
|
||||
function compareRecord(actual, expected, tol, where, flightPaths) {
|
||||
equal(actual.kind, expected.kind, `${where} kind`);
|
||||
const a = actual.value;
|
||||
const e = expected.value;
|
||||
switch (expected.kind) {
|
||||
case 'pose':
|
||||
comparePose(a, e, tol, where);
|
||||
break;
|
||||
case 'project':
|
||||
e.forEach((s, i) => nearVec(a[i], s, tol.pixels, `${where} point ${i}`));
|
||||
break;
|
||||
case 'pickEllipsoid':
|
||||
e.forEach((p, i) => nearVec(a[i], p, tol.metres, `${where} pick ${i}`));
|
||||
break;
|
||||
case 'pickRay':
|
||||
e.forEach((r, i) => {
|
||||
nearVec(a[i].origin, r.origin, tol.metres, `${where} ray ${i} origin`);
|
||||
nearVec(
|
||||
a[i].direction,
|
||||
r.direction,
|
||||
tol.unit,
|
||||
`${where} ray ${i} direction`,
|
||||
);
|
||||
});
|
||||
break;
|
||||
case 'occluded':
|
||||
deepEqual(a, e, `${where} occluded`);
|
||||
break;
|
||||
case 'changed':
|
||||
e.forEach((c, i) =>
|
||||
near(
|
||||
a[i].count,
|
||||
c.count,
|
||||
tol.changedCount,
|
||||
`${where} changed at ${c.threshold}`,
|
||||
),
|
||||
);
|
||||
break;
|
||||
case 'viewRectangle':
|
||||
equal(a === null, e === null, `${where} viewRectangle null`);
|
||||
if (e)
|
||||
for (const side of ['west', 'south', 'east', 'north'])
|
||||
near(
|
||||
a[side],
|
||||
e[side],
|
||||
(tol.radians * 180) / Math.PI,
|
||||
`${where} viewRectangle ${side}`,
|
||||
);
|
||||
break;
|
||||
case 'matrices': {
|
||||
// The view's last column is a translation in metres; the rest is unit.
|
||||
e.view.forEach((v, i) =>
|
||||
near(
|
||||
a.view[i],
|
||||
v,
|
||||
i >= 12 ? tol.metres : tol.unit,
|
||||
`${where} view[${i}]`,
|
||||
),
|
||||
);
|
||||
// Depth terms come from the renderer's own near and far planes (the
|
||||
// contract fixes neither, and allows an infinite far plane).
|
||||
const n = a.near;
|
||||
const f = a.far;
|
||||
ok(Number.isFinite(n) && n > 0, `${where} near is a positive number`);
|
||||
ok(
|
||||
f === null || (Number.isFinite(f) && f > n),
|
||||
`${where} far is beyond near, or infinite`,
|
||||
);
|
||||
const depth =
|
||||
f === null
|
||||
? { 10: -1, 14: -2 * n }
|
||||
: { 10: -(f + n) / (f - n), 14: (-2 * f * n) / (f - n) };
|
||||
e.projection.forEach((v, i) =>
|
||||
near(
|
||||
a.projection[i],
|
||||
depth[i] ?? v,
|
||||
tol.unit * Math.max(1, Math.abs(depth[i] ?? v)),
|
||||
`${where} projection[${i}]`,
|
||||
),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'flying':
|
||||
equal(a.flying, e.flying, `${where} flying`);
|
||||
if (flightPaths === 'trace') comparePose(a.pose, e.pose, tol, where);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`unknown record ${expected.kind}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {import('../index.js').ConformanceHarness} h */
|
||||
async function fresh(h) {
|
||||
return h.create({ viewport: SCRIPT_VIEWPORT });
|
||||
}
|
||||
|
||||
export function cameraChecks() {
|
||||
const traceChecks = CAMERA_SCRIPTS.map((script) => ({
|
||||
id: `camera.trace.${script.name}`,
|
||||
port: 'camera',
|
||||
title: `reference trace: ${script.name}`,
|
||||
async run(h) {
|
||||
const expected = goldens.scripts[script.name];
|
||||
ok(expected, `no reference trace for ${script.name}`);
|
||||
const r = await fresh(h);
|
||||
try {
|
||||
const run = await runCameraScript(
|
||||
contractDriver(r, {
|
||||
frame: () => h.frame(r),
|
||||
toEcef: lonLatToEcef(h),
|
||||
}),
|
||||
script,
|
||||
);
|
||||
equal(run.records.length, expected.records.length, 'record count');
|
||||
run.records.forEach((record, i) =>
|
||||
compareRecord(
|
||||
record,
|
||||
expected.records[i],
|
||||
h.tolerance,
|
||||
`${script.name} step ${expected.records[i].step}`,
|
||||
h.flightPaths,
|
||||
),
|
||||
);
|
||||
equal(run.flights.length, expected.flights.length, 'flight count');
|
||||
run.flights.forEach((f, i) => {
|
||||
equal(f.outcome, expected.flights[i].outcome, `flight ${i} outcome`);
|
||||
near(f.frames, expected.flights[i].frames, 1, `flight ${i} frames`);
|
||||
});
|
||||
} finally {
|
||||
r.destroy();
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
return [
|
||||
...traceChecks,
|
||||
{
|
||||
id: 'camera.flight.callbacks',
|
||||
port: 'camera',
|
||||
title: 'flight callbacks run synchronously; a new flight cancels the old',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const events = [];
|
||||
const first = r.camera.flyTo(
|
||||
{ lon: 0, lat: 0, height: 1e6 },
|
||||
{
|
||||
durationS: 1,
|
||||
onCancel: () => events.push('cancel1'),
|
||||
onComplete: () => events.push('done1'),
|
||||
},
|
||||
);
|
||||
ok(r.camera.flying, 'flying after flyTo');
|
||||
r.camera.flyTo(
|
||||
{ lon: 1, lat: 1, height: 1e6 },
|
||||
{ durationS: 0.5, onComplete: () => events.push('done2') },
|
||||
);
|
||||
deepEqual(
|
||||
events,
|
||||
['cancel1'],
|
||||
'the first flight was cancelled inside the second flyTo',
|
||||
);
|
||||
equal(await first.done, 'cancelled', 'first outcome');
|
||||
for (let i = 0; i < 40 && r.camera.flying; i++) await h.frame(r);
|
||||
deepEqual(events, ['cancel1', 'done2'], 'the second completed');
|
||||
ok(!r.camera.flying, 'not flying after completion');
|
||||
const third = r.camera.flyTo(
|
||||
{ lon: 2, lat: 2, height: 1e6 },
|
||||
{ durationS: 1, onCancel: () => events.push('cancel3') },
|
||||
);
|
||||
r.camera.cancelFlight();
|
||||
equal(
|
||||
events.at(-1),
|
||||
'cancel3',
|
||||
'cancelFlight runs onCancel inside the call',
|
||||
);
|
||||
equal(await third.done, 'cancelled', 'third outcome');
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.controls.holds',
|
||||
port: 'camera',
|
||||
title:
|
||||
'camera input holds are counted; a flight ending gives back only its own',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
ok(r.camera.controls.enabled, 'enabled at start');
|
||||
const release = r.input.suspendCameraControls('drag');
|
||||
ok(!r.camera.controls.enabled, 'a hold disables input');
|
||||
r.camera.flyTo({ lon: 0, lat: 0, height: 1e6 }, { durationS: 0.1 });
|
||||
for (let i = 0; i < 20 && r.camera.flying; i++) await h.frame(r);
|
||||
ok(!r.camera.flying, 'the flight ended');
|
||||
ok(!r.camera.controls.enabled, 'the drag hold survives the flight end');
|
||||
const second = r.camera.controls.suspend('cockpit');
|
||||
release();
|
||||
release();
|
||||
ok(!r.camera.controls.enabled, 'one hold still out');
|
||||
second();
|
||||
ok(r.camera.controls.enabled, 'enabled with no holds out');
|
||||
const [min, max] = r.camera.controls.pitchRange;
|
||||
ok(
|
||||
-Math.PI / 2 <= min && min <= max && max <= Math.PI / 2,
|
||||
'pitchRange is an ordered range of pitches',
|
||||
);
|
||||
r.camera.controls.pitchRange = [-1.2, -0.1];
|
||||
deepEqual(
|
||||
[...r.camera.controls.pitchRange],
|
||||
[-1.2, -0.1],
|
||||
'pitchRange is settable',
|
||||
);
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.onCommand',
|
||||
port: 'camera',
|
||||
title: 'every camera command is announced before it runs',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const seen = [];
|
||||
const off = r.camera.onCommand((c) => seen.push(c.kind));
|
||||
const target = h.toEcef({ lon: 0, lat: 0, height: 0 });
|
||||
r.camera.setView({ destination: { lon: 0, lat: 0, height: 1000 } });
|
||||
r.camera.lookAt(target, { heading: 0, pitch: -0.5, range: 1000 });
|
||||
r.camera.release();
|
||||
r.camera.flyTo({ lon: 1, lat: 1, height: 1000 }, { durationS: 1 });
|
||||
r.camera.cancelFlight();
|
||||
r.camera.flyToBounds({ center: target, radius: 10 }, { durationS: 1 });
|
||||
r.camera.cancelFlight();
|
||||
r.camera.follow({
|
||||
key: 'k',
|
||||
position: () => target,
|
||||
frame: 'enu',
|
||||
viewFrom: { x: 0, y: -100, z: 100 },
|
||||
});
|
||||
off();
|
||||
r.camera.follow(null);
|
||||
deepEqual(
|
||||
seen,
|
||||
[
|
||||
'setView',
|
||||
'lookAt',
|
||||
'release',
|
||||
'flyTo',
|
||||
'cancelFlight',
|
||||
'flyToBounds',
|
||||
'cancelFlight',
|
||||
'follow',
|
||||
],
|
||||
'commands',
|
||||
);
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.moveEnd',
|
||||
port: 'camera',
|
||||
title: 'moveStart on movement; moveEnd 500 ms after the last change',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const events = [];
|
||||
r.camera.on('moveStart', () => events.push(['start', h.now(r)]));
|
||||
r.camera.on('moveEnd', () => events.push(['end', h.now(r)]));
|
||||
await h.frame(r);
|
||||
r.camera.move('forward', 1000);
|
||||
await h.frame(r);
|
||||
equal(events[0]?.[0], 'start', 'moveStart after the move');
|
||||
const movedAt = h.now(r);
|
||||
for (let i = 0; i < 45; i++) await h.frame(r);
|
||||
const end = events.find(([kind]) => kind === 'end');
|
||||
ok(end, 'moveEnd fired');
|
||||
ok(
|
||||
end[1] - movedAt >= 500 - 1e-6,
|
||||
`moveEnd waited 500 ms (${end[1] - movedAt})`,
|
||||
);
|
||||
ok(
|
||||
end[1] - movedAt < 500 + 2 * (1000 / 60) + 1e-6,
|
||||
'moveEnd came within two frames of 500 ms',
|
||||
);
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.follow',
|
||||
port: 'camera',
|
||||
title: 'a follow keeps the eye at its offset from a moving target',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const changes = [];
|
||||
r.camera.on('followChanged', () =>
|
||||
changes.push(r.camera.followed?.key ?? null),
|
||||
);
|
||||
const base = h.toEcef({ lon: -97.74, lat: 30.27, height: 1000 });
|
||||
const start = r.frame.time();
|
||||
const target = {
|
||||
key: 'test:mover',
|
||||
position: (t) => ({
|
||||
x: base.x + (t - start) * 0.2,
|
||||
y: base.y,
|
||||
z: base.z,
|
||||
}),
|
||||
frame: 'enu',
|
||||
viewFrom: { x: 0, y: -800, z: 400 },
|
||||
};
|
||||
r.camera.follow(target);
|
||||
equal(r.camera.followed, target, 'followed');
|
||||
await h.frame(r);
|
||||
ok(r.camera.followFramed, 'framed after a frame');
|
||||
const range0 = dist(
|
||||
r.camera.pose().position,
|
||||
target.position(r.frame.time()),
|
||||
);
|
||||
near(range0, Math.hypot(800, 400), 1, 'starting range');
|
||||
for (let i = 0; i < 30; i++) {
|
||||
r.frame.setTime(r.frame.time() + 1000);
|
||||
await h.frame(r);
|
||||
near(
|
||||
dist(r.camera.pose().position, target.position(r.frame.time())),
|
||||
range0,
|
||||
1e-3 * range0,
|
||||
`range at frame ${i}`,
|
||||
);
|
||||
}
|
||||
r.camera.follow(null);
|
||||
equal(r.camera.followed, null, 'cleared');
|
||||
ok(r.camera.pose().frameIsIdentity, 'back in the world frame');
|
||||
deepEqual(changes, ['test:mover', null], 'followChanged');
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.rect',
|
||||
port: 'camera',
|
||||
title:
|
||||
'a rectangle destination looks straight down and keeps the whole rectangle in view',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const rect = { west: -98, south: 30, east: -97.5, north: 30.4 };
|
||||
r.camera.setView({ destination: { rect } });
|
||||
await h.frame(r);
|
||||
const pose = r.camera.pose();
|
||||
near(pose.pitch, -Math.PI / 2, 1e-3, 'pitch');
|
||||
for (const [lon, lat] of [
|
||||
[rect.west, rect.north],
|
||||
[rect.east, rect.north],
|
||||
[rect.west, rect.south],
|
||||
[rect.east, rect.south],
|
||||
]) {
|
||||
const s = r.query.project(h.toEcef({ lon, lat, height: 0 }));
|
||||
ok(
|
||||
s &&
|
||||
s.x >= -1 &&
|
||||
s.x <= SCRIPT_VIEWPORT.width + 1 &&
|
||||
s.y >= -1 &&
|
||||
s.y <= SCRIPT_VIEWPORT.height + 1,
|
||||
`corner ${lon},${lat} in view (${JSON.stringify(s)})`,
|
||||
);
|
||||
}
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.viewRectangle',
|
||||
port: 'camera',
|
||||
title:
|
||||
'viewRectangle holds the ground in view, is the whole globe from afar, null facing away',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
const at = async (height, pitch = -Math.PI / 2) => {
|
||||
r.camera.setView({
|
||||
destination: { lon: -97.74, lat: 30.27, height },
|
||||
orientation: { heading: 0, pitch, roll: 0 },
|
||||
});
|
||||
await h.frame(r);
|
||||
return r.camera.viewRectangle();
|
||||
};
|
||||
const down = await at(5000);
|
||||
ok(
|
||||
down &&
|
||||
down.west < -97.74 &&
|
||||
down.east > -97.74 &&
|
||||
down.south < 30.27 &&
|
||||
down.north > 30.27 &&
|
||||
down.east - down.west < 0.2,
|
||||
`straight down holds the centre (${JSON.stringify(down)})`,
|
||||
);
|
||||
const tilted = await at(2000, -0.3);
|
||||
ok(tilted && tilted.north > 30.3, 'tilted: cut at the horizon');
|
||||
deepEqual(
|
||||
await at(15000000),
|
||||
{ west: -180, south: -90, east: 180, north: 90 },
|
||||
'from afar: the whole globe',
|
||||
);
|
||||
equal(await at(15000000, Math.PI / 2), null, 'facing away: null');
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.followItem',
|
||||
port: 'camera',
|
||||
title: 'following a drawn item tracks where the renderer draws it',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
if (!r.capabilities.has('motionSegments')) {
|
||||
r.destroy();
|
||||
return { skip: 'no motionSegments' };
|
||||
}
|
||||
const t0 = r.frame.time();
|
||||
const from = h.toEcef({ lon: -97.74, lat: 30.27, height: 1000 });
|
||||
const to = h.toEcef({ lon: -97.7, lat: 30.27, height: 1000 });
|
||||
const set = r.draw.icons({
|
||||
id: 'conf:follow',
|
||||
motionClock: { kind: 'scene' },
|
||||
});
|
||||
set.set([
|
||||
{
|
||||
id: 'm',
|
||||
pos: from,
|
||||
image: 'data:,',
|
||||
size: [16, 16],
|
||||
motion: { kind: 'lerp', from, to, t0, t1: t0 + 60000 },
|
||||
},
|
||||
]);
|
||||
r.camera.follow({
|
||||
key: 'conf:follow:m',
|
||||
// Deliberately stale: the drawn item is the answer.
|
||||
position: () => from,
|
||||
item: { set: 'conf:follow', id: 'm' },
|
||||
frame: 'enu',
|
||||
viewFrom: { x: 0, y: -500, z: 300 },
|
||||
});
|
||||
await h.frame(r);
|
||||
const range0 = dist(r.camera.pose().position, from);
|
||||
r.frame.setTime(t0 + 30000);
|
||||
await h.frame(r);
|
||||
const mid = {
|
||||
x: (from.x + to.x) / 2,
|
||||
y: (from.y + to.y) / 2,
|
||||
z: (from.z + to.z) / 2,
|
||||
};
|
||||
near(
|
||||
dist(r.camera.pose().position, mid),
|
||||
range0,
|
||||
1,
|
||||
'the eye keeps its range from the drawn position',
|
||||
);
|
||||
set.dispose();
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'camera.fov',
|
||||
port: 'camera',
|
||||
title: 'setFov sets the vertical field of view',
|
||||
async run(h) {
|
||||
const r = await fresh(h);
|
||||
r.camera.setFov({ vertical: 0.5 });
|
||||
near(r.camera.pose().fovy, 0.5, 1e-12, 'fovy');
|
||||
near(
|
||||
r.camera.pose().aspectRatio,
|
||||
SCRIPT_VIEWPORT.width / SCRIPT_VIEWPORT.height,
|
||||
1e-9,
|
||||
'aspect',
|
||||
);
|
||||
r.destroy();
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* @module render/conformance/expect
|
||||
* @description Assertions for the conformance suite. Plain functions that
|
||||
* throw, so the suite runs in Node and in a browser page alike.
|
||||
*/
|
||||
|
||||
export class ConformanceError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'ConformanceError';
|
||||
}
|
||||
}
|
||||
|
||||
export function ok(value, message) {
|
||||
if (!value) throw new ConformanceError(message);
|
||||
}
|
||||
|
||||
export function equal(actual, expected, message) {
|
||||
if (!Object.is(actual, expected))
|
||||
throw new ConformanceError(
|
||||
`${message}: expected ${show(expected)}, got ${show(actual)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function deepEqual(actual, expected, message) {
|
||||
if (JSON.stringify(actual) !== JSON.stringify(expected))
|
||||
throw new ConformanceError(
|
||||
`${message}: expected ${show(expected)}, got ${show(actual)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function near(actual, expected, tolerance, message) {
|
||||
if (
|
||||
!(Number.isFinite(actual) && Number.isFinite(expected)) ||
|
||||
Math.abs(actual - expected) > tolerance
|
||||
)
|
||||
throw new ConformanceError(
|
||||
`${message}: expected ${expected} ± ${tolerance}, got ${actual}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Angles in radians, compared around the circle. */
|
||||
export function nearAngle(actual, expected, tolerance, message) {
|
||||
const tau = Math.PI * 2;
|
||||
let d = Math.abs(actual - expected) % tau;
|
||||
if (d > Math.PI) d = tau - d;
|
||||
if (!(d <= tolerance))
|
||||
throw new ConformanceError(
|
||||
`${message}: expected ${expected} ± ${tolerance} rad, got ${actual}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function nearVec(actual, expected, tolerance, message) {
|
||||
if (actual === null || expected === null) {
|
||||
equal(actual, expected, message);
|
||||
return;
|
||||
}
|
||||
const d = Math.hypot(
|
||||
actual.x - expected.x,
|
||||
actual.y - expected.y,
|
||||
(actual.z ?? 0) - (expected.z ?? 0),
|
||||
);
|
||||
if (!(d <= tolerance))
|
||||
throw new ConformanceError(
|
||||
`${message}: ${show(actual)} is ${d} from ${show(expected)} (± ${tolerance})`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function rejects(promiseOrFn, message) {
|
||||
try {
|
||||
await (typeof promiseOrFn === 'function' ? promiseOrFn() : promiseOrFn);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
throw new ConformanceError(`${message}: did not throw`);
|
||||
}
|
||||
|
||||
export function throws(fn, message) {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
throw new ConformanceError(`${message}: did not throw`);
|
||||
}
|
||||
|
||||
function show(value) {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 9.8 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"renderer": "cesium",
|
||||
"size": {
|
||||
"width": 640,
|
||||
"height": 360
|
||||
},
|
||||
"views": [
|
||||
"icons-top.png",
|
||||
"icons-tilted.png",
|
||||
"points-top.png",
|
||||
"lines-top.png",
|
||||
"lines-tilted.png",
|
||||
"shapes-top.png",
|
||||
"shapes-tilted.png",
|
||||
"models-oblique.png",
|
||||
"city-orbit.png",
|
||||
"city-city.png",
|
||||
"city-street.png"
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* @module render/conformance
|
||||
* @description The renderer conformance suite. It runs every check against
|
||||
* a renderer through the contract alone, in Node or in a browser page, and
|
||||
* reports each as passed, failed or skipped.
|
||||
*
|
||||
* A harness says how to make the renderer under test and drive its clock:
|
||||
*
|
||||
* ```js
|
||||
* const report = await runConformance({
|
||||
* name: 'stub',
|
||||
* create: ({ viewport, capabilities }) => makeRenderer(...),
|
||||
* frame: (r) => advanceOneFrame(r), // 1/60 s on a virtual clock
|
||||
* now: (r) => clockMs(r),
|
||||
* toEcef: ({ lon, lat, height }) => ecef,
|
||||
* tolerance: DEFAULT_TOLERANCE,
|
||||
* flightPaths: 'trace', // or 'endpoints'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Optional harness members widen what is checked: `pointer(r, type, x, y)`
|
||||
* (synthetic input), `scriptHeights(r, fn)` (heights from a function),
|
||||
* `wallTime(r)` (the wall clock a `live` motion clock reads),
|
||||
* `assets.model` (a glTF URL). `create` may return null when it cannot
|
||||
* make a renderer with fewer capabilities; those checks are then skipped.
|
||||
*/
|
||||
import { cameraChecks } from './checks/camera.js';
|
||||
import { portChecks } from './checks/ports.js';
|
||||
|
||||
/**
|
||||
* @typedef {object} ConformanceTolerance
|
||||
* @property {number} metres Positions and heights.
|
||||
* @property {number} unit Unit vectors (direction, up, right).
|
||||
* @property {number} radians Heading, pitch and roll.
|
||||
* @property {number} pixels Screen positions.
|
||||
* @property {number} changedCount `changed` events per script.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} ConformanceHarness
|
||||
* @property {string} name
|
||||
* @property {(options: {viewport: {width: number, height: number}, capabilities?: string[]}) => Promise<import('../contract/renderer').Renderer|null>} create
|
||||
* @property {(r: import('../contract/renderer').Renderer) => void|Promise<void>} frame
|
||||
* @property {(r: import('../contract/renderer').Renderer) => number} now
|
||||
* @property {(p: {lon: number, lat: number, height?: number}) => {x: number, y: number, z: number}} toEcef
|
||||
* @property {ConformanceTolerance} tolerance
|
||||
* @property {'trace'|'endpoints'} flightPaths Whether flight paths are compared frame by frame, or only where flights end.
|
||||
* @property {(r: object, type: string, x: number, y: number, extra?: object) => void|Promise<void>} [pointer]
|
||||
* @property {(r: object, fn: (point: {lon: number, lat: number}, against?: string) => number|null) => void} [scriptHeights]
|
||||
* @property {(r: object) => number} [wallTime] Epoch ms the renderer's `live` motion clock reads.
|
||||
* @property {{model?: string}} [assets]
|
||||
*/
|
||||
|
||||
/**
|
||||
* Tolerances the renderer meets when it reproduces the reference camera: under a
|
||||
* millimetre at city scale, well under a pixel on screen.
|
||||
* @type {Readonly<ConformanceTolerance>}
|
||||
*/
|
||||
export const DEFAULT_TOLERANCE = Object.freeze({
|
||||
metres: 1e-3,
|
||||
unit: 1e-9,
|
||||
radians: 1e-9,
|
||||
pixels: 1e-3,
|
||||
changedCount: 0,
|
||||
});
|
||||
|
||||
/** Every check, in run order. */
|
||||
export function conformanceChecks() {
|
||||
return [...portChecks(), ...cameraChecks()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ConformanceHarness} harness
|
||||
* @param {{only?: (id: string) => boolean}} [options]
|
||||
* @returns {Promise<{harness: string, passed: number, failed: number, skipped: number,
|
||||
* results: Array<{id: string, port: string, title: string, status: 'pass'|'fail'|'skip', detail?: string, ms: number}>}>}
|
||||
*/
|
||||
export async function runConformance(harness, options = {}) {
|
||||
const results = [];
|
||||
for (const c of conformanceChecks()) {
|
||||
if (options.only && !options.only(c.id)) continue;
|
||||
const start = Date.now();
|
||||
let status = 'pass';
|
||||
let detail;
|
||||
try {
|
||||
const outcome = await c.run(harness);
|
||||
if (outcome?.skip) {
|
||||
status = 'skip';
|
||||
detail = outcome.skip;
|
||||
}
|
||||
} catch (error) {
|
||||
status = 'fail';
|
||||
detail = error?.message ?? String(error);
|
||||
}
|
||||
results.push({
|
||||
id: c.id,
|
||||
port: c.port,
|
||||
title: c.title,
|
||||
status,
|
||||
...(detail ? { detail } : {}),
|
||||
ms: Date.now() - start,
|
||||
});
|
||||
}
|
||||
const count = (s) => results.filter((r) => r.status === s).length;
|
||||
return {
|
||||
harness: harness.name,
|
||||
passed: count('pass'),
|
||||
failed: count('fail'),
|
||||
skipped: count('skip'),
|
||||
results,
|
||||
};
|
||||
}
|
||||
|
||||
export { CAMERA_SCRIPTS, SCRIPT_VIEWPORT } from './cameraScripts.js';
|
||||
export { CALIBRATION_PATH, REFERENCE_SCENES, sceneSupport } from './scenes.js';
|
||||
export {
|
||||
VISUAL_TOLERANCE,
|
||||
compareImages,
|
||||
drawScene,
|
||||
referenceName,
|
||||
} from './visual.js';
|
||||
export { contractDriver, runCameraScript, tracePose } from './cameraRunner.js';
|
||||
export * as expect from './expect.js';
|
||||
@@ -0,0 +1,558 @@
|
||||
/**
|
||||
* @module render/conformance/scenes
|
||||
* @description The reference scenes: one per primitive family, a city scene
|
||||
* that mixes them, and a calibration path. Each is built from contract calls
|
||||
* only, so the Cesium renderer and the stub draw it alike, and each has fixed views to capture.
|
||||
*
|
||||
* The scenes load nothing from the network: the globe is bare (no imagery,
|
||||
* no photoreal tiles, no atmosphere), so what a capture shows depends on the
|
||||
* renderer alone. Images are inline SVG.
|
||||
*
|
||||
* A scene is `{ id, family, capability, build(renderer, ctx), views }`:
|
||||
* `build` returns a disposer; `ctx` has `toEcef` and optional `assets`
|
||||
* (`model`: a glTF URL). A scene whose capability the renderer lacks, or
|
||||
* whose asset the context lacks, is not drawn.
|
||||
*/
|
||||
import { AUSTIN } from './cameraScripts.js';
|
||||
|
||||
/** Looking down at Austin from `height`, tilted by `pitch`. */
|
||||
const over = (height, pitch = -Math.PI / 2, heading = 0, at = AUSTIN) => ({
|
||||
destination: { ...at, height },
|
||||
orientation: { heading, pitch, roll: 0 },
|
||||
});
|
||||
|
||||
/** A point `east`, `north` metres from `center`, approximately. */
|
||||
function offsetFrom(center, east, north, height = 0) {
|
||||
return {
|
||||
lon: center.lon + east / (111320 * Math.cos((center.lat * Math.PI) / 180)),
|
||||
lat: center.lat + north / 110540,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
/** A point `east`, `north` metres from Austin, approximately. */
|
||||
const offset = (east, north, height = 0) =>
|
||||
offsetFrom(AUSTIN, east, north, height);
|
||||
|
||||
const svg = (body, size = 32) => ({
|
||||
svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 32 32">${body}</svg>`,
|
||||
});
|
||||
const ICONS = {
|
||||
dot: svg('<circle cx="16" cy="16" r="14" fill="#ffffff"/>'),
|
||||
arrow: svg('<path d="M16 2 L28 30 L16 23 L4 30 Z" fill="#ffffff"/>'),
|
||||
square: svg(
|
||||
'<rect x="3" y="3" width="26" height="26" fill="#ffffff" stroke="#000000" stroke-width="3"/>',
|
||||
),
|
||||
};
|
||||
|
||||
const BG = {
|
||||
sky: {
|
||||
atmosphere: false,
|
||||
stars: false,
|
||||
milkyWay: 0,
|
||||
sun: false,
|
||||
moon: false,
|
||||
fog: false,
|
||||
lighting: false,
|
||||
},
|
||||
};
|
||||
|
||||
/** Bare globe, empty sky: nothing in a capture but the scene. */
|
||||
async function bare(r) {
|
||||
await r.globe.setBase({
|
||||
photoreal: null,
|
||||
terrain: { kind: 'ellipsoid' },
|
||||
imagery: [],
|
||||
});
|
||||
r.globe.setGlobeVisible(true);
|
||||
r.globe.sky.set(BG.sky);
|
||||
}
|
||||
|
||||
/** Disposes every set it was given. */
|
||||
const disposeAll =
|
||||
(...handles) =>
|
||||
() =>
|
||||
handles.forEach((h) => h.dispose());
|
||||
|
||||
const ring = (ctx, center, radius, count, height = 0) =>
|
||||
Array.from({ length: count + 1 }, (_, i) => {
|
||||
const a = (i / count) * Math.PI * 2;
|
||||
return ctx.toEcef(
|
||||
offsetFrom(center, Math.cos(a) * radius, Math.sin(a) * radius, height),
|
||||
);
|
||||
});
|
||||
|
||||
/** @type {ReadonlyArray<object>} */
|
||||
export const REFERENCE_SCENES = Object.freeze([
|
||||
{
|
||||
id: 'icons',
|
||||
family: 'icons',
|
||||
capability: null,
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.icons({ id: 'ref:icons' });
|
||||
const items = [];
|
||||
const colors = ['#ff3b30', '#34c759', '#0a84ff', '#ffd60a'];
|
||||
for (let row = 0; row < 4; row++)
|
||||
for (let col = 0; col < 6; col++) {
|
||||
const id = `i${row}${col}`;
|
||||
const pos = ctx.toEcef(offset((col - 2.5) * 250, (1.5 - row) * 250));
|
||||
// Drawn over the globe: at 0 m a tilted view would hide their lower half.
|
||||
const base = {
|
||||
id,
|
||||
pos,
|
||||
size: [24 + col * 4, 24 + col * 4],
|
||||
color: colors[row],
|
||||
disableDepthTest: Infinity,
|
||||
};
|
||||
if (row === 0) items.push({ ...base, image: ICONS.dot });
|
||||
if (row === 1)
|
||||
items.push({
|
||||
...base,
|
||||
image: ICONS.arrow,
|
||||
rotationMode: 'screen',
|
||||
rotation: (col * Math.PI) / 6,
|
||||
});
|
||||
if (row === 2)
|
||||
items.push({
|
||||
...base,
|
||||
image: ICONS.arrow,
|
||||
rotationMode: 'course',
|
||||
course: col * 60,
|
||||
});
|
||||
if (row === 3)
|
||||
items.push({
|
||||
...base,
|
||||
image: ICONS.square,
|
||||
anchor: col % 2 ? 'bottom' : 'center',
|
||||
alpha: 0.4 + col * 0.1,
|
||||
});
|
||||
}
|
||||
set.set(items);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [
|
||||
{ name: 'top', view: over(3000) },
|
||||
{ name: 'tilted', view: over(1500, -0.6, 0, offset(0, -2300)) },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'points',
|
||||
family: 'points',
|
||||
capability: null,
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.points({ id: 'ref:points' });
|
||||
const items = [];
|
||||
for (let i = 0; i < 8; i++)
|
||||
items.push({
|
||||
id: `p${i}`,
|
||||
pos: ctx.toEcef(offset((i - 3.5) * 180, 150)),
|
||||
pixelSize: 4 + i * 3,
|
||||
color: [1, i / 7, 0, 1],
|
||||
});
|
||||
for (let i = 0; i < 8; i++)
|
||||
items.push({
|
||||
id: `q${i}`,
|
||||
pos: ctx.toEcef(offset((i - 3.5) * 180, -150)),
|
||||
pixelSize: 18,
|
||||
color: '#0a84ff',
|
||||
outlineColor: '#ffffff',
|
||||
outlineWidth: i,
|
||||
});
|
||||
set.set(items);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [{ name: 'top', view: over(2500) }],
|
||||
},
|
||||
{
|
||||
id: 'lines',
|
||||
family: 'lines',
|
||||
capability: null,
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.lines({ id: 'ref:lines' });
|
||||
const row = (north, height = 0) => [
|
||||
ctx.toEcef(offset(-1200, north, height)),
|
||||
ctx.toEcef(offset(1200, north, height)),
|
||||
];
|
||||
set.set([
|
||||
{
|
||||
id: 'solid',
|
||||
positions: row(600),
|
||||
widthPx: 2,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: '#ffffff' },
|
||||
},
|
||||
{
|
||||
id: 'wide',
|
||||
positions: row(400),
|
||||
widthPx: 8,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: '#ff3b30' },
|
||||
},
|
||||
{
|
||||
id: 'glow',
|
||||
positions: row(200),
|
||||
widthPx: 12,
|
||||
mode: '3d',
|
||||
style: { kind: 'glow', color: '#34c759', power: 0.25 },
|
||||
},
|
||||
{
|
||||
id: 'dash',
|
||||
positions: row(0),
|
||||
widthPx: 4,
|
||||
mode: '3d',
|
||||
style: { kind: 'dash', color: '#ffd60a', length: 16 },
|
||||
},
|
||||
{
|
||||
id: 'arrow',
|
||||
positions: row(-200),
|
||||
widthPx: 14,
|
||||
mode: '3d',
|
||||
style: { kind: 'arrow', color: '#0a84ff' },
|
||||
},
|
||||
{
|
||||
id: 'raised',
|
||||
positions: row(-400, 300),
|
||||
widthPx: 3,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: '#bf5af2' },
|
||||
},
|
||||
{
|
||||
id: 'geodesic',
|
||||
positions: row(-600),
|
||||
widthPx: 3,
|
||||
mode: 'geodesic',
|
||||
style: { kind: 'solid', color: '#64d2ff' },
|
||||
},
|
||||
{
|
||||
id: 'loop',
|
||||
positions: ring(ctx, offset(0, 0), 900, 48),
|
||||
widthPx: 2,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: '#ff9f0a' },
|
||||
},
|
||||
]);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [
|
||||
{ name: 'top', view: over(4500) },
|
||||
{ name: 'tilted', view: over(2500, -0.45, 0, offset(0, -3500)) },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'shapes',
|
||||
family: 'shapes',
|
||||
capability: null,
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.shapes({ id: 'ref:shapes' });
|
||||
// Flat shapes sit 5 m up: at 0 m they share depth with the globe.
|
||||
const lift = 5;
|
||||
const square = (east, north, half) => [
|
||||
offset(east - half, north - half, lift),
|
||||
offset(east + half, north - half, lift),
|
||||
offset(east + half, north + half, lift),
|
||||
offset(east - half, north + half, lift),
|
||||
];
|
||||
set.set([
|
||||
{
|
||||
id: 'polygon',
|
||||
geometry: { kind: 'polygon', rings: [square(-700, 400, 250)] },
|
||||
fill: [1, 0.23, 0.19, 0.8],
|
||||
outline: '#ffffff',
|
||||
},
|
||||
{
|
||||
id: 'holed',
|
||||
geometry: {
|
||||
kind: 'polygon',
|
||||
rings: [square(0, 400, 280), square(0, 400, 120)],
|
||||
},
|
||||
fill: '#34c759',
|
||||
},
|
||||
{
|
||||
id: 'extruded',
|
||||
geometry: { kind: 'polygon', rings: [square(700, 400, 200)] },
|
||||
fill: '#0a84ff',
|
||||
extrudeHeight: 400,
|
||||
},
|
||||
{
|
||||
id: 'ellipse',
|
||||
geometry: {
|
||||
kind: 'ellipse',
|
||||
center: offset(-700, -400, 5),
|
||||
semiMajor: 300,
|
||||
semiMinor: 160,
|
||||
rotation: 0.5,
|
||||
},
|
||||
fill: [1, 0.84, 0.04, 0.7],
|
||||
},
|
||||
{
|
||||
id: 'rectangle',
|
||||
geometry: {
|
||||
kind: 'rectangle',
|
||||
rect: {
|
||||
west: offset(-250, 0).lon,
|
||||
south: offset(0, -650).lat,
|
||||
east: offset(250, 0).lon,
|
||||
north: offset(0, -150).lat,
|
||||
},
|
||||
height: 5,
|
||||
},
|
||||
fill: '#bf5af2',
|
||||
},
|
||||
{
|
||||
id: 'box',
|
||||
geometry: {
|
||||
kind: 'box',
|
||||
center: offset(700, -400, 150),
|
||||
dimensions: { x: 300, y: 300, z: 300 },
|
||||
},
|
||||
fill: '#ff9f0a',
|
||||
},
|
||||
{
|
||||
id: 'outline',
|
||||
geometry: { kind: 'polygon', rings: [square(0, -1000, 200)] },
|
||||
outline: '#ffffff',
|
||||
outlineOnly: true,
|
||||
},
|
||||
]);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [
|
||||
{ name: 'top', view: over(5000) },
|
||||
{ name: 'tilted', view: over(2500, -0.5, 0.3, offset(0, -3600)) },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'models',
|
||||
family: 'models',
|
||||
capability: 'models',
|
||||
needs: ['model'],
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
r.globe.sky.set({ lighting: true });
|
||||
// No wait on `ready` here: a model that never loads would hang the
|
||||
// run, and `whenSettled` before each view waits for loading models.
|
||||
const set = r.draw.models({ id: 'ref:models' });
|
||||
set.set([
|
||||
{
|
||||
id: 'plane',
|
||||
pos: offset(0, 0, 300),
|
||||
url: ctx.assets.model,
|
||||
orientation: { heading: 0.6, pitch: 0, roll: 0 },
|
||||
scale: 4,
|
||||
minPixelSize: 64,
|
||||
},
|
||||
]);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [{ name: 'oblique', view: over(330, -0.2, 0, offset(0, -140)) }],
|
||||
},
|
||||
{
|
||||
id: 'quads',
|
||||
family: 'quads',
|
||||
capability: 'quads',
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.quads({ id: 'ref:quads' });
|
||||
set.set([
|
||||
{
|
||||
id: 'card',
|
||||
center: offset(0, 0, 200),
|
||||
orientation: { x: 0, y: 0, z: 0, w: 1 },
|
||||
size: [400, 250],
|
||||
source: { image: ICONS.square },
|
||||
outline: { color: '#ffffff', widthPx: 2 },
|
||||
},
|
||||
]);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [{ name: 'oblique', view: over(1500, -0.5, 0, offset(0, -1600)) }],
|
||||
},
|
||||
{
|
||||
id: 'meshes',
|
||||
family: 'meshes',
|
||||
capability: 'meshes',
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.meshes({ id: 'ref:meshes' });
|
||||
// A square pyramid, 400 m across and 300 m tall.
|
||||
const positions = new Float32Array([
|
||||
-200, -200, 0, 200, -200, 0, 200, 200, 0, -200, 200, 0, 0, 0, 300,
|
||||
]);
|
||||
const indices = new Uint16Array([0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4]);
|
||||
set.set([
|
||||
{
|
||||
id: 'pyramid',
|
||||
origin: ctx.toEcef(offset(0, 0)),
|
||||
positions,
|
||||
indices,
|
||||
color: '#ff9f0a',
|
||||
flat: true,
|
||||
},
|
||||
]);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [{ name: 'oblique', view: over(1200, -0.5, 0, offset(0, -1400)) }],
|
||||
},
|
||||
{
|
||||
id: 'fields',
|
||||
family: 'fields',
|
||||
capability: 'fields',
|
||||
async build(r) {
|
||||
await bare(r);
|
||||
const width = 32;
|
||||
const height = 16;
|
||||
const values = new Float32Array(width * height).map(
|
||||
(_, i) => (i % width) / width,
|
||||
);
|
||||
const field = r.draw.field({
|
||||
kind: 'scalarRaster',
|
||||
id: 'ref:scalar',
|
||||
values,
|
||||
width,
|
||||
height,
|
||||
rectangle: { west: -100, south: 28, east: -95, north: 32 },
|
||||
ramp: [
|
||||
{ value: 0, color: '#0a84ff' },
|
||||
{ value: 0.5, color: '#34c759' },
|
||||
{ value: 1, color: '#ff3b30' },
|
||||
],
|
||||
alpha: 0.8,
|
||||
});
|
||||
return () => field.dispose();
|
||||
},
|
||||
views: [
|
||||
{
|
||||
name: 'regional',
|
||||
view: over(900000, -Math.PI / 2, 0, { lon: -97.5, lat: 30 }),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'agents',
|
||||
family: 'agents',
|
||||
capability: 'agents',
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const set = r.draw.agents({ id: 'ref:agents' });
|
||||
set.set([
|
||||
{
|
||||
id: 'road',
|
||||
positions: [ctx.toEcef(offset(-800, 0)), ctx.toEcef(offset(800, 0))],
|
||||
count: 20,
|
||||
speedMps: 0,
|
||||
color: '#ffd60a',
|
||||
pixelSize: 6,
|
||||
},
|
||||
]);
|
||||
return disposeAll(set);
|
||||
},
|
||||
views: [{ name: 'top', view: over(2500) }],
|
||||
},
|
||||
{
|
||||
id: 'city',
|
||||
family: 'city',
|
||||
capability: null,
|
||||
async build(r, ctx) {
|
||||
await bare(r);
|
||||
const shapes = r.draw.shapes({ id: 'ref:city:blocks' });
|
||||
const blocks = [];
|
||||
for (let i = 0; i < 5; i++)
|
||||
for (let j = 0; j < 5; j++) {
|
||||
const e = (i - 2) * 220;
|
||||
const n = (j - 2) * 220;
|
||||
blocks.push({
|
||||
id: `b${i}${j}`,
|
||||
geometry: {
|
||||
kind: 'polygon',
|
||||
rings: [
|
||||
[
|
||||
offset(e - 80, n - 80),
|
||||
offset(e + 80, n - 80),
|
||||
offset(e + 80, n + 80),
|
||||
offset(e - 80, n + 80),
|
||||
],
|
||||
],
|
||||
},
|
||||
fill: [0.55, 0.6, 0.7, 1],
|
||||
extrudeHeight: 40 + ((i * 7 + j * 13) % 9) * 25,
|
||||
});
|
||||
}
|
||||
shapes.set(blocks);
|
||||
const roads = r.draw.lines({ id: 'ref:city:roads' });
|
||||
const road = (id, a, b) => ({
|
||||
id,
|
||||
positions: [ctx.toEcef(a), ctx.toEcef(b)],
|
||||
widthPx: 3,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: '#ffd60a' },
|
||||
});
|
||||
roads.set([
|
||||
...[-330, -110, 110, 330].map((n, k) =>
|
||||
road(`ew${k}`, offset(-600, n, 2), offset(600, n, 2)),
|
||||
),
|
||||
...[-330, -110, 110, 330].map((e, k) =>
|
||||
road(`ns${k}`, offset(e, -600, 2), offset(e, 600, 2)),
|
||||
),
|
||||
]);
|
||||
const vehicles = r.draw.icons({ id: 'ref:city:vehicles' });
|
||||
vehicles.set(
|
||||
Array.from({ length: 12 }, (_, k) => ({
|
||||
id: `v${k}`,
|
||||
pos: ctx.toEcef(offset(-500 + k * 90, -110, 5)),
|
||||
image: ICONS.arrow,
|
||||
size: [20, 20],
|
||||
color: '#ff3b30',
|
||||
rotationMode: 'course',
|
||||
course: 90,
|
||||
})),
|
||||
);
|
||||
const sensors = r.draw.points({ id: 'ref:city:sensors' });
|
||||
sensors.set(
|
||||
Array.from({ length: 10 }, (_, k) => ({
|
||||
id: `s${k}`,
|
||||
pos: ctx.toEcef(offset(110, -550 + k * 110, 5)),
|
||||
pixelSize: 8,
|
||||
color: '#34c759',
|
||||
outlineColor: '#000000',
|
||||
outlineWidth: 1,
|
||||
})),
|
||||
);
|
||||
return disposeAll(shapes, roads, vehicles, sensors);
|
||||
},
|
||||
views: [
|
||||
{ name: 'orbit', view: over(15000000) },
|
||||
{ name: 'city', view: over(1800, -0.6, 0.4, offset(-1200, -2600)) },
|
||||
{ name: 'street', view: over(60, -0.08, 0, offset(-150, -700)) },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
/**
|
||||
* The calibration path: the city scene seen from orbit down to the street,
|
||||
* the poses a quality calibration (and the performance budget) samples.
|
||||
*/
|
||||
export const CALIBRATION_PATH = Object.freeze({
|
||||
scene: 'city',
|
||||
poses: Object.freeze([
|
||||
over(15000000),
|
||||
over(1500000),
|
||||
over(60000, -1.2),
|
||||
over(6000, -0.8, 0.3, offset(-800, -3000)),
|
||||
over(1200, -0.5, 0.5, offset(-600, -1200)),
|
||||
over(250, -0.25, 0.2, offset(-250, -800)),
|
||||
over(60, -0.08, 0, offset(-150, -700)),
|
||||
]),
|
||||
});
|
||||
|
||||
/** Whether a renderer and context can draw a scene; the reason when not. */
|
||||
export function sceneSupport(scene, renderer, ctx = {}) {
|
||||
if (scene.capability && !renderer.capabilities.has(scene.capability))
|
||||
return `no ${scene.capability}`;
|
||||
for (const need of scene.needs ?? [])
|
||||
if (!ctx.assets?.[need]) return `no ${need} asset`;
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PORTS } from '../contract/index.js';
|
||||
import { createStubRenderer } from '../stub/index.js';
|
||||
import { toEcef } from '../stub/math.js';
|
||||
import { CALIBRATION_PATH, REFERENCE_SCENES, sceneSupport } from './scenes.js';
|
||||
import { compareImages } from './visual.js';
|
||||
|
||||
/**
|
||||
* The stub behind proxies that throw on any member the contract does not
|
||||
* list, so a scene that reaches past the contract fails here.
|
||||
*/
|
||||
const MEMBERS = { ...PORTS, handle: { dispose: null, update: null } };
|
||||
|
||||
function contractOnly(renderer) {
|
||||
const guard = (target, port, prefix = '') =>
|
||||
new Proxy(target, {
|
||||
get(obj, key, receiver) {
|
||||
if (typeof key === 'symbol' || key === 'then')
|
||||
return Reflect.get(obj, key, receiver);
|
||||
const member = prefix + key;
|
||||
if (!(member in MEMBERS[port]))
|
||||
throw new Error(`${port}.${member} is not in the contract`);
|
||||
const value = Reflect.get(obj, key, receiver);
|
||||
if (port === 'draw' && typeof value === 'function')
|
||||
return (...args) =>
|
||||
guard(
|
||||
value.apply(obj, args),
|
||||
key === 'field' || key === 'celestial' ? 'handle' : 'drawSet',
|
||||
);
|
||||
const nested = Object.keys(MEMBERS[port]).some((m) =>
|
||||
m.startsWith(`${member}.`),
|
||||
);
|
||||
if (value && typeof value === 'object' && nested)
|
||||
return guard(value, port, `${member}.`);
|
||||
return typeof value === 'function' ? value.bind(obj) : value;
|
||||
},
|
||||
});
|
||||
const wrapped = {};
|
||||
for (const port of Object.keys(PORTS.renderer)) {
|
||||
const value = renderer[port];
|
||||
wrapped[port] =
|
||||
MEMBERS[port] && typeof value === 'object' ? guard(value, port) : value;
|
||||
}
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
const ctx = { toEcef, assets: { model: '/models/c172.glb' } };
|
||||
|
||||
test('every reference scene builds and disposes on the stub through the contract alone', async () => {
|
||||
const ids = new Set();
|
||||
for (const scene of REFERENCE_SCENES) {
|
||||
assert.ok(!ids.has(scene.id), `${scene.id} is unique`);
|
||||
ids.add(scene.id);
|
||||
const stub = createStubRenderer();
|
||||
// Models report ready once their asset loads; the stub has none to load.
|
||||
if (scene.capability === 'models') continue;
|
||||
assert.equal(sceneSupport(scene, stub, ctx), null, scene.id);
|
||||
const renderer = contractOnly(stub);
|
||||
const dispose = await scene.build(renderer, ctx);
|
||||
assert.ok(
|
||||
stub.testing.sets().length > 0 || scene.family === 'fields',
|
||||
`${scene.id} drew something`,
|
||||
);
|
||||
for (const view of scene.views) renderer.camera.setView(view.view);
|
||||
dispose();
|
||||
assert.deepEqual(
|
||||
stub.testing.sets(),
|
||||
[],
|
||||
`${scene.id} left nothing behind`,
|
||||
);
|
||||
assert.ok(scene.views.length > 0, `${scene.id} has views`);
|
||||
}
|
||||
for (const family of [
|
||||
'icons',
|
||||
'points',
|
||||
'lines',
|
||||
'shapes',
|
||||
'models',
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
'agents',
|
||||
'city',
|
||||
])
|
||||
assert.ok(ids.has(family), `a ${family} scene`);
|
||||
});
|
||||
|
||||
test('a scene a renderer cannot draw says why', () => {
|
||||
const stub = createStubRenderer({ capabilities: [] });
|
||||
const models = REFERENCE_SCENES.find((s) => s.id === 'models');
|
||||
assert.equal(sceneSupport(models, stub, ctx), 'no models');
|
||||
assert.equal(
|
||||
sceneSupport(models, createStubRenderer(), {}),
|
||||
'no model asset',
|
||||
);
|
||||
});
|
||||
|
||||
test('the calibration path runs from orbit to street over the city scene', () => {
|
||||
assert.ok(REFERENCE_SCENES.some((s) => s.id === CALIBRATION_PATH.scene));
|
||||
const heights = CALIBRATION_PATH.poses.map((p) => p.destination.height);
|
||||
assert.deepEqual(
|
||||
heights,
|
||||
[...heights].sort((a, b) => b - a),
|
||||
);
|
||||
assert.ok(heights[0] >= 1e7 && heights.at(-1) <= 100);
|
||||
});
|
||||
|
||||
const image = (w, h, fill) => {
|
||||
const data = new Uint8ClampedArray(w * h * 4);
|
||||
for (let p = 0; p < data.length; p += 4) data.set(fill(p / 4), p);
|
||||
return { width: w, height: h, data };
|
||||
};
|
||||
|
||||
test('the image comparison passes rounding and fails a moved item', () => {
|
||||
const base = image(100, 100, (i) =>
|
||||
i % 100 > 40 && i % 100 < 60 && i < 5000
|
||||
? [255, 0, 0, 255]
|
||||
: [20, 30, 40, 255],
|
||||
);
|
||||
const rounded = image(100, 100, (i) =>
|
||||
[...base.data.slice(i * 4, i * 4 + 3)]
|
||||
.map((c) => Math.min(255, c + 2))
|
||||
.concat(255),
|
||||
);
|
||||
assert.equal(compareImages(rounded, base).match, true);
|
||||
const moved = image(100, 100, (i) =>
|
||||
i % 100 > 10 && i % 100 < 30 && i < 5000
|
||||
? [255, 0, 0, 255]
|
||||
: [20, 30, 40, 255],
|
||||
);
|
||||
const result = compareImages(moved, base);
|
||||
assert.equal(result.match, false);
|
||||
assert.ok(result.diffFraction > 0.1);
|
||||
assert.ok(result.solidPixels > 100);
|
||||
assert.equal(
|
||||
compareImages(
|
||||
image(10, 10, () => [0, 0, 0, 255]),
|
||||
base,
|
||||
).match,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('the image comparison drops one-pixel fringes and catches a small item', () => {
|
||||
const blank = image(100, 100, () => [20, 30, 40, 255]);
|
||||
// Antialiasing: a one-pixel ring and a one-pixel line differ, nothing solid.
|
||||
const fringe = image(100, 100, (i) => {
|
||||
const x = i % 100;
|
||||
const y = (i - x) / 100;
|
||||
const ring = Math.abs(Math.hypot(x - 50, y - 50) - 20) < 0.5;
|
||||
return ring || x === 80 ? [200, 200, 200, 255] : [20, 30, 40, 255];
|
||||
});
|
||||
const fringed = compareImages(fringe, blank);
|
||||
assert.ok(fringed.diffPixels > 100, 'many pixels differ');
|
||||
assert.equal(fringed.solidPixels, 0);
|
||||
assert.equal(fringed.match, true);
|
||||
// The smallest reference item: a 4 px point.
|
||||
const point = image(100, 100, (i) => {
|
||||
const x = i % 100;
|
||||
const y = (i - x) / 100;
|
||||
return Math.hypot(x - 30.5, y - 30.5) <= 2.2
|
||||
? [255, 0, 0, 255]
|
||||
: [20, 30, 40, 255];
|
||||
});
|
||||
const dropped = compareImages(blank, point);
|
||||
assert.ok(dropped.solidPixels > 2, `solid ${dropped.solidPixels}`);
|
||||
assert.equal(dropped.match, false);
|
||||
});
|
||||
|
||||
test('the image comparison catches a dropped thin line and a one-pixel shift', () => {
|
||||
const at = (fill) =>
|
||||
image(200, 200, (i) => {
|
||||
const x = i % 200;
|
||||
return fill(x, (i - x) / 200) ? [255, 255, 255, 255] : [20, 30, 40, 255];
|
||||
});
|
||||
const blank = at(() => false);
|
||||
// These 160 px lines, 2 and 3 px wide, cover 320 and 480 px: over the
|
||||
// 250 px limit. A thin change covering less passes (see visual.js).
|
||||
for (const width of [2, 3]) {
|
||||
const line = at(
|
||||
(x, y) => x >= 20 && x < 180 && y >= 100 && y < 100 + width,
|
||||
);
|
||||
assert.equal(
|
||||
compareImages(blank, line).match,
|
||||
false,
|
||||
`a dropped ${width} px line`,
|
||||
);
|
||||
}
|
||||
const box = (dx, dy) =>
|
||||
at((x, y) => x >= 40 + dx && x < 160 + dx && y >= 50 + dy && y < 150 + dy);
|
||||
// A 120×100 box moved leaves strips on the sides it moves across: caught
|
||||
// when they cover more than 250 px. Moved 1 px along one axis, it covers 200
|
||||
// and passes; these cover more.
|
||||
for (const [dx, dy] of [
|
||||
[1, 1],
|
||||
[2, 0],
|
||||
[2, 2],
|
||||
])
|
||||
assert.equal(
|
||||
compareImages(box(dx, dy), box(0, 0)).match,
|
||||
false,
|
||||
`a box moved by (${dx}, ${dy})`,
|
||||
);
|
||||
});
|
||||
|
||||
test('the image comparison takes pixel data that does not start on a word', () => {
|
||||
const base = image(4, 4, () => [20, 30, 40, 255]);
|
||||
const bytes = new Uint8ClampedArray(base.data.length + 1);
|
||||
bytes.set(base.data, 1);
|
||||
const sliced = { width: 4, height: 4, data: bytes.subarray(1) };
|
||||
assert.equal(compareImages(sliced, base).match, true);
|
||||
});
|
||||
|
||||
test('a thin change under 250 px passes, as documented', () => {
|
||||
const at = (fill) =>
|
||||
image(200, 200, (i) => {
|
||||
const x = i % 200;
|
||||
return fill(x, (i - x) / 200) ? [255, 255, 255, 255] : [20, 30, 40, 255];
|
||||
});
|
||||
const line = at((x, y) => x >= 20 && x < 100 && y >= 100 && y < 102);
|
||||
const result = compareImages(
|
||||
at(() => false),
|
||||
line,
|
||||
);
|
||||
assert.equal(result.solidPixels, 0);
|
||||
assert.equal(result.mismatchedPixels, 160);
|
||||
assert.equal(result.match, true);
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* @module render/conformance/visual
|
||||
* @description The visual checks: draw a reference scene from one of its
|
||||
* views, capture it, and compare the capture with the reference image under
|
||||
* a perceptual tolerance.
|
||||
*
|
||||
* Pixels are compared as pixelmatch compares them (its algorithm, ported;
|
||||
* pixelmatch is ISC-licensed, copyright Mapbox): by YIQ difference, which
|
||||
* weighs brightness over hue as the eye does, and excusing a differing pixel
|
||||
* that is antialiasing in either image, one on an edge between two flat
|
||||
* colours. A dropped or moved item differs inside its body and along hard
|
||||
* edges, which are not excused. A differing pixel whose four neighbours
|
||||
* differ too is solid: antialiasing differs along one-pixel fringes and has
|
||||
* none. Two images match when at most `maxSolidPixels` pixels are solid and
|
||||
* at most `maxMismatchedPixels` are unexcused.
|
||||
*
|
||||
* The two measures cover each other. Measured on the default renderer at
|
||||
* 640×360, against references drawn with 4× MSAA:
|
||||
*
|
||||
* | Change | Solid | Unexcused |
|
||||
* | ------------------------------ | ----: | --------: |
|
||||
* | Drawn with 1×, 2× or 8× MSAA | 0 | ≤ 192 |
|
||||
* | The smallest point (4 px) gone | 7 | 8 |
|
||||
* | An arrow line reversed | 24 | 88 |
|
||||
* | An arrow icon turned | 64 | 91 |
|
||||
* | A 2 px line gone | ≥ 267 | ≥ 536 |
|
||||
* | The whole view moved 1 px | ≥ 36 | ≥ 480 |
|
||||
* | An icon gone | ~ 300 | ~ 300 |
|
||||
*
|
||||
* The limit: a solid pixel needs a change at least 3 px thick, so a change
|
||||
* that is nowhere that thick (a thin line gone, an item moved a pixel or two)
|
||||
* passes when it covers at most 250 px: a missing 2 px line up to 125 px
|
||||
* long, say, or a 20 px box moved 1 or 2 px. A blob up to about 3×4 px is
|
||||
* under both limits too (2 solid pixels). Larger thin changes, and any
|
||||
* change whose 3 px core is more than two pixels, are caught; the smallest
|
||||
* item in the scenes, the 4 px point, leaves 7.
|
||||
*/
|
||||
|
||||
/** Tolerances the default renderer meets against its own references with any antialiasing. */
|
||||
export const VISUAL_TOLERANCE = Object.freeze({
|
||||
threshold: 0.1,
|
||||
maxSolidPixels: 2,
|
||||
maxMismatchedPixels: 250,
|
||||
});
|
||||
|
||||
/** The largest YIQ difference two RGB colours can have. */
|
||||
const MAX_YIQ_DELTA = 35215;
|
||||
|
||||
/** Composites a channel over black, so transparent and black read the same. */
|
||||
const over = (c, a) => (c * a) / 255;
|
||||
|
||||
const rgb = (d, p) => [
|
||||
over(d[p], d[p + 3]),
|
||||
over(d[p + 1], d[p + 3]),
|
||||
over(d[p + 2], d[p + 3]),
|
||||
];
|
||||
const brightness = ([r, g, b]) =>
|
||||
r * 0.29889531 + g * 0.58662247 + b * 0.11448223;
|
||||
|
||||
function yiqDelta([r1, g1, b1], [r2, g2, b2]) {
|
||||
const i = (r, g, b) => r * 0.59597799 - g * 0.2741761 - b * 0.32180189;
|
||||
const q = (r, g, b) => r * 0.21147017 - g * 0.52261711 + b * 0.31114694;
|
||||
const dy = brightness([r1, g1, b1]) - brightness([r2, g2, b2]);
|
||||
const di = i(r1, g1, b1) - i(r2, g2, b2);
|
||||
const dq = q(r1, g1, b1) - q(r2, g2, b2);
|
||||
return 0.5053 * dy * dy + 0.299 * di * di + 0.1957 * dq * dq;
|
||||
}
|
||||
|
||||
/** Whether (x, y) has more than two neighbours of exactly its own colour. */
|
||||
function hasManySiblings(px, x1, y1, w, h) {
|
||||
const val = px[y1 * w + x1];
|
||||
let zeroes = x1 === 0 || y1 === 0 || x1 === w - 1 || y1 === h - 1 ? 1 : 0;
|
||||
for (let x = Math.max(x1 - 1, 0); x <= Math.min(x1 + 1, w - 1); x++)
|
||||
for (let y = Math.max(y1 - 1, 0); y <= Math.min(y1 + 1, h - 1); y++) {
|
||||
if (x === x1 && y === y1) continue;
|
||||
if (px[y * w + x] === val && ++zeroes > 2) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether (x1, y1) of `img` is antialiasing: a pixel between its darkest and
|
||||
* brightest neighbours, one of which is flat (has siblings) in both images.
|
||||
*/
|
||||
function antialiased(img, px, otherPx, x1, y1, w, h) {
|
||||
const here = brightness(rgb(img, (y1 * w + x1) * 4));
|
||||
let zeroes = x1 === 0 || y1 === 0 || x1 === w - 1 || y1 === h - 1 ? 1 : 0;
|
||||
let min = 0;
|
||||
let max = 0;
|
||||
let minX;
|
||||
let minY;
|
||||
let maxX;
|
||||
let maxY;
|
||||
for (let x = Math.max(x1 - 1, 0); x <= Math.min(x1 + 1, w - 1); x++)
|
||||
for (let y = Math.max(y1 - 1, 0); y <= Math.min(y1 + 1, h - 1); y++) {
|
||||
if (x === x1 && y === y1) continue;
|
||||
const delta = here - brightness(rgb(img, (y * w + x) * 4));
|
||||
if (delta === 0) {
|
||||
if (++zeroes > 2) return false;
|
||||
} else if (delta < min) {
|
||||
min = delta;
|
||||
minX = x;
|
||||
minY = y;
|
||||
} else if (delta > max) {
|
||||
max = delta;
|
||||
maxX = x;
|
||||
maxY = y;
|
||||
}
|
||||
}
|
||||
if (min === 0 || max === 0) return false;
|
||||
return (
|
||||
(hasManySiblings(px, minX, minY, w, h) &&
|
||||
hasManySiblings(otherPx, minX, minY, w, h)) ||
|
||||
(hasManySiblings(px, maxX, maxY, w, h) &&
|
||||
hasManySiblings(otherPx, maxX, maxY, w, h))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{width: number, height: number, data: Uint8ClampedArray}} actual
|
||||
* @param {{width: number, height: number, data: Uint8ClampedArray}} expected
|
||||
* @param {{threshold?: number, maxSolidPixels?: number, maxMismatchedPixels?: number, diff?: Uint8ClampedArray}} [options]
|
||||
* `diff`, when given, is filled with an RGBA image of the differences:
|
||||
* mismatches red, excused antialiasing yellow.
|
||||
* @returns {{match: boolean, diffPixels: number, diffFraction: number, solidPixels: number, mismatchedPixels: number, reason?: string}}
|
||||
*/
|
||||
export function compareImages(actual, expected, options = {}) {
|
||||
const { threshold, maxSolidPixels, maxMismatchedPixels } = {
|
||||
...VISUAL_TOLERANCE,
|
||||
...options,
|
||||
};
|
||||
if (actual.width !== expected.width || actual.height !== expected.height)
|
||||
return {
|
||||
match: false,
|
||||
diffPixels: NaN,
|
||||
diffFraction: 1,
|
||||
solidPixels: NaN,
|
||||
mismatchedPixels: NaN,
|
||||
reason: `size ${actual.width}×${actual.height}, reference ${expected.width}×${expected.height}`,
|
||||
};
|
||||
const { width: w, height: h } = actual;
|
||||
// Whole pixels compare as 32-bit words; data that does not start on a
|
||||
// word (a sliced Node buffer) is copied first.
|
||||
const aligned = (d) =>
|
||||
d.byteOffset % 4 === 0 ? d : new Uint8ClampedArray(d);
|
||||
const a = aligned(actual.data);
|
||||
const b = aligned(expected.data);
|
||||
const aPx = new Uint32Array(a.buffer, a.byteOffset, w * h);
|
||||
const bPx = new Uint32Array(b.buffer, b.byteOffset, w * h);
|
||||
const limit = MAX_YIQ_DELTA * threshold * threshold;
|
||||
const diff = options.diff;
|
||||
const differing = new Uint8Array(w * h);
|
||||
let diffPixels = 0;
|
||||
let mismatchedPixels = 0;
|
||||
for (let y = 0; y < h; y++)
|
||||
for (let x = 0; x < w; x++) {
|
||||
const k = y * w + x;
|
||||
const p = k * 4;
|
||||
const differs =
|
||||
aPx[k] !== bPx[k] && yiqDelta(rgb(a, p), rgb(b, p)) > limit;
|
||||
let mismatch = false;
|
||||
if (differs) {
|
||||
differing[k] = 1;
|
||||
diffPixels += 1;
|
||||
mismatch =
|
||||
!antialiased(a, aPx, bPx, x, y, w, h) &&
|
||||
!antialiased(b, bPx, aPx, x, y, w, h);
|
||||
if (mismatch) mismatchedPixels += 1;
|
||||
}
|
||||
if (diff) {
|
||||
// Differences over a faded copy of the reference.
|
||||
const faded = 40 + over(b[p + 1], b[p + 3]) * 0.25;
|
||||
diff[p] = differs ? 255 : faded;
|
||||
diff[p + 1] = differs ? (mismatch ? 0 : 220) : faded;
|
||||
diff[p + 2] = differs ? 0 : faded;
|
||||
diff[p + 3] = 255;
|
||||
}
|
||||
}
|
||||
// Solid: a differing pixel whose four neighbours differ too.
|
||||
let solidPixels = 0;
|
||||
for (let y = 1; y < h - 1; y++)
|
||||
for (let x = 1; x < w - 1; x++) {
|
||||
const k = y * w + x;
|
||||
if (
|
||||
differing[k] &&
|
||||
differing[k - 1] &&
|
||||
differing[k + 1] &&
|
||||
differing[k - w] &&
|
||||
differing[k + w]
|
||||
)
|
||||
solidPixels += 1;
|
||||
}
|
||||
return {
|
||||
match:
|
||||
solidPixels <= maxSolidPixels && mismatchedPixels <= maxMismatchedPixels,
|
||||
diffPixels,
|
||||
diffFraction: diffPixels / (w * h),
|
||||
solidPixels,
|
||||
mismatchedPixels,
|
||||
};
|
||||
}
|
||||
|
||||
/** The file a view's reference image is stored under. */
|
||||
export const referenceName = (sceneId, viewName) =>
|
||||
`${sceneId}-${viewName}.png`;
|
||||
|
||||
/**
|
||||
* Draws a scene, then each of its views once the renderer has settled.
|
||||
* @param {object} renderer
|
||||
* @param {object} scene One of `REFERENCE_SCENES`.
|
||||
* @param {{toEcef: Function, assets?: object}} ctx
|
||||
* @param {(view: {name: string}, capture: Blob, settle: {state: string, blockers: string[]}) => void|Promise<void>} onView
|
||||
* `settle` is what `whenSettled` answered; a capture that did not settle
|
||||
* is no reference and no pass.
|
||||
*/
|
||||
export async function drawScene(renderer, scene, ctx, onView) {
|
||||
const dispose = await scene.build(renderer, ctx);
|
||||
try {
|
||||
for (const view of scene.views) {
|
||||
renderer.camera.setView(view.view);
|
||||
const settle = await renderer.whenSettled({ timeoutMs: 20000 });
|
||||
await onView(view, await renderer.capture({ type: 'png' }), settle);
|
||||
}
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
}
|
||||