{
  "version": 3,
  "sources": ["map_3d_core.js"],
  "sourcesContent": ["// @ts-check\n/*\n * static/js/map_3d_core.js \u2014 the 3D terrain map's pure parts (SNOW-1438).\n *\n * /map/'s 3D view (map_view_3d.js, behind the map_3d flag)\n * draws the relief with MapLibre's own terrain on the swisstopo winter map\n * (docs/decisions/a-3d-map-is-maplibre-terrain.md). SNOW-1450 retired the\n * /map/3d/ sandbox this file was first written for, and its own parts went\n * with it. What can be decided without a map or a DOM is here, so Vitest\n * can pin it:\n *\n *   - the elevation source and terrain spec handed to MapLibre, and the\n *     loader behind it that falls back from Mapterhorn to AWS;\n *   - the opening camera;\n *   - a route share link into 3D (`/routes/s/<token>/3d/`), which /map/'s\n *     route Shares copy while the map is in 3D;\n *   - the frame-time probe (`?probe=1`, SNOW-1448): the camera passes it\n *     flies and the summary of the frame intervals it records, measured\n *     against the budget of a median frame under FRAME_BUDGET_MS;\n *   - /map/'s frame watchdog (SNOW-1455): the budget for one window of\n *     about two seconds of moving time (a median under 45 ms), judged by\n *     frameWindowFails, and the watch that trips on five failing windows\n *     in a row. Loosened on 6 Nov 2026: the first cut also failed a p95\n *     over 66 ms after two windows, and laid flat the very phone whose\n *     probe run had passed (Hugo), because tiles arriving mid-gesture\n *     stall a frame without the map being slow. Loosened again on 7 Nov\n *     (SNOW-1463): a 33 ms bar sat exactly on 30 fps (33.3 ms), so an\n *     iPad drawing a steady 30 fps failed on noise, and a Pixel 9 that\n *     drew at 16.7 ms tripped close in while tiles loaded. The bar is now\n *     45 ms over five windows, and an interval either of whose frames saw\n *     tiles loading is not timed at all. The probe's own verdict\n *     (frameStats().withinBudget) is not what the watch reads;\n *   - the 3D test's verdict (SNOW-1456): each pass's intervals go\n *     through a fresh createFrameWatch, the watchdog's own rule, so the\n *     test and the fallback cannot disagree. judgePass says whether a\n *     pass was measured (FRAME_WINDOWS_TO_TRIP full windows at least, so\n *     a slow pass could trip), whether it kept up, how many of its\n *     windows were slow and how much time was skipped for tiles loading;\n *     testVerdict turns the passes into smooth, stutter, slow or\n *     unmeasured. The p95 is never read.\n *\n * Exports (frozen `self.pwaMap3dCore`):\n *\n *   DEM_SOURCE_ID / TERRAIN_EXAGGERATION / OPENING_CAMERA / MAX_PITCH / MAX_PIXEL_RATIO\n *   LARGE_CANVAS_PIXEL_RATIO / LARGE_CANVAS_PIXELS / pixelRatioFor(dpr, w, h)\n *   prefetchDemTiles(centre, mapZoom) / tileUrl(template, tile)\n *   skySpec() / sunlightPaint()\n *   DEM_TILE_SIZE / DEM_PROTOCOL / DEM_FALLBACK_TILE_URL / DEM_FALLBACK_AFTER\n *   demSource() / parseDemUrl(url) / createDemLoader(options)\n *   terrainSpec()\n *   routeShare3dUrl(shareUrl, query)\n *   FRAME_BUDGET_MS / PROBE_PASSES / frameStats(intervals, budgetMs?)\n *   FRAME_WINDOW_MS / FRAME_WINDOWS_TO_TRIP\n *   frameWindowFails(stats) / createFrameWatch({onWindow}?)\n *   TEST_VERDICTS / judgePass(intervals, loading?) / testVerdict(passes)\n */\n(function () {\n  'use strict';\n\n  /** The raster-dem source's id. */\n  const DEM_SOURCE_ID = 'map-3d-dem';\n\n  /** The elevation tiles' size in pixels, and the deepest zoom asked for. */\n  const DEM_TILE_SIZE = 512;\n  const DEM_MAX_ZOOM = 15;\n\n  /**\n   * The page's elevation protocol, the fallback tiles (AWS's open Terrarium\n   * set: 256 px, global, z0\u201315, no token) and how many Mapterhorn failures\n   * in a row send every later tile straight to them.\n   */\n  const DEM_PROTOCOL = 'map3ddem';\n  const DEM_FALLBACK_TILE_URL = 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png';\n  const DEM_FALLBACK_AFTER = 3;\n\n  /**\n   * How much the relief is stretched upwards. 1 is true scale; a little\n   * more reads better on a phone-sized screen, and more than 1.5 starts to\n   * make 30\u00B0 look like 40\u00B0, which on a map about steepness is a lie.\n   */\n  const TERRAIN_EXAGGERATION = 1.3;\n\n  /** Where the page opens: over Saas-Fee, looking up the Allalin. */\n  const OPENING_CAMERA = Object.freeze({\n    center: Object.freeze([7.87, 46.07]),\n    zoom: 12.6,\n    pitch: 64,\n    bearing: 215,\n  });\n\n  /**\n   * The canvas's pixel-ratio ceiling. A 3x phone draws 2.25x the pixels of\n   * 2x for detail nobody sees on a tilted map, and every frame pays for it.\n   */\n  const MAX_PIXEL_RATIO = 2;\n\n  /**\n   * The ratio a large canvas draws at in 3D (SNOW-1464). An iPad at 2x\n   * fills three million pixels a frame; at 1.5x it fills 1.7 million, and a\n   * tilted map at arm's length looks the same.\n   */\n  const LARGE_CANVAS_PIXEL_RATIO = 1.5;\n\n  /**\n   * A canvas that would draw more device pixels than this at the capped\n   * ratio is large. A phone at 2x (390 x 844, 1.3 million) stays under; an\n   * iPad (744 x 1011, 3.0 million) and a 2x laptop go over.\n   */\n  const LARGE_CANVAS_PIXELS = 2500000;\n\n  /**\n   * The pixel ratio 3D draws at: the device's, capped at MAX_PIXEL_RATIO,\n   * and at LARGE_CANVAS_PIXEL_RATIO on a large canvas. Never raises a\n   * device's own ratio.\n   *\n   * @param {number} devicePixelRatio\n   * @param {number} cssWidth\n   * @param {number} cssHeight\n   * @returns {number}\n   */\n  function pixelRatioFor(devicePixelRatio, cssWidth, cssHeight) {\n    const capped = Math.min(devicePixelRatio || 1, MAX_PIXEL_RATIO);\n    const drawn = (cssWidth || 0) * (cssHeight || 0) * capped * capped;\n    return drawn > LARGE_CANVAS_PIXELS ? Math.min(capped, LARGE_CANVAS_PIXEL_RATIO) : capped;\n  }\n\n  /** MapLibre's ceiling is 85; past this the horizon eats the screen. */\n  const MAX_PITCH = 80;\n\n  /**\n   * The sky and the haze toward the horizon: an alpine blue overhead fading\n   * to a pale horizon, with the haze kept off the near ground so the\n   * foreground stays crisp. MapLibre paint values, so hex here.\n   *\n   * @returns {Record<string, unknown>}\n   */\n  function skySpec() {\n    return {\n      'sky-color': '#5b9bd5',\n      'horizon-color': '#dbe9f6',\n      'fog-color': '#e6eef7',\n      'sky-horizon-blend': 0.8,\n      'horizon-fog-blend': 0.9,\n      'fog-ground-blend': 0.15,\n      'atmosphere-blend': ['interpolate', ['linear'], ['zoom'], 10, 1, 14, 0.6],\n    };\n  }\n\n  /**\n   * The sunlight layer's paint: a north-west sun fixed to the map (so the\n   * light does not swing as the camera turns), soft: enough to model the\n   * ridges, with shade light enough that swisstopo's hachures read through.\n   *\n   * @returns {Record<string, unknown>}\n   */\n  function sunlightPaint() {\n    return {\n      'hillshade-exaggeration': 0.3,\n      'hillshade-illumination-anchor': 'map',\n      'hillshade-illumination-direction': 315,\n      'hillshade-shadow-color': '#4a5878',\n      'hillshade-highlight-color': '#ffffff',\n      'hillshade-accent-color': '#7a8799',\n    };\n  }\n\n  /**\n   * The elevation source. Its tiles go through the page's `map3ddem://`\n   * protocol (createDemLoader): Mapterhorn's Terrarium-encoded 512 px\n   * tiles first (in production our own copy of them, MAP_3D_DEM_TILE_URL),\n   * AWS's when they fail. Mapterhorn goes to z17 over\n   * Switzerland; z15 (about 2 m a pixel) is past what the terrain mesh can\n   * show, and each zoom past it quadruples the tiles.\n   *\n   * @returns {{type: 'raster-dem', tiles: string[], encoding: 'terrarium', tileSize: number, maxzoom: number, attribution: string}}\n   */\n  function demSource() {\n    return {\n      type: 'raster-dem',\n      tiles: [`${DEM_PROTOCOL}://{z}/{x}/{y}`],\n      encoding: 'terrarium',\n      tileSize: DEM_TILE_SIZE,\n      maxzoom: DEM_MAX_ZOOM,\n      attribution: '<a href=\"https://mapterhorn.com/attribution\" target=\"_blank\" rel=\"noopener\">\u00A9 Mapterhorn</a>'\n        + ' \u00B7 <a href=\"https://github.com/tilezen/joerd/blob/master/docs/attribution.md\" target=\"_blank\" rel=\"noopener\">Terrain Tiles</a>',\n    };\n  }\n\n  /**\n   * A `map3ddem://z/x/y` URL's tile, or null for anything else.\n   *\n   * @param {string} url\n   * @returns {{z: number, x: number, y: number}|null}\n   */\n  function parseDemUrl(url) {\n    const match = new RegExp(`^${DEM_PROTOCOL}://(\\\\d+)/(\\\\d+)/(\\\\d+)$`).exec(url);\n    if (!match) return null;\n    return { z: Number(match[1]), x: Number(match[2]), y: Number(match[3]) };\n  }\n\n  /**\n   * Loads one elevation tile for the `map3ddem://` protocol: Mapterhorn\n   * first, then AWS's Terrarium tile of the same z/x/y. A Mapterhorn tile is\n   * 512 px and an AWS one 256 px over the same ground, so the AWS tile is\n   * enlarged (`enlarge`, nearest-neighbour: Terrarium heights are encoded\n   * across the three channels, so blending neighbours would invent heights).\n   *\n   * A 404 is a hole in Mapterhorn's pyramid, and a 204 a tile outside our\n   * copy's supported area (SNOW-1444); either falls back for that tile\n   * only. A network failure or a 5xx counts as Mapterhorn being down: after\n   * DEM_FALLBACK_AFTER in a row the loader goes straight to AWS for the rest\n   * of the visit, so an outage does not cost every tile a failed request. A\n   * Mapterhorn success before then resets the count; one that lands after\n   * (a request already in flight) does not lift the latch.\n   *\n   * SNOW-1453: a 504 carrying `X-SW-Cache: miss` is the service worker's\n   * own answer offline for a tile it does not hold\n   * (`_synthesizedGatewayTimeout`), not Mapterhorn being down. It falls\n   * back for that tile without counting, like a 404: otherwise three\n   * misses past a downloaded area's edge would latch the loader to AWS,\n   * and the area's pinned tiles would never be asked for again.\n   *\n   * @param {{primary: string, fallback: string, fetchTile: (url: string, signal: AbortSignal) => Promise<Response>, enlarge: (blob: Blob) => Promise<any>}} options\n   * @returns {{load: (tile: {z: number, x: number, y: number}, signal: AbortSignal) => Promise<{data: any}>, usingFallback: () => boolean}}\n   */\n  function createDemLoader(options) {\n    let failures = 0;\n    // Once set, never cleared: a Mapterhorn request started before the\n    // latch may still succeed after it, and must not reopen Mapterhorn.\n    let latched = false;\n    const fail = () => {\n      failures += 1;\n      if (failures >= DEM_FALLBACK_AFTER) latched = true;\n    };\n    return {\n      async load(tile, signal) {\n        if (!latched) {\n          try {\n            const response = await options.fetchTile(tileUrl(options.primary, tile), signal);\n            // SNOW-1444: our copy covers the supported area only, and its\n            // Worker answers 204 No Content for a tile outside it, the way\n            // a PMTiles server answers for a tile the archive lacks. Like a\n            // 404 that is \"not here\", so it falls back without counting.\n            if (response.ok && response.status !== 204) {\n              if (!latched) failures = 0;\n              return { data: await response.arrayBuffer() };\n            }\n            if (response.status !== 404 && response.status !== 204 && !isOfflineMiss(response)) fail();\n          } catch (err) {\n            if (signal.aborted) throw err;\n            fail();\n          }\n        }\n        const response = await options.fetchTile(tileUrl(options.fallback, tile), signal);\n        if (!response.ok) {\n          throw new Error(`map_3d: no elevation tile ${tile.z}/${tile.x}/${tile.y} (${response.status})`);\n        }\n        return { data: await options.enlarge(await response.blob()) };\n      },\n      usingFallback: () => latched,\n    };\n  }\n\n  /**\n   * Whether a response is the service worker's offline miss: a 504 it\n   * made up because it holds no copy and may not use the network\n   * (static/js/sw.js `_synthesizedGatewayTimeout`, `X-SW-Cache: miss`).\n   *\n   * @param {Response} response\n   * @returns {boolean}\n   */\n  function isOfflineMiss(response) {\n    return response.status === 504 && !!response.headers && response.headers.get('X-SW-Cache') === 'miss';\n  }\n\n  /**\n   * The elevation tiles a 3-D view around a point will ask for first, so\n   * /map/'s 3D roundel can warm the browser's cache before the page opens.\n   * MapLibre draws 512 px terrain about two zooms below the map's own, so\n   * this is the 3x3 block at that zoom around the centre.\n   *\n   * @param {{lng: number, lat: number}} centre\n   * @param {number} mapZoom The camera zoom the 3-D map will open at.\n   * @returns {Array<{z: number, x: number, y: number}>}\n   */\n  function prefetchDemTiles(centre, mapZoom) {\n    const z = Math.max(0, Math.min(DEM_MAX_ZOOM, Math.round(mapZoom) - 2));\n    const n = 2 ** z;\n    const lat = Math.max(-85, Math.min(85, centre.lat)) * Math.PI / 180;\n    const cx = Math.floor(((centre.lng + 180) / 360) * n);\n    const cy = Math.floor(((1 - Math.asinh(Math.tan(lat)) / Math.PI) / 2) * n);\n    /** @type {Array<{z: number, x: number, y: number}>} */\n    const out = [];\n    for (let dy = -1; dy <= 1; dy += 1) {\n      for (let dx = -1; dx <= 1; dx += 1) {\n        const y = cy + dy;\n        if (y < 0 || y >= n) continue;\n        out.push({ z, x: (((cx + dx) % n) + n) % n, y });\n      }\n    }\n    return out;\n  }\n\n  /**\n   * One tile's URL from an XYZ template.\n   *\n   * @param {string} template\n   * @param {{z: number, x: number, y: number}} tile\n   * @returns {string}\n   */\n  function tileUrl(template, tile) {\n    return template.replace('{z}', String(tile.z)).replace('{x}', String(tile.x)).replace('{y}', String(tile.y));\n  }\n\n  /**\n   * The argument to `map.setTerrain`.\n   *\n   * @returns {{source: string, exaggeration: number}}\n   */\n  function terrainSpec() {\n    return { source: DEM_SOURCE_ID, exaggeration: TERRAIN_EXAGGERATION };\n  }\n\n  /**\n   * A route share link into 3D: `/routes/s/<token>/` (what routes'\n   * share-create answers) plus `3d/`, which opens /map/'s 3D view on the\n   * route (routes:share_redirect_3d). /map/'s route Shares copy it while\n   * the map is in 3D (SNOW-1450).\n   *\n   * @param {string} shareUrl The absolute route share link.\n   * @param {string} query A query to carry, such as `at=\u2026`, or `''`.\n   * @returns {string}\n   */\n  function routeShare3dUrl(shareUrl, query) {\n    const url = new URL('3d/', shareUrl.endsWith('/') ? shareUrl : `${shareUrl}/`);\n    url.search = query;\n    return url.toString();\n  }\n\n  /**\n   * The frame budget: a median frame under 45 ms. SNOW-1448 proposed 33 ms,\n   * but frame intervals come in display-refresh steps (16.7, 33.3 and 50 ms\n   * at 60 Hz, 41.7 ms at 120 Hz), and 33 ms sat on 30 fps, so a device\n   * drawing a steady 30 fps failed on noise (SNOW-1463). 45 ms passes 30\n   * and 24 fps cleanly and fails 20 fps cleanly; 50 ms would put a steady\n   * 20 fps on the edge, the same mistake again.\n   */\n  const FRAME_BUDGET_MS = 45;\n\n  /**\n   * The probe's camera passes. Each opens over Saas-Fee at OPENING_CAMERA's\n   * tilt and heading, waits for every tile to arrive, then turns the camera\n   * through a quarter circle at a steady rate while the frames are timed.\n   * The turn brings new ground into view, so the pass pays for tiles and\n   * draping as a reader's own panning does. The z9 pass is where the 3-D\n   * control is proposed to switch off: the most ground a tilted view draws.\n   * Each pass lasts 18 s (12 s until SNOW-1463), so that with some of its\n   * time skipped for tiles loading it still holds the FRAME_WINDOWS_TO_TRIP\n   * windows judgePass needs to call it measured.\n   */\n  const PROBE_PASSES = Object.freeze([\n    Object.freeze({ label: 'Saas-Fee z12.6', zoom: OPENING_CAMERA.zoom, turnDeg: 90, durationMs: 18000 }),\n    Object.freeze({ label: 'Valais z9', zoom: 9, turnDeg: 90, durationMs: 18000 }),\n  ]);\n\n  /**\n   * Summarise the intervals between animation frames, in milliseconds.\n   *\n   * The median is the budget's measure. The 95th percentile and the share of\n   * frames over budget say whether a good median hides stutter. Percentiles\n   * are nearest-rank, so every figure is an interval that happened.\n   *\n   * @param {number[]} intervals Milliseconds between consecutive frames.\n   * @param {number} [budgetMs] The budget the frames are held to.\n   * @returns {{frames: number, medianMs: number, p95Ms: number, worstMs: number,\n   *   overBudget: number, fps: number, withinBudget: boolean}|null}\n   *   Null when there are no usable intervals.\n   */\n  function frameStats(intervals, budgetMs) {\n    const budget = budgetMs || FRAME_BUDGET_MS;\n    const sorted = (intervals || [])\n      .filter((ms) => Number.isFinite(ms) && ms > 0)\n      .sort((a, b) => a - b);\n    if (!sorted.length) return null;\n    /** @param {number} p */\n    const rank = (p) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];\n    const round = (/** @type {number} */ ms) => Math.round(ms * 10) / 10;\n    const medianMs = rank(0.5);\n    const over = sorted.filter((ms) => ms > budget).length;\n    return {\n      frames: sorted.length,\n      medianMs: round(medianMs),\n      p95Ms: round(rank(0.95)),\n      worstMs: round(sorted[sorted.length - 1]),\n      overBudget: Math.round((over / sorted.length) * 100) / 100,\n      fps: Math.round(1000 / medianMs),\n      withinBudget: medianMs < budget,\n    };\n  }\n\n  /** How much moving time one watchdog window holds, in milliseconds. */\n  const FRAME_WINDOW_MS = 2000;\n\n  /**\n   * How many failing windows in a row trip /map/'s watchdog: about ten\n   * seconds of moving time under about 22 fps (three until SNOW-1463).\n   */\n  const FRAME_WINDOWS_TO_TRIP = 5;\n\n  /**\n   * Whether one window of frames is over the budget: a median of\n   * FRAME_BUDGET_MS or more. The p95 is not judged: a stall while tiles\n   * arrive and drape lifts it on a phone that draws 3-D well (Hugo's\n   * Mali-G715 run: median 16.7 ms, p95 50 ms over Saas-Fee), and only a\n   * map that is slow throughout lifts the median. Reads frameStats'\n   * output; no frames is not a failure.\n   *\n   * @param {{medianMs: number}|null|undefined} stats\n   * @returns {boolean}\n   */\n  function frameWindowFails(stats) {\n    if (!stats) return false;\n    return stats.medianMs >= FRAME_BUDGET_MS;\n  }\n\n  /**\n   * The frame watchdog's state. Intervals are pushed one at a time; once\n   * the timed ones add up to FRAME_WINDOW_MS the window closes and is\n   * judged by frameWindowFails. FRAME_WINDOWS_TO_TRIP failing windows in a\n   * row trip it, and a passing window starts the count again. A window\n   * carries over from one gesture to the next, and so does the count; only\n   * `reset` clears them. Once tripped, it stays tripped until `reset`.\n   *\n   * An interval pushed with `loading` set is skipped (SNOW-1463): tiles\n   * arriving and draping stall frames on a device that draws what it\n   * already has well, so it neither counts towards the window's time nor\n   * joins its median. The window is kept, and its skipped time is reported.\n   *\n   * `onWindow`, if given, hears every closed window, for the debug trace.\n   *\n   * @param {{onWindow?: (window: {medianMs: number, frames: number,\n   *   skippedMs: number, slow: boolean, failing: number, tripped: boolean}) => void}} [options]\n   * @returns {{push: (intervalMs: number, loading?: boolean) => boolean, reset: () => void}}\n   *   `push` answers whether the watch has tripped.\n   */\n  function createFrameWatch(options) {\n    const onWindow = options && typeof options.onWindow === 'function' ? options.onWindow : null;\n    /** @type {number[]} */\n    let frames = [];\n    let elapsed = 0;\n    let skipped = 0;\n    let failing = 0;\n    let tripped = false;\n    return {\n      push(intervalMs, loading) {\n        if (tripped) return true;\n        if (!Number.isFinite(intervalMs) || intervalMs <= 0) return false;\n        if (loading) {\n          skipped += intervalMs;\n          return false;\n        }\n        frames.push(intervalMs);\n        elapsed += intervalMs;\n        if (elapsed < FRAME_WINDOW_MS) return false;\n        const stats = frameStats(frames);\n        const slow = frameWindowFails(stats);\n        failing = slow ? failing + 1 : 0;\n        if (failing >= FRAME_WINDOWS_TO_TRIP) tripped = true;\n        if (onWindow && stats) {\n          onWindow({\n            medianMs: stats.medianMs,\n            frames: stats.frames,\n            skippedMs: Math.round(skipped),\n            slow,\n            failing,\n            tripped,\n          });\n        }\n        frames = [];\n        elapsed = 0;\n        skipped = 0;\n        return tripped;\n      },\n      reset() {\n        frames = [];\n        elapsed = 0;\n        skipped = 0;\n        failing = 0;\n        tripped = false;\n      },\n    };\n  }\n\n  /**\n   * The verdicts a measured 3D test gives (SNOW-1456), as POST\n   * /api/map-3d-test/ accepts them (apps/map/models.py Map3dDeviceTest).\n   * `unmeasured` is not one: an unmeasured run is never sent.\n   */\n  const TEST_VERDICTS = Object.freeze(['smooth', 'stutter', 'slow']);\n\n  /**\n   * Judge one pass of the 3D test by the watchdog's own rule.\n   *\n   * The pass is fed through a fresh createFrameWatch, loading flags and\n   * all, so the test skips what the watchdog skips. A pass with fewer than\n   * FRAME_WINDOWS_TO_TRIP closed windows was not measured: a slow device\n   * could not have tripped on it. A measured pass keeps up unless the\n   * watch trips; `windows` and `slowWindows` count the closed windows and\n   * those frameWindowFails, and `skippedMs` the time skipped for tiles\n   * loading, for the Details.\n   *\n   * @param {number[]} intervals Milliseconds between consecutive frames.\n   * @param {boolean[]} [loading] Per interval, whether tiles were loading.\n   * @returns {{measured: boolean, keptUp: boolean, windows: number, slowWindows: number, skippedMs: number}}\n   */\n  function judgePass(intervals, loading) {\n    let windows = 0;\n    let slowWindows = 0;\n    let tripped = false;\n    let skippedMs = 0;\n    const watch = createFrameWatch({\n      onWindow(closed) {\n        windows += 1;\n        if (closed.slow) slowWindows += 1;\n      },\n    });\n    (intervals || []).forEach((ms, i) => {\n      if (!Number.isFinite(ms) || ms <= 0) return;\n      const isLoading = !!(loading && loading[i]);\n      if (isLoading) skippedMs += ms;\n      if (watch.push(ms, isLoading)) {\n        // Latched here; the watch starts afresh so the Details count every\n        // window of the pass, not just those up to the trip.\n        tripped = true;\n        watch.reset();\n      }\n    });\n    const measured = windows >= FRAME_WINDOWS_TO_TRIP;\n    return { measured, keptUp: measured && !tripped, windows, slowWindows, skippedMs: Math.round(skippedMs) };\n  }\n\n  /**\n   * The 3D test's verdict over its passes, in PROBE_PASSES' order: every\n   * pass keeps up, `smooth`; only the last (the z9 pass, the most ground a\n   * tilted view draws) falls behind, `stutter`; otherwise `slow`. Any pass\n   * not measured, or no passes at all, makes the run `unmeasured`.\n   *\n   * @param {Array<{intervals: number[], loading?: boolean[]}>} passes\n   * @returns {'smooth'|'stutter'|'slow'|'unmeasured'}\n   */\n  function testVerdict(passes) {\n    const judged = (passes || []).map((pass) => judgePass(pass && pass.intervals, pass && pass.loading));\n    if (!judged.length || judged.some((pass) => !pass.measured)) return 'unmeasured';\n    if (judged.every((pass) => pass.keptUp)) return 'smooth';\n    const last = judged.length - 1;\n    if (last > 0 && judged.slice(0, last).every((pass) => pass.keptUp)) return 'stutter';\n    return 'slow';\n  }\n\n  self.pwaMap3dCore = Object.freeze({\n    TEST_VERDICTS: TEST_VERDICTS,\n    judgePass: judgePass,\n    testVerdict: testVerdict,\n    FRAME_BUDGET_MS: FRAME_BUDGET_MS,\n    FRAME_WINDOW_MS: FRAME_WINDOW_MS,\n    FRAME_WINDOWS_TO_TRIP: FRAME_WINDOWS_TO_TRIP,\n    frameWindowFails: frameWindowFails,\n    createFrameWatch: createFrameWatch,\n    PROBE_PASSES: PROBE_PASSES,\n    frameStats: frameStats,\n    DEM_SOURCE_ID: DEM_SOURCE_ID,\n    TERRAIN_EXAGGERATION: TERRAIN_EXAGGERATION,\n    OPENING_CAMERA: OPENING_CAMERA,\n    MAX_PITCH: MAX_PITCH,\n    MAX_PIXEL_RATIO: MAX_PIXEL_RATIO,\n    LARGE_CANVAS_PIXEL_RATIO: LARGE_CANVAS_PIXEL_RATIO,\n    LARGE_CANVAS_PIXELS: LARGE_CANVAS_PIXELS,\n    pixelRatioFor: pixelRatioFor,\n    prefetchDemTiles: prefetchDemTiles,\n    skySpec: skySpec,\n    sunlightPaint: sunlightPaint,\n    tileUrl: tileUrl,\n    DEM_TILE_SIZE: DEM_TILE_SIZE,\n    DEM_PROTOCOL: DEM_PROTOCOL,\n    DEM_FALLBACK_TILE_URL: DEM_FALLBACK_TILE_URL,\n    DEM_FALLBACK_AFTER: DEM_FALLBACK_AFTER,\n    demSource: demSource,\n    parseDemUrl: parseDemUrl,\n    createDemLoader: createDemLoader,\n    terrainSpec: terrainSpec,\n    routeShare3dUrl: routeShare3dUrl,\n  });\n})();\n"],
  "mappings": "CAwDC,UAAY,CACX,aAGA,MAAMA,EAAgB,aAWhBC,EAAe,WACfC,EAAwB,0EAWxBC,EAAiB,OAAO,OAAO,CACnC,OAAQ,OAAO,OAAO,CAAC,KAAM,KAAK,CAAC,EACnC,KAAM,KACN,MAAO,GACP,QAAS,GACX,CAAC,EAMKC,EAAkB,EAOlBC,EAA2B,IAO3BC,EAAsB,KAY5B,SAASC,EAAcC,EAAkBC,EAAUC,EAAW,CAC5D,MAAMC,EAAS,KAAK,IAAIH,GAAoB,EAAGJ,CAAe,EAE9D,OADeK,GAAY,IAAMC,GAAa,GAAKC,EAASA,EAC7CL,EAAsB,KAAK,IAAIK,EAAQN,CAAwB,EAAIM,CACpF,CAGA,MAAMC,EAAY,GASlB,SAASC,GAAU,CACjB,MAAO,CACL,YAAa,UACb,gBAAiB,UACjB,YAAa,UACb,oBAAqB,GACrB,oBAAqB,GACrB,mBAAoB,IACpB,mBAAoB,CAAC,cAAe,CAAC,QAAQ,EAAG,CAAC,MAAM,EAAG,GAAI,EAAG,GAAI,EAAG,CAC1E,CACF,CASA,SAASC,GAAgB,CACvB,MAAO,CACL,yBAA0B,GAC1B,gCAAiC,MACjC,mCAAoC,IACpC,yBAA0B,UAC1B,4BAA6B,UAC7B,yBAA0B,SAC5B,CACF,CAYA,SAASC,GAAY,CACnB,M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S_PIXELS", "pixelRatioFor", "devicePixelRatio", "cssWidth", "cssHeight", "capped", "MAX_PITCH", "skySpec", "sunlightPaint", "demSource", "parseDemUrl", "url", "match", "createDemLoader", "options", "failures", "latched", "fail", "tile", "signal", "response", "tileUrl", "isOfflineMiss", "err", "prefetchDemTiles", "centre", "mapZoom", "z", "n", "lat", "cx", "cy", "out", "dy", "dx", "y", "template", "terrainSpec", "routeShare3dUrl", "shareUrl", "query", "FRAME_BUDGET_MS", "PROBE_PASSES", "frameStats", "intervals", "budgetMs", "budget", "sorted", "ms", "a", "b", "rank", "p", "round", "medianMs", "over", "FRAME_WINDOW_MS", "FRAME_WINDOWS_TO_TRIP", "frameWindowFails", "stats", "createFrameWatch", "onWindow", "frames", "elapsed", "skipped", "failing", "tripped", "intervalMs", "loading", "slow", "TEST_VERDICTS", "judgePass", "windows", "slowWindows", "skippedMs", "watch", "closed", "i", "isLoading", "measured", "testVerdict", "passes", "judged", "pass", "last"]
}
