diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 7a2558023..69618d849 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2517,6 +2517,7 @@ "src/layers/streetLevel/policy.js", "src/layers/streetLevel/state.js", "src/layers/streetLevel/lineCoverage.js", + "src/render/color.js", "src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/providers/mapillary/decode.js", diff --git a/src/input/dispatcher.js b/src/input/dispatcher.js index 744d8e1f9..7aa2beb28 100644 --- a/src/input/dispatcher.js +++ b/src/input/dispatcher.js @@ -108,6 +108,9 @@ const dispatchers = new WeakMap(); * @property {boolean} surface Whether the hit is the map itself. * @property {(width: number, height: number) => object|undefined} pickWindow * `scene.pick` with a wider window. + * @property {(width: number, height: number) => {id: string|null, drawHit: import('../render/contract/query').Hit|null, surface: boolean}} windowHit + * `pickWindow` read as `id`, `drawHit` and `surface` are: for layers that + * pick wider than the click without reading the renderer's pick. * @property {(limit?: number, width?: number, height?: number) => object[]} drill * `scene.drillPick`, at most `limit` hits. * @property {() => Cesium.Cartesian3|null} ground The world position under @@ -346,6 +349,16 @@ function createClickEvent(viewer, click, gesture) { pickThroughFollowHelper(scene.pick(position, width, height)), ); }, + windowHit(width, height) { + return once(`windowHit:${width}x${height}`, () => { + const picked = this.pickWindow(width, height); + return { + id: resolvePickId(picked), + drawHit: drawHitOf(picked), + surface: isSurfacePick(picked), + }; + }); + }, drill(limit = DRILL_DEPTH, width, height) { const key = `${width}x${height}`; const done = drills.get(key); diff --git a/src/layers/streetLevel/groundClick.js b/src/layers/streetLevel/groundClick.js index 16e15704f..640b79990 100644 --- a/src/layers/streetLevel/groundClick.js +++ b/src/layers/streetLevel/groundClick.js @@ -13,15 +13,14 @@ export function groundClickHeightOk(viewer) { * active `groundClick` providers, without moving the camera. The height is * measured at the click, not read from the cached flag. * @param {{state: object, openNearest: Function, isAvailable: (entry: object) => boolean}} options - * @returns {(screenPosition: {x: number, y: number}, picked?: object) => Promise|false} + * @returns {(click: {surface: boolean, ground: () => {x: number, y: number, z: number}|null}) => Promise|false} + * `surface`: whether the click hit the map itself; `ground`: the world + * position under it, null over the sky. */ export function createGroundClick({ state, openNearest, isAvailable }) { - return function openAtGround(screenPosition, picked) { - const scenePick = state.services.scenePick; - if (!state.enabled || !state.viewer || !scenePick?.pickGroundPosition) - return false; - if (!scenePick.isSurfacePick(picked) || !groundClickHeightOk(state.viewer)) - return false; + return function openAtGround({ surface, ground: groundAt }) { + if (!state.enabled || !state.viewer) return false; + if (!surface || !groundClickHeightOk(state.viewer)) return false; const providerIds = [...state.providers.values()] .filter( (entry) => @@ -32,7 +31,7 @@ export function createGroundClick({ state, openNearest, isAvailable }) { ) .map((entry) => entry.def.id); if (!providerIds.length) return false; - const position = scenePick.pickGroundPosition(state.viewer, screenPosition); + const position = groundAt(); const ground = position && toLonLatH(position); if (!ground) return false; return openNearest( diff --git a/src/layers/streetLevel/groundClick.test.mjs b/src/layers/streetLevel/groundClick.test.mjs index 09d97e5c9..e6d14b268 100644 --- a/src/layers/streetLevel/groundClick.test.mjs +++ b/src/layers/streetLevel/groundClick.test.mjs @@ -16,6 +16,8 @@ const viewerWith = (viewer) => /** * A layer state with providers `{id, on, groundClick, configured, available}`; * `picked` is where the depth buffer lands, `ellipsoid` the fallback hit. + * `click(pick)` clicks as the click dispatcher reports it: whether `pick` + * is the map itself, and the ground under the click. */ function harness({ providers = [ @@ -30,7 +32,7 @@ function harness({ const opened = []; const state = { enabled, - services: { scenePick }, + services: {}, providers: new Map( providers.map( ({ @@ -65,7 +67,12 @@ function harness({ }, isAvailable: (entry) => entry.available, }); - return { opened, openAtGround }; + const click = (pick) => + openAtGround({ + surface: scenePick.isSurfacePick(pick), + ground: () => scenePick.pickGroundPosition(state.viewer, { x: 1, y: 1 }), + }); + return { opened, click }; } const near = (point) => @@ -74,8 +81,8 @@ const near = (point) => test('a click on the map opens the click-to-open providers there, without moving the camera', () => { for (const picked of [undefined, { primitive: TILESET }, { content: {} }]) { - const { opened, openAtGround } = harness(); - openAtGround({ x: 10, y: 20 }, picked); + const { opened, click } = harness(); + click(picked); assert.equal(opened.length, 1, JSON.stringify(picked)); assert.ok(near(opened[0].point)); assert.deepEqual(opened[0].options, { @@ -86,11 +93,11 @@ test('a click on the map opens the click-to-open providers there, without moving }); test('where the depth buffer names no place, the ellipsoid answers', () => { - const { opened, openAtGround } = harness({ + const { opened, click } = harness({ picked: new Cesium.Cartesian3(500, 0, 0), ellipsoid: GROUND, }); - openAtGround({ x: 1, y: 1 }); + click(undefined); assert.ok(near(opened[0].point)); }); @@ -119,8 +126,8 @@ test('nothing opens over another layer’s object, the sky, from high up, off it { options: { enabled: false }, label: 'layer off' }, ]; for (const { picked, options = {}, label } of cases) { - const { opened, openAtGround } = harness(options); - assert.equal(openAtGround({ x: 1, y: 1 }, picked), false, label); + const { opened, click } = harness(options); + assert.equal(click(picked), false, label); assert.equal(opened.length, 0, label); } }); diff --git a/src/layers/streetLevel/index.js b/src/layers/streetLevel/index.js index 7f9dc5a66..b6411f9d1 100644 --- a/src/layers/streetLevel/index.js +++ b/src/layers/streetLevel/index.js @@ -15,7 +15,8 @@ import { } from './uiState.js'; import { canvasSize, groundUnderCamera, viewCentre } from './view.js'; import { toLonLatH } from '../../geo/index.js'; -import { findCamera } from '../../render/rendererOf.js'; +import { findCamera, findQuery } from '../../render/rendererOf.js'; +import { isPickedWorldPosition } from '../../data/scenePick.js'; import { createGroundClick, groundClickHeightOk } from './groundClick.js'; import { msg, t, translateKnown } from '../../i18n/index.js'; import { @@ -258,12 +259,27 @@ export function createStreetLevelLayer({ nearestLookup = null; } - /** Ground under the screen centre; null for sky, undefined when it cannot aim. */ + /** + * Ground under the screen centre: the drawn surface, else the ellipsoid; + * null for sky, undefined when it cannot aim. + */ function screenCentreGround() { const { width, height } = canvasSize(state.viewer); - const pick = state.services.scenePick?.pickGroundPosition; - if (!pick || !width || !height) return undefined; - const position = pick(state.viewer, { x: width / 2, y: height / 2 }); + const query = state.viewer ? findQuery(state.viewer) : null; + if (!query || !width || !height) return undefined; + const [x, y] = [width / 2, height / 2]; + // A pick that fails is a miss, as the ellipsoid's is. + const attempt = (pick) => { + try { + const position = pick(); + return isPickedWorldPosition(position) ? position : null; + } catch { + return null; + } + }; + const position = + attempt(() => query.pickPosition(x, y)) ?? + attempt(() => query.pickEllipsoid(x, y)); const ground = position && toLonLatH(position); return ground ? { lon: ground.lon, lat: ground.lat } : null; } diff --git a/src/layers/streetLevel/index.test.mjs b/src/layers/streetLevel/index.test.mjs index b7a0a5ac0..acb14fc3c 100644 --- a/src/layers/streetLevel/index.test.mjs +++ b/src/layers/streetLevel/index.test.mjs @@ -920,7 +920,6 @@ test('off Google 3D not even Google\u2019s script is loaded for Street View', as test('the button’s “centre of the view” is the ground under the middle of the screen', async (t) => { const { createStreetLevelLayer: create } = await import('./index.js'); - const scenePick = await import('../../data/scenePick.js'); const lookups = []; const provider = fakeProvider({ nearestImage: async (point) => { @@ -941,7 +940,7 @@ test('the button’s “centre of the view” is the ground under the middle of }); viewer.scene.canvas.clientWidth = 1000; viewer.scene.canvas.clientHeight = 600; - const layer = create({ providers: [provider], services: { scenePick } }); + const layer = create({ providers: [provider] }); layer.init(viewer); layer.enable(viewer); t.after(() => { @@ -954,9 +953,45 @@ test('the button’s “centre of the view” is the ground under the middle of assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9); }); +test('a pick that fails at the screen centre counts as a miss, and the ellipsoid answers', async (t) => { + const { createStreetLevelLayer: create } = await import('./index.js'); + const lookups = []; + const provider = fakeProvider({ + nearestImage: async (point) => { + lookups.push(point); + return null; + }, + }); + const saved = globalThis.document; + const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) }); + globalThis.document = Object.assign(new EventTarget(), { + createElement: () => ({ getContext: () => drawing }), + }); + const viewer = fakeViewer(); + Object.assign(viewer.scene, { + pickPositionSupported: true, + pickPosition: () => { + throw new Error('no depth'); + }, + }); + viewer.camera.pickEllipsoid = () => + Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0); + viewer.scene.canvas.clientWidth = 1000; + viewer.scene.canvas.clientHeight = 600; + const layer = create({ providers: [provider] }); + layer.init(viewer); + layer.enable(viewer); + t.after(() => { + layer.destroy(); + globalThis.document = saved; + }); + await layer.openNearest(undefined, { aim: 'screen-centre' }); + assert.equal(lookups.length, 1); + assert.ok(Math.abs(lookups[0].lat - 38.5799) < 1e-9); +}); + test('the button aimed at the sky opens nothing, and says to aim at a street', async (t) => { const { createStreetLevelLayer: create } = await import('./index.js'); - const scenePick = await import('../../data/scenePick.js'); const lookups = []; const provider = fakeProvider({ nearestImage: async (point) => { @@ -978,7 +1013,7 @@ test('the button aimed at the sky opens nothing, and says to aim at a street', a viewer.camera.pickEllipsoid = () => undefined; viewer.scene.canvas.clientWidth = 1000; viewer.scene.canvas.clientHeight = 600; - const layer = create({ providers: [provider], services: { scenePick } }); + const layer = create({ providers: [provider] }); layer.init(viewer); layer.enable(viewer); t.after(() => { diff --git a/src/layers/streetLevel/lineCoverage.js b/src/layers/streetLevel/lineCoverage.js index 873bfeacf..8754faae5 100644 --- a/src/layers/streetLevel/lineCoverage.js +++ b/src/layers/streetLevel/lineCoverage.js @@ -1,13 +1,18 @@ -import * as Cesium from 'cesium'; import { passesImageryFilter } from './filter.js'; +import { STREET_LEVEL_SET_PREFIX } from './policy.js'; import { groundUnderCamera, viewFocus, visibleBbox } from './view.js'; import { tilesForBbox } from './tileMath.js'; import { msg } from '../../i18n/index.js'; -import { findCamera } from '../../render/rendererOf.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { cssColor } from '../../render/color.js'; +import { findCamera, findDraw } from '../../render/rendererOf.js'; -/** Sequences per primitive: smaller batches build, and show, sooner. */ +/** Line parts per draw set: smaller batches build, and show, sooner. */ const SEQUENCE_PRIMITIVE_BATCH = 120; +/** Line sets made so far, so every set id is new. */ +let lineSets = 0; + /** Hint above the street-zoom ceiling, where no coverage is drawn. */ export const ZOOM_IN_HINT = msg('Zoom in to see street-level coverage'); /** Hint when no ground is in view within range (looking at the sky). */ @@ -32,7 +37,10 @@ export function freshCoverage({ keyless = false } = {}) { zoom: null, /** Current zoom's tiles by `z/x/y` key. */ tiles: new Map(), - /** The selected sequence drawn over the coverage, or null. */ + /** + * The selected sequence drawn over the coverage: `{set, sequenceId}`, + * the tiles drawing that sequence's lines hidden; or null. + */ highlight: null, /** Tile key → its request's controller; any entry means LOADING. */ pending: new Map(), @@ -46,46 +54,62 @@ export function freshCoverage({ keyless = false } = {}) { blockTimer: null, debounceTimer: null, removeCameraListener: null, - terrainReady: null, hint: '', }; } -/** Line instances for sequences' parts, every part picking its sequence. */ -function lineInstances(sequences, color, width, prefix) { - const attributes = { - color: Cesium.ColorGeometryInstanceAttribute.fromColor(color), - }; - const instances = []; - for (const sequence of sequences) - for (const coordinates of sequence.parts) { - let positions; - try { - positions = Cesium.Cartesian3.fromDegreesArray(coordinates.flat()); - } catch { - continue; - } - if (positions.length < 2) continue; - instances.push( - new Cesium.GeometryInstance({ - geometry: new Cesium.GroundPolylineGeometry({ positions, width }), - id: `${prefix}${sequence.id}`, - attributes, - }), - ); - } - return instances; +/** ECEF positions of a part's `[lon, lat]` points; null for a part that cannot be drawn. */ +function partPositions(coordinates) { + if (!Array.isArray(coordinates) || coordinates.length < 2) return null; + const positions = []; + for (const point of coordinates) { + const [lon, lat] = point ?? []; + if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null; + positions.push(fromDegrees(lon, lat)); + } + return positions; } -/** Draped lines that follow terrain and 3D tiles (Google 3D) alike. */ -function linePrimitive(geometryInstances, asynchronous) { - return new Cesium.GroundPolylinePrimitive({ - geometryInstances, - appearance: new Cesium.PolylineColorAppearance(), - classificationType: Cesium.ClassificationType.BOTH, - asynchronous, - allowPicking: true, - }); +/** + * Draped line items for sequences' parts, on terrain and 3D tiles (Google + * 3D) alike. Every part picks its sequence (`meta.pick`, ``); + * its id is that, or with `#` added where it is taken already. + */ +function lineItems(sequences, color, widthPx, prefix) { + const style = { kind: 'solid', color }; + const taken = new Set(); + const unique = (pick) => { + let id = pick; + for (let n = 1; taken.has(id); n++) id = `${pick}#${n}`; + taken.add(id); + return id; + }; + const items = []; + for (const sequence of sequences) { + const pick = `${prefix}${sequence.id}`; + for (const coordinates of sequence.parts) { + const positions = partPositions(coordinates); + if (!positions) continue; + items.push({ + id: unique(pick), + positions, + widthPx, + mode: 'draped', + clampTo: 'both', + style, + meta: { pick, sequenceId: sequence.id }, + }); + } + } + return items; +} + +/** A CSS colour at `alpha`; a colour it cannot read is passed on as it is. */ +function withAlpha(css, alpha) { + const color = cssColor(css); + if (!color) return css; + color[3] = alpha; + return color; } function pointsOf(sequence) { @@ -166,9 +190,14 @@ export function createLineCoverage({ render?.governorRequestRender?.(renderKey); } - function ensureTerrainReady() { - return (state.coverage.terrainReady ||= - Cesium.GroundPolylinePrimitive.initializeTerrainHeights()); + /** A new line set; null without a renderer to draw on. */ + function newLineSet() { + const draw = state.viewer ? findDraw(state.viewer) : null; + return draw + ? draw.lines({ + id: `${STREET_LEVEL_SET_PREFIX}${renderKey}:${++lineSets}`, + }) + : null; } function tileKey({ x, y, z }) { @@ -209,34 +238,52 @@ export function createLineCoverage({ return drawn; } - /** Batched draped primitives for a tile's sequences. */ - function buildSequencePrimitives(sequences) { - const instances = lineInstances( - sequences, - Cesium.Color.fromCssColorString(colors.coverage).withAlpha(0.92), - tuning.lineWidthPx, - pickPrefix, - ); - const primitives = []; - for (let i = 0; i < instances.length; i += SEQUENCE_PRIMITIVE_BATCH) - primitives.push( - linePrimitive(instances.slice(i, i + SEQUENCE_PRIMITIVE_BATCH), true), - ); - return primitives; + /** The sequence the highlight draws, whose lines the tiles hide; or null. */ + const highlighted = () => state.coverage.highlight?.sequenceId ?? null; + + /** + * Show or hide a sequence's lines in a tile, in place: only whether they + * show changes, so nothing is built again. + */ + function showParts(entry, sequenceId, show) { + const parts = sequenceId === null ? null : entry.parts.get(sequenceId); + if (!parts) return; + const bySet = new Map(); + for (const part of parts) { + part.item = { ...part.item, show }; + if (!bySet.has(part.set)) bySet.set(part.set, []); + bySet.get(part.set).push(part.item); + } + for (const [set, items] of bySet) set.upsert(items); + } + + /** The tiles hide `sequenceId`'s lines (the highlight draws them), and show the rest. */ + function hideInTiles(sequenceId) { + const highlight = state.coverage.highlight; + const was = highlighted(); + if (was === sequenceId) return; + if (highlight) highlight.sequenceId = sequenceId; + for (const entry of state.coverage.tiles.values()) { + showParts(entry, was, true); + showParts(entry, sequenceId, false); + } + } + + function dropHighlight() { + hideInTiles(null); + state.coverage.highlight?.set.dispose(); + state.coverage.highlight = null; } /** * Draw the selected sequence again over the coverage, in the selection - * colour, from every loaded tile it crosses; none when nothing is selected. - * Built at once: its tiles loaded, so the terrain table has too. + * colour, from every loaded tile it crosses; none when nothing is + * selected. One set, redrawn in place (the old line shows until the new + * one is ready); the tiles hide their own lines of the sequence, so it + * shows whichever set is drawn over which. */ function highlight(sequenceId = state.sequence.selectedId) { - const scene = state.viewer?.scene; - if (state.coverage.highlight) { - scene?.groundPrimitives?.remove(state.coverage.highlight); - state.coverage.highlight = null; - } - if (!sequenceId || !scene) return; + if (!sequenceId || !state.viewer) return dropHighlight(); // From every loaded line, drawn or not: a sequence selected after its // tiles were drawn may have been left out by their caps. const current = filter(); @@ -245,46 +292,70 @@ export function createLineCoverage({ const sequence = entry.sequenceList.find(({ id }) => id === sequenceId); if (sequence && passes(sequence, current)) parts.push(...sequence.parts); } - const instances = lineInstances( + const items = lineItems( [{ id: sequenceId, parts }], - Cesium.Color.fromCssColorString(colors.selected), + colors.selected, tuning.lineWidthPx + 1, pickPrefix, ); - if (!instances.length) return; - state.coverage.highlight = scene.groundPrimitives.add( - linePrimitive(instances, false), - ); + if (!items.length) return dropHighlight(); + if (!state.coverage.highlight) { + const set = newLineSet(); + if (!set) return; + state.coverage.highlight = { set, sequenceId: null }; + } + state.coverage.highlight.set.set(items); + hideInTiles(sequenceId); requestRender(); } - function attachPrimitive(entry) { - const scene = state.viewer?.scene; - if (!scene) return; + /** + * Draw a tile's lines, in batches of line parts: its sets redraw in + * place, the old lines showing until the new ones are ready; a set more + * is made only for a batch more. + */ + function drawTile(entry) { // Lookup, picking and counts follow what is drawn, not the whole tile. const sequences = drawnSequences(entry); entry.sequences = new Map(sequences.map((s) => [s.id, s])); - entry.primitives = buildSequencePrimitives(sequences); - for (const primitive of entry.primitives) - scene.groundPrimitives.add(primitive); + const hidden = highlighted(); + const items = lineItems( + sequences, + withAlpha(colors.coverage, 0.92), + tuning.lineWidthPx, + pickPrefix, + ).map((item) => + item.meta.sequenceId === hidden ? { ...item, show: false } : item, + ); + const batches = []; + for (let i = 0; i < items.length; i += SEQUENCE_PRIMITIVE_BATCH) + batches.push(items.slice(i, i + SEQUENCE_PRIMITIVE_BATCH)); + while (entry.sets.length > batches.length) entry.sets.pop().dispose(); + entry.parts = new Map(); + batches.forEach((batch, i) => { + entry.sets[i] ??= newLineSet(); + const set = entry.sets[i]; + if (!set) return; + set.set(batch); + for (const item of batch) { + const { sequenceId } = item.meta; + if (!entry.parts.has(sequenceId)) entry.parts.set(sequenceId, []); + entry.parts.get(sequenceId).push({ set, item }); + } + }); + entry.sets = entry.sets.filter(Boolean); } - function detachPrimitive(entry) { - const scene = state.viewer?.scene; - for (const primitive of entry.primitives || []) { - try { - scene?.groundPrimitives?.remove(primitive); - } catch { - /* already gone */ - } - } - entry.primitives = []; + function undrawTile(entry) { + for (const set of entry.sets) set.dispose(); + entry.sets = []; + entry.parts = new Map(); } function removeTile(key) { const entry = state.coverage.tiles.get(key); if (!entry) return; - detachPrimitive(entry); + undrawTile(entry); state.coverage.tiles.delete(key); } @@ -296,12 +367,7 @@ export function createLineCoverage({ state.coverage.pending.set(key, controller); notify(); try { - // Fetch and the one-time terrain-height table load run side by side, - // both handled from the start so an early tile failure is not unhandled. - const [decoded] = await Promise.all([ - fetchTile(tile, { signal: controller.signal }), - ensureTerrainReady(), - ]); + const decoded = await fetchTile(tile, { signal: controller.signal }); // Only an abort, a zoom change, a clear or a newer request for this tile // discards it; a refresh that still wants the tile keeps it. if ( @@ -312,14 +378,14 @@ export function createLineCoverage({ ) return; const sequences = decoded?.sequences || []; - const entry = { primitives: [], sequences: new Map() }; + const entry = { sets: [], parts: new Map(), sequences: new Map() }; // Newest first, unless the provider ordered them itself; the per-tile // cap applies to what passes the filter. entry.sequenceList = tuning.keepOrder ? sequences : sequences.sort((a, b) => (b.capturedAt || 0) - (a.capturedAt || 0)); entry.total = sequences.length; - attachPrimitive(entry); + drawTile(entry); state.coverage.tiles.set(key, entry); state.coverage.lastError = null; // Over the new lines, and along any of the selection's parts they add. @@ -423,7 +489,7 @@ export function createLineCoverage({ return { zoom, tiles }; } - /** Recompute the tile set for the current camera and reconcile primitives. */ + /** Recompute the tile set for the current camera and reconcile what is drawn. */ function refresh() { const viewer = state.viewer; if (!viewer || !state.context.isActive() || state.coverage.blocked) return; @@ -486,10 +552,7 @@ export function createLineCoverage({ /** Rebuild every loaded tile from its decoded lines (after a filter change). */ function rebuild() { - for (const entry of state.coverage.tiles.values()) { - detachPrimitive(entry); - attachPrimitive(entry); - } + for (const entry of state.coverage.tiles.values()) drawTile(entry); highlight(); requestRender(); notify(); diff --git a/src/layers/streetLevel/lineCoverage.test.mjs b/src/layers/streetLevel/lineCoverage.test.mjs index 7fec1a348..20a0b5ab9 100644 --- a/src/layers/streetLevel/lineCoverage.test.mjs +++ b/src/layers/streetLevel/lineCoverage.test.mjs @@ -10,7 +10,13 @@ import { import { resolveFilter } from './filter.js'; import { encodeCoverageTile } from './providers/mapillary/coverageFixture.mjs'; import { decodeCoverageTile } from './providers/mapillary/decode.js'; -import { rayCamera, streetPorts } from '../../testSupport/streetLevelFakes.mjs'; +import { + drawnLineSets, + rayCamera, + streetPorts, +} from '../../testSupport/streetLevelFakes.mjs'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; +import { createCesiumDraw } from '../../render/cesium/draw.js'; import { bindRenderer } from '../../render/rendererOf.js'; import { COLORS, @@ -52,26 +58,11 @@ function createCoverage({ state, source, zoomFor = coverageZoomForHeight }) { const RAD = Math.PI / 180; // Node has no WebGL context to report line-width limits; a browser's -// context sets these on startup, and appearances validate against them. +// context sets these on startup, and the renderer's lines validate against them. Cesium.ContextLimits._minimumAliasedLineWidth = 1; Cesium.ContextLimits._maximumAliasedLineWidth = 10; const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); -/** A scene collection that remembers what is on the globe. */ -function collection() { - const items = new Set(); - return { - items, - add(primitive) { - items.add(primitive); - return primitive; - }, - remove(primitive) { - return items.delete(primitive); - }, - }; -} - /** The centre of the z14 tile holding a point, so a small view is one tile. */ function tileCentre(lon, lat) { const x = lonToTileX(lon, 14); @@ -84,15 +75,14 @@ function tileCentre(lon, lat) { }; } -/** A viewer looking straight down on a 0.004° square around `view`. */ -function fakeViewer(view) { +/** A viewer looking straight down on a 0.004° square around `view`, drawing on a fake draw port. */ +function fakeViewer(view, { draw = fakeDrawPort() } = {}) { const viewer = { view, + draw, scene: { canvas: { clientWidth: 100, clientHeight: 100 }, globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 }, - groundPrimitives: collection(), - primitives: collection(), }, camera: { get positionCartographic() { @@ -113,7 +103,7 @@ function fakeViewer(view) { }, }, }; - bindRenderer(viewer, streetPorts(viewer, { camera: true })); + bindRenderer(viewer, streetPorts(viewer, { camera: true, draw })); return viewer; } @@ -130,9 +120,12 @@ function deferredSource() { }; } -function setup({ zoomFor } = {}) { +function setup({ zoomFor, draw } = {}) { const centre = tileCentre(-121.4944, 38.5816); - const viewer = fakeViewer({ lon: centre.lon, lat: centre.lat, height: 900 }); + const viewer = fakeViewer( + { lon: centre.lon, lat: centre.lat, height: 900 }, + draw ? { draw } : {}, + ); const source = deferredSource(); const state = { viewer, @@ -147,9 +140,8 @@ function setup({ zoomFor } = {}) { }, coverage: { ...freshCoverage(), - // The key status is in; skip Cesium's one-time terrain table download. + // The key status is in. blocked: null, - terrainReady: Promise.resolve(), }, sequence: { selectedId: null }, }; @@ -169,8 +161,8 @@ function setup({ zoomFor } = {}) { }); const tileKey = `14/${centre.tile.x}/${centre.tile.y}`; const onGlobe = () => - viewer.scene.groundPrimitives.items.size + - viewer.scene.primitives.items.size; + drawnLineSets(viewer, { empty: true }).filter((set) => set.items.size) + .length; return { viewer, source, state, coverage, bytes, tileKey, onGlobe, centre }; } @@ -211,18 +203,55 @@ test('a superseded tile request cannot strand lines on the globe', async () => { }); test('sequence lines are draped on the globe and on 3D tiles alike', async () => { - const { viewer, source, coverage, bytes } = setup(); + const { viewer, source, coverage, bytes, centre } = setup(); coverage.refresh(); source.calls[0].resolve(bytes); await settle(); - const { groundPrimitives, primitives } = viewer.scene; - assert.equal(primitives.items.size, 0); - assert.equal(groundPrimitives.items.size, 1); - const [line] = groundPrimitives.items; - assert.ok(line instanceof Cesium.GroundPolylinePrimitive); - assert.equal(line.classificationType, Cesium.ClassificationType.BOTH); + const sets = drawnLineSets(viewer, { empty: true }); + assert.equal(sets.length, 1); + const [line] = sets[0].items.values(); + assert.equal( + line.id, + `${PICK_PREFIX.sequence}seq-1`, + 'it picks its sequence', + ); + assert.equal(line.meta.pick, `${PICK_PREFIX.sequence}seq-1`); + assert.equal(line.mode, 'draped'); + assert.equal(line.clampTo, 'both'); + assert.equal(line.widthPx, COVERAGE_TUNING.lineWidthPx); + assert.equal(line.style.kind, 'solid'); + assert.equal(line.style.color[3], 0.92); + assert.equal(line.positions.length, 2); + const start = Cesium.Cartesian3.fromDegrees(centre.lon - 0.001, centre.lat); + // Within the tile encoding's rounding. + assert.ok(Cesium.Cartesian3.distance(line.positions[0], start) < 1); + coverage.clear(); + assert.equal(drawnLineSets(viewer, { empty: true }).length, 0); +}); + +test("a sequence's parts are drawn apart, every one picking the sequence", async () => { + const { viewer, source, coverage, centre } = setup(); + coverage.refresh(); + const part = (dLat) => [ + [centre.lon - 0.001, centre.lat + dLat], + [centre.lon + 0.001, centre.lat + dLat], + ]; + source.calls[0].resolve( + encodeCoverageTile(centre.tile, { + sequences: [{ id: 'seq-1', parts: [part(0), part(0.0005)] }], + }), + ); + await settle(); + const items = [...drawnLineSets(viewer, { empty: true })[0].items.values()]; + const pick = `${PICK_PREFIX.sequence}seq-1`; + assert.deepEqual( + items.map(({ id, meta }) => [id, meta.pick]), + [ + [pick, pick], + [`${pick}#1`, pick], + ], + ); coverage.clear(); - assert.equal(groundPrimitives.items.size, 0); }); test('panning off a tile that is still loading stops counting it as loading', async () => { @@ -249,7 +278,7 @@ test('panning off a tile that is still loading stops counting it as loading', as test('a zoomFor in the older {zoom, kind} shape still draws its lines', async () => { // Providers written before the core went slim (#1139's Vegbilder) answer // an object: it must not ask for no tiles and say nothing. - const { viewer, source, coverage, bytes } = setup({ + const { source, coverage, bytes, onGlobe } = setup({ zoomFor: (height) => { const zoom = coverageZoomForHeight(height); return zoom == null ? null : { zoom, kind: 'sequence' }; @@ -260,7 +289,7 @@ test('a zoomFor in the older {zoom, kind} shape still draws its lines', async () assert.equal(source.calls[0].z, 14); source.calls[0].resolve(bytes); await settle(); - assert.equal(viewer.scene.groundPrimitives.items.size, 1, 'its line drawn'); + assert.equal(onGlobe(), 1, 'its line drawn'); assert.equal(coverage.stats().hint, ''); coverage.clear(); }); @@ -278,15 +307,15 @@ test('a zoom level is read from either shape; an overview or a bad answer draws }); test('from orbit nothing is requested or drawn, and the hint says to zoom in', async () => { - const { viewer, source, state, coverage, bytes } = setup(); + const { viewer, source, state, coverage, bytes, onGlobe } = setup(); coverage.refresh(); source.calls[0].resolve(bytes); await settle(); - assert.ok(viewer.scene.groundPrimitives.items.size > 0, 'street lines'); + assert.ok(onGlobe() > 0, 'street lines'); viewer.view.height = 20_000_000; coverage.refresh(); assert.equal(source.calls.length, 1, 'no tile is asked for'); - assert.equal(viewer.scene.groundPrimitives.items.size, 0, 'nothing drawn'); + assert.equal(onGlobe(), 0, 'nothing drawn'); assert.equal(state.coverage.zoom, null); assert.equal(coverage.stats().hint, ZOOM_IN_HINT); viewer.view.height = 900; @@ -537,22 +566,112 @@ test('the selected sequence is drawn over the coverage, and goes with the select coverage.refresh(); source.calls[0].resolve(bytes); await settle(); - const lines = () => [...viewer.scene.groundPrimitives.items]; + const lines = () => drawnLineSets(viewer, { empty: true }); assert.equal(lines().length, 1, 'the coverage'); + const [tile] = lines(); + const own = () => [...tile.items.values()][0]; + const writes = tile.writes; coverage.highlight('seq-1'); assert.equal(lines().length, 2); const highlight = lines().at(-1); - assert.equal(state.coverage.highlight, highlight, 'drawn last, on top'); - assert.equal(highlight.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(state.coverage.highlight.set.id, highlight.spec.id); + const [line] = highlight.items.values(); + assert.equal(line.mode, 'draped'); + assert.equal(line.clampTo, 'both'); + assert.equal(line.widthPx, COVERAGE_TUNING.lineWidthPx + 1); + assert.equal(line.style.color, COLORS.selected); + assert.equal(line.meta.pick, `${PICK_PREFIX.sequence}seq-1`); + // The tile hides its own line of it, whichever set draws over which. + assert.equal(own().show, false, 'hidden under the highlight'); + assert.equal(tile.writes, writes + 1, 'one write: only its show changed'); + // Selected again: the one highlight, redrawn in place. + coverage.highlight('seq-1'); + assert.equal(lines().at(-1), highlight, 'the same set'); coverage.highlight('not-drawn'); assert.equal(lines().length, 1, 'nothing to highlight off the map'); + assert.equal(own().show, true, 'the tile draws it again'); + coverage.highlight('seq-1'); coverage.highlight(null); assert.equal(state.coverage.highlight, null); + assert.equal(own().show, true); coverage.clear(); assert.equal(lines().length, 0); }); -test('a tile that lands with the selected sequence draws the highlight again, on top', async () => { +test('parts and repeated ids each keep their own line', async () => { + const { viewer, source, coverage, centre } = setup(); + coverage.refresh(); + const part = (dLat) => [ + [centre.lon - 0.001, centre.lat + dLat], + [centre.lon + 0.001, centre.lat + dLat], + ]; + source.calls[0].resolve( + encodeCoverageTile(centre.tile, { + sequences: [ + { id: 'a', parts: [part(0), part(0.0002)] }, + // Its id is what a second part of `a` would be numbered. + { id: 'a#1', parts: [part(0.0004)] }, + ], + }), + ); + await settle(); + const items = [...drawnLineSets(viewer, { empty: true })[0].items.values()]; + assert.equal(items.length, 3, 'no line drawn over another'); + assert.deepEqual(items.map(({ meta }) => meta.sequenceId).sort(), [ + 'a', + 'a', + 'a#1', + ]); + coverage.clear(); +}); + +test('a rebuild draws in place, with a set more or fewer as the batches need', async () => { + const { viewer, source, state, coverage, centre } = setup(); + const line = (n) => [ + [ + [centre.lon - 0.001, centre.lat + n * 1e-6], + [centre.lon + 0.001, centre.lat + n * 1e-6], + ], + ]; + const sequences = Array.from({ length: 130 }, (_, i) => ({ + id: `s-${i}`, + parts: line(i), + capturedAt: 1_000 + i, + isPano: i === 0, + })); + coverage.refresh(); + source.calls[0].resolve(encodeCoverageTile(centre.tile, { sequences })); + await settle(); + const sets = () => drawnLineSets(viewer, { empty: true }); + const [first] = sets(); + assert.equal(sets().length, 2, '120 parts, then 10'); + state.sequence.selectedId = 's-0'; + coverage.highlight(); + // 360° only: one line left, in the first set, redrawn in place. + state.filter = { pano: 'pano', sinceDays: 0 }; + coverage.rebuild(); + assert.deepEqual( + sets().map((set) => set.spec.id), + [first.spec.id, state.coverage.highlight.set.id], + 'the second set goes; the first draws in place', + ); + assert.equal(first.items.get(`${PICK_PREFIX.sequence}s-0`).show, false); + // Everything again: a set more for the second batch. + state.filter = { pano: 'all', sinceDays: 0 }; + coverage.rebuild(); + assert.equal(sets().length, 3); + assert.equal(sets()[0], first); + const own = sets() + .filter((set) => set.spec.id !== state.coverage.highlight.set.id) + .map((set) => set.items.get(`${PICK_PREFIX.sequence}s-0`)) + .filter(Boolean); + assert.equal(own.length, 1, 'drawn once, oldest last'); + assert.equal(own[0].show, false, 'still hidden under the highlight'); + coverage.clear(); + assert.equal(sets().length, 0); +}); + +test('a tile that lands with the selected sequence is highlighted, its own line hidden', async () => { const { viewer, source, state, coverage, bytes } = setup(); state.sequence.selectedId = 'seq-1'; coverage.refresh(); @@ -560,9 +679,12 @@ test('a tile that lands with the selected sequence draws the highlight again, on source.calls[0].resolve(bytes); await settle(); assert.ok(state.coverage.highlight, 'highlighted once its tile is in'); + const [tile, highlight] = drawnLineSets(viewer, { empty: true }); + assert.equal(highlight.spec.id, state.coverage.highlight.set.id); assert.equal( - [...viewer.scene.groundPrimitives.items].at(-1), - state.coverage.highlight, + tile.items.get(`${PICK_PREFIX.sequence}seq-1`).show, + false, + 'the tile hides its own line of it', ); coverage.clear(); }); @@ -572,12 +694,12 @@ test("a zoom change drops the old zoom's lines", async () => { coverage.refresh(); source.calls[0].resolve(bytes); await settle(); - const [old] = viewer.scene.groundPrimitives.items; + const [old] = drawnLineSets(viewer, { empty: true }); assert.ok(old, 'the z14 lines are drawn'); viewer.view.height = 3000; // zoom out to z13 coverage.refresh(); assert.equal(state.coverage.zoom, 13); - assert.equal(viewer.scene.groundPrimitives.items.has(old), false); + assert.equal(old.disposed, true); assert.ok(state.coverage.pending.size > 0, 'the new zoom is loading'); coverage.clear(); }); @@ -606,12 +728,8 @@ test('a rate limit holds every refresh inside its wait, not only the first', asy coverage.unblock(); }); -test('a tile that fails before the terrain table loads is reported at once, never unhandled', async () => { +test('a tile that fails is reported at once, never unhandled', async () => { const { source, state, coverage, tileKey } = setup(); - let terrainLoaded; - state.coverage.terrainReady = new Promise((resolve) => { - terrainLoaded = resolve; - }); const unhandled = []; const onUnhandled = (reason) => unhandled.push(reason); process.on('unhandledRejection', onUnhandled); @@ -624,8 +742,6 @@ test('a tile that fails before the terrain table loads is reported at once, neve assert.equal(state.coverage.lastError, 'Mapillary tiles HTTP 500'); assert.deepEqual(unhandled, []); } finally { - terrainLoaded(); - await settle(); process.off('unhandledRejection', onUnhandled); } }); @@ -660,3 +776,94 @@ test('the selected sequence is drawn and highlighted even past the per-tile cap' assert.ok(state.coverage.highlight, 'the selected line is highlighted'); coverage.clear(); }); + +test('on the Cesium renderer the lines drape on terrain and tiles, and the highlight stays on top', async () => { + const added = []; + const scene = { + camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) }, + frameState: { mode: Cesium.SceneMode.SCENE3D }, + primitives: { + add: (primitive) => (added.push(primitive), primitive), + remove: (primitive) => { + const at = added.indexOf(primitive); + if (at >= 0) added.splice(at, 1); + return at >= 0; + }, + get length() { + return added.length; + }, + get: (i) => added[i], + }, + requestRender() {}, + }; + const { port } = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const { source, state, coverage, bytes } = setup({ draw: port }); + state.sequence.selectedId = 'seq-1'; + coverage.refresh(); + source.calls[0].resolve(bytes); + await settle(); + const grounds = () => added.map((host) => host.get(host.length - 1)); + const [tile, highlight] = grounds(); + assert.equal(state.coverage.lastError, null); + assert.equal(added.length, 2, 'the tile, then the highlight over it'); + assert.ok(tile instanceof Cesium.GroundPolylinePrimitive); + assert.equal(tile.classificationType, Cesium.ClassificationType.BOTH); + const [instance] = tile.geometryInstances; + assert.equal(instance.id.id, `${PICK_PREFIX.sequence}seq-1`); + assert.equal(instance.id.meta.pick, `${PICK_PREFIX.sequence}seq-1`); + assert.equal( + highlight.geometryInstances[0].geometry.width, + COVERAGE_TUNING.lineWidthPx + 1, + ); + assert.equal( + added.at(-1).drawSetId, + state.coverage.highlight.set.id, + 'drawn last, on top', + ); + coverage.clear(); + assert.equal(added.length, 0, 'nothing left in the scene'); +}); + +test('a new selection hands the highlight over; a filter that hides it lets the tiles go back', async () => { + const { viewer, source, state, coverage, centre } = setup(); + const line = (dLat) => [ + [ + [centre.lon - 0.001, centre.lat + dLat], + [centre.lon + 0.001, centre.lat + dLat], + ], + ]; + coverage.refresh(); + source.calls[0].resolve( + encodeCoverageTile(centre.tile, { + sequences: [ + { id: 'a', parts: line(0), isPano: true }, + { id: 'b', parts: line(0.0005) }, + ], + }), + ); + await settle(); + const [tile] = drawnLineSets(viewer, { empty: true }); + // An item drawn without a `show` shows. + const shown = (id) => + tile.items.get(`${PICK_PREFIX.sequence}${id}`)?.show !== false; + coverage.highlight('a'); + assert.deepEqual([shown('a'), shown('b')], [false, true]); + coverage.highlight('b'); + assert.deepEqual([shown('a'), shown('b')], [true, false], 'a back, b hidden'); + const highlight = drawnLineSets(viewer).at(-1); + assert.equal( + [...highlight.items.values()][0].meta.sequenceId, + 'b', + 'the one set now draws b', + ); + // 360° only: b is filtered out, so nothing is highlighted or hidden. + state.sequence.selectedId = 'b'; + state.filter = { pano: 'pano', sinceDays: 0 }; + coverage.rebuild(); + assert.equal(state.coverage.highlight, null); + assert.equal(shown('a'), true, 'the tile draws a itself again'); + coverage.clear(); +}); diff --git a/src/layers/streetLevel/policy.js b/src/layers/streetLevel/policy.js index 4bf7f953d..31b364b22 100644 --- a/src/layers/streetLevel/policy.js +++ b/src/layers/streetLevel/policy.js @@ -11,6 +11,9 @@ export const STREET_LEVEL_LAYER_ID = 'street-level'; */ export const CLICK_PICK_WINDOW_PX = 9; +/** Draw-set ids of Street Level's lines, cones and marker start with this. */ +export const STREET_LEVEL_SET_PREFIX = 'street-level:'; + /** Pick id of the viewer position marker; the core owns it, not a provider. */ export const POSITION_PICK_ID = 'sl:pos'; diff --git a/src/layers/streetLevel/providers/kartaview/provider.test.mjs b/src/layers/streetLevel/providers/kartaview/provider.test.mjs index f73709d6c..955dc952d 100644 --- a/src/layers/streetLevel/providers/kartaview/provider.test.mjs +++ b/src/layers/streetLevel/providers/kartaview/provider.test.mjs @@ -17,6 +17,7 @@ import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs'; import { bindStreetViewer, coverageViewer, + drawnLineSets, tileCentre, } from '../../../../testSupport/streetLevelFakes.mjs'; import { fakeDrawPort } from '../../../../testSupport/fakeDrawPort.mjs'; @@ -735,10 +736,7 @@ function coverageSetup( return { query }; }; const centre = tileCentre(-83.0458, 42.3314); - const viewer = coverageViewer( - { lon: centre.lon, lat: centre.lat, height }, - t, - ); + const viewer = coverageViewer({ lon: centre.lon, lat: centre.lat, height }); const tiles = []; let hold = null; env.source.getTile = (tile) => { @@ -817,7 +815,7 @@ test('a filter thins the lines to those its PNG mask draws; without one they all env.instance.setFilter(); assert.ok(await until(() => env.instance.coverageStats().loading)); assert.equal( - env.viewer.scene.groundPrimitives.items.size, + drawnLineSets(env.viewer).length, 0, 'the unfiltered lines are not shown as filtered ones', ); @@ -834,7 +832,7 @@ test('a filter thins the lines to those its PNG mask draws; without one they all `startDate=${new Date(since).toISOString().slice(0, 10)}`, ); assert.equal(env.instance.coverageStats().hint, NO_COVERAGE_HINT); - assert.equal(env.viewer.scene.groundPrimitives.items.size, 0); + assert.equal(drawnLineSets(env.viewer).length, 0); // The same filter again asks KartaView for nothing. env.instance.setFilter(); for (let i = 0; i < 5; i++) await settle(); diff --git a/src/layers/streetLevel/providers/mapillary/provider.test.mjs b/src/layers/streetLevel/providers/mapillary/provider.test.mjs index 5c078028e..f9aca0a0e 100644 --- a/src/layers/streetLevel/providers/mapillary/provider.test.mjs +++ b/src/layers/streetLevel/providers/mapillary/provider.test.mjs @@ -87,14 +87,6 @@ test('cone thinning across the date line drops images metres apart', () => { /** A viewer looking straight down on downtown Sacramento from 900 m. */ function streetViewer() { - const collection = () => ({ - add: (item) => item, - remove: () => true, - contains: () => false, - get length() { - return 0; - }, - }); const event = () => ({ addEventListener: () => () => {} }); const camera = Object.assign( rayCamera({ @@ -112,8 +104,6 @@ function streetViewer() { scene: { canvas: { clientWidth: 100, clientHeight: 100 }, globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 }, - primitives: collection(), - groundPrimitives: collection(), preRender: event(), postRender: event(), requestRender() {}, @@ -123,13 +113,7 @@ function streetViewer() { return viewer; } -test('coverage asks for no tiles before the key status is known, and none without a key', async (t) => { - // Skip Cesium's one-time terrain table download for draped lines. - t.mock.method( - Cesium.GroundPolylinePrimitive, - 'initializeTerrainHeights', - async () => {}, - ); +test('coverage asks for no tiles before the key status is known, and none without a key', async () => { for (const configured of [false, true]) { let answer; const tiles = []; diff --git a/src/layers/streetLevel/providers/panoramax/provider.test.mjs b/src/layers/streetLevel/providers/panoramax/provider.test.mjs index a0d28dc95..1b22b778f 100644 --- a/src/layers/streetLevel/providers/panoramax/provider.test.mjs +++ b/src/layers/streetLevel/providers/panoramax/provider.test.mjs @@ -18,6 +18,7 @@ import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs'; import { bindStreetViewer, coverageViewer, + drawnLineSets, tileCentre, } from '../../../../testSupport/streetLevelFakes.mjs'; import { fakeDrawPort } from '../../../../testSupport/fakeDrawPort.mjs'; @@ -636,7 +637,7 @@ function coverageSetup(t, { sequences = [], filter, height = 900 } = {}) { }, { filter }, ); - const viewer = coverageViewer({ ...centre, height }, t); + const viewer = coverageViewer({ ...centre, height }); env.instance.init(viewer); t.after(() => env.instance.destroy(viewer)); return { @@ -693,12 +694,12 @@ test('the selected sequence’s line is drawn again over the coverage, and goes const env = coverageSetup(t, { sequences: [line('a'), line('b')] }); env.instance.activate(env.viewer); assert.ok(await until(() => env.instance.coverageStats().count === 2)); - const ground = env.viewer.scene.groundPrimitives.items; - const drawn = ground.size; + const lines = () => drawnLineSets(env.viewer).length; + const drawn = lines(); await env.instance.selectSequence('a'); - assert.equal(ground.size, drawn + 1, 'one highlight over the lines'); + assert.equal(lines(), drawn + 1, 'one highlight over the lines'); env.instance.clearSequence(); - assert.equal(ground.size, drawn); + assert.equal(lines(), drawn); }); test('coverage hints: nothing while loading, “no pictures” once an empty view has loaded', async (t) => { @@ -721,7 +722,7 @@ test('from high up nothing is drawn or fetched, and the panel says to zoom in', assert.equal(env.instance.coverageStats().count, 0); assert.equal(env.instance.coverageStats().loading, false); assert.deepEqual(env.source.calls.tiles, []); - assert.equal(env.viewer.scene.groundPrimitives.items.size, 0); + assert.equal(drawnLineSets(env.viewer).length, 0); }); test('switching off clears the cones and forgets a pending line click', async (t) => { diff --git a/src/layers/streetLevel/registry.js b/src/layers/streetLevel/registry.js index 5e51929a6..62463fde3 100644 --- a/src/layers/streetLevel/registry.js +++ b/src/layers/streetLevel/registry.js @@ -27,7 +27,7 @@ export function filtersOf(provider) { * @property {(context: ProviderContext) => ProviderInstance} create * * @typedef {object} ProviderContext Handed to `create()` once by the core. - * @property {object} services Scene services: picking, input, render, sprites, scenePick (ground clicks need it). + * @property {object} services Scene services: picking, input, render, sprites (a `scenePick` given is not read). * @property {() => {pano: string, sinceMs: number|null}} getFilter Filter resolved against now; read it on every use so "since N days" keeps up. * @property {() => boolean} isActive Layer enabled and this provider switched on. * @property {() => void} notify Ask the core to publish a new UI snapshot. diff --git a/src/layers/streetLevel/selection.js b/src/layers/streetLevel/selection.js index b0c932699..9e01729b6 100644 --- a/src/layers/streetLevel/selection.js +++ b/src/layers/streetLevel/selection.js @@ -1,4 +1,8 @@ -import { CLICK_PICK_WINDOW_PX, STREET_LEVEL_LAYER_ID } from './policy.js'; +import { + CLICK_PICK_WINDOW_PX, + STREET_LEVEL_LAYER_ID, + STREET_LEVEL_SET_PREFIX, +} from './policy.js'; import { inputFor } from '../../input/dispatcher.js'; import { toLonLatH } from '../../geo/index.js'; @@ -6,33 +10,39 @@ import { toLonLatH } from '../../geo/index.js'; export function createSelection({ state, parts }) { const { picking } = state.services; + /** + * The pick id a click hit: a line part of ours answers for its sequence + * (`meta.pick`); anything else by its own id. + */ + function pickIdOf({ drawHit, id }) { + if (drawHit?.set.startsWith(STREET_LEVEL_SET_PREFIX)) + return drawHit.meta?.pick ?? drawHit.id; + return id; + } + /** The id carries a provider's prefix: that provider handles the pick. */ function onClick(event) { - const viewer = state.viewer; - if (!viewer || !state.enabled) return; - const picked = event.pickWindow(CLICK_PICK_WINDOW_PX, CLICK_PICK_WINDOW_PX); - const id = picking?.resolvePickId - ? picking.resolvePickId(picked) - : picked?.id; - const route = parts.router.resolve(id); + if (!state.viewer || !state.enabled) return; + const hit = event.windowHit(CLICK_PICK_WINDOW_PX, CLICK_PICK_WINDOW_PX); + const route = parts.router.resolve(pickIdOf(hit)); // Not ours: the ground handler decides whether it is the map itself. if (!route) { - parts.openAtGround?.(event.position, picked); + parts.openAtGround?.({ surface: hit.surface, ground: groundOf(event) }); return; } // The position marker is the core's own: nothing to select. if (!route.instance) return; route.instance.handlePick(route.id, { - groundPoint: () => groundPointAt(viewer, event.position), + groundPoint: () => groundPointOf(event), }); } - /** Lon/lat of the ground under a screen point, or null (sky, no picker). */ - function groundPointAt(viewer, screenPosition) { - const position = state.services.scenePick?.pickGroundPosition?.( - viewer, - screenPosition, - ); + /** The world position under a click, measured when first asked; null over the sky. */ + const groundOf = (event) => () => event.ground(); + + /** Lon/lat of the ground under a click, or null (sky). */ + function groundPointOf(event) { + const position = event.ground(); const ground = position && toLonLatH(position); return ground ? { lon: ground.lon, lat: ground.lat } : null; } diff --git a/src/layers/streetLevel/selection.test.mjs b/src/layers/streetLevel/selection.test.mjs index 5e034ea53..07f55b9e1 100644 --- a/src/layers/streetLevel/selection.test.mjs +++ b/src/layers/streetLevel/selection.test.mjs @@ -6,7 +6,12 @@ import { createPickRouter } from './pickRouter.js'; import { fakeInput } from '../../input/testDoubles.mjs'; /** The selection installed on a stand-in viewer, with what its clicks reach. */ -function harness({ selected = false, services = {}, providers = [] } = {}) { +function harness({ + selected = false, + services = {}, + providers = [], + sceneExtras = {}, +} = {}) { const saved = globalThis.document; globalThis.document = new EventTarget(); // The document's keydown listeners, so a test can hand them any target. @@ -36,7 +41,11 @@ function harness({ selected = false, services = {}, providers = [] } = {}) { onwheel: null, }); const viewer = { - scene: { canvas, pick: () => scene.under && { id: scene.under } }, + scene: { + canvas, + pick: () => scene.under && { id: scene.under }, + ...sceneExtras, + }, }; const state = { viewer, @@ -66,7 +75,7 @@ function harness({ selected = false, services = {}, providers = [] } = {}) { positionId: 'sl:pos', }), hasSelectedSequence: () => sequences.selected, - openAtGround: (position, picked) => groundClicks.push({ position, picked }), + openAtGround: (click) => groundClicks.push(click), clearSequences() { sequences.cleared++; sequences.selected = false; @@ -118,8 +127,8 @@ test('a click on a line selects its sequence, on a cone opens its image, elsewhe assert.deepEqual([h.sequences.selects, h.opened], [['abc'], ['42']]); // The marker is ours; nothing and another layer's pick go to the ground. assert.deepEqual( - h.groundClicks.map(({ picked }) => picked?.id), - [undefined, 'cctv:7'], + h.groundClicks.map(({ surface }) => surface), + [true, false], ); } finally { h.restore(); @@ -193,18 +202,43 @@ test('a click on the position marker neither selects nor opens at the ground', ( } }); -test('a click on nothing of ours goes to the ground handler with the pick, which decides', () => { +test('a click on nothing of ours goes to the ground handler, told whether it hit the map', () => { const h = harness(); try { h.click(5); h.scene.under = 'flight:abc'; h.click(6); assert.deepEqual( - h.groundClicks.map(({ position, picked }) => [position.x, picked?.id]), - [ - [5, undefined], - [6, 'flight:abc'], - ], + h.groundClicks.map(({ surface }) => surface), + [true, false], + ); + assert.equal(h.groundClicks[0].ground(), null, 'no ground in this scene'); + } finally { + h.restore(); + } +}); + +test('a click on a part of a drawn line selects the sequence it belongs to', () => { + const h = harness(); + try { + h.scene.under = { + set: 'street-level:mapillary-coverage:1', + id: 'mly:seq:abc#2', + meta: { pick: 'mly:seq:abc' }, + }; + h.click(); + assert.deepEqual(h.sequences.selects, ['abc']); + // Another layer's set is not read for a Street Level pick. + h.scene.under = { + set: 'flights:1', + id: 'flight:1', + meta: { pick: 'mly:seq:xyz' }, + }; + h.click(); + assert.deepEqual(h.sequences.selects, ['abc']); + assert.deepEqual( + h.groundClicks.map(({ surface }) => surface), + [false], ); } finally { h.restore(); @@ -226,12 +260,11 @@ test('a click on a provider line hands it the ground under the click, measured o }, ], ], - services: { - scenePick: { - pickGroundPosition: (viewer, position) => { - groundPicks.push(position); - return Cesium.Cartesian3.fromDegrees(-83.0458, 42.3314, 190); - }, + sceneExtras: { + pickPositionSupported: true, + pickPosition: (position) => { + groundPicks.push(position); + return Cesium.Cartesian3.fromDegrees(-83.0458, 42.3314, 190); }, }, }); diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index cc18a85d5..29b4df0a7 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -1060,8 +1060,11 @@ export function createCesiumDraw({ was.id.meta = item.meta; // A ground primitive still building takes its show once it is ready // (`swapReady`), so a show change never restarts the build. - if (was.ground.ready) showPart(was, show); - else was.pendingShow = show; + // A show queued while it built is stale once a newer one is applied. + if (was.ground.ready) { + showPart(was, show); + was.pendingShow = undefined; + } else was.pendingShow = show; } return true; } diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 4b2173e00..374f3fc32 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -1386,6 +1386,35 @@ test('lines that change only whether they show, or where an undraped one runs, c set.dispose(); })); +test('a draped line shown after it is ready keeps that show through the swap', () => + withImageClasses(() => { + const { draw, frame, scene } = drawOver(); + const set = draw.lines({ id: 'swapped' }); + const draped = (show) => ({ + id: 'a', + positions: [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ], + widthPx: 2.5, + mode: 'draped', + style: { kind: 'solid', color: '#7fe6ed' }, + show, + }); + set.set([draped(true)]); + const ground = scene.added[0].get(1); + const show = new Uint8Array([1]); + ground.getGeometryInstanceAttributes = () => ({ show }); + // Hidden while it builds: queued for the swap. + set.upsert([draped(false)]); + // Ready, but not yet swapped in, when it is shown again. + Object.defineProperty(ground, 'ready', { value: true }); + set.upsert([draped(true)]); + frame(); + assert.deepEqual([...show], [1], 'the newer show, not the queued one'); + set.dispose(); + })); + test('icons blend as their set says', () => { const { scene, draw } = drawOver(); const set = draw.icons({ id: 'pins', blend: 'translucent' }); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index b02df8523..77bf1a947 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -86,7 +86,6 @@ "src/layers/satellites/state.js", "src/layers/satellites/testing.js", "src/layers/satellites/tracking.js", - "src/layers/streetLevel/lineCoverage.js", "src/layers/traffic/animation.js", "src/layers/traffic/lifecycle.js", "src/layers/traffic/rendering.js", diff --git a/src/testSupport/streetLevelFakes.mjs b/src/testSupport/streetLevelFakes.mjs index d8b6da6d0..ac0398a39 100644 --- a/src/testSupport/streetLevelFakes.mjs +++ b/src/testSupport/streetLevelFakes.mjs @@ -198,12 +198,6 @@ export function fakeCesiumViewer({ view = false } = {}) { flights, scene: { canvas, - primitives: { add: (p) => p, remove() {} }, - groundPrimitives: { add: (p) => p, remove() {} }, - // Enough of a scene for the position marker to clamp to the ground. - frameState: { mode: Cesium.SceneMode.SCENE3D }, - updateHeight: () => () => {}, - getHeight: () => undefined, }, camera, creditDisplay: { @@ -286,7 +280,9 @@ export function rayCamera({ * through what its `pickEllipsoid` hits), heights from its scene's * `sampleHeight` (3D tiles: only while its globe is hidden) and its * globe's `getHeight` (terrain), and pre-render from its scene's - * `preRender`; drawing goes to `draw` (a fake draw port by default), and + * `preRender`; positions under a screen point from its scene's + * `pickPosition` (when `pickPositionSupported`) and its camera's + * `pickEllipsoid`; drawing goes to `draw` (a fake draw port by default), and * with `camera` the camera is `liveCamera`'s. For `bindFakeCesiumCamera`'s * `ports`, or `bindRenderer`. * @param {object} viewer @@ -319,6 +315,14 @@ export function streetPorts( ); return { origin, direction }; }, + pickPosition(x, y) { + const scene = viewer.scene ?? {}; + if (!scene.pickPositionSupported) return null; + return scene.pickPosition?.({ x, y }) ?? null; + }, + pickEllipsoid(x, y) { + return viewer.camera?.pickEllipsoid?.({ x, y }) ?? null; + }, sampleHeightNow(point, { against = 'surface' } = {}) { const scene = viewer.scene ?? {}; if (against === 'terrain') @@ -394,36 +398,13 @@ export function tileCentre(lon, lat, z = 14) { }; } -/** A scene collection that remembers what is on the globe. */ -function sceneCollection() { - const items = new Set(); - return { - items, - add(primitive) { - items.add(primitive); - return primitive; - }, - remove(primitive) { - return items.delete(primitive); - }, - }; -} - /** * A viewer looking straight down on a 0.004° square around `view` * (`{lon, lat, height}`, mutable), enough for line coverage to attach, - * refresh and draw. Cesium's one-time terrain-height download is skipped. + * refresh and draw, on a fake draw port (`viewer.draw`; `drawnLineSets` + * lists what it draws). */ -export function coverageViewer(view, t) { - const initialize = Cesium.GroundPolylinePrimitive.initializeTerrainHeights; - Cesium.GroundPolylinePrimitive.initializeTerrainHeights = () => - Promise.resolve(); - t?.after(() => { - Cesium.GroundPolylinePrimitive.initializeTerrainHeights = initialize; - }); - // Node has no WebGL context to report line-width limits. - Cesium.ContextLimits._minimumAliasedLineWidth = 1; - Cesium.ContextLimits._maximumAliasedLineWidth = 10; +export function coverageViewer(view) { const listeners = () => { const set = new Set(); return { @@ -439,11 +420,6 @@ export function coverageViewer(view, t) { scene: { canvas: { clientWidth: 100, clientHeight: 100 }, globe: { show: false, ellipsoid: Cesium.Ellipsoid.WGS84 }, - frameState: { mode: Cesium.SceneMode.SCENE3D }, - updateHeight: () => () => {}, - getHeight: () => undefined, - groundPrimitives: sceneCollection(), - primitives: sceneCollection(), postRender: listeners(), preRender: listeners(), }, @@ -469,5 +445,23 @@ export function coverageViewer(view, t) { computeViewRectangle: () => undefined, }, }; - return bindFakeCesiumCamera(viewer, streetPorts(viewer)); + viewer.draw = fakeDrawPort(); + return bindFakeCesiumCamera( + viewer, + streetPorts(viewer, { draw: viewer.draw }), + ); +} + +/** + * The live Street Level line sets on `viewer.draw`, oldest (drawn lowest) + * first: those with lines in them, or with `empty` every one. + */ +export function drawnLineSets(viewer, { empty = false } = {}) { + return [...viewer.draw.sets.values()].filter( + (set) => + !set.disposed && + set.kind === 'lines' && + set.spec.id.startsWith('street-level:') && + (empty || set.items.size > 0), + ); }