diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index d0e08fd37..6693011e9 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -20,6 +20,7 @@ "src/render/cesium/frame.js", "src/render/cesium/query.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -898,6 +899,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -1048,6 +1050,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/data/followed.js", @@ -1488,6 +1491,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -1593,6 +1597,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -1795,6 +1800,7 @@ "src/queries/heights.js", "src/render/cesium/effects.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/camera.js", @@ -1881,6 +1887,7 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/layers/firms/index.js", @@ -1973,6 +1980,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -2039,6 +2047,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -2123,6 +2132,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -2319,6 +2329,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/cesium/frame.js", "src/render/cesium/follow.js", @@ -2445,6 +2456,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -2727,6 +2739,7 @@ "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -2901,6 +2914,7 @@ "src/render/cesium/credits.js", "src/render/cesium/tileRequests.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraInput.js", @@ -3128,6 +3142,7 @@ "src/render/cesium/globe.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/quality.js", "src/render/cesium/credits.js", "src/render/cesium/effects.js", @@ -4124,6 +4139,7 @@ "src/render/cesium/query.js", "src/render/cesium/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/imagery.js", @@ -4801,6 +4817,7 @@ "src/render/cesium/heights.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -5475,6 +5492,7 @@ "src/render/cesium/query.js", "src/render/cesium/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/cameraControls.js", @@ -5618,6 +5636,7 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/data/cameraSensitivity.js", @@ -5872,6 +5891,7 @@ "src/render/cesium/query.js", "src/render/cesium/heights.js", "src/render/cesium/draw.js", + "src/geo/polyline.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/frame.js", @@ -6157,6 +6177,7 @@ "modules": [ "src/render/contract/index.js", "src/render/stub/index.js", + "src/geo/polyline.js", "src/render/motion/iconMotion.js", "src/geo/horizon.js", "src/render/conformance/index.js", diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index 506606c8b..94b49085a 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -219,6 +219,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'localGeojsonLod.js', 'motionModel.js', 'pickRegistry.js', + 'polyline.js', 'query.js', 'rendererOf.js', 'router.js', diff --git a/src/geo/polyline.js b/src/geo/polyline.js new file mode 100644 index 000000000..edd3dc924 --- /dev/null +++ b/src/geo/polyline.js @@ -0,0 +1,34 @@ +/** + * @module geo/polyline + * @description Where a fraction of a polyline's length falls, measured + * straight between its ECEF positions: what a line's `revealFraction` + * draws up to. + */ + +const span = (a, b) => Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z); + +/** + * The segment a fraction of the polyline's length ends on, and how far + * along it (`t`, 0..1): fractions past 0 and up to 1 only. Null when there + * is no length to measure, or the fraction is outside `(0, 1]`. + * @param {ReadonlyArray<{x: number, y: number, z: number}>} positions + * @param {number} fraction + * @returns {{index: number, t: number} | null} + */ +export function alongLength(positions, fraction) { + if (!(fraction > 0) || fraction > 1 || positions.length < 2) return null; + const lengths = []; + let total = 0; + for (let i = 0; i + 1 < positions.length; i++) { + lengths.push(span(positions[i], positions[i + 1])); + total += lengths[i]; + } + if (!(total > 0)) return null; + let left = fraction * total; + for (let i = 0; i < lengths.length; i++) { + if (left <= lengths[i]) + return { index: i, t: lengths[i] > 0 ? left / lengths[i] : 0 }; + left -= lengths[i]; + } + return { index: lengths.length - 1, t: 1 }; +} diff --git a/src/geo/polyline.test.mjs b/src/geo/polyline.test.mjs new file mode 100644 index 000000000..225f1f28d --- /dev/null +++ b/src/geo/polyline.test.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { alongLength } from './polyline.js'; + +const p = (x) => ({ x, y: 0, z: 0 }); + +test('alongLength finds where a fraction of a polyline’s length ends', () => { + assert.deepEqual(alongLength([p(0), p(1), p(4)], 0.5), { + index: 1, + t: 1 / 3, + }); + assert.deepEqual(alongLength([p(0), p(1), p(4)], 1), { index: 1, t: 1 }); + assert.deepEqual(alongLength([p(0), p(1), p(4)], 0.25), { index: 0, t: 1 }); +}); + +test('alongLength has nothing to say without a length or a fraction in (0, 1]', () => { + assert.equal(alongLength([p(0), p(1)], 0), null); + assert.equal(alongLength([p(0), p(1)], 1.5), null); + assert.equal(alongLength([p(0), p(0)], 0.5), null); + assert.equal(alongLength([p(0)], 0.5), null); +}); diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 80e094e08..1bea0f258 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -26,6 +26,7 @@ * `findDraw` for one (`rendererOf.js`). */ import * as Cesium from 'cesium'; +import { alongLength } from '../../geo/polyline.js'; import { provideUnboundDraw } from '../rendererOf.js'; import { listenerList, toCartesian, uncaught } from './common.js'; import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js'; @@ -156,6 +157,66 @@ czm_material czm_getMaterial(czm_materialInput materialInput) { return m; }`; +/** The line styles the port drapes. */ +const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow']); + +// Whether Cesium's approximate terrain heights have been asked for. +let terrainHeightsAsked = false; + +/** + * Whether a ground polyline can be built in the frame it is made: Cesium + * needs its approximate terrain heights loaded for that. The first time + * one is wanted they are asked for (as Cesium's entities ask, which then + * build those lines the same way); until they load, false. + */ +function groundSyncs() { + if (Cesium.ApproximateTerrainHeights.initialized) return true; + if (!terrainHeightsAsked) { + terrainHeightsAsked = true; + try { + Cesium.GroundPolylinePrimitive.initializeTerrainHeights().catch(() => {}); + } catch { + // Nowhere to load them from: such lines are rebuilt as before. + } + } + return false; +} + +/** The prefix of a revealed line's material types, one per style kind. */ +const REVEAL_MATERIAL = 'DrawRevealLine'; + +/** + * A line drawn only up to `reveal` along its texture (`st.s`, 0 at its + * start, 1 at its end), in its own style past that: the rest is discarded, + * so it neither draws nor picks. + */ +const REVEAL_SOURCE = ` +czm_material czm_getMaterial(czm_materialInput materialInput) { + if (materialInput.st.s > reveal) discard; + return revealed; +}`; + +/** + * Where along a drawn line's texture its first `fraction` of length ends, + * for the reveal material. A ground polyline's texture runs along its + * length; a polyline's runs evenly per vertex, so `positions` (as drawn) + * map the length onto it. Nothing past 0, everything from 1. + * @param {number} fraction + * @param {Array<{x: number, y: number, z: number}>} [positions] + */ +export function revealUniform(fraction, positions) { + if (!(fraction > 0)) return -1; + if (fraction >= 1) return 2; + if (!positions) return fraction; + // As a polyline draws them: neighbours at one place are one vertex. + positions = Cesium.arrayRemoveDuplicates( + positions, + Cesium.Cartesian3.equalsEpsilon, + ); + const at = alongLength(positions, fraction); + return at ? (at.index + at.t) / (positions.length - 1) : 2; +} + /** * The `flow` lines' clock, seconds, for a line flowing at `speed` cells a * second: wrapped to one cell's time, which draws the same dashes, so the @@ -221,6 +282,8 @@ export function createCesiumDraw({ record.pickIds = []; record.placed = []; record.patchable = null; + // The lines as the host this build replaces draws them. + record.drawnParts = record.lineParts; record.lineParts = null; build(record); setsVersion += 1; @@ -479,6 +542,7 @@ export function createCesiumDraw({ scene.primitives.remove(record.retiring); record.retiring = null; record.retiringFlows = null; + record.retiringParts = null; } /** @@ -824,6 +888,7 @@ export function createCesiumDraw({ record.spec.clampTo, ); let primitive; + let dot; if (heightReference === Cesium.HeightReference.NONE) { points ??= new Cesium.PointPrimitiveCollection({ blendOption: pointBlendOf(record.spec.blend), @@ -834,15 +899,6 @@ export function createCesiumDraw({ show, id: pickId(record, item), }); - const placed = place(record, primitive, position, show); - record.patchable ??= new Map(); - record.patchable.set(item.id, { - primitive, - placed, - at: placeOf(item), - lodGroup: item.lodGroup, - }); - continue; } else { // Point primitives cannot follow the ground. dots ??= new Cesium.BillboardCollection({ scene }); @@ -853,8 +909,16 @@ export function createCesiumDraw({ distanceDisplayCondition: displayConditionOf(item.displayRange), id: pickId(record, item), }); + dot = { dot: dotLook(item).key, heightReference }; } - place(record, primitive, position, show); + record.patchable ??= new Map(); + record.patchable.set(item.id, { + primitive, + placed: place(record, primitive, position, show), + at: placeOf(item), + lodGroup: item.lodGroup, + ...dot, + }); } let host = points ?? dots ?? new Cesium.PointPrimitiveCollection(); if (points && dots) { @@ -889,22 +953,29 @@ export function createCesiumDraw({ PLACE_KEYS.map((key) => item.pos?.[key]).concat(item.height); /** - * Upsert unclamped points in place, without a rebuild, when every item - * is one the set draws as a point primitive now and stays unclamped in - * the same LOD group: then how it looks, where it is, its `meta` and - * whether it shows change on the point it has. False, changing nothing, - * otherwise. + * Upsert points in place, without a rebuild, when every item is one the + * set draws now, in the same LOD group, and stays drawn the same way: an + * unclamped point stays unclamped (then how it looks changes on the point + * it has), a clamped dot clamps the same way and keeps its look (the dot + * image it is drawn with). Where it is, its `meta`, its display range and + * whether it shows change in place; a dot moved follows the ground where + * it now is. False, changing nothing, otherwise. */ function patchPoints(record, list) { const patchable = record.patchable; if (record.kind !== 'points' || !patchable) return false; for (const item of list) { const was = patchable.get(item.id); - if ( - !was || - heightReferenceOf(item.height, record.spec.clampTo) !== - Cesium.HeightReference.NONE || - item.lodGroup !== was.lodGroup + if (!was || item.lodGroup !== was.lodGroup) return false; + const heightReference = heightReferenceOf( + item.height, + record.spec.clampTo, + ); + if (was.dot === undefined) { + if (heightReference !== Cesium.HeightReference.NONE) return false; + } else if ( + heightReference !== was.heightReference || + dotLook(item).key !== was.dot ) return false; } @@ -918,7 +989,13 @@ export function createCesiumDraw({ was.placed.position = position; was.at = at; } - Object.assign(was.primitive, pointLook(item)); + if (was.dot === undefined) Object.assign(was.primitive, pointLook(item)); + else { + was.primitive.distanceDisplayCondition = displayConditionOf( + item.displayRange, + ); + was.primitive.disableDepthTestDistance = item.disableDepthTest ?? 0; + } was.primitive.id.meta = item.meta; was.placed.shown = show; was.primitive.show = shownNow(record, was.placed); @@ -927,10 +1004,10 @@ export function createCesiumDraw({ } /** - * A clamped point as Cesium's entity points draw one: a billboard of a - * dot drawn at its pixel size, one texture per look. + * How a clamped point's dot is drawn: its image (by key) and the scale + * it is drawn at. */ - function addDot(collection, item, options) { + function dotLook(item) { const color = toColor(item.color); const outlineColor = toColor(item.outlineColor ?? [0, 0, 0, 0]); const outlineWidth = Math.round(item.outlineWidth ?? 0); @@ -943,73 +1020,136 @@ export function createCesiumDraw({ } const css = color.toCssColorString(); const cssOutline = outlineColor.toCssColorString(); + return { + key: JSON.stringify([css, pixelSize, cssOutline, outlineWidth, scale]), + image: JSON.stringify([css, pixelSize, cssOutline, outlineWidth]), + alpha: color.alpha, + css, + cssOutline, + outlineWidth, + pixelSize, + scale, + }; + } + + /** + * A clamped point as Cesium's entity points draw one: a billboard of a + * dot drawn at its pixel size, one texture per look. + */ + function addDot(collection, item, options) { + const look = dotLook(item); const billboard = collection.add({ ...options, - scale, + scale: look.scale, disableDepthTestDistance: item.disableDepthTest ?? 0, }); billboard.setImage( - JSON.stringify([css, pixelSize, cssOutline, outlineWidth]), + look.image, Cesium.createBillboardPointCallback( - color.alpha, - css, - cssOutline, - outlineWidth, - pixelSize, + look.alpha, + look.css, + look.cssOutline, + look.outlineWidth, + look.pixelSize, ), ); return billboard; } /** - * A `flow` line's material: dashes that run toward the line's end, over a - * faint line between them, at `speed` cells a second (`flowTime` keeps - * its clock). The dash pattern of the route annotations, which drew their - * routes before the draw port. + * A line's material; with `reveal` (where along its texture the line + * ends, `revealUniform`), one drawing only that far. A flow material + * (the route annotations' dashes, which run toward the line's end on the + * clock `flowTime` keeps) is noted for the frame clock. */ - function flowMaterial(style) { - return new Cesium.Material({ - fabric: { - type: FLOW_MATERIAL, - uniforms: { - color: toColor(style.color), - time: flowTime(style.speed), - repeat: style.repeat, - duty: style.duty, - speed: style.speed, - }, - source: FLOW_SOURCE, - }, - }); + function lineMaterial(record, style, reveal) { + const fabric = lineFabric(style); + // Built from its type, then given its values, as `fromType` does: + // values in the fabric would be merged into copies of the type's. + const template = ({ type, source, uniforms }) => + source ? { type, source, uniforms } : { type }; + const material = + reveal === undefined + ? new Cesium.Material({ fabric: template(fabric) }) + : new Cesium.Material({ + fabric: { + type: `${REVEAL_MATERIAL}_${style.kind}`, + materials: { revealed: template(fabric) }, + uniforms: { reveal }, + source: REVEAL_SOURCE, + }, + }); + const drawn = reveal === undefined ? material : material.materials.revealed; + Object.assign(drawn.uniforms, fabric.uniforms); + const flow = flowOf(material, style); + if (flow) record.flowMaterials.push(flow); + return material; } - function lineMaterial(style) { + /** + * The flow material a line's material runs on (itself, or what a revealed + * line draws), for the frame clock; null for other styles. + */ + const flowOf = (material, style) => + style.kind !== 'flow' + ? null + : material.type === FLOW_MATERIAL + ? material + : material.materials.revealed; + + /** Stop running the clock of a line material that no longer draws. */ + function dropFlow(record, material, style) { + const flow = material && flowOf(material, style); + if (flow) + record.flowMaterials = record.flowMaterials.filter((m) => m !== flow); + } + + /** Whether a line draws only the first part of its length. */ + const revealed = (item) => item.revealFraction !== undefined; + + /** The fabric of a line style's material. */ + function lineFabric(style) { switch (style.kind) { case 'flow': - return flowMaterial(style); + return { + type: FLOW_MATERIAL, + uniforms: { + color: toColor(style.color), + time: flowTime(style.speed), + repeat: style.repeat, + duty: style.duty, + speed: style.speed, + }, + source: FLOW_SOURCE, + }; case 'solid': - return Cesium.Material.fromType('Color', { - color: toColor(style.color), - }); + return { type: 'Color', uniforms: { color: toColor(style.color) } }; case 'glow': - return Cesium.Material.fromType('PolylineGlow', { - color: toColor(style.color), - glowPower: style.power, - taperPower: style.taper ?? 1, - }); + return { + type: 'PolylineGlow', + uniforms: { + color: toColor(style.color), + glowPower: style.power, + taperPower: style.taper ?? 1, + }, + }; case 'dash': - return Cesium.Material.fromType('PolylineDash', { - color: toColor(style.color), - gapColor: toColor(style.gapColor ?? [0, 0, 0, 0]), - dashLength: style.length, - ...(style.pattern16 !== undefined - ? { dashPattern: style.pattern16 } - : {}), - }); + return { + type: 'PolylineDash', + uniforms: { + color: toColor(style.color), + gapColor: toColor(style.gapColor ?? [0, 0, 0, 0]), + dashLength: style.length, + ...(style.pattern16 !== undefined + ? { dashPattern: style.pattern16 } + : {}), + }, + }; case 'arrow': - return Cesium.Material.fromType('PolylineArrow', { - color: toColor(style.color), - }); + return { + type: 'PolylineArrow', + uniforms: { color: toColor(style.color) }, + }; default: throw new Error(`the Cesium renderer has no ${style.kind} lines`); } @@ -1068,8 +1208,10 @@ export function createCesiumDraw({ function depthFailLine(record, item, id) { const positions = linePositions(item); if (!drawable(positions)) return null; - const material = lineMaterial(item.style); - if (item.style.kind === 'flow') record.flowMaterials.push(material); + const reveal = revealed(item) + ? revealUniform(item.revealFraction, positions) + : undefined; + const material = lineMaterial(record, item.style, reveal); return new Cesium.Primitive({ geometryInstances: new Cesium.GeometryInstance({ geometry: new Cesium.PolylineGeometry({ @@ -1084,78 +1226,122 @@ export function createCesiumDraw({ }), appearance: new Cesium.PolylineMaterialAppearance({ material }), depthFailAppearance: new Cesium.PolylineMaterialAppearance({ - material: Cesium.Material.fromType('Color', { - color: toColor(item.depthFailColor), - }), + material: lineMaterial( + record, + { kind: 'solid', color: item.depthFailColor }, + reveal, + ), }), show: item.show !== false, asynchronous: false, }); } + /** + * A draped line's geometry instance under its pick id: coloured per + * instance when `solid` (batched with others), else drawn by its + * primitive's material. + */ + function drapedInstance(item, part, solid, positions = linePositions(item)) { + const show = new Cesium.ShowGeometryInstanceAttribute(item.show !== false); + return new Cesium.GeometryInstance({ + geometry: new Cesium.GroundPolylineGeometry({ + positions, + width: item.widthPx, + arcType: Cesium.ArcType.GEODESIC, + }), + attributes: solid + ? { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.style.color), + ), + show, + } + : { show }, + id: part.id, + }); + } + + /** Whether a draped line draws in a batch of solid ones. */ + const batchable = (item) => item.style.kind === 'solid' && !revealed(item); + + /** + * A ground primitive of a draped line's own, drawn by a material (a + * style, or a reveal, a batch cannot draw) or, solid, by its colour. With + * `sync` it is built in the first frame it is updated in, as Cesium's + * entities build ground lines whose positions change: only once Cesium's + * approximate terrain heights are loaded (`groundSyncs`). + */ + function drapedPrimitive(record, item, part, sync, positions) { + const solid = batchable(item); + let appearance; + if (solid) { + appearance = new Cesium.PolylineColorAppearance(); + part.material = null; + } else { + part.material = lineMaterial( + record, + item.style, + revealed(item) ? revealUniform(item.revealFraction) : undefined, + ); + appearance = new Cesium.PolylineMaterialAppearance({ + material: part.material, + }); + } + return new Cesium.GroundPolylinePrimitive({ + geometryInstances: [drapedInstance(item, part, solid, positions)], + appearance, + classificationType: classificationOf(part.clampTo), + allowPicking: record.spec.pickable !== false, + asynchronous: !sync, + }); + } + function buildLines(record) { // Refused before anything changes, so the set keeps drawing as it was. for (const item of record.items.values()) - if ( - item.mode === 'draped' && - item.style.kind !== 'solid' && - item.style.kind !== 'flow' - ) - throw new Error('the Cesium renderer drapes solid and flow lines only'); + if (item.mode === 'draped' && !DRAPED_STYLES.has(item.style.kind)) + throw new Error( + 'the Cesium renderer drapes solid, glow, dash and flow lines only', + ); const polylines = new Cesium.PolylineCollection(); const draped = new Map(); - const flows = []; + // Draped lines a batch cannot draw, each with a primitive of its own. + const alone = []; // Each line as drawn, for upserts that change it in place. const parts = new Map(); - record.lineParts = parts; // What the old host's flow lines run on, while it still draws; a host // already retiring keeps drawing in its place, with its own. - if (!record.retiring) record.retiringFlows = record.flowMaterials ?? null; + if (!record.retiring) { + record.retiringFlows = record.flowMaterials ?? null; + record.retiringParts = record.drawnParts ?? null; + } record.flowMaterials = []; + record.lineParts = parts; // Lines with a depth-fail colour, beside the collection. let deep = null; for (const item of record.items.values()) { if (item.mode === 'draped') { - const kind = item.style.kind; const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; - const id = pickId(record, item); const part = { look: lineLook(item), positions: flatPositions(item.positions), clampTo, - id, + id: pickId(record, item), + // Its ground primitive: its batch's, or its own. ground: null, + batch: null, + material: null, + // Moved in place: drawn by a primitive of its own built at once. + solo: false, }; parts.set(item.id, part); - const show = new Cesium.ShowGeometryInstanceAttribute( - item.show !== false, - ); - const instance = new Cesium.GeometryInstance({ - geometry: new Cesium.GroundPolylineGeometry({ - positions: linePositions(item), - width: item.widthPx, - arcType: Cesium.ArcType.GEODESIC, - }), - attributes: - kind === 'solid' - ? { - color: Cesium.ColorGeometryInstanceAttribute.fromColor( - toColor(item.style.color), - ), - show, - } - : { show }, - id, - }); - if (kind === 'flow') { - // A material for the whole primitive: one primitive each. - const material = flowMaterial(item.style); - record.flowMaterials.push(material); - flows.push({ clampTo, instance, material, part }); + if (!batchable(item)) { + alone.push({ item, part }); continue; } if (!draped.has(clampTo)) draped.set(clampTo, []); - draped.get(clampTo).push(instance); + draped.get(clampTo).push(drapedInstance(item, part, true)); continue; } if (item.depthFailColor) { @@ -1166,16 +1352,23 @@ export function createCesiumDraw({ parts.set(item.id, { look: lineLook(item), id, deep: primitive }); continue; } - const material = lineMaterial(item.style); - if (item.style.kind === 'flow') record.flowMaterials.push(material); + const positions = linePositions(item); + const reveal = revealed(item) + ? revealUniform(item.revealFraction, positions) + : undefined; + const material = lineMaterial(record, item.style, reveal); const polyline = polylines.add({ - positions: linePositions(item), + positions, width: item.widthPx, material, show: item.show !== false, id: pickId(record, item), }); - parts.set(item.id, { look: lineLook(item), polyline }); + parts.set(item.id, { + look: lineLook(item), + polyline, + reveal: reveal === undefined ? null : material, + }); } let own = polylines; if (deep) { @@ -1184,8 +1377,10 @@ export function createCesiumDraw({ own.add(deep); } record.deepLines = deep; - noteFlows(record); - if (!draped.size && !flows.length) return replaceHost(record, own); + if (!draped.size && !alone.length) { + noteFlows(record); + return replaceHost(record, own); + } // Draped lines drape as the entities' clamped polylines do. const byClamp = new Map(); const ground = [...draped].map(([clampTo, geometryInstances]) => { @@ -1199,22 +1394,21 @@ export function createCesiumDraw({ return primitive; }); for (const part of parts.values()) - if (part.clampTo) part.ground = byClamp.get(part.clampTo) ?? null; - for (const { clampTo, instance, material, part } of flows) { - part.ground = new Cesium.GroundPolylinePrimitive({ - geometryInstances: [instance], - appearance: new Cesium.PolylineMaterialAppearance({ material }), - classificationType: classificationOf(clampTo), - allowPicking: record.spec.pickable !== false, - }); + if (part.clampTo && byClamp.has(part.clampTo)) { + part.ground = byClamp.get(part.clampTo); + part.batch = part.ground; + } + for (const { item, part } of alone) { + part.ground = drapedPrimitive(record, item, part, false); ground.push(part.ground); } + noteFlows(record); replaceHost(record, collect(own, ground), ground, own); } /** - * How a line draws, but for where it runs and whether it shows: lines - * that keep it can be changed in place. + * How a line draws, but for where it runs, whether it shows and how much + * of it is revealed: lines that keep it can be changed in place. */ const lineLook = (item) => JSON.stringify([ @@ -1225,7 +1419,7 @@ export function createCesiumDraw({ item.depthFailColor, item.segmentColors, item.segmentShow, - item.revealFraction, + revealed(item), item.frame, ]); @@ -1242,12 +1436,28 @@ export function createCesiumDraw({ const samePositions = (a, b) => a.length === b.length && a.every((value, i) => Object.is(value, b[i])); + /** + * Whether a draped line's upsert can change it in place: its ground + * primitive is still there and, unless it moves, ready or building as + * the set's pending one (or drawn alone); one that moves is built anew + * at once, which needs Cesium's terrain heights loaded. + */ + function drapedPatchable(record, was, item) { + if (was.ground?.isDestroyed() || was.batch?.isDestroyed()) return false; + if (!samePositions(flatPositions(item.positions), was.positions)) + return groundSyncs() && typeof record.host?.add === 'function'; + if (was.solo) return true; + return was.ground.ready || record.pending?.includes(was.ground); + } + /** * Upsert lines in place, without a rebuild, when every item is drawn now - * and looks the same: then only whether it shows, its `meta`, and where - * a line not draped runs change (one with a depth-fail colour is built - * anew, alone). A draped line keeps its positions, and - * its ground primitive must be ready. False, changing nothing, otherwise. + * and looks the same: then only whether it shows, its `meta`, how much of + * it is revealed and where it runs change. An undraped line moves on the + * polyline it has (one with a depth-fail colour is built anew, alone); a + * draped one that moves is drawn by a ground primitive of its own, built + * anew in the frame it moves (`drapedPatchable`). False, changing + * nothing, otherwise. */ function patchLines(record, list) { const parts = record.lineParts; @@ -1257,21 +1467,21 @@ export function createCesiumDraw({ if (!was || was.look !== lineLook(item)) return false; if (was.deep !== undefined && record.deepLines?.isDestroyed()) return false; - if ( - was.ground && - (was.ground.isDestroyed() || - (!was.ground.ready && !record.pending?.includes(was.ground)) || - !samePositions(flatPositions(item.positions), was.positions)) - ) - return false; + if (was.clampTo && !drapedPatchable(record, was, item)) return false; } for (const item of list) { const was = parts.get(item.id); const show = item.show !== false; if (was.polyline) { - was.polyline.positions = linePositions(item); + const positions = linePositions(item); + was.polyline.positions = positions; was.polyline.show = show; was.polyline.id.meta = item.meta; + if (was.reveal) + was.reveal.uniforms.reveal = revealUniform( + item.revealFraction, + positions, + ); continue; } if (was.deep !== undefined) { @@ -1279,16 +1489,29 @@ export function createCesiumDraw({ // Built anew where it now runs, under the same pick id. const deep = record.deepLines; const old = was.deep; - if (old) - record.flowMaterials = record.flowMaterials.filter( - (material) => material !== old.appearance.material, - ); + if (old) { + dropFlow(record, old.appearance.material, item.style); + dropFlow(record, old.depthFailAppearance.material, item.style); + } was.deep = depthFailLine(record, item, was.id); if (was.deep) deep.add(was.deep); if (old) deep.remove(old); continue; } was.id.meta = item.meta; + const flat = flatPositions(item.positions); + if (!samePositions(flat, was.positions)) { + moveDraped(record, was, item, flat); + continue; + } + if (was.material && revealed(item)) + was.material.uniforms.reveal = revealUniform(item.revealFraction); + if (was.solo) { + // Not yet drawn, it is built again showing as asked. + if (was.ground && was.ground.ready) showPart(was, show); + else if (was.ground) moveDraped(record, was, item, flat); + continue; + } // A ground primitive still building takes its show once it is ready // (`swapReady`), so a show change never restarts the build. // A show queued while it built is stale once a newer one is applied. @@ -1300,22 +1523,80 @@ export function createCesiumDraw({ return true; } + /** + * Draw a draped line where it now runs, in this frame: on a ground + * primitive of its own built at once, in place of its own one (or of its + * place in its batch, hidden there). Positions that make no line draw + * nothing until they do again. + */ + function moveDraped(record, part, item, flat) { + const host = record.host; + const old = part.ground; + if (old && old !== part.batch) { + dropFlow(record, part.material, item.style); + for (const list of new Set([record.pending, record.ground])) { + const at = list?.indexOf(old) ?? -1; + if (at >= 0) list.splice(at, 1); + } + host.remove(old); + } else if (old) { + // Its batch draws on without it, hidden now or once it is ready. + part.batchHidden = true; + if (old.ready) showOn(old, part.id, false); + } + hideRetiring(record, item.id); + part.solo = true; + part.positions = flat; + part.pendingShow = undefined; + const positions = linePositions(item); + part.material = null; + part.ground = drawable(positions) + ? drapedPrimitive(record, item, part, true, positions) + : null; + if (part.ground) host.add(part.ground); + } + + /** + * Hide where the host a set is rebuilding from still draws a draped line, + * once the line is drawn where it now is: else both would draw (and + * pick) until the rebuild is ready. + */ + function hideRetiring(record, id) { + const part = record.retiring && record.retiringParts?.get(id); + const ground = part?.ground; + if (ground && !ground.isDestroyed() && ground.ready) + showOn(ground, part.id, false); + } + /** A draped line part's show, on its ready ground primitive. */ - function showPart(part, show) { - const attributes = part.ground.getGeometryInstanceAttributes(part.id); + const showPart = (part, show) => showOn(part.ground, part.id, show); + + /** The show of the instance under pick id `id` in a ready ground primitive. */ + function showOn(ground, id, show) { + const attributes = ground.getGeometryInstanceAttributes(id); attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue( show, attributes.show, ); } - /** The shows patched in while a set's ground primitives were building. */ + /** + * The shows patched in while a set's ground primitives were building, + * and the lines drawn alone since, hidden in their batches. + */ function showPending(record) { - for (const part of record.lineParts?.values() ?? []) - if (part.pendingShow !== undefined && !part.ground.isDestroyed()) { + for (const part of record.lineParts?.values() ?? []) { + if (part.batchHidden && part.batch && !part.batch.isDestroyed()) + showOn(part.batch, part.id, false); + if ( + part.pendingShow !== undefined && + part.ground && + !part.ground.isDestroyed() + ) { showPart(part, part.pendingShow); part.pendingShow = undefined; } + } } /** One host for a set's own collection and its ground primitives. */ diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 59ad9134a..a4c5cf108 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import test from 'node:test'; import { bindRenderer, drawOf, findDraw } from '../rendererOf.js'; -import { createCesiumDraw } from './draw.js'; +import { createCesiumDraw, revealUniform } from './draw.js'; import { drawHitOf } from './drawHit.js'; // Node has no WebGL context to report line-width limits. @@ -2084,7 +2084,10 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del ); assert.equal( set.imageNear(row), - iconAtlas.slot(aircraftIcon('airliner', TRACKED_ICON_PX), TRACKED_ICON_PX), + iconAtlas.slot( + aircraftIcon('airliner', TRACKED_ICON_PX), + TRACKED_ICON_PX, + ), 'the near glyph at 192 px', ); assert.equal(set.imageSwitch(row), nearImageSwitchPx(2)); @@ -2106,7 +2109,9 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del Cesium.Cartographic.fromCartesian(drawn).longitude, ); assert.ok(lon > -97 && lon < -96.9, 'interpolating the fixes'); - assert.ok(Math.abs(set.course(row, tau) - icons._iconCourse('abc123')) < 0.01); + assert.ok( + Math.abs(set.course(row, tau) - icons._iconCourse('abc123')) < 0.01, + ); assert.equal(state._icons.expires('abc123'), now - 20_000); assert.deepEqual( drawHitOf(host._pickObject('abc123', null, { show: true })), @@ -2392,7 +2397,14 @@ test('flow lines run their dashes toward the end, draped or not, on the frame cl const shown = new Uint8Array([1]); draped.getGeometryInstanceAttributes = () => ({ show: shown }); set.upsert([ - { id: 'route', positions, widthPx: 9, mode: 'draped', style, show: false }, + { + id: 'route', + positions, + widthPx: 9, + mode: 'draped', + style, + show: false, + }, ]); assert.equal(scene.added[0], host, 'changed in place'); assert.deepEqual([...shown], [0]); @@ -2416,19 +2428,19 @@ test('flow lines run their dashes toward the end, draped or not, on the frame cl asked = 0; frame(); assert.equal(asked, 0, 'an emptied set asks for none'); - // Other styles still drape only solid. + // Arrows and patterns are not draped. assert.throws( () => set.set([ { - id: 'dash', + id: 'arrow', positions, widthPx: 1, mode: 'draped', - style: { kind: 'dash', color: '#fff', length: 8 }, + style: { kind: 'arrow', color: '#fff' }, }, ]), - /drapes solid and flow lines only/, + /drapes solid, glow, dash and flow lines only/, ); set.dispose(); })); @@ -2555,7 +2567,12 @@ test('a draped flow line still drawing while its rebuilds build keeps flowing', test('the directions layer draws its markers, flowing route and maneuver dots on a viewer of its own', async (t) => { // Materials check their uniforms against the DOM's image classes. - const names = ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']; + const names = [ + 'HTMLCanvasElement', + 'HTMLImageElement', + 'ImageBitmap', + 'OffscreenCanvas', + ]; const real = names.map((name) => globalThis[name]); for (const name of names) globalThis[name] ??= class {}; t.after(() => names.forEach((name, i) => (globalThis[name] = real[i]))); @@ -2698,12 +2715,18 @@ test('the directions layer draws its markers, flowing route and maneuver dots on test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on a viewer of its own', async (t) => { // Materials check their uniforms against the DOM's image classes. - const names = ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']; + const names = [ + 'HTMLCanvasElement', + 'HTMLImageElement', + 'ImageBitmap', + 'OffscreenCanvas', + ]; const real = names.map((name) => globalThis[name]); for (const name of names) globalThis[name] ??= class {}; t.after(() => names.forEach((name, i) => (globalThis[name] = real[i]))); await import('./frame.js'); - const { createLocalAdsbLayer } = await import('../../layers/localAdsb/index.js'); + const { createLocalAdsbLayer } = + await import('../../layers/localAdsb/index.js'); const { fakeInput } = await import('../../input/testDoubles.mjs'); const { toLonLatH } = await import('../../geo/ellipsoid.js'); const scene = fakeScene(); @@ -2735,7 +2758,10 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on band, source: 'feed', }); - const records = [aircraft('abc123', '1090', 0), aircraft('a1b2c3', '978', 0.1)]; + const records = [ + aircraft('abc123', '1090', 0), + aircraft('a1b2c3', '978', 0.1), + ]; const layer = createLocalAdsbLayer({ receiver: { getState: () => ({ aircraft: [] }), @@ -2752,7 +2778,10 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on render: { governorRequestRender: noop }, context: { registerEntityContext: noop, - selectEntityContext: (carrier) => ({ id: 'local-adsb:abc123', carrier }), + selectEntityContext: (carrier) => ({ + id: 'local-adsb:abc123', + carrier, + }), getSelectedEntityContext: () => ({ id: 'local-adsb:abc123' }), clearSelectedEntityContextForLayer: noop, removeEntityContextsForLayer: noop, @@ -2782,9 +2811,7 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on [icon.scaleByDistance.near, icon.scaleByDistance.nearValue], [1000, 3], ); - assert.ok( - icon.color.equals(Cesium.Color.fromCssColorString('#ff4fd8')), - ); + assert.ok(icon.color.equals(Cesium.Color.fromCssColorString('#ff4fd8'))); // The UAT-only aircraft's ring: an outline, shown as far as it is. const rings = hostOf(':rings'); assert.ok(rings instanceof Cesium.PointPrimitiveCollection); @@ -2823,3 +2850,434 @@ test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on clicks.destroy(); assert.equal(hostOf(':markers'), undefined, 'every set let go'); }); + +/** Run `fn` as if Cesium's approximate terrain heights had loaded. */ +function withTerrainHeights(fn) { + const heights = Cesium.ApproximateTerrainHeights; + const was = heights._terrainHeights; + heights._terrainHeights ??= {}; + try { + return fn(); + } finally { + heights._terrainHeights = was; + } +} + +test('draped glow and dash lines drape with their materials, each on a ground primitive of its own', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.lines({ id: 'styled', clampTo: 'terrain' }); + const positions = [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ]; + set.set([ + { + id: 'core', + positions, + widthPx: 5, + mode: 'draped', + style: { + kind: 'glow', + color: [1, 0.5, 0, 0.9], + power: 0.24, + taper: 0.7, + }, + }, + { + id: 'halo', + positions, + widthPx: 18, + mode: 'draped', + clampTo: 'both', + style: { kind: 'dash', color: '#d8954e', length: 18 }, + }, + ]); + const host = scene.added[0]; + const [glow, dash] = [host.get(1), host.get(2)]; + for (const ground of [glow, dash]) { + assert.ok(ground instanceof Cesium.GroundPolylinePrimitive); + assert.ok(ground.appearance instanceof Cesium.PolylineMaterialAppearance); + assert.equal(ground.show, false, 'hidden while it builds'); + } + assert.equal(glow.classificationType, Cesium.ClassificationType.TERRAIN); + assert.equal(dash.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(glow.geometryInstances[0].id.id, 'core'); + assert.equal(dash.geometryInstances[0].geometry.width, 18); + const glowMaterial = glow.appearance.material; + assert.equal(glowMaterial.type, 'PolylineGlow'); + assert.equal(glowMaterial.uniforms.glowPower, 0.24); + assert.equal(glowMaterial.uniforms.taperPower, 0.7); + assert.ok(glowMaterial.uniforms.color instanceof Cesium.Color); + const dashMaterial = dash.appearance.material; + assert.equal(dashMaterial.type, 'PolylineDash'); + assert.equal(dashMaterial.uniforms.dashLength, 18); + assert.ok( + Cesium.Color.equals( + dashMaterial.uniforms.gapColor, + Cesium.Color.TRANSPARENT, + ), + ); + set.dispose(); + })); + +test('revealFraction draws a line up to that fraction of its length, and changes in place', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.lines({ id: 'revealed' }); + const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0); + // Segments a quarter and three quarters of the length. + const air = (revealFraction, extra = {}) => ({ + id: 'air', + positions: [at(0), at(1), at(4)], + widthPx: 3, + mode: '3d', + style: { kind: 'solid', color: '#fff' }, + revealFraction, + ...extra, + }); + const ground = (revealFraction) => ({ + id: 'ground', + positions: [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ], + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: '#20e7f2' }, + revealFraction, + }); + set.set([air(0.5), ground(0.25)]); + const host = scene.added[0]; + const polyline = host.get(0).get(0); + assert.equal(polyline.material.type, 'DrawRevealLine_solid'); + // Half the length is a third of the way along the second segment, + // which a polyline's texture spans from 1/2 to 1. + assert.ok( + Math.abs(polyline.material.uniforms.reveal - (1 + 1 / 3) / 2) < 1e-3, + ); + assert.ok( + Cesium.Color.equals( + polyline.material.materials.revealed.uniforms.color, + Cesium.Color.WHITE, + ), + ); + // A revealed draped line draws alone, its texture along its length. + const draped = host.get(1); + assert.ok(draped instanceof Cesium.GroundPolylinePrimitive); + assert.equal(draped.appearance.material.type, 'DrawRevealLine_solid'); + assert.equal(draped.appearance.material.uniforms.reveal, 0.25); + // Revealed further, in place. + Object.defineProperty(draped, 'ready', { value: true }); + draped.getGeometryInstanceAttributes = () => ({ + show: new Uint8Array([1]), + }); + set.upsert([air(0.25), ground(0.75)]); + assert.equal(scene.added[0], host, 'not rebuilt'); + assert.ok(Math.abs(polyline.material.uniforms.reveal - 0.5) < 1e-3); + assert.equal(draped.appearance.material.uniforms.reveal, 0.75); + // Nothing at 0, everything at 1. + set.upsert([air(0), ground(1)]); + assert.ok(polyline.material.uniforms.reveal < 0); + assert.ok(draped.appearance.material.uniforms.reveal > 1); + // Dropping the reveal draws the line whole: a new look, rebuilt. + set.upsert([air(undefined)]); + assert.notEqual(scene.added.at(-1), host); + set.dispose(); + })); + +test('revealFraction reveals flow and depth-fail lines too, their clocks still run', () => + withImageClasses(() => { + const { scene, draw, frame } = drawOver(); + const set = draw.lines({ id: 'revealed-styles' }); + const flow = { + kind: 'flow', + color: '#39d0ff', + repeat: 8, + duty: 0.5, + speed: 1, + }; + set.set([ + { + id: 'route', + positions: [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ], + widthPx: 9, + mode: 'draped', + style: flow, + revealFraction: 0.5, + }, + { + id: 'head', + positions: [ + Cesium.Cartesian3.fromDegrees(0, 0, 100), + Cesium.Cartesian3.fromDegrees(0, 0, 300), + ], + widthPx: 2, + mode: '3d', + style: { kind: 'solid', color: '#f0f' }, + depthFailColor: [1, 0, 1, 0.45], + revealFraction: 0.5, + }, + ]); + const host = scene.added[0]; + const route = host.get(1).appearance.material; + assert.equal(route.type, 'DrawRevealLine_flow'); + const clock = route.materials.revealed; + assert.equal(clock.type, 'DrawFlowLine'); + clock.uniforms.time = -1; + frame(); + assert.ok(clock.uniforms.time >= 0, 'the revealed flow keeps its clock'); + const head = host.get(0).get(1).get(0); + assert.equal(head.appearance.material.uniforms.reveal, 0.5); + assert.equal(head.depthFailAppearance.material.uniforms.reveal, 0.5); + assert.ok( + Cesium.Color.equals( + head.depthFailAppearance.material.materials.revealed.uniforms.color, + new Cesium.Color(1, 0, 1, 0.45), + ), + ); + set.dispose(); + })); + +test('a draped line that moves is drawn where it now is in the same frame, once terrain heights are loaded', () => + withImageClasses(() => + withTerrainHeights(() => { + const { scene, draw, frame } = drawOver(); + const set = draw.lines({ id: 'growing' }); + const flow = { + kind: 'flow', + color: '#39d0ff', + repeat: 8, + duty: 0.5, + speed: 1, + }; + const line = (id, lon, extra = {}) => ({ + id, + positions: [ + { lon: 0, lat: 0 }, + { lon, lat: 1 }, + ], + widthPx: 3, + mode: 'draped', + style: { kind: 'solid', color: '#20e7f2' }, + ...extra, + }); + set.set([line('a', 1), line('b', 1), line('f', 1, { style: flow })]); + const host = scene.added[0]; + const batch = host.get(1); + const own = host.get(2); + const shows = new Map(); + const attributesOf = (primitive) => { + primitive.getGeometryInstanceAttributes = (id) => { + const key = `${primitive.geometryInstances.length}:${id.id}`; + if (!shows.has(key)) shows.set(key, { show: new Uint8Array([1]) }); + return shows.get(key); + }; + }; + attributesOf(batch); + // Moved while its batch still builds: drawn alone, built at once. + set.upsert([line('a', 2, { meta: 'moved' })]); + assert.equal(scene.added[0], host, 'the set is not rebuilt'); + const solo = host.get(host.length - 1); + assert.ok(solo instanceof Cesium.GroundPolylinePrimitive); + assert.equal(solo.asynchronous, false, 'built in the frame it is drawn'); + assert.equal(solo.geometryInstances[0].id.id, 'a'); + assert.equal(solo.geometryInstances[0].id.meta, 'moved'); + assert.notEqual(solo.show, false, 'shown at once'); + const end = solo.geometryInstances[0].geometry._positions.at(-1); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + end, + Cesium.Cartesian3.fromDegrees(2, 1), + 1e-6, + ), + ); + // Its place in the batch is hidden once the batch is ready. + Object.defineProperty(batch, 'ready', { value: true }); + Object.defineProperty(own, 'ready', { value: true }); + frame(); + assert.deepEqual([...shows.get('2:a').show], [0], 'hidden in the batch'); + assert.equal(batch.show, true, 'the batch still draws the rest'); + // Moved again: the one built for it is replaced. + set.upsert([line('a', 3)]); + const again = host.get(host.length - 1); + assert.notEqual(again, solo); + assert.ok(solo.isDestroyed(), 'the old one goes'); + // A flow line moved keeps flowing on its new material. + set.upsert([line('f', 2, { style: flow })]); + assert.ok(own.isDestroyed(), 'its own primitive replaced'); + const moved = host.get(host.length - 1); + const clock = moved.appearance.material; + assert.equal(clock.type, 'DrawFlowLine'); + clock.uniforms.time = -1; + frame(); + assert.ok(clock.uniforms.time >= 0); + // Positions that make no line draw nothing, until they do. + const count = host.length; + set.upsert([line('a', 0, { positions: [{ lon: 0, lat: 0 }] })]); + assert.equal(host.length, count - 1); + set.upsert([line('a', 4)]); + assert.equal(host.length, count); + // A show change on a ready one is in place. + const shown = host.get(host.length - 1); + Object.defineProperty(shown, 'ready', { value: true }); + attributesOf(shown); + set.upsert([line('a', 4, { show: false })]); + assert.equal(host.get(host.length - 1), shown); + assert.deepEqual([...shows.get('1:a').show], [0]); + set.dispose(); + assert.equal(scene.added.length, 0); + }), + )); + +test('a draped line that moves before terrain heights load is rebuilt, as before', () => + withImageClasses(() => { + const heights = Cesium.ApproximateTerrainHeights; + const was = heights._terrainHeights; + heights._terrainHeights = undefined; + try { + const { scene, draw } = drawOver(); + const set = draw.lines({ id: 'early' }); + const line = (lon) => ({ + id: 'a', + positions: [ + { lon: 0, lat: 0 }, + { lon, lat: 1 }, + ], + widthPx: 3, + mode: 'draped', + style: { kind: 'solid', color: '#fff' }, + }); + set.set([line(1)]); + const host = scene.added[0]; + set.upsert([line(2)]); + assert.notEqual(scene.added.at(-1), host, 'rebuilt'); + set.dispose(); + } finally { + heights._terrainHeights = was; + } + })); + +test('a clamped point that moves follows the ground where it now is, on the dot it has', () => { + const { scene, draw } = drawOver(); + const set = draw.points({ id: 'surge' }); + const front = (lon, extra = {}) => ({ + id: 'front', + pos: { lon, lat: 28 }, + height: 'clampGround', + pixelSize: 11, + color: '#e8b47c', + outlineColor: [0, 0, 0, 0.85], + outlineWidth: 3, + ...extra, + }); + set.set([front(85)]); + const host = scene.added[0]; + const dot = host.get(0); + scene.clamped.length = 0; + set.upsert([front(85.01, { meta: 'next', show: false })]); + assert.equal(scene.added[0], host, 'not rebuilt'); + assert.equal(host.get(0), dot, 'the same dot'); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + dot.position, + Cesium.Cartesian3.fromDegrees(85.01, 28), + 1e-6, + ), + ); + assert.equal(dot.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND); + assert.ok(scene.clamped.length > 0, 'clamped again where it now is'); + assert.equal(dot.id.meta, 'next'); + assert.equal(dot.show, false); + // A new look is a new dot image: rebuilt. + set.upsert([front(85.01, { pixelSize: 14 })]); + assert.notEqual(scene.added[0], host); + // So is clamping it no more. + const clamped = scene.added[0]; + set.upsert([front(85.01, { pixelSize: 14, height: undefined })]); + assert.notEqual(scene.added[0], clamped); + set.dispose(); +}); + +test('a revealed polyline maps its length onto its texture as Cesium draws it', () => { + const p = (x) => new Cesium.Cartesian3(x, 0, 0); + // Its texture runs evenly over its vertices, neighbours at one place one. + assert.equal(revealUniform(0.5, [p(0), p(0), p(1), p(2)]), 0.5); + assert.ok(Math.abs(revealUniform(0.25, [p(0), p(1), p(4)]) - 0.5) < 1e-12); + assert.equal(revealUniform(0.4), 0.4, 'a ground line: its length'); + assert.equal(revealUniform(0, [p(0), p(1)]), -1); + assert.equal(revealUniform(1, [p(0), p(1)]), 2); +}); + +test('a set of draped flow lines only asks for the frames they flow on', () => + withImageClasses(() => { + const scene = fakeScene(); + let asked = 0; + const request = scene.requestRender; + scene.requestRender = function () { + asked += 1; + return request.call(this); + }; + const { draw, frame } = drawOver(scene); + const set = draw.lines({ id: 'draped-flow' }); + set.set([ + { + id: 'route', + positions: [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ], + widthPx: 9, + mode: 'draped', + style: { + kind: 'flow', + color: '#39d0ff', + repeat: 8, + duty: 0.5, + speed: 1, + }, + }, + ]); + asked = 0; + frame(); + assert.ok(asked > 0, 'it flows on in the frames that follow'); + set.dispose(); + })); + +test('a draped line moved while its set rebuilds is no longer drawn where it was', () => + withImageClasses(() => + withTerrainHeights(() => { + const { scene, draw, frame } = drawOver(); + const set = draw.lines({ id: 'rebuilding' }); + const line = (id, lon) => ({ + id, + positions: [ + { lon: 0, lat: 0 }, + { lon, lat: 1 }, + ], + widthPx: 3, + mode: 'draped', + style: { kind: 'solid', color: '#fff' }, + }); + set.set([line('a', 1), line('b', 1)]); + const first = scene.added[0]; + const ground = first.get(1); + Object.defineProperty(ground, 'ready', { value: true }); + const shows = new Map(); + ground.getGeometryInstanceAttributes = (id) => { + if (!shows.has(id.id)) shows.set(id.id, { show: new Uint8Array([1]) }); + return shows.get(id.id); + }; + frame(); + // Rebuilt: the first host draws on until the new one is ready. + set.set([line('a', 1), line('b', 1), line('c', 1)]); + assert.ok(scene.added.includes(first), 'the first still draws'); + set.upsert([line('a', 2)]); + assert.deepEqual([...shows.get('a').show], [0], 'hidden where it was'); + assert.equal(shows.get('b'), undefined, 'the rest still draw there'); + set.dispose(); + }), + )); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 1f07bb8db..ca6b026d2 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -41,6 +41,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.icons.distance', 'draw.icons.update', 'draw.lines.styles', + 'draw.lines.drape', 'draw.ids', 'draw.models', 'draw.motion', diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index c27b82015..b7cfa30fd 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -1417,6 +1417,135 @@ export function portChecks() { lines.dispose(); }, ), + check( + 'draw.lines.drape', + 'draped glow and dash lines draw and pick; a revealed line draws only its first part; a draped line and a clamped point that move every frame are drawn where they now are in the next frame', + async (h, r) => { + await overAustin(h, r); + const at = (dLon, dLat = 0) => + h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat }); + const lines = r.draw.lines({ id: 'conf:line-drape' }); + const mine = (pos, id) => { + const s = r.query.project(pos); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some((hit) => hit.set === 'conf:line-drape' && hit.id === id), + ); + }; + lines.set([ + { + id: 'glow', + positions: [at(-0.003, 0.002), at(0.003, 0.002)], + widthPx: 12, + mode: 'draped', + style: { kind: 'glow', color: [1, 0.6, 0.2, 1], power: 0.25 }, + }, + { + id: 'dash', + positions: [at(-0.003, -0.002), at(0.003, -0.002)], + widthPx: 12, + mode: 'draped', + style: { + kind: 'dash', + color: [1, 0.6, 0.2, 1], + gapColor: [0.2, 0.6, 1, 1], + length: 16, + }, + }, + { + id: 'reveal', + positions: [at(-0.003), at(0.003)], + widthPx: 12, + mode: 'draped', + style: { kind: 'solid', color: '#20e7f2' }, + revealFraction: 0.5, + }, + ]); + await drawn(h, r); + await settled(r); + await drawn(h, r); + ok(mine(at(0, 0.002), 'glow'), 'a draped glow line picks'); + ok(mine(at(0, -0.002), 'dash'), 'a draped dash line picks'); + ok(mine(at(-0.0015), 'reveal'), 'revealed: its first half draws'); + ok(!mine(at(0.0015), 'reveal'), 'revealed: its second half does not'); + lines.upsert([ + { + id: 'reveal', + positions: [at(-0.003), at(0.003)], + widthPx: 12, + mode: 'draped', + style: { kind: 'solid', color: '#20e7f2' }, + revealFraction: 1, + }, + ]); + await drawn(h, r); + ok(mine(at(0.0015), 'reveal'), 'revealed whole: all of it draws'); + // A draped line growing every frame. Its first moves may take a + // few frames while the renderer readies itself to build it at once. + const growing = (end) => ({ + id: 'growing', + positions: [at(-0.003, 0.004), at(end, 0.004)], + widthPx: 12, + mode: 'draped', + style: { kind: 'solid', color: '#ff00ff' }, + }); + lines.upsert([growing(-0.002)]); + let ready = false; + for (let i = 0; i < 300 && !ready; i++) { + lines.upsert([growing(-0.002 + (i % 2) * 1e-6)]); + await drawn(h, r, 1); + ready = mine(at(-0.0025, 0.004), 'growing'); + } + ok(ready, 'the growing line draws'); + const points = r.draw.points({ id: 'conf:line-drape-point' }); + const front = (dLon) => ({ + id: 'front', + pos: { lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + 0.003, height: 0 }, + height: 'clampGround', + pixelSize: 16, + color: '#ff0000', + // On the surface it would be half under it. + disableDepthTest: Infinity, + }); + const point = (dLon) => { + const s = r.query.project(at(dLon, 0.003)); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some((hit) => hit.set === 'conf:line-drape-point'), + ); + }; + points.set([front(-0.002)]); + await drawn(h, r); + await settled(r); + await drawn(h, r); + ok(point(-0.002), 'the clamped point draws'); + for (let i = 1; i <= 4; i++) { + const end = -0.002 + i * 0.001; + lines.upsert([growing(end)]); + points.upsert([front(-0.002 + i * 0.001)]); + await drawn(h, r, 1); + ok( + mine(at(end - 0.0004, 0.004), 'growing'), + `grown, frame ${i}: drawn to its new end`, + ); + ok( + point(-0.002 + i * 0.001), + `moved, frame ${i}: the point is there`, + ); + ok( + i < 2 || !point(-0.002 + (i - 2) * 0.001), + `moved, frame ${i}: not where it was`, + ); + } + equal(lines.size(), 4, 'every line held'); + points.dispose(); + lines.dispose(); + }, + ), check( 'draw.points.update', 'an upserted point is drawn where it now is once drawn again, and shows only within its display range', diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 9bdbe4583..ec852d516 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -10,6 +10,7 @@ * loop on a virtual clock, one frame at a time, in the contract's order. */ import { horizonFrom } from '../../geo/horizon.js'; +import { alongLength } from '../../geo/polyline.js'; import { createInputRouter } from '../input/router.js'; import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js'; import { createStubCamera } from './camera.js'; @@ -559,6 +560,24 @@ export function createStubRenderer(options = {}) { const hits = []; for (const [setId, set] of sets) { if (!set.show || set.spec.pickable === false) continue; + if (set.kind === 'lines') { + for (const item of set.items.values()) { + if (item.show === false || item.pickable === false) continue; + // Lines in the sky's frame are not picked where they are drawn. + if (item.frame === 'inertial') continue; + const p = lineHit(item, x, y, Math.max(halfW, halfH)); + if (p) + hits.push({ + set: setId, + id: item.id, + meta: item.meta, + surface: false, + position: p, + depth: magnitude(sub(p, eye().position)), + }); + } + continue; + } if ( set.kind !== 'icons' && set.kind !== 'points' && @@ -612,6 +631,68 @@ export function createStubRenderer(options = {}) { return hits; } + /** + * A line's positions as ECEF, cut at its `revealFraction` of length (as + * drawn straight between its positions). + */ + function revealedLine(item) { + const flat = item.positions instanceof Float64Array; + const n = flat ? item.positions.length / 3 : item.positions.length; + const points = []; + for (let i = 0; i < n; i++) + points.push( + flat + ? vec( + item.positions[i * 3], + item.positions[i * 3 + 1], + item.positions[i * 3 + 2], + ) + : toEcef(item.positions[i]), + ); + const fraction = item.revealFraction; + if (fraction === undefined || fraction >= 1) return points; + const at = alongLength(points, fraction); + if (!at) return []; + const { index, t } = at; + return [ + ...points.slice(0, index + 1), + add(points[index], scale(sub(points[index + 1], points[index]), t)), + ]; + } + + /** + * Where a line is under the pixel `(x, y)`: the nearest point of a + * drawn segment within half its width (and `slack`) of it, or null. + */ + function lineHit(item, x, y, slack) { + const points = revealedLine(item); + const reach = (item.widthPx ?? 1) / 2 + slack; + let best = null; + let bestDistance = Infinity; + for (let i = 0; i + 1 < points.length; i++) { + if (item.segmentShow?.[i] === false) continue; + const a = points[i]; + const b = points[i + 1]; + if (isOccluded(a) && isOccluded(b)) continue; + const sa = project(a); + const sb = project(b); + if (!sa || !sb) continue; + const dx = sb.x - sa.x; + const dy = sb.y - sa.y; + const span = dx * dx + dy * dy; + const t = + span > 0 + ? Math.max(0, Math.min(1, ((x - sa.x) * dx + (y - sa.y) * dy) / span)) + : 0; + const distance = Math.hypot(sa.x + dx * t - x, sa.y + dy * t - y); + if (distance <= reach && distance < bestDistance) { + bestDistance = distance; + best = add(a, scale(sub(b, a), t)); + } + } + return best; + } + function surfaceHit(x, y) { const position = rayEllipsoid(pickRay(x, y)); return position