A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.
JavaScript 3d-globecesiumflight-trackinggeospatialgeospatial-intelligencegisosintphotogrammetrysatellite-trackingspatial-intelligencewebglworldview
Merge upstream/main (KartaView #1121 merged) into pr/panoramax
Said Turkseverda0d370fa332
diff --cc DATA_SOURCES.mdindex 944e4e3fc,15bcfbf2a..6d083a5ea--- a/DATA_SOURCES.md+++ b/DATA_SOURCES.md@@@ -22,8 -22,7 +22,8 @@@ How to read this| **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" || **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles cached for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on || **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer |- | **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on |+ | **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on |+| **Panoramax** (`api.panoramax.xyz` meta-catalogue: vector tiles and STAC search; pictures from the federated instance holding each one, e.g. `panoramax.openstreetmap.fr`, `panoramax.ign.fr`) | Street Level: coverage lines and density points, nearest-picture lookups, a sequence's pictures as cones, and the picture itself, fetched by the browser. Keyless; tiles cached by the browser for an hour (the API's own header) | Per picture: mostly [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), IGN's [Licence Ouverte 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/); the API needs no token | "© Panoramax contributors, licence per picture" on the globe while the provider is on; the caption names each picture's author and licence || **OpenStreetMap** | Map and place data (roads, military areas and names, ALPR, place search, outlines); via vector tiles, hourly ALPR extract, bundled data, Nominatim and optional self-configured Overpass | [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/) | © OpenStreetMap contributors || **Google Map Tiles API** (Photorealistic 3D Tiles) + Places/Geocoding | The 3D globe, voice scene context, and on-demand nearby installation search | Google Maps Platform ToS (proprietary, your own key + billing) | "Google" / "Google Maps" logo — **shown in-app**, required || **OpenSky Network** | Primary worldwide live-flight snapshot | Non-commercial research/education license | Schäfer et al., _"Bringing Up OpenSky"_, IPSN 2014 + opensky-network.org |diff --cc README.mdindex 0611c6487,4029db402..c28ab74ac--- a/README.md+++ b/README.md@@@ -300,9 -300,9 +300,9 @@@ Twenty layers and map sources. **Eighte| 🛰️ **Satellites** | 838-object catalog, color-coded by class with a live legend — the **DENSE** chip drops in the whole Starlink shell | CelesTrak | 🟢 || 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 || 🚗 **Traffic** | Simulated vehicles on OSM roads. With TomTom, live flow speeds drive the simulation and congestion colors below ~8 km; individual vehicle positions are not live observations | TomTom + OSM | 🟢 simulation · 🟡 live flow speeds |- | 📹 **CCTV Mesh** | ~3,900 public cameras projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 |+ | 📹 **CCTV Mesh** | ~3,900 public cameras projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen), plus opt-in New York City (NYC DOT TMC, needs your own NYC DOT agreement). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 || 📷 **Mapped ALPR Cameras** | License-plate-reader camera locations tagged by OpenStreetMap contributors, loaded one city-sized view at a time, with **SHOW NEAREST**. Locations and tags only: no plate data, no video | OpenStreetMap (incl. DeFlock mapping) | 🟢 |-| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer and **FOLLOW**. Mapillary, Google Street View and KartaView; Panoramax planned | Mapillary · Google · KartaView | 🟢 KartaView · 🟡 Mapillary token · 🔴 Google Maps key |+| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer and **FOLLOW**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key || 📻 **Radio** | Geolocated world radio with an **analog tuner** — drag the needle across up to 750 stations and the globe flies to each broadcaster | Radio Browser / broadcasters | 🟢 || 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland | Operator GTFS-Realtime feeds | 🟢 || 🚲 **Bikeshare** | Live station availability | GBFS | 🟢 |@@@ -340,13 -340,13 +340,13 @@@ _The Space Missions layer replaying a F## 📷 Street Level-> Street-level photos from any provider in one panel. This build ships **Mapillary** (a free client token), **Google Street View** (your Google Maps key) and **KartaView** (no key).+> Street-level photos from any provider in one panel. This build ships **Mapillary** (a free client token), **Google Street View** (your Google Maps key), **KartaView** and **Panoramax** (no key).-**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** needs nothing: its public API is keyless.+**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** and **Panoramax** need nothing: their public APIs are keyless.- **Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary; Street View panoramas are all 360°, so with Street View lit the filters and legend are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. KartaView photos are undated on its map, so the filters do not apply to it. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): from orbit its dots show where it has pictures, and below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND**, **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos), and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo.-**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary and KartaView; Street View panoramas are all 360°, so with Street View lit the filters and legend are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it under the slider; KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds, and the unfiltered lines show meanwhile. On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND**, **FIT / FILL** (Mapillary, and flat KartaView photos), and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo.++**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary and KartaView; Street View panoramas are all 360°, so with Street View lit the filters and legend are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it under the slider; KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds, and the unfiltered lines show meanwhile. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): from orbit its dots show where it has pictures, and below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND**, **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos), and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo.- Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.kartaview-1` KartaView on, `0.m.0_0.r.panoramax-1` Panoramax on (a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.-Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1` KartaView on, as the app writes it (`0.m.0_0.r.kartaview-1` works too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.++Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1` KartaView on, as the app writes it (`0.m.0_0.r.kartaview-1` works too, and `0.m.0_0.r.panoramax-1` lights Panoramax; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.## 🎖️ Field Missionsdiff --cc scripts/qa-street-level.mjsindex 7c131a220,c47a3f9f8..6f87762cf--- a/scripts/qa-street-level.mjs+++ b/scripts/qa-street-level.mjs@@@ -965,9 -1087,18 +1110,18 @@@ async function main()),`cones for the whole drive: ${JSON.stringify((await ui()).sequence)}`,);+ // The drive runs north; the photos' compass says 200°.+ assert.ok(+ await uiUntil(+ (u) =>+ Number.isFinite(u.street.bearing) &&+ Math.min(u.street.bearing, 360 - u.street.bearing) < 2,+ ),+ `the camera looks along the drive, not where the compass points: ${(await ui()).street.bearing}`,+ );}const before = street.imageId;- await clickPanelControl(page, '.sl-kv-step-next');+ await clickPanelControl(page, '.sl-photo-step-next');assert.ok(await uiUntil((u, was) =>diff --cc src/layers/streetLevel/photoViewer.jsindex 0457e9f76,000000000..a7e86cb42mode 100644,000000..100644--- a/src/layers/streetLevel/photoViewer.js+++ b/src/layers/streetLevel/photoViewer.js@@@ -1,800 -1,0 +1,832 @@@+import {+ createPanoramaRenderer,+ PANO_FOV_DEFAULT_DEG,+ wrapDegrees,+} from './panorama.js';++/** A photo download (tens of kilobytes to a few megabytes). */+export const IMAGE_TIMEOUT_MS = 15_000;++/** A picture file or decoded side past these is refused (a photo is a few MB). */+export const MAX_IMAGE_BYTES = 48 * 1024 * 1024;+export const MAX_IMAGE_SIDE = 16_384;++/** Panorama texture widths: enough for a docked viewer, and for an expanded one. */+export const PANO_MID_SIZE = Object.freeze([2048, 1024]);+export const PANO_FULL_SIZE = Object.freeze([4096, 2048]);++/**+ * Load an image within the timeout. A CORS-clean one (for WebGL) is decoded+ * off the main thread into an ImageBitmap where the browser can: uploading+ * a decoded bitmap costs a fraction of uploading an <img> (90 ms → 15 ms for+ * 4096×2048 on a phone-class CPU). `resize` shrinks a bitmap while decoding+ * it (a panorama larger than any texture the viewer uploads).+ * @param {string} url+ * @param {{crossOrigin?: boolean, timeoutMs?: number, resize?: [number, number]|null, failure?: string}} [options]+ */+export function loadImage(+ url,+ {+ crossOrigin = true,+ timeoutMs = IMAGE_TIMEOUT_MS,+ resize = null,+ failure = 'The photo could not be loaded',+ signal = null,+ } = {},+) {+ if (+ crossOrigin &&+ url &&+ typeof globalThis.createImageBitmap === 'function' &&+ typeof globalThis.fetch === 'function'+ )+ return loadBitmap(url, timeoutMs, resize, failure, signal);+ return new Promise((resolve, reject) => {+ if (!url) return reject(new Error(failure));+ const image = new Image();+ if (crossOrigin) image.crossOrigin = 'anonymous';+ image.decoding = 'async';+ const timer = setTimeout(() => {+ image.src = '';+ reject(new Error(failure));+ }, timeoutMs);+ image.onload = () => {+ clearTimeout(timer);+ resolve(image);+ };+ image.onerror = () => {+ clearTimeout(timer);+ reject(new Error(failure));+ };+ image.src = url;+ });+}++async function loadBitmap(url, timeoutMs, resize, failure, signal) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ // The caller's abort (the photo changed) stops a multi-megabyte download.+ const onAbort = () => controller.abort();+ if (signal?.aborted) controller.abort();+ signal?.addEventListener?.('abort', onAbort, { once: true });+ try {+ const response = await fetch(url, {+ mode: 'cors',+ signal: controller.signal,+ });+ if (!response.ok) throw new Error(failure);+ // Picture hosts are not ours: refuse a file or an image past any real+ // photo's size before it is decoded.+ const length = Number(response.headers?.get?.('content-length'));+ if (length > MAX_IMAGE_BYTES) throw new Error(failure);+ const blob = await boundedBlob(response, failure);+ const bitmap = await (resize+ ? createImageBitmap(blob, {+ resizeWidth: resize[0],+ resizeHeight: resize[1],+ resizeQuality: 'high',+ })+ : createImageBitmap(blob));+ // (A resized decode reports its new size: this guards unresized ones.)+ if (bitmap.width > MAX_IMAGE_SIDE || bitmap.height > MAX_IMAGE_SIDE) {+ bitmap.close?.();+ throw new Error(failure);+ }+ return bitmap;+ } catch {+ throw new Error(failure);+ } finally {+ clearTimeout(timer);+ signal?.removeEventListener?.('abort', onAbort);+ }+}++/**+ * The body as a Blob, read with a running count so a host that sends no+ * length (or a false one) cannot fill memory before the cap is checked.+ */+async function boundedBlob(response, failure) {+ const reader = response.body?.getReader?.();+ if (!reader) {+ const blob = await response.blob();+ if (blob.size > MAX_IMAGE_BYTES) throw new Error(failure);+ return blob;+ }+ const chunks = [];+ let total = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > MAX_IMAGE_BYTES) {+ reader.cancel().catch(() => {});+ throw new Error(failure);+ }+ chunks.push(value);+ }+ return new Blob(chunks, {+ type: response.headers?.get?.('content-type') || 'image/jpeg',+ });+}++/** The panorama size a canvas this wide can show sharply at this field of view. */+export function panoSizeFor(canvasPixels, fovDeg) {+ const needed = (Math.max(1, canvasPixels) * 360) / Math.max(1, fovDeg);+ return needed > PANO_MID_SIZE[0] ? PANO_FULL_SIZE : PANO_MID_SIZE;+}++/**+ * @typedef {object} PhotoSources Where a provider's photo comes from.+ * @property {(photo: object) => boolean} hasPano A 360° photo with an equirectangular image.+ * @property {(photo: object) => {url: string, width: number, resize?: [number, number]|null}|null} panoFirst+ * The panorama shown first, its texture width (0 when it is only a preview), and a size to shrink it to.+ * @property {(photo: object, size: [number, number], view: {expanded: boolean}) => {url: string, resize?: [number, number]|null, timeoutMs?: number}|null} panoSharp+ * A sharper panorama for a canvas that needs `size`, or null; `expanded` while the viewer is.+ * @property {(photo: object) => Array<string>} flatFirst Flat versions to try in turn.+ * @property {(photo: object, pixels: number) => string|null} flatSharp+ * A sharper flat version for a picture this many device pixels wide, or null.+ * @property {(photo: object) => {title?: string|null, creator?: string|null, license?: string|null, externalUrl: string, capturedAtPrecision?: 'day'|'month'}} describe++ * @property {(photo: object) => number|null} [bearingOf] Where the camera looked (default `photo.heading`).+ */++/**+ * Viewer adapter for providers whose photos are plain image files: a flat+ * photo in an <img>, a 360° photo on a WebGL panorama (drag to look, wheel+ * or pinch to zoom), and ‹ › to step along the sequence (also ← →). Poses+ * follow the view direction.+ *+ * Photos are normalized by the provider: `{id, sequenceId, lon, lat,+ * heading, isPano, capturedAt}` plus whatever its `sources` read.+ *+ * @param {object} options+ * @param {string} options.providerId+ * @param {string} options.name Provider name for labels and messages, e.g. 'KartaView'.+ * @param {PhotoSources} options.sources+ * @param {(photoId: string) => Promise<object>} options.getPhoto A normalized photo.+ * @param {(photo: object, delta: -1|1) => Promise<string|null>} options.step The photo `delta` along the sequence, or null at its end.+ * @param {(imageId: string) => void} options.onStep Open the photo ‹ › chose (through the core, so loading and errors show).+ * @param {(photo: object) => void} [options.onShown] A photo is on screen.++ * @param {(imageId: string) => void} [options.onReopen] Draw the same photo again after a GPU reset (default: `onStep`).+ * @param {() => boolean} [options.onEscape] Esc in the docked viewer: true when it was used (e.g. a selection cleared).+ * @param {object} [options.render] Render governor.+ * @param {(url: string, options?: object) => Promise<HTMLImageElement|ImageBitmap>} [options.load]+ * @param {(canvas: HTMLCanvasElement) => object} [options.createRenderer]+ * @returns {import('./registry.js').ViewerAdapter}+ */+export function createPhotoViewer({+ providerId,+ name,+ sources,+ getPhoto,+ step,+ onStep,+ onShown = () => {},++ onReopen = onStep,+ onEscape = () => false,+ render,+ load = loadImage,+ createRenderer = createPanoramaRenderer,+}) {+ const LOAD_FAILED = `The ${name} photo could not be loaded`;+ const listeners = new Set();+ let root = null;+ let picture = null;+ let canvas = null;+ let prevButton = null;+ let nextButton = null;+ let renderer = null;+ /** WebGL failed once: 360° photos show their front view instead. */+ let rendererFailed = false;+ let photo = null;+ /** What shows: 'flat', 'pano' or null. */+ let showing = null;+ let openSeq = 0;+ let renderMode = 'letterbox';+ let drag = null;+ let poseFrame = 0;+ let removeListeners = [];+ /** The document the viewer was built in (new canvases come from it). */+ let documentOf = null;+ /** A context loss's look direction, for the reopen of that photo. */+ let restoreView = null;+ /** The panel's viewer box, where Esc is listened for (null: the root). */+ let escapeTarget = null;+ /** Width of the panorama texture on screen (0: the preview). */+ let panoWidth = 0;+ /** The sharper panorama on its way, for which open (resizes come in bursts). */+ let panoComing = null;++ /** A resize came while it loaded: look again once it lands. */++ let lookAgain = false;+ /** The sharper flat version on screen or on its way (one download each). */+ let flatSharpUrl = null;+ /** The photo an open is fetching: ‹ › step on from it, not the old one. */+ let openingId = null;+ /** ‹ › chose this photo: keep the panorama's look direction for it. */+ let keepViewFor = null;+ /** ‹ › presses run one after another, each from where the last one went. */+ let steps = Promise.resolve();++ const loadAs = (url, options) =>+ load(url, { failure: LOAD_FAILED, ...options });++ function requestRender() {+ render?.governorRequestRender?.(`${providerId}-viewer`);+ }++ function emit() {+ if (!photo || !showing) return;++ // A lost GPU context, still being recovered: the open that redraws the++ // panorama poses once it is on screen.++ if (showing === 'pano' && !renderer) return;+ const view = showing === 'pano' ? renderer.getView() : null;- const heading = photo.heading;++ const heading = sources.bearingOf++ ? sources.bearingOf(photo)++ : photo.heading;+ const described = sources.describe(photo);+ const pose = {+ providerId,+ imageId: photo.id,+ position: { lon: photo.lon, lat: photo.lat },+ bearing:+ heading === null || heading === undefined+ ? null+ : view+ ? wrapDegrees(heading + view.yaw)+ : heading,+ tilt: view ? view.pitch : 0,+ altitude: null,+ isPano: showing === 'pano',+ capturedAt: photo.capturedAt,+ capturedAtPrecision: described.capturedAtPrecision || 'day',+ title: described.title ?? null,+ creator: described.creator ?? null,+ license: described.license ?? null,+ sequenceId: photo.sequenceId,+ externalUrl: described.externalUrl,+ };+ for (const listener of [...listeners]) {+ try {+ listener(pose);+ } catch {+ /* listener errors are the core's to log */+ }+ }+ requestRender();+ }++ /** Re-emit on the next frame: a drag moves the view many times a frame. */+ function emitSoon() {+ if (poseFrame) return;+ poseFrame = requestAnimationFrame(() => {+ poseFrame = 0;+ emit();+ });+ }++ function syncButtons() {+ const enabled = Boolean(photo?.sequenceId) && showing !== null;+ if (prevButton) prevButton.disabled = !enabled;+ if (nextButton) nextButton.disabled = !enabled;+ if (enabled) checkEnds(photo);+ }++ /** Disable ‹ or › at once where the sequence ends (it also warms the neighbours). */+ function checkEnds(target) {+ for (const [delta, button] of [+ [-1, prevButton],+ [1, nextButton],+ ])+ step(target, delta).then(+ (id) => {+ if (photo === target && button && !id) disable(button);+ },+ () => {},+ );+ }++ /** Disable a step button, keeping keyboard focus in the viewer. */+ function disable(button) {+ if (button.ownerDocument?.activeElement === button) root?.focus?.();+ button.disabled = true;+ }++ function show(kind) {+ showing = kind;+ if (picture) picture.hidden = kind !== 'flat';+ if (canvas) canvas.hidden = kind !== 'pano';+ if (root) root.dataset.kind = kind || '';+ syncButtons();+ }++ function applyRenderMode() {+ if (picture)+ picture.style.objectFit = renderMode === 'fill' ? 'cover' : 'contain';+ }++ function ensureRenderer() {+ if (renderer || rendererFailed || !canvas) return renderer;+ try {+ renderer = createRenderer(canvas);+ } catch {+ rendererFailed = true;+ renderer = null;+ }+ return renderer;+ }++ /**+ * A lost WebGL context (GPU reset, memory pressure) takes the panorama+ * with it: drop the renderer, and show the photo again on a new one.+ */+ function onContextLost(event) {+ event.preventDefault?.();+ const lost = renderer;+ renderer = null;+ // The new renderer starts facing the photo's heading: keep the user's look.+ if (showing === 'pano' && photo && lost)+ restoreView = { id: photo.id, view: lost.getView() };+ try {+ lost?.destroy();+ } catch {+ /* already gone */+ }+ // A lost canvas hands back its lost context: draw on a new element.+ const fresh = makeCanvas(documentOf);+ fresh.hidden = canvas.hidden;+ canvas.replaceWith?.(fresh);+ canvas = fresh;+ // Show the photo again through the core, unless a newer one is opening.+ if (showing === 'pano' && photo && openingId === null) {+ const again = photo.id;+ show(null);+ openingId = again;- onStep(again);++ onReopen(again);+ }+ }++ /** The panorama canvas, wired for drag, pinch, wheel and context loss. */+ function makeCanvas(doc) {+ const element = doc.createElement('canvas');+ element.className = 'sl-photo-pano';+ element.hidden = true;+ listen(element, 'pointerdown', onPointerDown);+ listen(element, 'pointermove', onPointerMove);+ listen(element, 'pointerup', onPointerUp);+ listen(element, 'pointercancel', onPointerUp);+ listen(element, 'wheel', onWheel, { passive: false });+ listen(element, 'webglcontextlost', onContextLost);+ return element;+ }++ /**+ * Step along the sequence from the photo showing, or from the one on its+ * way after an earlier press, and open it through the core.+ */+ function stepBy(delta) {+ steps = steps.then(async () => {+ const fromId = openingId ?? photo?.id;+ if (!fromId || !root) return;+ let from;+ let nextId = null;+ try {+ from = await getPhoto(fromId);+ if (from.sequenceId) nextId = await step(from, delta);+ } catch {+ // Not the end of the sequence, just no answer: the press is lost.+ return;+ }+ // Closed, or another photo was opened meanwhile.+ if ((openingId ?? photo?.id) !== fromId) return;+ if (!nextId) {+ const button = delta < 0 ? prevButton : nextButton;+ if (button && photo?.id === fromId) disable(button);+ return;+ }+ openingId = nextId;+ keepViewFor = nextId;+ onStep(nextId);+ });+ }++ /** Pointers on the panorama: one drags the view, two pinch the zoom. */+ const pointers = new Map();+ let pinch = null;++ function pinchSpan() {+ const [a, b] = [...pointers.values()];+ return Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));+ }++ function onPointerDown(event) {+ if (showing !== 'pano' || !renderer) return;+ if (event.pointerType === 'mouse' && event.button !== 0) return;+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });+ canvas.setPointerCapture?.(event.pointerId);+ if (pointers.size === 2) {+ drag = null;+ pinch = { span: pinchSpan(), fov: renderer.getView().fov };+ return;+ }+ drag = {+ id: event.pointerId,+ x: event.clientX,+ y: event.clientY,+ view: renderer.getView(),+ };+ canvas.classList.add('sl-photo-dragging');+ }++ function onPointerMove(event) {+ if (pointers.has(event.pointerId))+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });+ if (pinch && pointers.size === 2 && renderer) {+ renderer.setView({ fov: pinch.fov * (pinch.span / pinchSpan()) });+ return;+ }+ if (!drag || event.pointerId !== drag.id || !renderer) return;+ const { fov } = drag.view;+ const width = Math.max(1, canvas.clientWidth);+ const height = Math.max(1, canvas.clientHeight);+ const vertical = fov;+ const horizontal = fov * (width / height);+ renderer.setView({+ yaw: drag.view.yaw - ((event.clientX - drag.x) / width) * horizontal,+ pitch: drag.view.pitch + ((event.clientY - drag.y) / height) * vertical,+ });+ emitSoon();+ }++ function onPointerUp(event) {+ pointers.delete(event.pointerId);+ if (pointers.size < 2) pinch = null;+ if (!drag || event.pointerId !== drag.id) return;+ drag = null;+ canvas.classList.remove('sl-photo-dragging');+ }++ function onWheel(event) {+ if (showing !== 'pano' || !renderer) return;+ event.preventDefault();+ const { fov } = renderer.getView();+ renderer.setView({ fov: fov * Math.exp(event.deltaY * 0.001) });+ }++ /**+ * Docked, Esc anywhere in the viewer's box (the photo, its toolbar, its+ * caption) is the provider's before the panel's, which would collapse;+ * expanded, the dialog's own Esc shrinks it.+ */+ function onEscapeKey(event) {+ if (+ event.key !== 'Escape' ||+ event.shiftKey ||+ event.defaultPrevented ||+ root?.closest?.('.sl-viewer-wrap-expanded') ||+ !onEscape()+ )+ return;+ event.preventDefault();+ event.stopPropagation();+ }++ function onKeyDown(event) {+ if (!escapeTarget) onEscapeKey(event);+ if (+ event.defaultPrevented ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey+ )+ return;+ const pano = showing === 'pano' && renderer;+ const turn = { ArrowLeft: -1, ArrowRight: 1 }[event.key];+ // Shift+← → look around a panorama; ← → step along the sequence.+ if (turn && event.shiftKey && pano) {+ event.preventDefault();+ const { yaw, fov } = renderer.getView();+ renderer.setView({ yaw: yaw + (turn * fov) / 4 });+ emitSoon();+ } else if (turn) {+ event.preventDefault();+ stepBy(turn);+ } else if ((event.key === 'ArrowUp' || event.key === 'ArrowDown') && pano) {+ event.preventDefault();+ const { pitch, fov } = renderer.getView();+ renderer.setView({+ pitch: pitch + ((event.key === 'ArrowUp' ? 1 : -1) * fov) / 6,+ });+ emitSoon();+ } else if (['+', '=', '-', '_'].includes(event.key) && pano) {+ event.preventDefault();+ const { fov } = renderer.getView();+ renderer.setView({+ fov: fov * (event.key === '+' || event.key === '=' ? 0.85 : 1 / 0.85),+ });+ }+ }++ function listen(target, type, handler, options) {+ target.addEventListener(type, handler, options);+ removeListeners.push(() =>+ target.removeEventListener(type, handler, options),+ );+ }++ function build(host) {+ const doc = host.ownerDocument;+ documentOf = doc;+ root = doc.createElement('div');+ root.className = 'sl-photo-viewer';+ root.dataset.provider = providerId;+ root.tabIndex = 0;+ root.setAttribute('role', 'group');+ root.setAttribute(+ 'aria-label',+ `${name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom`,+ );+ picture = doc.createElement('img');+ picture.className = 'sl-photo-flat';+ picture.alt = `${name} street-level photo`;+ picture.draggable = false;+ picture.hidden = true;+ canvas = makeCanvas(doc);+ const nav = (label, glyph, delta) => {+ const button = doc.createElement('button');+ button.type = 'button';+ button.className = `sl-photo-step sl-photo-step-${delta < 0 ? 'prev' : 'next'}`;+ button.textContent = glyph;+ button.title = label;+ button.setAttribute('aria-label', label);+ button.disabled = true;+ listen(button, 'click', (event) => {+ event.stopPropagation();+ stepBy(delta);+ });+ return button;+ };+ prevButton = nav('Previous photo in this sequence (←)', '‹', -1);+ nextButton = nav('Next photo in this sequence (→)', '›', 1);+ root.append(picture, canvas, prevButton, nextButton);+ host.append(root);+ listen(root, 'keydown', onKeyDown);+ // The viewer's box in the panel; without one, the root's own handler+ // takes Esc (one listener per element and type).+ escapeTarget = host.closest?.('.sl-viewer-wrap') ?? null;+ if (escapeTarget) listen(escapeTarget, 'keydown', onEscapeKey);+ applyRenderMode();+ }++ function teardown() {+ pointers.clear();+ pinch = null;+ for (const remove of removeListeners) remove();+ removeListeners = [];+ if (poseFrame) cancelAnimationFrame(poseFrame);+ poseFrame = 0;+ drag = null;+ renderer?.destroy();+ renderer = null;+ root?.remove();+ root = picture = canvas = prevButton = nextButton = null;+ showing = null;+ photo = null;+ }+- /** Device pixels across the viewer (its picture or canvas). */++ /** Device pixels across the flat photo's frame (its longer side). */+ function viewerPixels() {- const ratio = Math.min(globalThis.devicePixelRatio || 1, 2);++ const ratio = globalThis.devicePixelRatio || 1;+ const element = showing === 'pano' ? canvas : picture;- return (element?.clientWidth || root?.clientWidth || 0) * ratio;++ const side = Math.max(++ element?.clientWidth || 0,++ element?.clientHeight || 0,++ );++ return (side || root?.clientWidth || 0) * ratio;+ }++ /** A sharper version once the first is on screen, if nothing replaced it. */+ async function upgrade(target, seq, kind) {+ // A 360° photo shown flat (no WebGL) keeps its front view.+ if (kind === 'flat' && target.isPano) return;+ if (kind === 'pano') {+ const size = panoSizeNow();+ if (size[0] <= panoWidth) return;- if (panoComing?.seq === seq && size[0] <= panoComing.width) return;++ // Resizes come in bursts while the panel animates: one load at a time++ // for this photo, and one more look once it lands.++ if (panoComing?.seq === seq) {++ lookAgain = true;++ return;++ }+ const sharp = sources.panoSharp(target, size, {+ expanded: Boolean(root?.closest?.('.sl-viewer-wrap-expanded')),+ });+ if (!sharp?.url) return;+ const coming = { seq, width: size[0], controller: new AbortController() };+ panoComing = coming;++ lookAgain = false;+ try {+ const image = await loadAs(sharp.url, {+ crossOrigin: true,+ signal: coming.controller.signal,+ resize: sharp.resize ?? null,+ ...(sharp.timeoutMs ? { timeoutMs: sharp.timeoutMs } : {}),+ });+ if (seq !== openSeq || photo !== target || showing !== 'pano') {+ image.close?.();+ return;+ }+ if (!renderer || size[0] <= panoWidth) {+ image.close?.();+ return;+ }+ renderer.setImage(image);+ panoWidth = size[0];+ requestRender();+ } catch {+ /* the first version stays */+ } finally {- if (panoComing === coming) panoComing = null;++ if (panoComing === coming) {++ panoComing = null;++ if (lookAgain && seq === openSeq && photo === target) {++ lookAgain = false;++ upgrade(target, seq, 'pano');++ }++ }+ }+ return;+ }+ const url = sources.flatSharp(target, viewerPixels());+ if (!url || url === flatSharpUrl) return;+ flatSharpUrl = url;+ try {+ const image = await loadAs(url, { crossOrigin: false });+ if (seq !== openSeq || photo !== target || showing !== 'flat') return;+ picture.src = image.src;+ requestRender();+ } catch {+ // The first version stays; a later resize may try again.+ if (flatSharpUrl === url && photo === target) flatSharpUrl = null;+ }+ }++ /** Another photo, or none: a sharper panorama still on its way is not needed. */+ function dropSharpPanorama() {+ panoComing?.controller?.abort();+ panoComing = null;++ lookAgain = false;+ }++ /** The sharp panorama this viewer needs now: 2,048 docked, 4,096 expanded. */+ function panoSizeNow() {+ const ratio = Math.min(globalThis.devicePixelRatio || 1, 2);+ const width = (canvas?.clientWidth || 0) * ratio;+ return panoSizeFor(width, renderer?.getView().fov ?? PANO_FOV_DEFAULT_DEG);+ }++ async function showPano(target, seq, keepView) {+ // If the panorama fails, the caller shows the front view rather than+ // waiting on it twice.+ const first = sources.panoFirst(target);+ if (!first?.url) throw new Error(LOAD_FAILED);+ const image = await loadAs(first.url, {+ crossOrigin: true,+ resize: first.resize ?? null,+ });+ if (seq !== openSeq) {+ image.close?.();+ return false;+ }+ // The context may have been lost while this loaded: build on the new+ // canvas, or let the caller show the front view.+ if (!ensureRenderer()) {+ image.close?.();+ throw new Error(LOAD_FAILED);+ }+ const restore = restoreView?.id === target.id ? restoreView.view : null;+ restoreView = null;+ if (restore) renderer.setView(restore);+ else if (!keepView || showing !== 'pano')+ renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG });+ photo = target;+ // Shown first: a hidden canvas measures 0 and would be sized 1×1.+ show('pano');+ renderer.setImage(image);+ panoWidth = first.width || 0;+ panoComing = null;+ return true;+ }++ async function showFlat(target, seq) {+ const urls = sources.flatFirst(target).filter(Boolean);+ let image;+ let failure = null;+ for (const url of urls) {+ try {+ image = await loadAs(url, { crossOrigin: false });+ break;+ } catch (error) {+ failure = error;+ if (seq !== openSeq) return false;+ }+ }+ if (!image) throw failure || new Error(LOAD_FAILED);+ if (seq !== openSeq) return false;+ picture.src = image.src;+ flatSharpUrl = null;+ photo = target;+ show('flat');+ return true;+ }++ async function openPhoto(id, seq, keepView) {+ const target = await getPhoto(id);+ if (seq !== openSeq) return;+ let shown = false;+ if (sources.hasPano(target) && ensureRenderer()) {+ try {+ shown = await showPano(target, seq, keepView);+ } catch {+ // The panorama failed: its front view is better than nothing.+ if (seq !== openSeq) return;+ shown = await showFlat(target, seq);+ }+ } else shown = await showFlat(target, seq);+ if (!shown) return;+ emit();+ onShown(target);+ upgrade(target, seq, showing);+ }++ const adapter = {+ async mount(host) {+ if (!host) throw new Error('Street Level viewer has no host element');+ if (root && root.parentNode === host) return;+ teardown();+ rendererFailed = false;+ build(host);+ },++ /** Resolves once the photo is on screen and its pose was emitted. */+ async open(imageId) {+ if (!root) throw new Error(`${name} viewer is not mounted`);+ const id = String(imageId);+ const seq = ++openSeq;+ dropSharpPanorama();+ const keepView = keepViewFor === id;+ keepViewFor = null;+ openingId = id;+ try {+ await openPhoto(id, seq, keepView);+ } finally {+ if (openingId === id && seq === openSeq) openingId = null;+ }+ },++ close() {+ openSeq++;+ dropSharpPanorama();+ openingId = null;+ keepViewFor = null;+ photo = null;+ flatSharpUrl = null;+ show(null);+ if (picture) picture.removeAttribute('src');+ renderer?.clear?.();+ },++ unmount() {+ openSeq++;+ dropSharpPanorama();+ openingId = null;+ keepViewFor = null;+ flatSharpUrl = null;+ teardown();+ },++ resize() {+ renderer?.resize();+ // Expanded: a docked viewer's panorama or flat version is now too soft.+ if (showing === 'pano' && photo && panoSizeNow()[0] > panoWidth)+ upgrade(photo, openSeq, 'pano');+ else if (showing === 'flat' && photo) upgrade(photo, openSeq, 'flat');+ },++ /** FIT / FILL frame a flat photo; a panorama has no frame to fit. */+ supportsRenderModes: () => showing !== 'pano',++ setRenderMode(mode) {+ renderMode = mode === 'fill' ? 'fill' : 'letterbox';+ applyRenderMode();+ },+++ /** The photo's direction became known (its drive loaded): pose again. */++ refreshPose() {++ emit();++ },+++ onPose(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ return adapter;+}diff --cc src/layers/streetLevel/providers/kartaview/index.jsindex 59f2f8d7d,ae05983a4..31587b03f--- a/src/layers/streetLevel/providers/kartaview/index.js+++ b/src/layers/streetLevel/providers/kartaview/index.js@@@ -1,10 -1,12 +1,15 @@@import { createLineCoverage } from '../../lineCoverage.js';+import { createLru, createTileCache } from '../../tileCache.js';++export { createTileCache } from '../../tileCache.js';import { createSequenceCones, thinImages } from '../../sequenceCones.js';import { metresBetween } from '../../view.js';- import { decodeCoverageTile } from './decode.js';+ import {+ chainSegments,+ maskedSegments,+ readMaskImage,+ tileSegments,+ } from './decode.js';import { createKartaViewSource } from './source.js';import { createKartaViewViewer } from './viewer.js';import {@@@ -361,13 -483,17 +435,24 @@@ export function createKartaViewProviderstep,onStep: openStepped,onShown: recentreCones,+ // After a GPU reset the same photo is drawn again by the viewer+ // itself: going through the core would cancel a lookup the user+ // started. A failure still shows.+ onReopen: (photoId) =>+ viewer+ .open(photoId)+ .catch((error) =>+ context.actions.reportError(+ error?.message || 'The KartaView photo could not be loaded',+ ),+ ),+ // Esc in the viewer clears the selected drive, as the panel says.+ onEscape: () => {+ if (!state.sequence.selectedId) return false;+ cones.clearSelection();+ drawnPage = null;+ return true;+ },render: context.services?.render,...viewerOptions,});diff --cc src/layers/streetLevel/providers/kartaview/provider.test.mjsindex 81749b665,706988904..a043063fa--- a/src/layers/streetLevel/providers/kartaview/provider.test.mjs+++ b/src/layers/streetLevel/providers/kartaview/provider.test.mjs@@@ -747,23 -896,213 +896,234 @@@ test('a photo no page lists steps to thassert.equal(env.poses.at(-1), 's-4');});+test('Esc in the docked viewer clears the selected drive and is consumed; with none, it goes on to the panel', async (t) => {+ const env = await mounted({ sequences: { s: [0, 1, 2, 3] } });+ await withCones(t, env);+ await env.instance.viewer.open('s-1');+ await env.instance.selectSequence('s');+ assert.ok(await until(() => env.instance.sequenceStats().images === 4));+ const root = env.next.parentNode;+ const press = () => {+ const flags = { stopped: false, prevented: false };+ root.fire('keydown', {+ key: 'Escape',+ stopPropagation: () => (flags.stopped = true),+ preventDefault: () => (flags.prevented = true),+ });+ return flags;+ };+ assert.deepEqual(press(), { stopped: true, prevented: true });+ assert.equal(env.instance.sequenceStats().selectedId, null, 'drive cleared');+ assert.deepEqual(press(), { stopped: false, prevented: false });+});+++ test('the panel counts the drive’s photos, not the thinned page of them the cones show', async (t) => {+ const env = await mounted({+ sequences: { s: Array.from({ length: 40 }, (_, i) => i) },+ });+ const asked = [];+ env.source.getSequenceCount = async (id) => {+ asked.push(id);+ return 2385;+ };+ await withCones(t, env);+ await env.instance.viewer.open('s-3');+ await env.instance.selectSequence('s');+ assert.ok(+ await until(() => env.instance.sequenceStats().images === 2385),+ `images: ${env.instance.sequenceStats().images}`,+ );+ // Asked once per drive.+ env.instance.clearSequence();+ await env.instance.viewer.open('s-30');+ await env.instance.selectSequence('s');+ assert.ok(await until(() => env.instance.sequenceStats().images === 2385));+ assert.deepEqual(asked, ['s']);+ });++ test('after a GPU reset the photo is drawn again by the viewer, not through the core; a failure is reported', async () => {+ const source = fakeSource();+ const record = {+ ...photoRecord('pano', { seq: 'p', index: 0 }),+ projection: 'SPHERE',+ fieldOfView: '360',+ filepathProc: '2022/10/6/wrapped_proc/pano.jpg',+ };+ source.getPhoto = async () => record;+ const view = { yaw: 0, pitch: 0, fov: 80 };+ let failLoads = false;+ const definition = createKartaViewProvider({+ source,+ viewerOptions: {+ load: async (url) => {+ if (failLoads)+ throw new Error('The KartaView photo could not be loaded');+ return { src: url };+ },+ createRenderer: () => ({+ setImage() {},+ setView: (next) => Object.assign(view, next),+ getView: () => ({ ...view }),+ resize() {},+ clear() {},+ destroy() {},+ }),+ },+ });+ const { context, actions } = fakeContext();+ const errors = [];+ context.actions.reportError = (message) => errors.push(message);+ const instance = definition.create(context);+ actions.instance = instance;+ const host = fakeHost();+ await instance.viewer.mount(host);+ const poses = [];+ instance.viewer.onPose((pose) => poses.push(pose.imageId));+ await instance.viewer.open('pano');+ const canvas = () => host.children[0].children[1];+ const kind = () => host.children[0].dataset.kind;+ canvas().fire('webglcontextlost');+ assert.equal(kind(), '', 'cleared while it is drawn again');+ assert.ok(await until(() => kind() === 'pano'), 'drawn again');+ assert.ok(poses.length >= 2);+ assert.deepEqual(actions.opened, [], 'the core (and its lookup) left alone');+ failLoads = true;+ canvas().fire('webglcontextlost');+ assert.ok(await until(() => errors.length === 1));+ assert.match(errors[0], /could not be loaded/);+ });++ test('the marker is KartaView’s own cone, and it points along the drive, not at a wrong compass', async () => {+ const env = setup({+ sequences: { s: Array.from({ length: 10 }, (_, i) => i) },+ });+ assert.deepEqual(env.definition.marker, {+ kind: 'view-cone',+ color: '#635bff',+ });+ // Photos run east (photoRecord puts index i at 5·i m east); the compass says 200°.+ const getPhoto = env.source.getPhoto;+ env.source.getPhoto = async (id) => ({+ ...(await getPhoto(id)),+ heading: '200',+ });+ const getPage = env.source.getSequencePhotos;+ env.source.getSequencePhotos = async (...args) => {+ const page = await getPage(...args);+ return {+ ...page,+ photos: page.photos.map((record) => ({ ...record, heading: '200' })),+ };+ };+ const host = fakeHost();+ await env.instance.viewer.mount(host);+ const bearings = [];+ env.instance.viewer.onPose((pose) => bearings.push(pose.bearing));+ await env.instance.viewer.open('s-4');+ assert.equal(bearings[0], 200, 'the compass until the drive is known');+ assert.ok(+ await until(() => Math.abs(bearings.at(-1) - 90) < 1),+ `then along the drive: ${bearings}`,+ );+ });++ /** Hold `seq`'s page `page` until the returned function is called. */+ function holdPage(source, seq, page) {+ const getPage = source.getSequencePhotos;+ let release;+ const gate = new Promise((resolve) => (release = resolve));+ source.getSequencePhotos = async (id, options) => {+ if (id === seq && options.page === page) await gate;+ return getPage(id, options);+ };+ return () => release();+ }++ test('a photo opened while the cones first load is the one they centre on', async (t) => {+ const size = SEQUENCE_PAGE_SIZE;+ const env = await mounted({+ sequences: { s: Array.from({ length: size * 5 }, (_, i) => i) },+ });+ const cones = await withCones(t, env);+ const release = holdPage(env.source, 's', 1);+ await env.instance.viewer.open('s-10');+ const selected = env.instance.selectSequence('s');+ // A line click further along the drive while page 1 is still loading:+ // nothing is drawn yet for its re-centre to move.+ await env.instance.viewer.open(`s-${size * 4 + 10}`);+ release();+ await selected;+ assert.ok(+ await until(+ () => !env.instance.sequenceStats().loading && cones.count() > 0,+ ),+ );+ assert.ok(+ cones()[0] <= size * 4 + 10 && cones()[1] >= size * 4 + 10,+ `around the newer photo, not the first: ${cones()}`,+ );+ });++ test('a sequence page that lands while a lost GPU context recovers still draws its cones', async (t) => {+ const env = setup({ sequences: { p: [0, 1, 2, 3] } });+ const sphere = (record) => ({+ ...record,+ projection: 'SPHERE',+ fieldOfView: '360',+ filepathProc: `2022/10/6/wrapped_proc/${record.id}.jpg`,+ });+ const getPhoto = env.source.getPhoto;+ env.source.getPhoto = async (id) => sphere(await getPhoto(id));+ const getPage = env.source.getSequencePhotos;+ env.source.getSequencePhotos = async (...args) => {+ const page = await getPage(...args);+ return { ...page, photos: page.photos.map(sphere) };+ };+ const release = holdPage(env.source, 'p', 1);+ let holdImages = false;+ let releaseImage = null;+ const view = { yaw: 0, pitch: 0, fov: 80 };+ const definition = createKartaViewProvider({+ source: env.source,+ viewerOptions: {+ load: async (url) => {+ if (holdImages) await new Promise((r) => (releaseImage = r));+ return { src: url };+ },+ createRenderer: () => ({+ setImage() {},+ setView: (next) => Object.assign(view, next),+ getView: () => ({ ...view }),+ resize() {},+ clear() {},+ destroy() {},+ }),+ },+ });+ const { context, actions } = fakeContext();+ const errors = [];+ context.actions.reportError = (message) => errors.push(message);+ const instance = definition.create(context);+ actions.instance = instance;+ const cones = await withCones(t, { instance });+ const host = fakeHost();+ await instance.viewer.mount(host);+ await instance.viewer.open('p-0');+ // › to the next panorama; the GPU resets while it loads.+ holdImages = true;+ const opening = instance.viewer.open('p-1');+ assert.ok(await until(() => releaseImage !== null));+ host.children[0].children[1].fire('webglcontextlost');+ const selected = instance.selectSequence('p');+ release();+ await selected;+ assert.ok(+ await until(() => !instance.sequenceStats().loading && cones.count() > 0),+ 'the page is drawn, not dropped',+ );+ releaseImage();+ await opening;+ assert.equal(host.children[0].dataset.kind, 'pano', 'p-1 shows');+ // reportError(null) clears; nothing was reported.+ assert.deepEqual(errors.filter(Boolean), []);+ });diff --cc src/layers/streetLevel/providers/kartaview/source.jsindex 11637514e,ddf21817f..58b8602f4--- a/src/layers/streetLevel/providers/kartaview/source.js+++ b/src/layers/streetLevel/providers/kartaview/source.js@@@ -14,14 -19,19 +19,22 @@@ importPHOTO_API_TIMEOUT_MS,TILE_CONCURRENCY,TILE_TIMEOUT_MS,+ photoFilterParams,} from './policy.js';+import { createLimiter } from '../../limiter.js';++export { createLimiter } from '../../limiter.js';- /** An HTTP or API failure; `retryAfterSec` is set while KartaView rate-limits. */+ /**+ * An HTTP or API failure; `retryAfterSec` is set while KartaView rate-limits,+ * `timedOut` when it did not answer in time (the one failure worth asking+ * again at once).+ */export class KartaViewSourceError extends Error {- constructor(message, { status = 0, retryAfterSec = null } = {}) {+ constructor(+ message,+ { status = 0, retryAfterSec = null, timedOut = false } = {},+ ) {super(message);this.name = 'KartaViewSourceError';this.status = status;diff --cc src/layers/streetLevel/providers/kartaview/viewer.jsindex 31c052cb9,9aa4639c5..d33adef97--- a/src/layers/streetLevel/providers/kartaview/viewer.js+++ b/src/layers/streetLevel/providers/kartaview/viewer.js@@@ -6,9 -7,11 +6,10 @@@ importFLAT_FULL_SIZE,FLAT_VIEW_SIZE,IMAGE_TIMEOUT_MS,+ KARTAVIEW_NAME,KARTAVIEW_PROVIDER_ID,- PANO_FULL_SIZE,- PANO_MID_SIZE,PANO_PREVIEW_SIZE,+ cameraBearing,kartaViewPhotoUrl,resizedImageUrl,} from './policy.js';@@@ -26,35 -56,33 +27,42 @@@ export function loadImage(url, options});}-async function loadBitmap(url, timeoutMs) {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeoutMs);- try {- const response = await fetch(url, {- mode: 'cors',- signal: controller.signal,- });- if (!response.ok) throw new Error(LOAD_FAILED);- return await createImageBitmap(await response.blob());- } catch {- throw new Error(LOAD_FAILED);- } finally {- clearTimeout(timer);- }-}--/** Free a decoded bitmap nobody will draw (an <img> has nothing to free). */-function release(image) {- image?.close?.();-}--/** The panorama size a canvas this wide can show sharply at this field of view. */-export function panoSizeFor(canvasPixels, fovDeg) {- const needed = (Math.max(1, canvasPixels) * 360) / Math.max(1, fovDeg);- return needed > PANO_MID_SIZE[0] ? PANO_FULL_SIZE : PANO_MID_SIZE;-}+/**+ * Where KartaView photos come from. Only KartaView's image proxy can shrink+ * a 13,000 px panorama, so panoramas and flat upgrades go through it.+ * @type {import('../../photoViewer.js').PhotoSources}+ */+const KARTAVIEW_SOURCES = Object.freeze({+ hasPano: (photo) => Boolean(photo.isPano && photo.urls.pano),+ panoFirst: (photo) => ({+ url: resizedImageUrl(photo.urls.pano, PANO_PREVIEW_SIZE),+ width: 0,+ }),+ panoSharp: (photo, size) => ({+ url: resizedImageUrl(photo.urls.pano, size),+ }),+ // The proxy's 1,280 px version is a few hundred kB; KartaView's own+ // "large thumbnail" can be 1.7 MB. Either serves when the other fails.+ // A 360° photo's front view is only on storage.+ flatFirst: (photo) => [+ photo.isPano ? null : resizedImageUrl(photo.urls.full, FLAT_VIEW_SIZE),+ photo.urls.view,+ ],- flatSharp: (photo) => resizedImageUrl(photo.urls.full, FLAT_FULL_SIZE),++ // A docked viewer shows the 1,280 px version in full: the 2,560 px one++ // (~0.6 MB a photo) waits until the viewer is bigger than that.++ flatSharp: (photo, pixels) =>++ pixels > FLAT_VIEW_SIZE[0]++ ? resizedImageUrl(photo.urls.full, FLAT_FULL_SIZE)++ : null,++ // The camera's direction, which the drive's track may refine.++ bearingOf: (photo) => cameraBearing(photo),+ describe: (photo) => ({+ // KartaView's only place name is the sequence's, where the drive began.+ title: null,+ creator: null,+ externalUrl: kartaViewPhotoUrl(photo),+ }),+});/*** Viewer adapter for KartaView photos: a flat photo in an <img>, a 360°diff --cc src/layers/streetLevel/tileCache.jsindex 7fc9bb889,000000000..d6c0a91e5mode 100644,000000..100644--- a/src/layers/streetLevel/tileCache.js+++ b/src/layers/streetLevel/tileCache.js@@@ -1,50 -1,0 +1,51 @@@+/** Decoded coverage tiles kept, and for how long. */+export const TILE_CACHE_SIZE = 24;+export const TILE_CACHE_TTL_MS = 10 * 60_000;++/** Least-recently-used map: reading an entry renews it. */+export function createLru(limit) {+ const map = new Map();+ return {+ get(key) {+ if (!map.has(key)) return undefined;+ const value = map.get(key);+ map.delete(key);+ map.set(key, value);+ return value;+ },+ set(key, value) {+ map.delete(key);+ map.set(key, value);+ while (map.size > limit) map.delete(map.keys().next().value);+ },+ delete: (key) => map.delete(key),+ clear: () => map.clear(),+ };+}++/**- * Loaded (decoded) coverage tiles by `z/x/y`, at most `size`, each for++ * Loaded (decoded) coverage tiles by `keyOf` (default `z/x/y`), at most `size`, each for+ * `ttlMs`: a pan back, or a zoom across bands and back, neither fetches nor+ * decodes them again. A load that fails is not kept.+ */+export function createTileCache({+ load,+ size = TILE_CACHE_SIZE,+ ttlMs = TILE_CACHE_TTL_MS,+ now = Date.now,++ keyOf = (tile) => `${tile.z}/${tile.x}/${tile.y}`,+}) {+ const kept = createLru(size);+ return {+ async get(tile, options) {- const key = `${tile.z}/${tile.x}/${tile.y}`;++ const key = keyOf(tile);+ const entry = kept.get(key);+ if (entry && now() - entry.at < ttlMs) return entry.tile;+ const loaded = await load(tile, options);+ kept.set(key, { at: now(), tile: loaded });+ return loaded;+ },+ /** Forget every tile (the layer is off: its memory goes back). */+ clear: () => kept.clear(),+ };+}diff --cc src/tooling/streetLevelQa.test.mjsindex 564cecadc,6a29b4f69..cd5ff501c--- a/src/tooling/streetLevelQa.test.mjs+++ b/src/tooling/streetLevelQa.test.mjs@@@ -744,111 -750,78 +750,187 @@@ test('KartaView fixtures draw the drive);});+test('Panoramax fixtures: two sequences on one street, searches honour sequence and filters, unknown calls are flagged', async () => {+ const {+ answerPanoramaxRequest,+ describePanoramaxCall,+ PNX_LINE,+ PNX_SEQUENCES,+ panoramaxHdDownloads,+ panoramaxPictures,+ panoramaxTile,+ resetPanoramaxFixture,+ } = await import('../../scripts/fixtures/street-level/panoramax.mjs');+ const { decodeCoverageTile, decodePictures } =+ await import('../layers/streetLevel/providers/panoramax/decode.js');+ const { normalizeItem } =+ await import('../layers/streetLevel/providers/panoramax/policy.js');+ resetPanoramaxFixture();+ const pictures = panoramaxPictures();+ assert.deepEqual(+ [...new Set(pictures.map((p) => p.sequenceId))],+ [...PNX_SEQUENCES],+ );+ assert.ok(pictures.some((p) => p.isPano));+ // Coverage: both lines in a z14 tile on the street; cones in z15.+ const z = 14;+ const x = lonToTileX((PNX_LINE.west + PNX_LINE.east) / 2, z);+ const y = latToTileY(PNX_LINE.lat, z);+ const lines = decodeCoverageTile(panoramaxTile(z, x, y), { x, y, z });+ assert.deepEqual(+ lines.sequences.map((s) => s.id).sort(),+ [...PNX_SEQUENCES].sort(),+ );+ const t15 = {+ x: lonToTileX(pictures[20].lon, 15),+ y: latToTileY(PNX_LINE.lat, 15),+ z: 15,+ };+ assert.ok(+ decodePictures(panoramaxTile(15, t15.x, t15.y), t15, PNX_SEQUENCES[0])+ .length > 0,+ );+ // A search for one sequence near the street gives only its pictures, nearest first.+ const at = pictures[30];+ const ask = (query) =>+ JSON.parse(+ answerPanoramaxRequest({+ method: 'GET',+ url: `https://api.panoramax.xyz/api/search?${query}`,+ }).body,+ ).features.map(normalizeItem);+ const own = ask(+ `place_position=${at.lon},${at.lat}&place_distance=0-50&limit=5&collections=${PNX_SEQUENCES[1]}`,+ );+ assert.ok(own.length > 0);+ assert.ok(own.every((p) => p.sequenceId === PNX_SEQUENCES[1]));+ assert.equal(own[0].nextId && typeof own[0].nextId, 'string');+ const panos = ask(+ `place_position=${at.lon},${at.lat}&place_distance=0-200&limit=50&filter=field_of_view%3D360`,+ );+ assert.ok(panos.length > 0 && panos.every((p) => p.isPano));+ assert.deepEqual(+ ask(+ `place_position=${at.lon},${at.lat}&place_distance=0-200&limit=50&datetime=2024-01-01T00:00:00.000Z/..`,+ ).every((p) => p.sequenceId === PNX_SEQUENCES[0]),+ true,+ 'the second sequence is older',+ );+ // A box has every picture in it, those looking away included; a place+ // search leaves out pictures the point is behind (all look east).+ const d = 0.0002;+ const boxed = ask(+ `bbox=${at.lon - d},${at.lat - d},${at.lon + d},${at.lat + d}&limit=100`,+ );+ assert.ok(+ boxed.some((p) => p.lon < at.lon) && boxed.some((p) => p.lon > at.lon),+ );+ const placed = ask(+ `place_position=${at.lon},${at.lat}&place_distance=0-30&limit=50`,+ );+ assert.ok(placed.length > 0);+ assert.ok(+ placed.every((p) => p.lon <= at.lon + 1e-7),+ 'none it is behind',+ );+ const one = ask(`ids=${at.id}&limit=1`);+ assert.equal(one[0].id, at.id);+ // Its pictures, and only those, are served; HD downloads are counted.+ const file = (name) =>+ answerPanoramaxRequest({+ method: 'GET',+ url: `https://panoramax.openstreetmap.fr/derivates/${name}`,+ });+ assert.equal(file(`${at.id}/sd.jpg`).status, 200);+ assert.equal(file(`${at.id}/hd.jpg`).status, 200);+ assert.equal(panoramaxHdDownloads(), 1);+ assert.equal(file('nope/sd.jpg').known, false);+ const unknown = answerPanoramaxRequest({+ method: 'GET',+ url: 'https://api.panoramax.xyz/api/collections/x/items',+ });+ assert.equal(unknown.known, false);+ assert.equal(+ describePanoramaxCall(+ 'GET',+ new URL('https://api.panoramax.xyz/api/map/14/1/2.mvt'),+ ),+ 'GET api.panoramax.xyz/api/map/{z}/{x}/{y}.mvt',+ );+});+++ /** The alpha of a fixture PNG (8-bit RGBA, unfiltered rows, as it writes them). */+ function fixturePngAlpha(bytes) {+ const width = bytes.readUInt32BE(16);+ const height = bytes.readUInt32BE(20);+ const idat = [];+ for (let at = 8; at < bytes.length;) {+ const length = bytes.readUInt32BE(at);+ const type = bytes.toString('ascii', at + 4, at + 8);+ if (type === 'IDAT') idat.push(bytes.subarray(at + 8, at + 8 + length));+ at += 12 + length;+ }+ const rows = inflateSync(Buffer.concat(idat));+ const alpha = new Uint8Array(width * height);+ for (let y = 0; y < height; y++)+ for (let x = 0; x < width; x++)+ alpha[y * width + x] = rows[y * (width * 4 + 1) + 1 + x * 4 + 3];+ return { width, height, alpha };+ }++ test('KartaView fixtures filter like KartaView: PNG tiles by view and upload date, the photo search by projection', () => {+ const body = (answer) => JSON.parse(answer.body);+ const z = 14;+ const x = lonToTileX(KV_LINE.lon, z);+ const y = latToTileY((KV_LINE.south + KV_LINE.north) / 2, z);+ assert.equal(x, lonToTileX(KV_OLD_STREET.lon, z), 'both streets in a tile');+ const base = `https://api.kartaview.org/2.0/sequence/tiles/${x}/${y}/${z}`;+ const segments = tileSegments(+ body(answerKartaViewRequest({ method: 'GET', url: `${base}.json` })),+ );+ const lons = (kept) => [...new Set(kept.map((segment) => segment[0][0]))];+ const keptFor = (query) => {+ const answer = answerKartaViewRequest({+ method: 'GET',+ url: `${base}.png?${query}`,+ });+ assert.equal(answer.contentType, 'image/png');+ assert.equal(answer.known, true);+ return lons(+ maskedSegments(segments, fixturePngAlpha(answer.body), { x, y, z }),+ );+ };+ assert.deepEqual(+ lons(segments).sort(),+ [KV_LINE.lon, KV_OLD_STREET.lon].sort(),+ );+ assert.deepEqual(keptFor('fieldOfView=360'), [KV_LINE.lon]);+ assert.deepEqual(keptFor('fieldOfView=plane').sort(), lons(segments).sort());+ const lastYear = new Date(Date.now() - 365 * 86_400_000)+ .toISOString()+ .slice(0, 10);+ assert.deepEqual(keptFor(`startDate=${lastYear}`), [KV_LINE.lon]);+ assert.deepEqual(keptFor('startDate=2099-01-01'), []);+ assert.equal(+ describeKartaViewCall('GET', new URL(`${base}.png?fieldOfView=360`)),+ 'GET api.kartaview.org/2.0/sequence/tiles/{x}/{y}/{z}.png?fieldOfView',+ );+ // The photo search: 360° only, and nothing uploaded after the drive.+ resetKartaViewFixture();+ const search = (extra) => {+ answerKartaViewRequest({+ method: 'GET',+ url: 'https://api.kartaview.org/2.0/photo/?lat=0&lng=0',+ });+ return body(+ answerKartaViewRequest({+ method: 'GET',+ url: `https://api.kartaview.org/2.0/photo/?lat=${KV_LINE.south + 0.002}&lng=${KV_LINE.lon}&zoomLevel=18&itemsPerPage=10${extra}`,+ }),+ ).result.data;+ };+ const panos = search('&projection=SPHERE');+ assert.ok(panos.length > 0);+ assert.ok(panos.every((record) => record.projection === 'SPHERE'));+ assert.deepEqual(search('&startDate=2099-01-01'), []);+ });