diff --git a/.Rbuildignore b/.Rbuildignore index d180bc04..bc356d45 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,4 +1,5 @@ ^.*\.Rproj$ +^\.git$ ^\.Rproj\.user$ ^docs$ ^vignettes$ @@ -20,4 +21,8 @@ CLAUDE.md .DS_Store ^tools/check-save-map-integration\.R$ ^tmp$ +^slider-demo\.R$ +^flowmap-demo\.R$ +^tooltip-demo\.R$ +^flowmap-screenshot\.png$ ^\.dockerignore$ diff --git a/DESCRIPTION b/DESCRIPTION index 8f68790c..d3a5ace8 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,9 +1,11 @@ Package: mapgl Title: Interactive Maps with 'Mapbox GL JS' and 'MapLibre GL JS' Version: 0.4.9.9000 -Date: 2026-06-12 -Authors@R: - person(given = "Kyle", family = "Walker", email = "kyle@walker-data.com", role = c("aut", "cre")) +Date: 2026-06-16 +Authors@R: c( + person(given = "Kyle", family = "Walker", email = "kyle@walker-data.com", role = c("aut", "cre")), + person(given = "Egor", family = "Kotov", email = "kotov.egor@gmail.com", role = "ctb", + comment = "flowmap support and histogram time control, adapted from #205")) Description: Provides an interface to the 'Mapbox GL JS' () and the 'MapLibre GL JS' () interactive mapping libraries to help users create custom interactive maps in R. Users can create interactive globe visualizations; layer 'sf' objects to create @@ -13,6 +15,7 @@ URL: https://walker-data.com/mapgl/ BugReports: https://github.com/walkerke/mapgl/issues License: MIT + file LICENSE Encoding: UTF-8 +LazyData: true Roxygen: list(markdown = TRUE) RoxygenNote: 7.3.3 Depends: diff --git a/LICENSE.note b/LICENSE.note new file mode 100644 index 00000000..635e7b27 --- /dev/null +++ b/LICENSE.note @@ -0,0 +1,86 @@ +This package as a whole is licensed under the MIT License (see LICENSE file). + +It bundles several third-party JavaScript components. The FlowmapGL browser bundle shipped at `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js` is generated from npm release packages by `data-raw/flowmap-vendor/build-flowmap.sh build`. + +Below are the licenses of the individual bundled components: + +| Package | Version | License | Source | +| --- | --- | --- | --- | +| @deck.gl/core | 9.3.2 | MIT | https://github.com/visgl/deck.gl.git | +| @deck.gl/layers | 9.3.2 | MIT | https://github.com/visgl/deck.gl.git | +| @deck.gl/mapbox | 9.3.2 | MIT | https://github.com/visgl/deck.gl.git | +| @esbuild/darwin-arm64 | 0.28.0 | MIT | git+https://github.com/evanw/esbuild.git | +| @flowmap.gl/data | 9.3.0 | Apache-2.0 | git@github.com:visgl/flowmap.gl.git | +| @flowmap.gl/layers | 9.3.0 | Apache-2.0 | git@github.com:visgl/flowmap.gl.git | +| @loaders.gl/core | 4.4.2 | MIT | https://github.com/visgl/loaders.gl | +| @loaders.gl/images | 4.4.2 | MIT | https://github.com/visgl/loaders.gl | +| @loaders.gl/loader-utils | 4.4.2 | MIT | https://github.com/visgl/loaders.gl | +| @loaders.gl/schema | 4.4.2 | MIT | https://github.com/visgl/loaders.gl | +| @loaders.gl/schema-utils | 4.4.2 | MIT | https://github.com/visgl/loaders.gl | +| @loaders.gl/worker-utils | 4.4.2 | MIT | https://github.com/visgl/loaders.gl | +| @luma.gl/core | 9.3.3 | MIT | https://github.com/visgl/luma.gl | +| @luma.gl/engine | 9.3.3 | MIT | https://github.com/visgl/luma.gl | +| @luma.gl/shadertools | 9.3.3 | MIT | https://github.com/visgl/luma.gl | +| @luma.gl/webgl | 9.3.3 | MIT | https://github.com/visgl/luma.gl | +| @mapbox/tiny-sdf | 2.2.0 | BSD-2-Clause | git+https://github.com/mapbox/tiny-sdf.git | +| @math.gl/core | 4.1.0 | MIT | https://github.com/visgl/math.gl.git | +| @math.gl/polygon | 4.1.0 | MIT | https://github.com/visgl/math.gl.git | +| @math.gl/sun | 4.1.0 | MIT | https://github.com/visgl/math.gl.git | +| @math.gl/types | 4.1.0 | MIT | https://github.com/visgl/math.gl.git | +| @math.gl/web-mercator | 4.1.0 | MIT | https://github.com/visgl/math.gl.git | +| @probe.gl/env | 4.1.1 | MIT | https://github.com/visgl/probe.gl.git | +| @probe.gl/log | 4.1.1 | MIT | https://github.com/visgl/probe.gl.git | +| @probe.gl/stats | 4.1.1 | MIT | https://github.com/visgl/probe.gl.git | +| @swc/helpers | 0.5.23 | Apache-2.0 | git+https://github.com/swc-project/swc.git | +| @types/command-line-args | 5.2.3 | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped.git | +| @types/command-line-usage | 5.0.4 | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped.git | +| @types/geojson | 7946.0.16 | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped.git | +| @types/node | 24.12.4 | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped.git | +| @types/offscreencanvas | 2019.7.3 | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped.git | +| ansi-styles | 4.3.0 | MIT | chalk/ansi-styles | +| apache-arrow | 21.1.0 | Apache-2.0 | git+https://github.com/apache/arrow-js.git | +| array-back | 6.2.3 | MIT | git+https://github.com/75lb/array-back.git | +| chalk | 4.1.2 | MIT | chalk/chalk | +| chalk-template | 0.4.0 | MIT | chalk/chalk-template | +| color-convert | 2.0.1 | MIT | Qix-/color-convert | +| color-name | 1.1.4 | MIT | git@github.com:colorjs/color-name.git | +| command-line-args | 6.0.2 | MIT | git+https://github.com/75lb/command-line-args.git | +| command-line-usage | 7.0.4 | MIT | https://github.com/75lb/command-line-usage | +| d3 | 7.9.0 | ISC | https://github.com/d3/d3.git | +| d3-array | 3.2.4 | ISC | https://github.com/d3/d3-array.git | +| d3-color | 3.1.0 | ISC | https://github.com/d3/d3-color.git | +| d3-format | 3.1.2 | ISC | https://github.com/d3/d3-format.git | +| d3-geo | 3.1.1 | ISC | https://github.com/d3/d3-geo.git | +| d3-interpolate | 3.0.1 | ISC | https://github.com/d3/d3-interpolate.git | +| d3-scale | 4.0.2 | ISC | https://github.com/d3/d3-scale.git | +| d3-scale-chromatic | 3.1.0 | ISC | https://github.com/d3/d3-scale-chromatic.git | +| d3-time | 3.1.0 | ISC | https://github.com/d3/d3-time.git | +| d3-time-format | 4.1.0 | ISC | https://github.com/d3/d3-time-format.git | +| earcut | 2.2.4 | ISC | git://github.com/mapbox/earcut.git | +| esbuild | 0.28.0 | MIT | git+https://github.com/evanw/esbuild.git | +| find-replace | 5.0.2 | MIT | git+https://github.com/75lb/find-replace.git | +| flatbuffers | 25.9.23 | Apache-2.0 | git+https://github.com/google/flatbuffers.git | +| gl-matrix | 3.4.4 | MIT | https://github.com/toji/gl-matrix.git | +| has-flag | 4.0.0 | MIT | sindresorhus/has-flag | +| internmap | 2.0.3 | ISC | https://github.com/mbostock/internmap.git | +| json-bignum | 0.0.3 | MIT | https://github.com/datalanche/json-bignum.git | +| kdbush | 4.1.0 | ISC | git://github.com/mourner/kdbush.git | +| lil-gui | 0.19.0 | MIT | https://github.com/georgealways/lil-gui | +| lodash.camelcase | 4.3.0 | MIT | lodash/lodash | +| mjolnir.js | 3.0.0 | MIT | https://github.com/visgl/mjolnir.js | +| reselect | 5.2.0 | MIT | https://github.com/reduxjs/reselect.git | +| seedrandom | 3.0.5 | MIT | git://github.com/davidbau/seedrandom.git | +| supports-color | 7.2.0 | MIT | chalk/supports-color | +| table-layout | 4.1.1 | MIT | https://github.com/75lb/table-layout | +| tslib | 2.8.1 | 0BSD | https://github.com/Microsoft/tslib.git | +| typical | 7.3.0 | MIT | git+https://github.com/75lb/typical.git | +| undici-types | 7.16.0 | MIT | git+https://github.com/nodejs/undici.git | +| wordwrapjs | 5.1.1 | MIT | https://github.com/75lb/wordwrapjs | + +## Bundled data + +The `bixi_locations` and `bixi_flows` datasets are derived from BIXI Montréal +Open Data (https://bixi.com/fr/donnees-ouvertes), © BIXI Montréal and released +under the BIXI Montréal Open Data license. The data were prepared for the +FlowmapBlue project (https://github.com/FlowmapBlue/FlowmapBlue) by Ilya +Boyandin (https://github.com/ilyabo). diff --git a/NAMESPACE b/NAMESPACE index 7259be64..0d6256ed 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -15,6 +15,7 @@ export(add_draw_control) export(add_features_to_draw) export(add_fill_extrusion_layer) export(add_fill_layer) +export(add_flowmap) export(add_fullscreen_control) export(add_geocoder_control) export(add_geolocate_control) @@ -37,11 +38,13 @@ export(add_raster_source) export(add_reset_control) export(add_scale_control) export(add_screenshot_control) +export(add_slider_control) export(add_source) export(add_symbol_layer) export(add_vector_source) export(add_video_source) export(add_view) +export(as_time_property) export(basemap_style) export(bivariate_palettes) export(bivariate_scale) @@ -60,6 +63,7 @@ export(enable_shiny_hover) export(esri_open_style) export(esri_style) export(fit_bounds) +export(flowmap_color_schemes) export(fly_to) export(get_breaks) export(get_column) @@ -91,6 +95,7 @@ export(number_format) export(on_section) export(openfreemap_style) export(palette_to_lut) +export(popup_style) export(print_map) export(query_rendered_features) export(renderMapboxgl) @@ -100,6 +105,8 @@ export(renderMaplibreCompare) export(save_map) export(set_config_property) export(set_filter) +export(set_flowmap_filter) +export(set_flowmap_settings) export(set_fog) export(set_layout_property) export(set_paint_property) @@ -112,6 +119,7 @@ export(set_style) export(set_terrain) export(set_tooltip) export(set_view) +export(slider_style) export(step_equal_interval) export(step_expr) export(step_jenks) @@ -120,6 +128,7 @@ export(story_leaflet) export(story_map) export(story_maplibre) export(story_section) +export(tooltip_style) export(turf_area) export(turf_buffer) export(turf_center_of_mass) @@ -132,6 +141,7 @@ export(turf_filter) export(turf_intersect) export(turf_union) export(turf_voronoi) +export(update_slider_control) import(base64enc) import(geojsonsf) import(grDevices) diff --git a/NEWS.md b/NEWS.md index 0bc923f3..0a1c1af9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,13 @@ # mapgl 0.5.0 +* Tooltips and popups now accept `{brace}` templates package-wide. Any layer's `tooltip`/`popup` (and `set_tooltip()`/`set_popup()`) can take a glue-style template such as `"{name}: {population}"`, in addition to the existing column name and `concat()`/`number_format()` expression forms; substituted values are HTML-escaped. + +* New `tooltip_style()` / `popup_style()` helpers theme tooltips and popups without hand-written HTML/CSS, mirroring `legend_style()`. Pass a preset (`"light"`/`"dark"`) or custom appearance (background, border, radius, font, padding, shadow) to the new `tooltip_style`/`popup_style` argument on layer functions (and `set_tooltip()`/`set_popup()`). Tooltips are unstyled by default, so existing maps are unchanged. + +* New `add_flowmap()` draws animated origin-destination flow maps powered by Flowmap.gl (deck.gl). It supports temporal flows, location clustering, customizable color schemes (`flowmap_color_schemes()`), CSS blend modes, and themeable tooltips and popups (per-object-type content via `list(location = , flow = )`, styled with `tooltip_style()`/`popup_style()`). Flow filters and settings can be updated reactively in Shiny with `set_flowmap_filter()` and `set_flowmap_settings()`, and a `"window"`-mode `add_slider_control()` can drive a flowmap's temporal range. The heavy flow-mapping libraries load on demand, so maps without a flowmap are unaffected. Adapted from Egor Kotov's contribution in #205, with the bundled `bixi_locations` and `bixi_flows` datasets as a ready-to-use example. + +* New `add_slider_control()` adds an interactive slider that filters and/or animates one or more layers by a numeric feature property. It composes with a layer's initial `filter`, later `set_filter()` calls, and interactive legends (intersecting via `["all", ...]`) rather than replacing them. Modes are `"sequential"` (one value), `"cumulative"` (everything through a value), and `"window"` (a selected range that can also drive flowmap time ranges; `window_behavior` chooses a `"resizable"` two-edge range or a `"fixed"`-width band you pan). Two presentations: the default `"compact"` slider, or `presentation = "timeline"` — a prominent, brushable histogram (drag the selected window across the bars, drag its edges to resize) modeled on Egor Kotov's FlowMapBlue time control (#205). Supports paint-property animation, an optional play button, and an optional density histogram (`histogram`/`histogram_data`/`counts`, drawn with d3 loaded on demand). New `slider_style()` presets and overrides control the container, play button, track, thumb, and histogram appearance, and `draggable = TRUE` lets the user reposition the panel anywhere on the map (as with `add_legend()`). Companions `update_slider_control()` (for Shiny proxies) and `as_time_property()` (coerce `Date`/`POSIXct` to a numeric filter property) round out the feature. + * Update MapLibre GL JS to v5.24.0 and Mapbox GL JS to v3.24.0. * Fixed `add_legend()` silently ignoring the `target` argument for MapLibre compare widgets: the compare dispatch checked for class `"maplibre_compare"` while the widget class is `"maplibregl_compare"`, so legends were attached as regular map legends instead of compare-level legends. diff --git a/R/data.R b/R/data.R new file mode 100644 index 00000000..80e3ef8f --- /dev/null +++ b/R/data.R @@ -0,0 +1,53 @@ +#' BIXI Montréal Bike Share Stations (2019) +#' +#' A dataset containing the names and coordinates of BIXI bicycle sharing +#' stations in Montréal, Quebec, Canada. +#' +#' @format A data frame with 618 rows and 4 variables: +#' \describe{ +#' \item{id}{Unique station ID (character, e.g., `"4000"`, `"MTL-ECO5.1-01"`)} +#' \item{name}{Station name (character, e.g., `"Jeanne-d'Arc / Ontario"`)} +#' \item{lat}{Latitude coordinate (numeric)} +#' \item{lon}{Longitude coordinate (numeric)} +#' } +#' @source BIXI Montréal Open Data (\url{https://bixi.com/fr/donnees-ouvertes}). +#' Prepared for \url{https://github.com/FlowmapBlue/FlowmapBlue} by Ilya Boyandin (\url{https://github.com/ilyabo}). +#' Data \enc{©}{(c)} BIXI Montréal, released under the BIXI Montréal Open Data +#' license (\url{https://bixi.com/fr/donnees-ouvertes}). +#' @seealso \code{\link{bixi_flows}} +#' @examples +#' # Convert to sf object to view on a map +#' if (requireNamespace("sf", quietly = TRUE)) { +#' bixi_sf <- sf::st_as_sf(bixi_locations, coords = c("lon", "lat"), crs = 4326) +#' print(head(bixi_sf)) +#' } +"bixi_locations" + +#' BIXI Montréal Hourly Bike Sharing Flows (July 1-7, 2019) +#' +#' A dataset containing hourly aggregated bike sharing trips between BIXI +#' stations in Montréal during the week of July 1 to July 7, 2019. +#' +#' To minimize the package footprint, the dataset has been truncated to a +#' **minimum of three trips** (retaining only flows where \code{count > 2}), +#' which reduces the rows from 213,227 to 6,092, and compresses the final size +#' to just **~22 KB**. +#' +#' @format A data frame with 6,092 rows and 4 variables: +#' \describe{ +#' \item{time}{Hourly timestamp (POSIXct, UTC)} +#' \item{origin}{Origin station ID (factor, matching \code{bixi_locations$id})} +#' \item{dest}{Destination station ID (factor, matching \code{bixi_locations$id})} +#' \item{count}{Aggregated number of bike sharing trips in that hour (integer)} +#' } +#' @source BIXI Montréal Open Data (\url{https://bixi.com/fr/donnees-ouvertes}). +#' Prepared for \url{https://github.com/FlowmapBlue/FlowmapBlue} by Ilya Boyandin (\url{https://github.com/ilyabo}). +#' Data \enc{©}{(c)} BIXI Montréal, released under the BIXI Montréal Open Data +#' license (\url{https://bixi.com/fr/donnees-ouvertes}). +#' Original interactive visualization on Flowmap.blue: +#' \url{https://www.flowmap.blue/1qTVOzkPB7U1ySI4g4uPtVBzzEDCI8n1WXAmQeZL15fE} +#' @seealso \code{\link{bixi_locations}} +#' @examples +#' # Check first few records +#' print(head(bixi_flows)) +"bixi_flows" diff --git a/R/flowmap.R b/R/flowmap.R new file mode 100644 index 00000000..51bf9d4d --- /dev/null +++ b/R/flowmap.R @@ -0,0 +1,1380 @@ +#' FlowMapGL color scheme names +#' +#' Returns the FlowMapGL 9.3.0 preset color scheme names supported by +#' [add_flowmap()]. These names are case-sensitive. +#' +#' @details +#' The bundled FlowMapGL presets are: +#' `r flowmap_color_schemes_markdown()`. +#' +#' @return A character vector of FlowMapGL preset names. +#' @export +#' +#' @examples +#' flowmap_color_schemes() +flowmap_color_schemes <- function() { + flowmap_color_scheme_registry() +} + + + +#' Adds a FlowmapGL layer for visualizing origin-destination flows between +#' point locations. +#' +#' @param map A map object created by [mapboxgl()] or [maplibre()]. +#' @param id A unique layer ID. +#' @param locations A data frame or `sf` point object with location data. +#' Data frames must include `id`, `lat`, and `lon` columns. `sf` point +#' objects must include `id`; coordinates are transformed to EPSG:4326 and +#' serialized as `lon`/`lat`. +#' @param flows A data frame with `origin`, `dest`, and `count` columns. +#' @param flow_color_scheme FlowMapGL preset color scheme name, a character +#' vector of at least two CSS colors, or a `mapgl_continuous_scale` object +#' created by [interpolate_palette()]. Preset names are case-sensitive; use +#' [flowmap_color_schemes()] to list them. +#' @param flow_opacity Layer opacity between 0 and 1. +#' @param flow_dark_mode Logical (`TRUE` or `FALSE`), or `"auto"`; whether to use FlowMapGL dark-mode +#' colors. If `"auto"`, the mode is dynamically detected based on the map style. +#' @param flow_blend Logical (`TRUE` or `FALSE`), `"auto"`, or a character string specifying a CSS +#' mix-blend-mode. +#' +#' Valid modes are: `"normal"`, `"multiply"`, `"screen"`, `"overlay"`, `"darken"`, +#' `"lighten"`, `"color-dodge"`, `"color-burn"`, `"hard-light"`, `"soft-light"`, +#' `"difference"`, `"exclusion"`, `"hue"`, `"saturation"`, `"color"`, and `"luminosity"`. +#' +#' **Recommendations**: +#' * On **dark basemaps**: `"screen"` looks best, creating a glowing additive effect where flows overlap. +#' * On **light basemaps**: `"multiply"` or `"darken"` looks best, increasing contrast against the light background. +#' +#' If `"auto"`, automatically chooses `"screen"` for dark styles and `"multiply"` for light styles. +#' If `before_id` or `slot` is specified (interleaved mode), `"auto"` quietly disables blending (`FALSE`) +#' without throwing a warning. If `TRUE`, defaults to `"screen"` when `flow_dark_mode` is `TRUE`, +#' and `"multiply"` when `FALSE`. If `FALSE`, no blending is applied. Note: CSS blending requires +#' a standalone canvas overlay and is ignored when `before_id` or `slot` is specified. +#' @param flow_fade_amount Controls how much lower-magnitude flows fade compared to higher ones. Range: 0-100. +#' @param flow_highlight_color Color used for highlighting hovered elements. +#' @param flow_locations_enabled Whether to show location circles. +#' @param flow_location_totals_enabled Whether to show incoming/outgoing totals as concentric circles at each location. +#' @param flow_location_labels_enabled Whether to show text labels at locations. +#' @param flow_lines_rendering_mode Controls how flow lines are rendered: `"straight"`, `"animated-straight"`, or `"curved"`. +#' @param flow_line_thickness_scale Multiplier for flow line thickness. +#' @param flow_line_curviness Multiplier for flow line curviness (only used when `flow_lines_rendering_mode` is `"curved"`). +#' @param flow_clustering_enabled Whether to cluster nearby locations when zoomed out. +#' @param flow_clustering_auto Whether to automatically adjust clustering level based on zoom. +#' @param flow_clustering_level Fixed clustering zoom level. Only used when `flow_clustering_auto` is `FALSE`. +#' @param flow_fade_enabled Whether to apply color fading to lower-magnitude flows. +#' @param flow_fade_opacity_enabled Whether to also fade opacity for lower-magnitude flows. +#' @param flow_adaptive_scales_enabled Whether to adapt flow thickness and +#' color scales to the current viewport. This controls the spatial scale +#' domain while panning and zooming. +#' @param flow_temporal_scale_domain For temporal flowmaps, whether flow +#' thickness and color scales use only the currently selected time range +#' (`"selected"`) or all flow data across the full time extent (`"all"`). +#' @param flow_max_top_flows_display_num Maximum number of flows to display. +#' @param flow_endpoints_in_viewport_mode Controls when a flow is considered visible based on endpoint locations: `"any"` or `"both"`. +#' @param flow_time_column Optional column name in `flows` for time data. +#' @param flow_selected_time_range Optional vector of two dates (or strings) for initial time filtering. +#' @param flow_selected_locations Optional vector of location IDs to select. +#' @param flow_location_filter_mode Optional location filter mode: `"ALL"`, `"INCOMING"`, `"OUTGOING"`, or `"BETWEEN"`. +#' @param tooltip Hover tooltip content. Use `FALSE`/`NULL` to disable, +#' `TRUE` for the default, a column name, a `{brace}` template, a +#' `concat()`/`number_format()` expression, or a named `list(location = , +#' flow = )` to set different content for hovered locations vs flows. +#' Available fields are, for locations: `name`, `id`, `lat`, `lon`, +#' `incoming`, `outgoing`, `internal` (plus any `locations` columns); for +#' flows: `count`, `origin_id`, `origin_name`, `dest_id`, `dest_name` (plus +#' any `flows` columns). +#' @param popup Click popup content. Same forms as `tooltip`; defaults to +#' `FALSE` (disabled). +#' @param tooltip_style Tooltip appearance. A preset string (`"light"`, +#' `"dark"`, or `"auto"`) or a [tooltip_style()] object (colors, border, +#' radius, font, padding, shadow, and `position = "floating"`/`"anchored"`). +#' Defaults to a light/dark preset matching `flow_dark_mode`. +#' @param popup_style Popup appearance; same forms as `tooltip_style`. +#' @param visibility Whether the layer is initially `"visible"` or `"none"`. +#' @param before_id Optional map layer ID to render before. +#' @param slot Optional Mapbox Standard slot. +#' +#' @return The modified map object with the flowmap layer added. +#' +#' @details +#' Mapbox and MapLibre layer paint arguments such as `fill_color`, +#' `circle_color`, and `line_color` require a scalar CSS color or a style +#' expression. Use `interpolate_palette(...)$expression` for data-driven layer +#' color ramps. FlowMapGL's `flow_color_scheme` accepts a preset name such as +#' `"Teal"`, a plain color ramp such as `c("red", "white", "blue")`, or an +#' `interpolate_palette(...)` scale object. +#' +#' Flow scale domains have separate spatial and temporal controls. +#' `flow_adaptive_scales_enabled = TRUE` rescales flow thickness and color for +#' the current viewport; `FALSE` keeps the scale tied to the broader map extent. +#' For temporal flowmaps, `flow_temporal_scale_domain = "selected"` rescales +#' within the selected time-control interval, while `"all"` keeps the scale +#' comparable across the full time extent. +#' @export +#' +#' @examples +#' # Create a flowmap centered on Montréal using the bundled datasets +#' maplibre( +#' style = carto_style("dark-matter"), +#' center = c(-73.58, 45.50), +#' zoom = 11, +#' projection = "mercator" +#' ) |> +#' add_flowmap( +#' id = "bixi-rides", +#' locations = bixi_locations, +#' flows = bixi_flows, +#' flow_time_column = "time", +#' flow_color_scheme = "Teal", +#' flow_dark_mode = TRUE +#' ) +#' +#' # To animate the flows over time, pair the flowmap with a window-mode +#' # slider that targets the same layer id; see [add_slider_control()]. +add_flowmap <- function( + map, + id, + locations, + flows, + flow_color_scheme = "Teal", + flow_opacity = 1, + flow_dark_mode = "auto", + flow_blend = "auto", + flow_fade_amount = 50, + flow_highlight_color = "#ff9b29", + flow_locations_enabled = TRUE, + flow_location_totals_enabled = TRUE, + flow_location_labels_enabled = FALSE, + flow_lines_rendering_mode = c("straight", "animated-straight", "curved"), + flow_line_thickness_scale = 1, + flow_line_curviness = 1, + flow_clustering_enabled = TRUE, + flow_clustering_auto = TRUE, + flow_clustering_level = NULL, + flow_fade_enabled = TRUE, + flow_fade_opacity_enabled = FALSE, + flow_adaptive_scales_enabled = TRUE, + flow_temporal_scale_domain = c("selected", "all"), + flow_max_top_flows_display_num = 5000, + flow_endpoints_in_viewport_mode = c("any", "both"), + flow_time_column = NULL, + flow_selected_time_range = NULL, + flow_selected_locations = NULL, + flow_location_filter_mode = c("ALL", "INCOMING", "OUTGOING", "BETWEEN"), + tooltip = TRUE, + popup = FALSE, + tooltip_style = NULL, + popup_style = NULL, + visibility = c("visible", "none"), + before_id = NULL, + slot = NULL +) { + if (!inherits(map, "mapboxgl") && !inherits(map, "maplibregl")) { + rlang::abort("`map` must be created by `mapboxgl()` or `maplibre()`.") + } + + if (!is.character(id) || length(id) != 1 || is.na(id) || !nzchar(id)) { + rlang::abort("`id` must be a non-empty character string.") + } + + visibility <- match.arg(visibility) + flow_lines_rendering_mode <- match.arg(flow_lines_rendering_mode) + flow_temporal_scale_domain <- match.arg(flow_temporal_scale_domain) + flow_endpoints_in_viewport_mode <- match.arg(flow_endpoints_in_viewport_mode) + flow_location_filter_mode <- match.arg(flow_location_filter_mode) + + if ( + !is.numeric(flow_opacity) || + length(flow_opacity) != 1 || + is.na(flow_opacity) || + flow_opacity < 0 || + flow_opacity > 1 + ) { + rlang::abort("`flow_opacity` must be a number between 0 and 1.") + } + + # Determine dark mode if "auto" + if (identical(flow_dark_mode, "auto")) { + flow_dark_mode <- is_dark_style(map$x$style) + } + + flow_dark_mode <- flowmap_validate_dark_mode(flow_dark_mode) + + # Default the tooltip/popup style to a light/dark preset matching the + # flowmap's dark mode (preserves the themed look); the user can override with + # a preset string or a tooltip_style()/popup_style() object that also carries + # the floating/anchored position. + tooltip_style_spec <- mapgl_normalize_tooltip_style( + tooltip_style %||% (if (flow_dark_mode) "dark" else "light"), + dark_mode = flow_dark_mode, + arg = "tooltip_style" + ) + popup_style_spec <- mapgl_normalize_tooltip_style( + popup_style %||% (if (flow_dark_mode) "dark" else "light"), + dark_mode = flow_dark_mode, + arg = "popup_style" + ) + + # Normalize interaction content (per object type) + tooltip_config <- flowmap_normalize_interaction( + tooltip, + default_enabled = TRUE, + behavior = "tooltip", + locations_df = locations, + flows_df = flows + ) + + popup_config <- flowmap_normalize_interaction( + popup, + default_enabled = FALSE, + behavior = "popup", + locations_df = locations, + flows_df = flows + ) + + use_interleaved <- !is.null(before_id) || !is.null(slot) + + # Resolve blend mode if "auto" + if (identical(flow_blend, "auto")) { + if (use_interleaved) { + flow_blend <- FALSE + } else { + flow_blend <- if (flow_dark_mode) "screen" else "multiply" + } + } else if (isTRUE(flow_blend)) { + # If explicitly TRUE, we still resolve to the best blend mode + flow_blend <- if (flow_dark_mode) "screen" else "multiply" + } + + if (use_interleaved && (!is.logical(flow_blend) || flow_blend)) { + rlang::warn( + "`flow_blend` is ignored when `before_id` or `slot` is specified. CSS blending requires a separate canvas overlay, which is not supported in interleaved mode." + ) + } + + if (is.logical(flow_blend)) { + if (length(flow_blend) != 1 || is.na(flow_blend)) { + rlang::abort("`flow_blend` must be `TRUE` or `FALSE`.") + } + } else if (is.character(flow_blend)) { + if ( + length(flow_blend) != 1 || + is.na(flow_blend) || + !nzchar(trimws(flow_blend)) + ) { + rlang::abort("`flow_blend` must be a valid CSS blend mode name.") + } + valid_modes <- c( + "normal", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "hue", + "saturation", + "color", + "luminosity" + ) + if (!flow_blend %in% valid_modes) { + rlang::abort(paste0( + "`flow_blend` must be one of the valid CSS mix-blend-mode values: ", + paste(paste0("\"", valid_modes, "\""), collapse = ", ") + )) + } + } else { + rlang::abort( + "`flow_blend` must be a logical (`TRUE` or `FALSE`) or a valid CSS blend mode string." + ) + } + + flowmap_validate_logical(flow_locations_enabled, "flow_locations_enabled") + flowmap_validate_logical( + flow_location_totals_enabled, + "flow_location_totals_enabled" + ) + flowmap_validate_logical( + flow_location_labels_enabled, + "flow_location_labels_enabled" + ) + flowmap_validate_logical(flow_clustering_enabled, "flow_clustering_enabled") + flowmap_validate_logical(flow_clustering_auto, "flow_clustering_auto") + flowmap_validate_logical(flow_fade_enabled, "flow_fade_enabled") + flowmap_validate_logical( + flow_fade_opacity_enabled, + "flow_fade_opacity_enabled" + ) + flowmap_validate_logical( + flow_adaptive_scales_enabled, + "flow_adaptive_scales_enabled" + ) + + if ( + !is.character(flow_highlight_color) || + length(flow_highlight_color) != 1 || + is.na(flow_highlight_color) + ) { + rlang::abort("`flow_highlight_color` must be a single string.") + } + + if ( + !is.numeric(flow_fade_amount) || + length(flow_fade_amount) != 1 || + is.na(flow_fade_amount) || + flow_fade_amount < 0 || + flow_fade_amount > 100 + ) { + rlang::abort("`flow_fade_amount` must be a number between 0 and 100.") + } + + if ( + !is.numeric(flow_max_top_flows_display_num) || + length(flow_max_top_flows_display_num) != 1 || + is.na(flow_max_top_flows_display_num) || + flow_max_top_flows_display_num <= 0 + ) { + rlang::abort("`flow_max_top_flows_display_num` must be a positive number.") + } + + if ( + !is.numeric(flow_line_thickness_scale) || + length(flow_line_thickness_scale) != 1 || + is.na(flow_line_thickness_scale) + ) { + rlang::abort("`flow_line_thickness_scale` must be a number.") + } + + if ( + !is.numeric(flow_line_curviness) || + length(flow_line_curviness) != 1 || + is.na(flow_line_curviness) + ) { + rlang::abort("`flow_line_curviness` must be a number.") + } + + if (!is.null(flow_clustering_level)) { + if ( + !is.numeric(flow_clustering_level) || + length(flow_clustering_level) != 1 || + is.na(flow_clustering_level) + ) { + rlang::abort("`flow_clustering_level` must be a number or NULL.") + } + } + + if (!is.null(flow_selected_time_range)) { + if (length(flow_selected_time_range) != 2) { + rlang::abort( + "`flow_selected_time_range` must be a vector of two elements (start and end)." + ) + } + } + + if (!is.null(flow_selected_locations)) { + flow_selected_locations <- as.character(flow_selected_locations) + } + + flow_color_scheme <- flowmap_normalize_color_scheme(flow_color_scheme) + before_id <- flowmap_validate_optional_string(before_id, "before_id") + slot <- flowmap_validate_optional_string(slot, "slot") + + locations <- flowmap_locations_to_df(locations) + flows <- flowmap_flows_to_df(flows, time_column = flow_time_column) + flowmap_validate_ids(locations, flows) + + flowmap_config <- list( + id = id, + data = list( + locations = locations, + flows = flows + ), + settings = list( + colorScheme = flow_color_scheme, + darkMode = flow_dark_mode, + opacity = flow_opacity, + flowBlend = flow_blend, + fadeAmount = flow_fade_amount, + highlightColor = flow_highlight_color, + locationsEnabled = flow_locations_enabled, + locationTotalsEnabled = flow_location_totals_enabled, + locationLabelsEnabled = flow_location_labels_enabled, + flowLinesRenderingMode = flow_lines_rendering_mode, + flowLineThicknessScale = flow_line_thickness_scale, + flowLineCurviness = flow_line_curviness, + clusteringEnabled = flow_clustering_enabled, + clusteringAuto = flow_clustering_auto, + clusteringLevel = flow_clustering_level, + fadeEnabled = flow_fade_enabled, + fadeOpacityEnabled = flow_fade_opacity_enabled, + adaptiveScalesEnabled = flow_adaptive_scales_enabled, + temporalScaleDomain = flow_temporal_scale_domain, + maxTopFlowsDisplayNum = flow_max_top_flows_display_num, + flowEndpointsInViewportMode = flow_endpoints_in_viewport_mode, + timeColumn = flow_time_column, + selectedTimeRange = flow_selected_time_range, + selectedLocations = flow_selected_locations, + locationFilterMode = flow_location_filter_mode + ), + visibility = visibility, + beforeId = before_id, + slot = slot + ) + + if (isTRUE(tooltip_config$enabled)) { + tooltip_config$style <- tooltip_style_spec + flowmap_config$tooltip <- tooltip_config + } + + if (isTRUE(popup_config$enabled)) { + popup_config$style <- popup_style_spec + flowmap_config$popup <- popup_config + } + + if (is.null(map$x$flowmaps)) { + map$x$flowmaps <- list() + } + + map <- attach_flowmap_dependencies(map) + + map$x$flowmaps <- c(map$x$flowmaps, list(flowmap_config)) + mapgl_record_flowmap_order( + map, + flowmap_index = length(map$x$flowmaps), + pending = is.null(before_id) && (is.logical(flow_blend) && !flow_blend) + ) +} + +#' Update flowmap filter +#' +#' Updates the filter state of a flowmap layer, including selected locations +#' and time range. +#' +#' @param proxy A map proxy object. +#' @param id The ID of the flowmap layer to update. +#' @param selected_locations Optional vector of location IDs to select. +#' @param location_filter_mode Optional location filter mode: `"ALL"`, `"INCOMING"`, `"OUTGOING"`, or `"BETWEEN"`. +#' @param selected_time_range Optional vector of two dates for time filtering. +#' +#' @return The modified map proxy. +#' @export +set_flowmap_filter <- function( + proxy, + id, + selected_locations = NULL, + location_filter_mode = NULL, + selected_time_range = NULL +) { + if (!is.character(id) || length(id) != 1 || is.na(id) || !nzchar(id)) { + rlang::abort("`id` must be a non-empty character string.") + } + + filter <- list() + if (!is.null(selected_locations)) { + if (!is.character(selected_locations) || anyNA(selected_locations)) { + rlang::abort( + "`selected_locations` must be a character vector (or `NULL`)." + ) + } + filter$selectedLocations <- selected_locations + } + if (!is.null(location_filter_mode)) { + filter$locationFilterMode <- flowmap_validate_choice( + location_filter_mode, + "location_filter_mode", + c("ALL", "INCOMING", "OUTGOING", "BETWEEN") + ) + } + if (!is.null(selected_time_range)) { + if (length(selected_time_range) != 2) { + rlang::abort("`selected_time_range` must be a vector of two elements.") + } + if ( + !(inherits(selected_time_range, "Date") || + inherits(selected_time_range, "POSIXt") || + is.numeric(selected_time_range)) || + anyNA(selected_time_range) + ) { + rlang::abort( + "`selected_time_range` elements must be `Date`, `POSIXct`, or numeric values (no missing values)." + ) + } + filter$selectedTimeRange <- selected_time_range + } + + if (length(filter) == 0) { + return(proxy) + } + + flowmap_invoke_method(proxy, "set_flowmap_filter", id = id, filter = filter) +} + +#' Update a flowmap setting +#' +#' Updates one setting of a flowmap layer. +#' +#' @param map A map object created by [mapboxgl()] or [maplibre()], or a proxy +#' object created by [mapboxgl_proxy()] or [maplibre_proxy()]. +#' @param id The ID of the flowmap layer to update. +#' @param name The setting name to update. Supported canonical FlowMapGL +#' setting names are `opacity`, `colorScheme`, `darkMode`, `fadeAmount`, +#' `highlightColor`, `locationsEnabled`, `locationTotalsEnabled`, +#' `locationLabelsEnabled`, `flowLinesRenderingMode`, +#' `flowLineThicknessScale`, `flowLineCurviness`, `clusteringEnabled`, +#' `clusteringAuto`, `clusteringLevel`, `fadeEnabled`, +#' `fadeOpacityEnabled`, `adaptiveScalesEnabled`, `temporalScaleDomain`, +#' `maxTopFlowsDisplayNum`, and `flowEndpointsInViewportMode`. +#' Snake-case aliases such as `color_scheme`, `temporal_scale_domain`, and +#' `max_top_flows_display_num` are accepted and normalized internally. +#' Filter state (`selectedTimeRange`, `selectedLocations`, and +#' `locationFilterMode`) must be updated with [set_flowmap_filter()]. +#' @param value The setting value. +#' +#' @return The modified map object. +#' +#' @details +#' `colorScheme` accepts the same values as `flow_color_scheme` in +#' [add_flowmap()]: a FlowMapGL preset name, a character vector of at least two +#' CSS colors, or a `mapgl_continuous_scale` object from +#' [interpolate_palette()]. `opacity` must be between 0 and 1. `fadeAmount` +#' must be between 0 and 100. `maxTopFlowsDisplayNum` must be positive. +#' `clusteringLevel` must be numeric or `NULL`. `flowLinesRenderingMode` must +#' be `"straight"`, `"animated-straight"`, or `"curved"`. +#' `temporalScaleDomain` must be `"selected"` or `"all"`. +#' `flowEndpointsInViewportMode` must be `"any"` or `"both"`. Boolean +#' settings must be scalar `TRUE` or `FALSE`. +#' @export +set_flowmap_settings <- function(map, id, name, value) { + setting <- flowmap_normalize_setting(name, value) + settings <- stats::setNames(list(setting$value), setting$name) + + flowmap_invoke_method( + map, + "set_flowmap_settings", + id = id, + settings = settings + ) +} + +flowmap_invoke_method <- function(map, type, ...) { + args <- list(...) + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) { + "mapboxgl-compare-proxy" + } else { + "maplibre-compare-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type, map = map$map_side), args) + ) + ) + } else { + proxy_class <- if (inherits(map, "mapboxgl_proxy")) { + "mapboxgl-proxy" + } else { + "maplibre-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type), args) + ) + ) + } + } else { + # Handle non-proxy case by updating map$x + # This ensures that if called on a map object, the settings are applied on first render + if (!is.null(map$x$flowmaps)) { + id <- args$id + for (i in seq_along(map$x$flowmaps)) { + if (map$x$flowmaps[[i]]$id == id) { + if (type == "set_flowmap_filter") { + # Merge filter into settings (JS init will pick it up) + if (!is.null(args$filter$selectedTimeRange)) { + map$x$flowmaps[[ + i + ]]$settings$selectedTimeRange <- args$filter$selectedTimeRange + } + if (!is.null(args$filter$selectedLocations)) { + map$x$flowmaps[[ + i + ]]$settings$selectedLocations <- args$filter$selectedLocations + } + if (!is.null(args$filter$locationFilterMode)) { + map$x$flowmaps[[ + i + ]]$settings$locationFilterMode <- args$filter$locationFilterMode + } + } else if (type == "set_flowmap_settings") { + # Merge settings + for (s in names(args$settings)) { + map$x$flowmaps[[i]]$settings[s] <- args$settings[s] + } + } + } + } + } + } + return(map) +} + +flowmap_validate_logical <- function(value, arg) { + if (!is.logical(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be TRUE or FALSE.")) + } +} + +flowmap_setting_name_map <- c( + opacity = "opacity", + colorScheme = "colorScheme", + color_scheme = "colorScheme", + darkMode = "darkMode", + dark_mode = "darkMode", + fadeAmount = "fadeAmount", + fade_amount = "fadeAmount", + highlightColor = "highlightColor", + highlight_color = "highlightColor", + locationsEnabled = "locationsEnabled", + locations_enabled = "locationsEnabled", + locationTotalsEnabled = "locationTotalsEnabled", + location_totals_enabled = "locationTotalsEnabled", + locationLabelsEnabled = "locationLabelsEnabled", + location_labels_enabled = "locationLabelsEnabled", + flowLinesRenderingMode = "flowLinesRenderingMode", + flow_lines_rendering_mode = "flowLinesRenderingMode", + flowLineThicknessScale = "flowLineThicknessScale", + flow_line_thickness_scale = "flowLineThicknessScale", + flowLineCurviness = "flowLineCurviness", + flow_line_curviness = "flowLineCurviness", + clusteringEnabled = "clusteringEnabled", + clustering_enabled = "clusteringEnabled", + clusteringAuto = "clusteringAuto", + clustering_auto = "clusteringAuto", + clusteringLevel = "clusteringLevel", + clustering_level = "clusteringLevel", + fadeEnabled = "fadeEnabled", + fade_enabled = "fadeEnabled", + fadeOpacityEnabled = "fadeOpacityEnabled", + fade_opacity_enabled = "fadeOpacityEnabled", + adaptiveScalesEnabled = "adaptiveScalesEnabled", + adaptive_scales_enabled = "adaptiveScalesEnabled", + temporalScaleDomain = "temporalScaleDomain", + temporal_scale_domain = "temporalScaleDomain", + maxTopFlowsDisplayNum = "maxTopFlowsDisplayNum", + max_top_flows_display_num = "maxTopFlowsDisplayNum", + flowEndpointsInViewportMode = "flowEndpointsInViewportMode", + flow_endpoints_in_viewport_mode = "flowEndpointsInViewportMode" +) + +flowmap_filter_setting_names <- c( + "selectedTimeRange", + "selected_time_range", + "selectedLocations", + "selected_locations", + "locationFilterMode", + "location_filter_mode" +) + +flowmap_supported_setting_names <- function() { + unique(unname(flowmap_setting_name_map)) +} + +flowmap_normalize_setting <- function(name, value) { + if ( + !is.character(name) || + length(name) != 1 || + is.na(name) || + !nzchar(trimws(name)) + ) { + rlang::abort("`name` must be a non-empty character string.") + } + + if (name %in% flowmap_filter_setting_names) { + rlang::abort( + paste0( + "`", + name, + "` is flowmap filter state. Use `set_flowmap_filter()` instead." + ) + ) + } + + normalized_name <- unname(flowmap_setting_name_map[name]) + if (is.na(normalized_name)) { + supported <- paste0("`", flowmap_supported_setting_names(), "`") + rlang::abort(paste0( + "`name` must be a supported FlowMapGL setting. Supported names are ", + paste(supported, collapse = ", "), + "." + )) + } + + list( + name = normalized_name, + value = flowmap_validate_setting_value(normalized_name, value) + ) +} + +flowmap_validate_setting_value <- function(name, value) { + switch( + name, + opacity = flowmap_validate_numeric_range( + value, + "value", + min = 0, + max = 1 + ), + colorScheme = flowmap_normalize_color_scheme(value, arg = "value"), + darkMode = flowmap_validate_logical_setting(value), + fadeAmount = flowmap_validate_numeric_range( + value, + "value", + min = 0, + max = 100 + ), + highlightColor = flowmap_validate_single_string(value, "value"), + locationsEnabled = flowmap_validate_logical_setting(value), + locationTotalsEnabled = flowmap_validate_logical_setting(value), + locationLabelsEnabled = flowmap_validate_logical_setting(value), + flowLinesRenderingMode = flowmap_validate_choice( + value, + "value", + c("straight", "animated-straight", "curved") + ), + flowLineThicknessScale = flowmap_validate_numeric_scalar(value, "value"), + flowLineCurviness = flowmap_validate_numeric_scalar(value, "value"), + clusteringEnabled = flowmap_validate_logical_setting(value), + clusteringAuto = flowmap_validate_logical_setting(value), + clusteringLevel = flowmap_validate_nullable_numeric_scalar(value, "value"), + fadeEnabled = flowmap_validate_logical_setting(value), + fadeOpacityEnabled = flowmap_validate_logical_setting(value), + adaptiveScalesEnabled = flowmap_validate_logical_setting(value), + temporalScaleDomain = flowmap_validate_choice( + value, + "value", + c("selected", "all") + ), + maxTopFlowsDisplayNum = flowmap_validate_positive_numeric_scalar( + value, + "value" + ), + flowEndpointsInViewportMode = flowmap_validate_choice( + value, + "value", + c("any", "both") + ) + ) +} + +flowmap_validate_logical_setting <- function(value) { + flowmap_validate_logical(value, "value") + value +} + +flowmap_validate_numeric_scalar <- function(value, arg) { + if (!is.numeric(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be a number.")) + } + + value +} + +flowmap_validate_nullable_numeric_scalar <- function(value, arg) { + if (is.null(value)) { + return(NULL) + } + + if (!is.numeric(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be a number or NULL.")) + } + + value +} + +flowmap_validate_positive_numeric_scalar <- function(value, arg) { + if (!is.numeric(value) || length(value) != 1 || is.na(value) || value <= 0) { + rlang::abort(paste0("`", arg, "` must be a positive number.")) + } + + value +} + +flowmap_validate_numeric_range <- function(value, arg, min, max) { + if ( + !is.numeric(value) || + length(value) != 1 || + is.na(value) || + value < min || + value > max + ) { + rlang::abort(paste0( + "`", + arg, + "` must be a number between ", + min, + " and ", + max, + "." + )) + } + + value +} + +flowmap_validate_choice <- function(value, arg, choices) { + if ( + !is.character(value) || + length(value) != 1 || + is.na(value) || + !value %in% choices + ) { + quoted <- paste0("`", choices, "`", collapse = ", ") + rlang::abort(paste0("`", arg, "` must be one of ", quoted, ".")) + } + + value +} + +flowmap_validate_single_string <- function(value, arg) { + if (!is.character(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be a single string.")) + } + + value +} + +# Normalize a flowmap tooltip/popup `input` into per-object-type content. +# A flowmap has two pickable object types (location, flow), so the content +# can differ per type via a named list(location=, flow=). Each content value +# is one of the package-wide tooltip forms (resolved in JS by +# resolveTooltipContent): TRUE (default template), FALSE/NULL (disabled), a +# column name, a {brace} template, or a concat()/number_format() expression. +flowmap_normalize_interaction <- function( + input, + default_enabled, + behavior, + locations_df, + flows_df +) { + if (is.null(input) || identical(input, FALSE)) { + return(list(enabled = FALSE)) + } + + has_named_types <- is.list(input) && + !is.null(names(input)) && + any(c("location", "flow") %in% names(input)) + + if (isTRUE(input)) { + loc <- TRUE + flw <- TRUE + } else if (is.character(input) && length(input) == 1 && !is.na(input)) { + loc <- input + flw <- input + } else if (has_named_types) { + loc <- input$location %||% default_enabled + flw <- input$flow %||% default_enabled + } else if (is.list(input)) { + # An expression (concat()/number_format()) applied to both object types. + loc <- input + flw <- input + } else { + rlang::abort(paste0( + "`", + behavior, + "` must be TRUE, FALSE, NULL, a column name, a {brace} template, a ", + "concat()/number_format() expression, or a named list with ", + "`location` and/or `flow`." + )) + } + + location <- flowmap_normalize_content(loc, behavior, "location") + flow <- flowmap_normalize_content(flw, behavior, "flow") + + enabled <- !identical(location, FALSE) || !identical(flow, FALSE) + + list(enabled = enabled, location = location, flow = flow) +} + +# Normalize a single content value for one object type. Returns TRUE (default), +# FALSE (disabled), a string (column name or {brace} template), or an +# expression list (concat()/number_format()), passed through to JS as-is. +flowmap_normalize_content <- function(value, behavior, type) { + if (is.null(value) || identical(value, FALSE)) { + return(FALSE) + } + if (isTRUE(value)) { + return(TRUE) + } + if ( + is.character(value) && + length(value) == 1 && + !is.na(value) && + nzchar(trimws(value)) + ) { + return(value) + } + if (is.list(value)) { + # A Mapbox-style expression (concat()/number_format()/get_column()). + return(value) + } + rlang::abort(paste0( + "`", + behavior, + "` content for `", + type, + "` must be TRUE, FALSE, a column name, a {brace} template string, or a ", + "concat()/number_format() expression." + )) +} + +# On-demand HTML dependencies for flowmap layers. Kept out of the always-on +# widget YAML so a map that never adds a flowmap does not ship ~1.6MB of JS. +# d3 is shared with the slider histogram strip; htmlwidgets dedupes by +# name + version, so attaching it from both places is safe. flowmap-gl and +# d3 are listed before flowmap-plugin so the plugin's globals are available. +flowmap_dependencies <- function() { + list( + htmltools::htmlDependency( + name = "d3", + version = "7.9.0", + src = c(file = system.file("htmlwidgets/lib/d3", package = "mapgl")), + script = "d3.min.js" + ), + htmltools::htmlDependency( + name = "flowmap-gl", + version = "9.3.0", + src = c( + file = system.file("htmlwidgets/lib/flowmap-gl", package = "mapgl") + ), + script = "flowmap-gl-bundle.min.js" + ), + htmltools::htmlDependency( + name = "flowmap-plugin", + version = "1.0.0", + src = c(file = system.file("htmlwidgets", package = "mapgl")), + script = "flowmap.js", + stylesheet = "flowmap.css" + ) + ) +} + +# Attach the flowmap dependencies to a map once, regardless of how many +# flowmap layers are added. +attach_flowmap_dependencies <- function(map) { + existing <- vapply( + map$dependencies, + function(dep) dep$name %||% "", + character(1) + ) + if ("flowmap-plugin" %in% existing) { + return(map) + } + map$dependencies <- c(map$dependencies, flowmap_dependencies()) + map +} + +mapgl_layer_order <- function(map) { + order <- attr(map, "mapgl_layer_order", exact = TRUE) + if (is.null(order)) { + order <- list(markers = list(), pending_flowmaps = integer()) + } + order +} + +mapgl_set_layer_order <- function(map, order) { + attr(map, "mapgl_layer_order") <- order + map +} + +mapgl_record_flowmap_order <- function(map, flowmap_index, pending) { + order <- mapgl_layer_order(map) + order$markers <- c( + order$markers, + list(list(type = "flowmap", index = flowmap_index)) + ) + + if (pending) { + order$pending_flowmaps <- c(order$pending_flowmaps, flowmap_index) + } + + mapgl_set_layer_order(map, order) +} + +mapgl_resolve_pending_flowmaps <- function(map, before_id) { + order <- mapgl_layer_order(map) + pending_flowmaps <- order$pending_flowmaps + + if (length(pending_flowmaps) == 0) { + return(map) + } + + for (flowmap_index in pending_flowmaps) { + if (flowmap_index > length(map$x$flowmaps)) { + next + } + + if (is.null(map$x$flowmaps[[flowmap_index]]$beforeId)) { + map$x$flowmaps[[flowmap_index]]$beforeId <- before_id + } + } + + order$pending_flowmaps <- integer() + mapgl_set_layer_order(map, order) +} + +mapgl_record_layer_order <- function(map, id) { + order <- mapgl_layer_order(map) + order$markers <- c(order$markers, list(list(type = "layer", id = id))) + mapgl_set_layer_order(map, order) +} + +flowmap_color_scheme_registry <- local({ + schemes <- NULL + + function() { + if (!is.null(schemes)) { + return(schemes) + } + + manifest_path <- system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json", + package = "mapgl", + mustWork = TRUE + ) + manifest <- jsonlite::read_json(manifest_path, simplifyVector = TRUE) + names <- manifest$colorSchemes$names + + if ( + !is.character(names) || + length(names) == 0 || + anyNA(names) || + any(!nzchar(names)) + ) { + rlang::abort( + "FlowMapGL color scheme metadata is missing from the vendored manifest." + ) + } + + schemes <<- names + schemes + } +}) + +flowmap_color_schemes_markdown <- function() { + schemes <- paste0("`", flowmap_color_scheme_registry(), "`") + if (length(schemes) == 1) { + return(schemes) + } + + paste0( + paste(schemes[-length(schemes)], collapse = ", "), + ", and ", + schemes[[length(schemes)]] + ) +} + +flowmap_validate_dark_mode <- function(flow_dark_mode) { + if ( + !is.logical(flow_dark_mode) || + length(flow_dark_mode) != 1 || + is.na(flow_dark_mode) + ) { + rlang::abort("`flow_dark_mode` must be `TRUE` or `FALSE`.") + } + + flow_dark_mode +} + +flowmap_validate_optional_string <- function(value, arg) { + if (is.null(value)) { + return(NULL) + } + + if ( + !is.character(value) || + length(value) != 1 || + is.na(value) || + !nzchar(trimws(value)) + ) { + rlang::abort(paste0( + "`", + arg, + "` must be `NULL` or a non-empty character string." + )) + } + + value +} + +flowmap_normalize_color_scheme <- function( + flow_color_scheme, + arg = "flow_color_scheme" +) { + arg_label <- paste0("`", arg, "`") + + if (inherits(flow_color_scheme, "mapgl_continuous_scale")) { + colors <- flow_color_scheme$colors + if (is.null(colors)) { + rlang::abort( + paste0(arg_label, " scale objects must contain a `colors` vector.") + ) + } + colors_arg_label <- paste0("`", arg, "$colors`") + return(mapgl_validate_color_vector(colors, colors_arg_label)) + } + + if (!is.character(flow_color_scheme)) { + rlang::abort(paste0( + arg_label, + " must be a FlowMapGL preset name, a CSS color vector, or a mapgl_continuous_scale object." + )) + } + + if (length(flow_color_scheme) == 1) { + if (is.na(flow_color_scheme) || !nzchar(trimws(flow_color_scheme))) { + rlang::abort(paste0(arg_label, " must not be missing or empty.")) + } + + if (flow_color_scheme %in% flowmap_color_scheme_registry()) { + return(flow_color_scheme) + } + + rlang::abort(paste0( + arg_label, + " must be one of `flowmap_color_schemes()` or a ", + "character vector of at least two CSS colors. Scalar color strings ", + "such as \"", + flow_color_scheme, + "\" are not valid FlowMapGL preset names." + )) + } + + mapgl_validate_color_vector(flow_color_scheme, arg_label) +} + +flowmap_locations_to_df <- function(locations) { + if (inherits(locations, "sfc")) { + locations <- sf::st_as_sf( + data.frame(id = seq_along(locations)), + geometry = locations + ) + } + + if (inherits(locations, "sf")) { + geometry_type <- as.character(sf::st_geometry_type( + locations, + by_geometry = TRUE + )) + if (!all(geometry_type == "POINT")) { + rlang::abort("`locations` must contain only POINT geometries.") + } + + if ( + !is.na(sf::st_crs(locations)) && sf::st_crs(locations) != sf::st_crs(4326) + ) { + locations <- sf::st_transform(locations, crs = 4326) + } + + coords <- sf::st_coordinates(locations) + locations <- sf::st_drop_geometry(locations) + locations$lon <- coords[, "X"] + locations$lat <- coords[, "Y"] + } else if (!is.data.frame(locations)) { + rlang::abort("`locations` must be a data frame or an sf point object.") + } + + locations <- as.data.frame(locations) + required <- c("id", "lat", "lon") + missing <- setdiff(required, names(locations)) + if (length(missing) > 0) { + rlang::abort(paste0( + "`locations` is missing required column", + if (length(missing) == 1) "" else "s", + ": ", + paste(missing, collapse = ", ") + )) + } + + if (!is.numeric(locations$lat) || !is.numeric(locations$lon)) { + rlang::abort("`locations$lat` and `locations$lon` must be numeric.") + } + + if (anyNA(locations$id) || anyNA(locations$lat) || anyNA(locations$lon)) { + rlang::abort( + "`locations` must not contain missing values in `id`, `lat`, or `lon`." + ) + } + + if (any(!is.finite(locations$lat)) || any(!is.finite(locations$lon))) { + rlang::abort( + "`locations$lat` and `locations$lon` must contain finite values." + ) + } + + locations$id <- as.character(locations$id) + if (anyDuplicated(locations$id)) { + rlang::abort("`locations$id` values must be unique.") + } + + if (!"name" %in% names(locations)) { + locations$name <- locations$id + } else { + locations$name <- as.character(locations$name) + } + + locations[, + unique(c( + "id", + "lat", + "lon", + "name", + setdiff(names(locations), c("id", "lat", "lon", "name")) + )), + drop = FALSE + ] +} + +flowmap_flows_to_df <- function(flows, time_column = NULL) { + if (!is.data.frame(flows)) { + rlang::abort("`flows` must be a data frame.") + } + + flows <- as.data.frame(flows) + required <- c("origin", "dest", "count") + missing <- setdiff(required, names(flows)) + if (length(missing) > 0) { + rlang::abort(paste0( + "`flows` is missing required column", + if (length(missing) == 1) "" else "s", + ": ", + paste(missing, collapse = ", ") + )) + } + + if (!is.numeric(flows$count)) { + rlang::abort("`flows$count` must be numeric.") + } + + if (anyNA(flows$origin) || anyNA(flows$dest) || anyNA(flows$count)) { + rlang::abort( + "`flows` must not contain missing values in `origin`, `dest`, or `count`." + ) + } + + if (any(!is.finite(flows$count))) { + rlang::abort("`flows$count` must contain finite values.") + } + + if (!is.null(time_column)) { + if (!time_column %in% names(flows)) { + rlang::abort(paste0( + "Time column '", + time_column, + "' not found in `flows`." + )) + } + flows$time <- flows[[time_column]] + } + + flows$origin <- as.character(flows$origin) + flows$dest <- as.character(flows$dest) + flows[, + unique(c( + "origin", + "dest", + "count", + if (!is.null(time_column)) "time", + setdiff( + names(flows), + c("origin", "dest", "count", if (!is.null(time_column)) "time") + ) + )), + drop = FALSE + ] +} + +flowmap_validate_ids <- function(locations, flows) { + ids <- locations$id + invalid_origins <- setdiff(unique(flows$origin), ids) + invalid_dests <- setdiff(unique(flows$dest), ids) + invalid <- unique(c(invalid_origins, invalid_dests)) + + if (length(invalid) > 0) { + rlang::abort(paste0( + "`flows$origin` and `flows$dest` must match `locations$id`; unknown ID", + if (length(invalid) == 1) "" else "s", + ": ", + paste(utils::head(invalid, 5), collapse = ", "), + if (length(invalid) > 5) ", ..." else "" + )) + } +} + +is_dark_style <- function(style) { + if (is.null(style)) { + # Default to light: the default Mapbox Standard / MapLibre styles are light, + # and dark mode is only assumed when a style explicitly looks dark. + return(FALSE) + } + + if (!is.character(style) || length(style) != 1 || is.na(style)) { + # If it's a list (like from basemap_style) + if (is.list(style)) { + bg_layer <- Filter( + function(l) isTRUE(l$type == "background"), + style$layers + ) + if (length(bg_layer) > 0) { + color <- bg_layer[[1]]$paint$`background-color` + if (is.character(color) && length(color) == 1) { + if (grepl("white|light|grey|gray", color, ignore.case = TRUE)) { + return(FALSE) + } + if (grepl("black|dark", color, ignore.case = TRUE)) { + return(TRUE) + } + } + } + } + return(FALSE) # Safe fallback: assume a light basemap + } + + # Dark patterns + if ( + grepl( + "dark|night|midnight|satellite|hybrid|imagery|nova", + style, + ignore.case = TRUE + ) + ) { + return(TRUE) + } + + # Light patterns + if ( + grepl( + "light|day|positron|voyager|streets|outdoors|basic|bright|topo|terrain", + style, + ignore.case = TRUE + ) + ) { + return(FALSE) + } + + # Default fallback if unknown: assume a light basemap + FALSE +} diff --git a/R/layers.R b/R/layers.R index 8ef18108..29552868 100644 --- a/R/layers.R +++ b/R/layers.R @@ -12,8 +12,9 @@ #' @param slot An optional slot for layer order. #' @param min_zoom The minimum zoom level for the layer. #' @param max_zoom The maximum zoom level for the layer. -#' @param popup A column name containing information to display in a popup on click. Columns containing HTML will be parsed. -#' @param tooltip A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. +#' @param popup Popup content shown on click: a column name, a `{brace}` template (e.g. `"{name}: {value}"`), or a `concat()`/`number_format()` expression. Columns containing HTML are parsed. +#' @param tooltip Tooltip content shown on hover; same forms as `popup`. +#' @param tooltip_style,popup_style Optional appearance for the tooltip/popup: a preset string (`"light"` or `"dark"`) or a [tooltip_style()] object. When omitted, the native (unstyled) appearance is kept. #' @param hover_options A named list of options for highlighting features in the layer on hover. #' @param before_id The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). #' @param filter An optional filter expression to subset features in the layer. @@ -68,7 +69,9 @@ add_layer <- function( tooltip = NULL, hover_options = NULL, before_id = NULL, - filter = NULL + filter = NULL, + tooltip_style = NULL, + popup_style = NULL ) { if (length(paint) == 0) { paint <- NULL @@ -78,6 +81,12 @@ add_layer <- function( layout <- NULL } + tooltip_style <- mapgl_normalize_tooltip_style( + tooltip_style, + arg = "tooltip_style" + ) + popup_style <- mapgl_normalize_tooltip_style(popup_style, arg = "popup_style") + # Convert sfc/sf objects to GeoJSON source if (inherits(source, "sfc")) { source <- sf::st_as_sf(source) @@ -95,6 +104,8 @@ add_layer <- function( ) } + map <- mapgl_resolve_pending_flowmaps(map, before_id = id) + map$x$layers <- c( map$x$layers, list(list( @@ -109,12 +120,16 @@ add_layer <- function( maxzoom = max_zoom, popup = popup, tooltip = tooltip, + tooltip_style = tooltip_style, + popup_style = popup_style, hover_options = hover_options, before_id = before_id, filter = filter )) ) + map <- mapgl_record_layer_order(map, id) + if (inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) { layer <- list( id = id, @@ -124,6 +139,8 @@ add_layer <- function( paint = paint, popup = popup, tooltip = tooltip, + tooltip_style = tooltip_style, + popup_style = popup_style, hover_options = hover_options, before_id = before_id ) @@ -206,8 +223,9 @@ add_layer <- function( #' @param slot An optional slot for layer order. #' @param min_zoom The minimum zoom level for the layer. #' @param max_zoom The maximum zoom level for the layer. -#' @param popup A column name containing information to display in a popup on click. Columns containing HTML will be parsed. -#' @param tooltip A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. +#' @param popup Popup content shown on click: a column name, a `{brace}` template (e.g. `"{name}: {value}"`), or a `concat()`/`number_format()` expression. Columns containing HTML are parsed. +#' @param tooltip Tooltip content shown on hover; same forms as `popup`. +#' @param tooltip_style,popup_style Optional appearance for the tooltip/popup: a preset string (`"light"` or `"dark"`) or a [tooltip_style()] object. When omitted, the native (unstyled) appearance is kept. #' @param hover_options A named list of options for highlighting features in the layer on hover. #' @param before_id The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). #' @param filter An optional filter expression to subset features in the layer. @@ -263,6 +281,8 @@ add_fill_layer <- function( max_zoom = NULL, popup = NULL, tooltip = NULL, + tooltip_style = NULL, + popup_style = NULL, hover_options = NULL, before_id = NULL, filter = NULL @@ -303,7 +323,9 @@ add_fill_layer <- function( tooltip, hover_options, before_id, - filter + filter, + tooltip_style = tooltip_style, + popup_style = popup_style ) return(map) @@ -358,10 +380,9 @@ add_fill_layer <- function( #' @param slot An optional slot for layer order. #' @param min_zoom The minimum zoom level for the layer. #' @param max_zoom The maximum zoom level for the layer. -#' @param popup A column name containing information to display in a popup on click. -#' Columns containing HTML will be parsed. -#' @param tooltip A column name containing information to display in a tooltip on hover. -#' Columns containing HTML will be parsed. +#' @param popup Popup content shown on click: a column name, a `{brace}` template (e.g. `"{name}: {value}"`), or a `concat()`/`number_format()` expression. Columns containing HTML are parsed. +#' @param tooltip Tooltip content shown on hover; same forms as `popup`. +#' @param tooltip_style,popup_style Optional appearance for the tooltip/popup: a preset string (`"light"` or `"dark"`) or a [tooltip_style()] object. When omitted, the native (unstyled) appearance is kept. #' @param hover_options A named list of options for highlighting features in the #' layer on hover. #' @param before_id The name of the layer that this layer appears "before", @@ -423,6 +444,8 @@ add_line_layer <- function( max_zoom = NULL, popup = NULL, tooltip = NULL, + tooltip_style = NULL, + popup_style = NULL, hover_options = NULL, before_id = NULL, filter = NULL @@ -483,7 +506,9 @@ add_line_layer <- function( tooltip, hover_options, before_id, - filter + filter, + tooltip_style = tooltip_style, + popup_style = popup_style ) return(map) @@ -617,8 +642,9 @@ add_heatmap_layer <- function( #' @param slot An optional slot for layer order. #' @param min_zoom The minimum zoom level for the layer. #' @param max_zoom The maximum zoom level for the layer. -#' @param popup A column name containing information to display in a popup on click. Columns containing HTML will be parsed. -#' @param tooltip A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. +#' @param popup Popup content shown on click: a column name, a `{brace}` template (e.g. `"{name}: {value}"`), or a `concat()`/`number_format()` expression. Columns containing HTML are parsed. +#' @param tooltip Tooltip content shown on hover; same forms as `popup`. +#' @param tooltip_style,popup_style Optional appearance for the tooltip/popup: a preset string (`"light"` or `"dark"`) or a [tooltip_style()] object. When omitted, the native (unstyled) appearance is kept. #' @param hover_options A named list of options for highlighting features in the layer on hover. #' @param before_id The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). #' @param filter An optional filter expression to subset features in the layer. @@ -688,6 +714,8 @@ add_fill_extrusion_layer <- function( max_zoom = NULL, popup = NULL, tooltip = NULL, + tooltip_style = NULL, + popup_style = NULL, hover_options = NULL, before_id = NULL, filter = NULL @@ -765,7 +793,9 @@ add_fill_extrusion_layer <- function( tooltip, hover_options, before_id, - filter + filter, + tooltip_style = tooltip_style, + popup_style = popup_style ) return(map) @@ -947,8 +977,9 @@ cluster_options <- function( #' @param slot An optional slot for layer order. #' @param min_zoom The minimum zoom level for the layer. #' @param max_zoom The maximum zoom level for the layer. -#' @param popup A column name containing information to display in a popup on click. Columns containing HTML will be parsed. -#' @param tooltip A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. +#' @param popup Popup content shown on click: a column name, a `{brace}` template (e.g. `"{name}: {value}"`), or a `concat()`/`number_format()` expression. Columns containing HTML are parsed. +#' @param tooltip Tooltip content shown on hover; same forms as `popup`. +#' @param tooltip_style,popup_style Optional appearance for the tooltip/popup: a preset string (`"light"` or `"dark"`) or a [tooltip_style()] object. When omitted, the native (unstyled) appearance is kept. #' @param hover_options A named list of options for highlighting features in the layer on hover. #' @param before_id The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). #' @param filter An optional filter expression to subset features in the layer. @@ -1053,6 +1084,8 @@ add_circle_layer <- function( max_zoom = NULL, popup = NULL, tooltip = NULL, + tooltip_style = NULL, + popup_style = NULL, hover_options = NULL, before_id = NULL, filter = NULL, @@ -1194,6 +1227,8 @@ add_circle_layer <- function( layout = layout, popup = popup, tooltip = tooltip, + tooltip_style = tooltip_style, + popup_style = popup_style, hover_options = hover_options, slot = slot, min_zoom = min_zoom, @@ -1216,7 +1251,9 @@ add_circle_layer <- function( tooltip, hover_options, before_id, - filter + filter, + tooltip_style = tooltip_style, + popup_style = popup_style ) } @@ -1430,6 +1467,7 @@ add_raster_layer <- function( #' @param max_zoom The maximum zoom level for the layer. #' @param popup A column name containing information to display in a popup on click. Columns containing HTML will be parsed. #' @param tooltip A column name containing information to display in a tooltip on hover. Columns containing HTML will be parsed. +#' @param tooltip_style,popup_style Optional appearance for the tooltip/popup: a preset string (`"light"` or `"dark"`) or a [tooltip_style()] object. When omitted, the native (unstyled) appearance is kept. #' @param hover_options A named list of options for highlighting features in the layer on hover. Not all elements of SVG icons can be styled. #' @param before_id The name of the layer that this layer appears "before", allowing you to insert layers below other layers in your basemap (e.g. labels). #' @param filter An optional filter expression to subset features in the layer. @@ -1564,6 +1602,8 @@ add_symbol_layer <- function( max_zoom = NULL, popup = NULL, tooltip = NULL, + tooltip_style = NULL, + popup_style = NULL, hover_options = NULL, before_id = NULL, filter = NULL, @@ -1777,6 +1817,8 @@ add_symbol_layer <- function( layout = layout, popup = popup, tooltip = tooltip, + tooltip_style = tooltip_style, + popup_style = popup_style, hover_options = hover_options, slot = slot, min_zoom = min_zoom, @@ -1799,7 +1841,9 @@ add_symbol_layer <- function( tooltip, hover_options, before_id, - filter + filter, + tooltip_style = tooltip_style, + popup_style = popup_style ) } diff --git a/R/plugins.R b/R/plugins.R index 5284738f..8283c2f9 100644 --- a/R/plugins.R +++ b/R/plugins.R @@ -329,13 +329,18 @@ compare.mapboxgl <- function( stylesheet = "layers-control.css" ) + dependencies <- c( + list(control_css), + unlist(lapply(maps, function(m) m$dependencies), recursive = FALSE) + ) + widget <- htmlwidgets::createWidget( name = "mapboxgl_compare", x, width = width, height = height, package = "mapgl", - dependencies = list(control_css), + dependencies = dependencies, elementId = if (is.null(shiny::getDefaultReactiveDomain())) elementId else NULL, sizingPolicy = htmlwidgets::sizingPolicy( @@ -408,13 +413,18 @@ compare.maplibre <- function( stylesheet = "layers-control.css" ) + dependencies <- c( + list(control_css), + unlist(lapply(maps, function(m) m$dependencies), recursive = FALSE) + ) + widget <- htmlwidgets::createWidget( name = "maplibregl_compare", x, width = width, height = height, package = "mapgl", - dependencies = list(control_css), + dependencies = dependencies, elementId = if (is.null(shiny::getDefaultReactiveDomain())) elementId else NULL, sizingPolicy = htmlwidgets::sizingPolicy( diff --git a/R/shiny.R b/R/shiny.R index 71c0283e..ba628395 100644 --- a/R/shiny.R +++ b/R/shiny.R @@ -524,12 +524,15 @@ move_layer <- function(map, layer_id, before_id = NULL) { #' #' @param map A map object created by the `mapboxgl` or `maplibre` function, or a proxy object. #' @param layer_id The ID of the layer to update. -#' @param tooltip The name of the tooltip to set. +#' @param tooltip Tooltip content: a column name, a `{brace}` template, or a +#' `concat()`/`number_format()` expression. #' @param layer Deprecated. Use `layer_id` instead. +#' @param style Optional tooltip appearance: a preset string (`"light"` or +#' `"dark"`) or a [tooltip_style()] object. #' #' @return The updated map object. #' @export -set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { +set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL, style = NULL) { # Handle backwards compatibility if (!is.null(layer) && is.null(layer_id)) { layer_id <- layer @@ -542,6 +545,7 @@ set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { if (is.null(layer_id)) { stop("layer_id is required") } + style_spec <- mapgl_normalize_tooltip_style(style, arg = "style") if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { if ( inherits(map, "mapboxgl_compare_proxy") || @@ -558,6 +562,7 @@ set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { type = "set_tooltip", layer = layer_id, tooltip = tooltip, + tooltip_style = style_spec, map = map$map_side ) ) @@ -573,7 +578,8 @@ set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { message = list( type = "set_tooltip", layer = layer_id, - tooltip = tooltip + tooltip = tooltip, + tooltip_style = style_spec ) ) ) @@ -590,12 +596,15 @@ set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { #' #' @param map A map object created by the `mapboxgl` or `maplibre` function, or a proxy object. #' @param layer_id The ID of the layer to update. -#' @param popup The name of the popup property or an expression to set. +#' @param popup Popup content: a column name, a `{brace}` template, or a +#' `concat()`/`number_format()` expression. #' @param layer Deprecated. Use `layer_id` instead. +#' @param style Optional popup appearance: a preset string (`"light"` or +#' `"dark"`) or a [tooltip_style()]/[popup_style()] object. #' #' @return The updated map object. #' @export -set_popup <- function(map, layer_id = NULL, popup, layer = NULL) { +set_popup <- function(map, layer_id = NULL, popup, layer = NULL, style = NULL) { # Handle backwards compatibility if (!is.null(layer) && is.null(layer_id)) { layer_id <- layer @@ -608,6 +617,7 @@ set_popup <- function(map, layer_id = NULL, popup, layer = NULL) { if (is.null(layer_id)) { stop("layer_id is required") } + style_spec <- mapgl_normalize_tooltip_style(style, arg = "style") if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { if ( inherits(map, "mapboxgl_compare_proxy") || @@ -624,6 +634,7 @@ set_popup <- function(map, layer_id = NULL, popup, layer = NULL) { type = "set_popup", layer = layer_id, popup = popup, + popup_style = style_spec, map = map$map_side ) ) @@ -639,7 +650,8 @@ set_popup <- function(map, layer_id = NULL, popup, layer = NULL) { message = list( type = "set_popup", layer = layer_id, - popup = popup + popup = popup, + popup_style = style_spec ) ) ) diff --git a/R/slider.R b/R/slider.R new file mode 100644 index 00000000..992f6190 --- /dev/null +++ b/R/slider.R @@ -0,0 +1,1027 @@ +#' Style a slider control +#' +#' Builds an appearance specification for [add_slider_control()]. Use a preset +#' string (`"light"`, `"dark"`, or `"auto"`) as a starting point and override +#' individual pieces of the control on top of it. The older +#' `background_color`, `text_color`, `accent_color`, and `width` arguments on +#' [add_slider_control()] continue to work for simple styling; use +#' `slider_style()` when you need control over the container, play button, +#' track, thumb, and histogram. +#' +#' @param preset Optional base theme: `"light"`, `"dark"`, or `"auto"`. +#' `"auto"` currently resolves to the light preset. +#' @param width Slider container width in pixels. +#' @param background_color CSS color for the control background. +#' @param background_opacity Numeric in `[0, 1]` for background opacity. +#' @param text_color CSS color for general text. +#' @param border_color CSS color for the container border. +#' @param border_width Border width in pixels. +#' @param border_radius Corner radius in pixels. +#' @param font_family CSS `font-family` string. +#' @param font_size Font size in pixels. +#' @param font_weight CSS `font-weight`. +#' @param padding Internal padding as a CSS size string or numeric pixels. +#' @param shadow Logical; whether to draw a drop shadow. +#' @param shadow_color CSS color of the drop shadow. +#' @param shadow_size Blur radius of the drop shadow in pixels. +#' @param title_color,title_size,title_weight Styling for the optional title. +#' @param value_color,value_size,value_weight Styling for the current value +#' label. +#' @param accent_color Main accent color. Used as the default active track, +#' thumb, play hover, and histogram color. +#' @param play_button_background,play_button_color,play_button_border_color +#' Styling for the play/pause button. +#' @param track_color,active_color CSS colors for the inactive and active track. +#' @param track_height Track height in pixels. +#' @param thumb_color,thumb_border_color CSS colors for the slider thumb. +#' @param thumb_size Thumb diameter in pixels. +#' @param histogram_height Histogram height in pixels. +#' @param histogram_bar_color Histogram bar color. +#' @param histogram_active_opacity,histogram_inactive_opacity Bar opacity for +#' selected and unselected histogram bins. +#' +#' @return A list of class `mapgl_slider_style`. +#' @export +#' +#' @examples +#' \dontrun{ +#' slider_style("dark", accent_color = "#9fd3ff") +#' +#' slider_style( +#' background_color = "rgba(20, 30, 48, 0.92)", +#' text_color = "#f8fafc", +#' active_color = "#7dd3fc", +#' thumb_size = 18 +#' ) +#' } +slider_style <- function( + preset = NULL, + width = NULL, + background_color = NULL, + background_opacity = NULL, + text_color = NULL, + border_color = NULL, + border_width = NULL, + border_radius = NULL, + font_family = NULL, + font_size = NULL, + font_weight = NULL, + padding = NULL, + shadow = NULL, + shadow_color = NULL, + shadow_size = NULL, + title_color = NULL, + title_size = NULL, + title_weight = NULL, + value_color = NULL, + value_size = NULL, + value_weight = NULL, + accent_color = NULL, + play_button_background = NULL, + play_button_color = NULL, + play_button_border_color = NULL, + track_color = NULL, + active_color = NULL, + track_height = NULL, + thumb_color = NULL, + thumb_border_color = NULL, + thumb_size = NULL, + histogram_height = NULL, + histogram_bar_color = NULL, + histogram_active_opacity = NULL, + histogram_inactive_opacity = NULL +) { + if (!is.null(preset)) { + preset <- match.arg(preset, c("light", "dark", "auto")) + } + + style <- list( + preset = preset, + width = width, + background_color = background_color, + background_opacity = background_opacity, + text_color = text_color, + border_color = border_color, + border_width = border_width, + border_radius = border_radius, + font_family = font_family, + font_size = font_size, + font_weight = font_weight, + padding = padding, + shadow = shadow, + shadow_color = shadow_color, + shadow_size = shadow_size, + title_color = title_color, + title_size = title_size, + title_weight = title_weight, + value_color = value_color, + value_size = value_size, + value_weight = value_weight, + accent_color = accent_color, + play_button_background = play_button_background, + play_button_color = play_button_color, + play_button_border_color = play_button_border_color, + track_color = track_color, + active_color = active_color, + track_height = track_height, + thumb_color = thumb_color, + thumb_border_color = thumb_border_color, + thumb_size = thumb_size, + histogram_height = histogram_height, + histogram_bar_color = histogram_bar_color, + histogram_active_opacity = histogram_active_opacity, + histogram_inactive_opacity = histogram_inactive_opacity + ) + + style <- style[!vapply(style, is.null, logical(1))] + class(style) <- "mapgl_slider_style" + style +} + +mapgl_slider_style_preset <- function(name) { + switch( + name, + light = list( + width = 280, + background_color = "#ffffffcc", + text_color = "#404040", + border_color = "rgba(0, 0, 0, 0.15)", + border_width = 1, + border_radius = 4, + font_family = "\"Open Sans\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif", + font_size = 12, + font_weight = 400, + padding = "10px 12px 8px 12px", + shadow = TRUE, + shadow_color = "rgba(0, 0, 0, 0.15)", + shadow_size = 6, + title_size = 13, + title_weight = 500, + value_size = 12, + value_weight = 500, + # accent_color is the single source of truth; the active/thumb/play/bar + # colors derive from it (in JS) unless explicitly overridden, so setting + # accent_color alone re-themes the whole control. + accent_color = "#4a90e2", + play_button_background = "#ffffff", + play_button_border_color = "rgba(0, 0, 0, 0.15)", + track_color = "rgba(0, 0, 0, 0.15)", + track_height = 4, + thumb_border_color = "#ffffff", + thumb_size = 15, + histogram_height = 46, + histogram_active_opacity = 1, + histogram_inactive_opacity = 0.28 + ), + dark = list( + width = 280, + background_color = "rgba(24, 30, 38, 0.92)", + text_color = "#f3f4f6", + border_color = "rgba(255, 255, 255, 0.18)", + border_width = 1, + border_radius = 6, + font_family = "\"Open Sans\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif", + font_size = 12, + font_weight = 400, + padding = "10px 12px 8px 12px", + shadow = TRUE, + shadow_color = "rgba(0, 0, 0, 0.35)", + shadow_size = 10, + title_size = 13, + title_weight = 600, + value_size = 12, + value_weight = 500, + # accent_color drives active/thumb/play/bar colors unless overridden. + accent_color = "#8cc8ff", + play_button_background = "rgba(255, 255, 255, 0.08)", + play_button_border_color = "rgba(255, 255, 255, 0.22)", + track_color = "rgba(255, 255, 255, 0.22)", + track_height = 4, + thumb_border_color = "#10151d", + thumb_size = 15, + histogram_height = 46, + histogram_active_opacity = 1, + histogram_inactive_opacity = 0.24 + ), + NULL + ) +} + +mapgl_normalize_slider_style <- function(x, arg = "slider_style") { + if (is.null(x)) { + return(NULL) + } + if (is.character(x) && length(x) == 1 && !is.na(x)) { + x <- slider_style(preset = x) + } + if (!inherits(x, "mapgl_slider_style")) { + rlang::abort(paste0( + "`", + arg, + "` must be a preset string (\"light\", \"dark\", or \"auto\") or a ", + "`slider_style()` object." + )) + } + + preset <- x$preset + base <- list() + if (!is.null(preset)) { + if (identical(preset, "auto")) { + preset <- "light" + } + base <- mapgl_slider_style_preset(preset) + if (is.null(base)) { + rlang::abort(sprintf("Unknown slider style preset \"%s\".", preset)) + } + } + + overrides <- x[setdiff(names(x), "preset")] + spec <- utils::modifyList(base, overrides) + if (length(spec) == 0) { + return(NULL) + } + spec +} + +#' Add a slider control to a map +#' +#' Adds an interactive slider to a Mapbox GL or MapLibre GL map that +#' steps through a sequence of values and filters one or more layers by +#' a numeric feature property. Works source-agnostically: GeoJSON, +#' vector tile, and PMTiles layers all compose through the same filter +#' pipeline. Optional play button animates through the steps; +#' `"cumulative"` mode accumulates features through the range rather +#' than swapping them. +#' +#' Values commonly represent time (years, months, epoch seconds) but +#' need not — any monotonic numeric sequence works (magnitude +#' thresholds, percentile coverage, depth bins, etc.). +#' +#' The slider composes with other filter sources rather than replacing +#' them: a layer's initial `filter =` argument, a subsequent +#' [set_filter()] call, and an interactive [add_legend()] can all be +#' active at the same time as the slider, and the layer's resolved +#' filter is the `["all", ...]` intersection. +#' +#' @section Date and time values: +#' The slider requires numeric values. Because `sf` objects are +#' serialized to GeoJSON via `geojsonsf::sf_geojson()`, `Date` and +#' `POSIXct` columns become JSON strings, not numbers — so you must +#' pre-coerce your time column to numeric before adding the layer. Use +#' [as_time_property()] for the common cases (year, month index, epoch +#' seconds, days-since-epoch). +#' +#' @section Positioning and collisions: +#' The slider is implemented as a native control and stacks beside +#' other native controls (navigation, scale, geolocate, fullscreen) via +#' Mapbox/MapLibre's built-in positioning. Overlays such as +#' [add_legend()] and [add_layers_control()] are absolutely-positioned +#' and do not participate in that flow — placing a slider in the same +#' corner as a legend will overlap it. Choose a different corner or +#' adjust the overlay's margins. +#' +#' @param map A map object created by [mapboxgl()] or [maplibre()], or a +#' proxy object from [mapboxgl_proxy()] / [maplibre_proxy()]. +#' @param layers Character vector of layer IDs the slider should affect. +#' Layers need not exist yet — if a matching layer is added later via +#' proxy, the slider's current filter and/or paint expression is +#' applied on its first paint. +#' @param property Name of the numeric feature property to filter on. +#' Optional: if `NULL`, no filter behavior. At least one of `property` +#' or `paint_property` must be supplied. +#' @param time_unit Optional. Only consequential when a target layer is a +#' flowmap (`add_flowmap()`): ordinary layers filter on the numeric +#' `property` directly, but flowmap layers need an absolute timestamp +#' range, so in `"window"` mode the numeric value is converted to a +#' flowmap time range using this unit. One of `"seconds"`, `"date"`, or +#' `"year"` (the absolute units produced by [as_time_property()]). +#' `"month"`/`"day"` are calendar indices, not instants, and cannot +#' drive a flowmap window. +#' @param values Numeric vector of steps. Required unless `min` and +#' `max` are supplied. +#' @param labels Optional character vector of display labels (one per +#' value). When omitted, labels default to `as.character(values)`, except +#' when `time_unit` is `"seconds"` or `"date"`: then the numeric values are +#' formatted back into readable timestamps (`"%Y-%m-%d %H:%M"` in UTC for +#' seconds, `"%Y-%m-%d"` for dates) so a time-driven slider does not display +#' raw epoch numbers. Pass an explicit vector to localize or change the +#' format. +#' @param min,max,step Numeric range specification used when `values` is +#' not supplied. `values` is generated via `seq(min, max, by = step)`. +#' @param mode One of `"sequential"` (default) — each step shows only +#' features matching that exact value; `"cumulative"` — shows +#' everything up through the current value; or `"window"` — shows a +#' moving `[start, end]` range (the end is the current value). Window +#' mode emits a range filter for ordinary layers and a +#' `selectedTimeRange` for flowmap layers, making it the mode used to +#' drive temporal flowmaps. Only applies when `property` is set. +#' @param window Only used when `mode = "window"`. `NULL` (default) makes +#' a cumulative range `[min(values), T]`; a positive number makes a +#' sliding window `[T - window, T]`, where `window` is expressed in the +#' same units as `values` (e.g. for [as_time_property()] `unit = +#' "date"`, `window = 7` is a 7-day window). +#' @param presentation Visual style of the control. `"compact"` (default) is +#' a small slider (optionally with a density strip behind it). `"timeline"` +#' renders a prominent, brushable histogram as the control itself -- drag the +#' selected window across the bars, or drag its edges to resize it (as in +#' FlowMapBlue's time control). `"timeline"` requires histogram data +#' (`counts` or `histogram_data`) and implies `histogram = TRUE`. +#' @param window_behavior Only used when `mode = "window"`. `"auto"` (default) +#' uses a fixed-duration window when `window` is supplied and a resizable +#' range otherwise. `"fixed"` pins the window width to `window` and moves the +#' whole `[end - window, end]` band. `"resizable"` lets the user drag either +#' edge to resize the selected range. +#' @param histogram Logical; if `TRUE`, draw a density strip behind the +#' slider showing how many features fall at each value (a data-density +#' backdrop, most useful with `mode = "window"` where the selected band +#' highlights the covered bars). Loads d3 on demand. Supply the bar +#' heights via `counts` or `histogram_data`. Default `FALSE`. +#' @param histogram_data Numeric vector of the raw property values across +#' your features; binned in R to the nearest `values` step to produce +#' the histogram bar heights. Use this when you have the underlying data +#' to hand. Ignored unless `histogram = TRUE`. +#' @param counts Numeric vector of pre-computed bar heights, one per +#' `values`. An alternative to `histogram_data` when you already have +#' per-step counts. Ignored unless `histogram = TRUE`. +#' @param initial_value Value to start on. In `"window"` mode this is the +#' window end value and defaults to the last value; other modes default +#' to the first value. +#' @param paint_property Optional Mapbox paint property the slider +#' should animate, supplied in snake_case to match the rest of the +#' package (e.g. `"fill_color"`, `"fill_extrusion_height"`, +#' `"circle_radius"`). Kebab-case is also accepted for convenience +#' when copying from Mapbox docs. Shortcut for the single-property +#' case; when set, `paint_expressions` must also be supplied. For +#' animating more than one paint property together (e.g. height *and* +#' color), use `paint_properties` instead. +#' @param paint_expressions List of Mapbox expressions, one per value in +#' `values`. On each step, the expression at the matching index is +#' applied to each target layer via `map.setPaintProperty()`. Build +#' expressions with [interpolate()], [match_expr()], or raw lists. +#' @param paint_properties Optional named list for animating multiple +#' paint properties simultaneously. Shape: +#' `list(fill_color = list(, , ...), fill_extrusion_height = list(...))` +#' — names are snake_case (kebab-case also accepted), each value is a +#' list of expressions the same length as `values`. Cannot be +#' combined with `paint_property`/`paint_expressions`. Each property's +#' pre-slider value is captured on mount and restored on removal, +#' independently. +#' @param play_button Logical; include a play/pause button next to the +#' slider. Default `FALSE`. +#' @param animation_duration Milliseconds to wait between steps while +#' playing. Default `1000`. +#' @param loop Logical; when playback reaches the last value, return to +#' the first. Default `TRUE`. +#' @param title Optional title shown above the slider. +#' @param show_value Logical; show the current label beside the slider. +#' Default `TRUE`. +#' @param slider_style Optional appearance for the slider: a preset string +#' (`"light"`, `"dark"`, or `"auto"`) or a [slider_style()] object. When +#' omitted, the legacy `width`, `background_color`, `text_color`, and +#' `accent_color` arguments are used. +#' @param width Slider container width in pixels. Default `280`. +#' @param position One of `"top-left"`, `"top-right"`, `"bottom-left"`, +#' `"bottom-right"`. Default `"top-left"`. +#' @param draggable Logical, whether the slider panel can be dragged to a new +#' position on the map by the user. Default `FALSE`, keeping it docked at +#' `position`. +#' @param background_color,text_color,accent_color Styling overrides. +#' Defaults match the package's other controls. For full control of the +#' slider appearance, use `slider_style`. +#' +#' @return The modified map or proxy object, invisibly. +#' +#' @examples +#' \dontrun{ +#' library(mapgl) +#' library(sf) +#' +#' quakes <- sf::read_sf( +#' "https://docs.mapbox.com/mapbox-gl-js/assets/significant-earthquakes-2015.geojson" +#' ) +#' quakes$month <- as.POSIXlt(quakes$time / 1000, origin = "1970-01-01")$mon +#' +#' mapboxgl(center = c(-45, 0), zoom = 0.25) |> +#' add_circle_layer( +#' id = "quakes", +#' source = quakes, +#' circle_color = "#FCA107", +#' circle_radius = 20, +#' circle_opacity = 0.75 +#' ) |> +#' add_slider_control( +#' layers = "quakes", +#' property = "month", +#' values = 0:11, +#' labels = month.name, +#' title = "Significant earthquakes in 2015", +#' play_button = TRUE +#' ) +#' +#' # --- Paint animation: step through a choropleth's color over years +#' # Given an sf object with columns pop2020, pop2021, ..., pop2024: +#' # mapboxgl() |> +#' # add_fill_layer(id = "tracts", source = tracts, fill_opacity = 0.85) |> +#' # add_slider_control( +#' # layers = "tracts", +#' # values = 2020:2024, +#' # paint_property = "fill_color", +#' # paint_expressions = lapply(2020:2024, function(y) { +#' # interpolate( +#' # column = paste0("pop", y), +#' # values = c(0, 5e5, 2e6), +#' # stops = c("#f7f4f9", "#67a9cf", "#02818a") +#' # ) +#' # }), +#' # play_button = TRUE +#' # ) +#' } +#' +#' @seealso [update_slider_control()], [as_time_property()] +#' @export +add_slider_control <- function( + map, + layers, + property = NULL, + time_unit = NULL, + values = NULL, + labels = NULL, + min = NULL, + max = NULL, + step = 1, + mode = c("sequential", "cumulative", "window"), + window = NULL, + presentation = c("compact", "timeline"), + window_behavior = c("auto", "resizable", "fixed"), + histogram = FALSE, + histogram_data = NULL, + counts = NULL, + initial_value = NULL, + paint_property = NULL, + paint_expressions = NULL, + paint_properties = NULL, + play_button = FALSE, + animation_duration = 1000, + loop = TRUE, + title = NULL, + show_value = TRUE, + slider_style = NULL, + width = 280, + position = "top-left", + draggable = FALSE, + background_color = "#ffffffcc", + text_color = "#404040", + accent_color = "#4a90e2" +) { + # ---- arg validation ------------------------------------------------- + mode <- match.arg(mode) + presentation <- match.arg(presentation) + window_behavior <- match.arg(window_behavior) + + if (!is.character(layers) || length(layers) == 0) { + rlang::abort("`layers` must be a non-empty character vector of layer IDs.") + } + + # Normalize paint property names: users supply snake_case to match + # the rest of the package (e.g. `fill_extrusion_height`), and we + # translate to the kebab-case Mapbox wire format (e.g. + # `fill-extrusion-height`). Kebab-case is also accepted for users + # copying straight from Mapbox docs — the replacement is idempotent. + to_mapbox_name <- function(x) gsub("_", "-", x) + + # Normalize single-property form into the multi-property shape so one + # validation and serialization path handles both. After this block, + # `paint_spec` is either NULL (no paint behavior) or a named list + # `list("fill-color" = list(...), "fill-extrusion-height" = ...)` + # with each value a list of length == length(values) and keys in + # Mapbox kebab-case. + using_single <- !is.null(paint_property) || !is.null(paint_expressions) + using_multi <- !is.null(paint_properties) + if (using_single && using_multi) { + rlang::abort(c( + "Supply either `paint_property`+`paint_expressions` or `paint_properties`, not both.", + i = "`paint_properties` is a named list shaped `list(fill_color = list(...), fill_extrusion_height = list(...))` and covers the multi-property case on its own." + )) + } + paint_spec <- NULL + if (using_single) { + if (is.null(paint_property) || is.null(paint_expressions)) { + rlang::abort( + "`paint_property` and `paint_expressions` must be supplied together." + ) + } + if ( + !is.character(paint_property) || + length(paint_property) != 1 || + nchar(paint_property) == 0 + ) { + rlang::abort("`paint_property` must be a single non-empty string.") + } + if (!is.list(paint_expressions)) { + rlang::abort( + "`paint_expressions` must be a list, one expression per value (use `list()`, not `c()`)." + ) + } + paint_spec <- stats::setNames( + list(paint_expressions), + to_mapbox_name(paint_property) + ) + } else if (using_multi) { + if (!is.list(paint_properties) || length(paint_properties) == 0) { + rlang::abort( + "`paint_properties` must be a non-empty named list (property name -> list of expressions)." + ) + } + prop_names <- names(paint_properties) + if (is.null(prop_names) || any(!nzchar(prop_names))) { + rlang::abort( + "`paint_properties` must be a named list with non-empty names, e.g. `list(fill_extrusion_height = list(...), fill_extrusion_color = list(...))`." + ) + } + normalized_names <- to_mapbox_name(prop_names) + if (any(duplicated(normalized_names))) { + rlang::abort( + "`paint_properties` names must be unique after snake_case -> kebab-case normalization." + ) + } + for (pn in prop_names) { + if (!is.list(paint_properties[[pn]])) { + rlang::abort( + sprintf( + "`paint_properties[[%s]]` must be a list of expressions (one per value).", + dQuote(pn, FALSE) + ) + ) + } + } + paint_spec <- stats::setNames(paint_properties, normalized_names) + } + + # At least one behavior must be configured: filter (property) or paint + # (paint_spec). Both can be active simultaneously. + has_filter <- !is.null(property) + has_paint <- !is.null(paint_spec) + if (!has_filter && !has_paint) { + rlang::abort(c( + "Slider has no effect configured.", + i = "Set `property` to drive a filter, or `paint_property`+`paint_expressions` (or `paint_properties`) to drive paint, or both." + )) + } + + if (has_filter) { + if ( + !is.character(property) || length(property) != 1 || nchar(property) == 0 + ) { + rlang::abort("`property` must be a single non-empty string.") + } + } + + # ---- window mode + time_unit --------------------------------------- + # `window` defines a moving [start, end] range instead of a point. + # The end is the current value T; the start is min(values) when + # `window` is NULL (cumulative range) or T - window (sliding range). + if (!is.null(window)) { + if (mode != "window") { + rlang::abort('`window` only applies when `mode = "window"`.') + } + if ( + !is.numeric(window) || + length(window) != 1 || + !is.finite(window) || + window <= 0 + ) { + rlang::abort("`window` must be a single positive number.") + } + } + if (mode == "window" && !has_filter) { + rlang::abort('`mode = "window"` requires `property` (range filtering needs a property to filter on).') + } + if (window_behavior == "auto") { + window_behavior <- if (mode == "window" && !is.null(window)) { + "fixed" + } else { + "resizable" + } + } + if (window_behavior == "fixed" && mode != "window") { + rlang::abort('`window_behavior = "fixed"` only applies when `mode = "window"`.') + } + if (window_behavior == "fixed" && is.null(window)) { + rlang::abort('`window_behavior = "fixed"` requires a positive `window` duration.') + } + + # The timeline presentation IS the histogram (you brush on it), so it + # implies the density data and turns the histogram on. + if (presentation == "timeline") { + if (is.null(counts) && is.null(histogram_data)) { + rlang::abort(c( + '`presentation = "timeline"` needs the bar data to draw the brushable histogram.', + i = "Supply `counts` (one per value) or `histogram_data` (raw values to bin)." + )) + } + histogram <- TRUE + } + + # `time_unit` is only consequential when a target layer is a flowmap: + # ordinary layers filter on the numeric property directly, but flowmap + # layers need an absolute timestamp range, so the JS side converts the + # numeric value to epoch-ms using this unit. Absolute units only + # (year/date/seconds); month/day are indices, not instants. + if (!is.null(time_unit)) { + time_unit <- match.arg( + time_unit, + c("year", "month", "day", "date", "seconds") + ) + } + absolute_units <- c("year", "date", "seconds") + + # Early validation against recorded flowmap ids (init path only; for + # proxy / late-added layers the JS guard handles it). A flowmap target + # in window mode needs an absolute time_unit to build selectedTimeRange. + flowmap_ids <- character(0) + if (!is.null(map$x) && !is.null(map$x$flowmaps)) { + flowmap_ids <- vapply( + map$x$flowmaps, + function(f) if (is.null(f$id)) NA_character_ else as.character(f$id), + character(1) + ) + flowmap_ids <- flowmap_ids[!is.na(flowmap_ids)] + } + if ( + mode == "window" && + length(intersect(layers, flowmap_ids)) > 0 && + (is.null(time_unit) || !time_unit %in% absolute_units) + ) { + rlang::abort(c( + "A flowmap layer is targeted in window mode, but `time_unit` is not an absolute time unit.", + i = 'Set `time_unit` to "seconds", "date", or "year" so the window can be converted to a flowmap time range.', + x = if (is.null(time_unit)) "`time_unit` is NULL." else + sprintf("`time_unit = \"%s\"` is a calendar index, not an instant.", time_unit) + )) + } + + # Build `values` from `min`/`max`/`step` if not supplied. + if (is.null(values)) { + if (is.null(min) || is.null(max)) { + rlang::abort( + "Supply either `values`, or both `min` and `max` (with optional `step`)." + ) + } + values <- seq(min, max, by = step) + } + + if (inherits(values, "Date") || inherits(values, "POSIXct") || inherits(values, "POSIXlt")) { + rlang::abort(c( + "`values` must be numeric; got a Date/POSIXct vector.", + i = "Use `as_time_property()` (or `as.numeric()`) to coerce first, and make sure the matching column in your data is also numeric." + )) + } + if (!is.numeric(values) || length(values) == 0) { + rlang::abort("`values` must be a non-empty numeric vector.") + } + if (any(!is.finite(values))) { + rlang::abort("`values` must be finite.") + } + + if (is.null(labels)) { + labels <- slider_default_labels(values, time_unit) + } else { + if (length(labels) != length(values)) { + rlang::abort("`labels` must have the same length as `values`.") + } + labels <- as.character(labels) + } + + if (is.null(initial_value)) { + # In window mode `initial_value` is the END handle. Default it to the + # last value so a NULL `window` spans the full [min, max] range and a + # sized `window` sits at the most-recent end. Point modes start first. + initial_index <- if (mode == "window") length(values) - 1L else 0L + } else { + matches <- which(values == initial_value) + if (length(matches) == 0) { + rlang::abort("`initial_value` must be one of `values`.") + } + # JS is 0-indexed. + initial_index <- as.integer(matches[1]) - 1L + } + + valid_positions <- c("top-left", "top-right", "bottom-left", "bottom-right") + if (!position %in% valid_positions) { + rlang::abort( + sprintf( + "`position` must be one of %s.", + paste(shQuote(valid_positions), collapse = ", ") + ) + ) + } + + slider_style_spec <- mapgl_normalize_slider_style( + slider_style, + arg = "slider_style" + ) + + # Every paint property's expression list must match `values` length + # (checked after `values` is resolved from `min`/`max`). Applies to + # both the single-form (normalized into paint_spec) and multi-form. + if (!is.null(paint_spec)) { + for (pn in names(paint_spec)) { + if (length(paint_spec[[pn]]) != length(values)) { + rlang::abort( + sprintf( + "Paint expressions for %s must have length %d (one per value); got %d.", + dQuote(pn, FALSE), + length(values), + length(paint_spec[[pn]]) + ) + ) + } + } + } + + # ---- histogram density strip ---------------------------------------- + # An optional d3 density strip drawn behind the slider/range. Binning + # happens here in R against the numeric `values` axis (NOT in JS against + # dates), which is what keeps the bars aligned to the handles and avoids + # the timezone/interval pitfalls of date binning in the browser. + histogram <- isTRUE(histogram) + hist_counts <- NULL + if (histogram) { + if (!is.null(counts)) { + if (!is.numeric(counts) || length(counts) != length(values)) { + rlang::abort( + "`counts` must be a numeric vector with one value per `values`." + ) + } + hist_counts <- as.numeric(counts) + } else if (!is.null(histogram_data)) { + if (!is.numeric(histogram_data)) { + rlang::abort("`histogram_data` must be a numeric vector.") + } + hd <- histogram_data[is.finite(histogram_data)] + sv <- sort(values) + if (length(sv) == 1) { + hist_counts <- length(hd) + } else { + # Nearest-value binning: breaks at the midpoints between sorted + # values so each datum lands on its closest step. + mids <- (sv[-length(sv)] + sv[-1]) / 2 + bin_idx <- findInterval(hd, mids) + 1L + tab <- tabulate(bin_idx, nbins = length(sv)) + # Map sorted-bin counts back to the original `values` order. + hist_counts <- numeric(length(values)) + hist_counts[order(values)] <- tab + } + } else { + rlang::abort(c( + "`histogram = TRUE` needs the bar heights.", + i = "Supply `counts` (one count per `values`) or `histogram_data` (raw numeric values to bin)." + )) + } + } + + # ---- build options payload ------------------------------------------ + # Use I() on numeric vectors so jsonlite does not unbox singleton + # numeric vectors into scalars. jsonlite defaults in htmlwidgets + # serialize length-1 atomic vectors as scalars; `values` may be + # length 1 in edge cases (weird but valid), and must round-trip as an + # array. + options <- list( + layers = as.list(layers), + property = property, + values = as.list(values), + labels = as.list(labels), + mode = mode, + presentation = presentation, + window_behavior = window_behavior, + initial_index = initial_index, + play_button = isTRUE(play_button), + animation_duration = as.integer(animation_duration), + loop = isTRUE(loop), + show_value = isTRUE(show_value), + width = as.integer(width), + position = position, + draggable = isTRUE(draggable), + background_color = background_color, + text_color = text_color, + accent_color = accent_color + ) + if (!is.null(slider_style_spec)) options$slider_style <- slider_style_spec + if (!is.null(title)) options$title <- title + if (!is.null(window)) options$window <- window + if (!is.null(time_unit)) options$time_unit <- time_unit + if (histogram) { + options$histogram <- TRUE + options$counts <- as.list(as.numeric(hist_counts)) + } + if (!is.null(paint_spec)) { + # Serialize as a named list of property -> list-of-expressions. + # The JS side treats this uniformly whether the user supplied the + # single-form or multi-form. + options$paint_properties <- paint_spec + } + + # ---- proxy / initial dispatch --------------------------------------- + if (inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + rlang::abort(c( + "`add_slider_control()` does not support compare proxies in this release.", + i = "Attach the slider to each map individually before creating the compare widget, or open an issue to request compare support." + )) + } + proxy_class <- if (inherits(map, "mapboxgl_proxy")) { + "mapboxgl-proxy" + } else { + "maplibre-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "add_slider_control", + options = options + ) + ) + ) + } else { + if (!is.null(map$x$slider_control)) { + rlang::warn( + "A slider control is already configured on this map; replacing it." + ) + } + map$x$slider_control <- options + # Load d3 on demand only when a histogram is requested (kept out of the + # always-on widget dependencies). Vendored from Egor Kotov's PR #205. + if (histogram) { + d3_dep <- htmltools::htmlDependency( + name = "d3", + version = "7.9.0", + src = c(file = system.file("htmlwidgets/lib/d3", package = "mapgl")), + script = "d3.min.js" + ) + map$dependencies <- c(map$dependencies, list(d3_dep)) + } + } + + return(map) +} + + +#' Update a slider control from Shiny +#' +#' Proxy-only companion to [add_slider_control()]. Moves the slider +#' to a specific value, starts or stops playback, or adjusts playback +#' speed without recreating the control. +#' +#' @param proxy A proxy object from [mapboxgl_proxy()] or +#' [maplibre_proxy()]. +#' @param value Numeric; one of the values the slider was created with. +#' The slider snaps to the closest value if an exact match is not +#' found. +#' @param playing Logical; `TRUE` starts playback, `FALSE` stops. +#' @param animation_duration Milliseconds per step when playing. +#' +#' @return The proxy object, invisibly. +#' @export +update_slider_control <- function( + proxy, + value = NULL, + playing = NULL, + animation_duration = NULL +) { + if (!inherits(proxy, "mapboxgl_proxy") && !inherits(proxy, "maplibre_proxy")) { + rlang::abort( + "`update_slider_control()` must be called on a mapboxgl_proxy or maplibre_proxy." + ) + } + if ( + inherits(proxy, "mapboxgl_compare_proxy") || + inherits(proxy, "maplibre_compare_proxy") + ) { + rlang::abort( + "`update_slider_control()` does not support compare proxies in this release." + ) + } + + options <- list() + if (!is.null(value)) { + if (!is.numeric(value) || length(value) != 1) { + rlang::abort("`value` must be a single numeric value.") + } + options$value <- value + } + if (!is.null(playing)) { + if (!is.logical(playing) || length(playing) != 1) { + rlang::abort("`playing` must be TRUE or FALSE.") + } + options$playing <- playing + } + if (!is.null(animation_duration)) { + options$animation_duration <- as.integer(animation_duration) + } + + proxy_class <- if (inherits(proxy, "mapboxgl_proxy")) { + "mapboxgl-proxy" + } else { + "maplibre-proxy" + } + + proxy$session$sendCustomMessage( + proxy_class, + list( + id = proxy$id, + message = list( + type = "update_slider_control", + options = options + ) + ) + ) + + return(proxy) +} + + +#' Coerce a time column to a numeric property for filtering +#' +#' Helper for preparing a `Date` or `POSIXct` column for use with +#' [add_slider_control()]. Because `sf` objects are serialized to +#' GeoJSON as JSON strings for date/time columns, the slider needs a +#' numeric counterpart to filter on. +#' +#' @param x A `Date`, `POSIXct`, or numeric vector. +#' @param unit One of: +#' * `"year"` — calendar year as integer (e.g. 2026). +#' * `"month"` — zero-based month index (0 = January). +#' * `"day"` — day of month. +#' * `"date"` — days since `1970-01-01`. +#' * `"seconds"` — seconds since the Unix epoch. +#' +#' @return An integer or numeric vector appropriate for attaching to an +#' `sf` object as a new column before calling +#' [add_slider_control()]. +#' +#' @examples +#' dates <- as.Date(c("2015-01-15", "2015-06-30", "2015-12-31")) +#' as_time_property(dates, "month") +#' as_time_property(dates, "year") +#' as_time_property(dates, "date") +#' +#' @export +as_time_property <- function( + x, + unit = c("year", "month", "day", "date", "seconds") +) { + unit <- match.arg(unit) + + posix <- if (inherits(x, "POSIXct") || inherits(x, "POSIXlt")) { + as.POSIXlt(x) + } else if (inherits(x, "Date")) { + as.POSIXlt(x) + } else if (is.numeric(x)) { + # Already numeric — return as-is (user presumably knows what they + # want) and let the switch just pass it through for seconds/date. + if (unit %in% c("seconds", "date")) return(as.numeric(x)) + rlang::abort( + "Numeric input is only supported with unit = \"seconds\" or \"date\"." + ) + } else { + rlang::abort("`x` must be a Date, POSIXct, or numeric vector.") + } + + switch( + unit, + year = as.integer(posix$year + 1900L), + month = as.integer(posix$mon), + day = as.integer(posix$mday), + date = as.numeric(as.Date(posix)), + seconds = as.numeric(as.POSIXct(posix)) + ) +} + +# Build readable default labels when none are supplied. For absolute time +# units the numeric `values` are timestamps (the inverse of as_time_property()), +# so they are formatted back into dates/times rather than shown as raw epoch +# numbers. UTC is used to mirror as_time_property()'s absolute encoding; pass +# an explicit `labels` vector to localize or change the format. +slider_default_labels <- function(values, time_unit = NULL) { + if (is.null(time_unit)) { + return(as.character(values)) + } + + switch( + time_unit, + seconds = format( + as.POSIXct(values, origin = "1970-01-01", tz = "UTC"), + "%Y-%m-%d %H:%M" + ), + date = format( + as.Date(values, origin = "1970-01-01"), + "%Y-%m-%d" + ), + as.character(values) + ) +} diff --git a/R/style_helpers.R b/R/style_helpers.R index fbd8f2e2..67dae54f 100644 --- a/R/style_helpers.R +++ b/R/style_helpers.R @@ -67,6 +67,142 @@ normalize_color_ramps <- function(color_ramps, selected_ramp = NULL, n = NULL) { normalized } +mapgl_validate_color_vector <- function(colors, arg = "`colors`") { + if (!is.character(colors) || length(colors) < 2) { + rlang::abort(paste0( + arg, + " must be a character vector with at least two CSS colors." + )) + } + + if (anyNA(colors) || any(!nzchar(trimws(colors)))) { + rlang::abort(paste0(arg, " must not contain missing or empty values.")) + } + + valid <- vapply(colors, mapgl_is_css_color, logical(1)) + if (!all(valid)) { + rlang::abort(paste0( + arg, + " contains invalid CSS color", + if (sum(!valid) == 1) "" else "s", + ": ", + paste(utils::head(colors[!valid], 5), collapse = ", "), + if (sum(!valid) > 5) ", ..." else "" + )) + } + + colors +} + +mapgl_is_css_color <- function(color) { + color <- trimws(color) + + if (grepl( + "^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$", + color, + perl = TRUE + )) { + return(TRUE) + } + + if (mapgl_is_rgb_css_color(color)) { + return(TRUE) + } + + !inherits( + try(grDevices::col2rgb(color, alpha = TRUE), silent = TRUE), + "try-error" + ) +} + +mapgl_is_rgb_css_color <- function(color) { + parsed <- mapgl_parse_rgb_css_color(color) + !is.null(parsed) +} + +mapgl_parse_rgb_css_color <- function(color) { + match <- regexec( + "^(rgba?)\\((.*)\\)$", + trimws(color), + ignore.case = TRUE, + perl = TRUE + ) + parts <- regmatches(trimws(color), match)[[1]] + if (length(parts) != 3) { + return(NULL) + } + + fun <- tolower(parts[[2]]) + values <- trimws(strsplit(parts[[3]], ",", fixed = TRUE)[[1]]) + expected_length <- if (fun == "rgb") 3 else 4 + if (length(values) != expected_length) { + return(NULL) + } + + channels <- vapply(values[1:3], mapgl_parse_css_channel, numeric(1)) + if (anyNA(channels)) { + return(NULL) + } + + alpha <- 1 + if (fun == "rgba") { + alpha <- mapgl_parse_css_alpha(values[[4]]) + if (is.na(alpha)) { + return(NULL) + } + } + + c(channels, alpha) +} + +mapgl_parse_css_channel <- function(value) { + if (!grepl("^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)%?$", value, perl = TRUE)) { + return(NA_real_) + } + + is_percent <- grepl("%$", value) + parsed <- as.numeric(sub("%$", "", value)) + if (!is.finite(parsed)) { + return(NA_real_) + } + + if (is_percent) { + if (parsed < 0 || parsed > 100) { + return(NA_real_) + } + parsed * 255 / 100 + } else { + if (parsed < 0 || parsed > 255) { + return(NA_real_) + } + parsed + } +} + +mapgl_parse_css_alpha <- function(value) { + if (!grepl("^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)%?$", value, perl = TRUE)) { + return(NA_real_) + } + + is_percent <- grepl("%$", value) + parsed <- as.numeric(sub("%$", "", value)) + if (!is.finite(parsed)) { + return(NA_real_) + } + + if (is_percent) { + if (parsed < 0 || parsed > 100) { + return(NA_real_) + } + parsed / 100 + } else { + if (parsed < 0 || parsed > 1) { + return(NA_real_) + } + parsed + } +} + #' Create an interpolation expression #' #' This function generates an interpolation expression that can be used to style your data. diff --git a/R/tooltips_popups.R b/R/tooltips_popups.R new file mode 100644 index 00000000..2ad10930 --- /dev/null +++ b/R/tooltips_popups.R @@ -0,0 +1,209 @@ +#' Style a tooltip or popup +#' +#' Builds a styling specification for map tooltips and popups, mirroring +#' [legend_style()]. Pass the result -- or simply a preset name like `"dark"` +#' -- to the `tooltip_style` / `popup_style` argument of a layer function or +#' [add_flowmap()]. Start from an optional light/dark `preset` and override any +#' individual properties on top of it. With no styling argument supplied, +#' tooltips keep their default (unstyled) appearance. +#' +#' @param preset Optional base theme: `"light"`, `"dark"`, or `"auto"` (resolve +#' to light or dark from the flowmap dark mode; ordinary layers treat +#' `"auto"` as light). Individual arguments below override the preset. +#' @param background_color CSS color for the tooltip/popup background. +#' @param background_opacity Numeric in `[0, 1]` for the background opacity. +#' @param text_color CSS color for the text. +#' @param border_color CSS color for the border. +#' @param border_width Border width in pixels. +#' @param border_radius Corner radius in pixels. +#' @param font_family CSS `font-family` string. +#' @param font_size Font size in pixels. +#' @param font_weight CSS `font-weight`. +#' @param padding Internal padding in pixels. +#' @param max_width Maximum width as a CSS size (e.g. `"320px"`). +#' @param shadow Logical; whether to draw a drop shadow. +#' @param shadow_color CSS color of the drop shadow. +#' @param shadow_size Blur radius of the drop shadow in pixels. +#' @param position For flowmap tooltips/popups, `"floating"` (cursor-following) +#' or `"anchored"` (pinned to the feature). Ignored by ordinary layers. +#' @param offset For floating flowmap tooltips, a numeric pixel offset or a +#' length-2 numeric `c(x, y)`. +#' +#' @return A list of class `mapgl_tooltip_style`. +#' @export +#' +#' @examples +#' \dontrun{ +#' # A dark preset, tweaked +#' tooltip_style("dark", border_radius = 8, font_size = 13) +#' +#' # Fully custom +#' tooltip_style( +#' background_color = "rgba(20,30,48,0.95)", +#' text_color = "#e6edf3", +#' border_radius = 6 +#' ) +#' } +tooltip_style <- function( + preset = NULL, + background_color = NULL, + background_opacity = NULL, + text_color = NULL, + border_color = NULL, + border_width = NULL, + border_radius = NULL, + font_family = NULL, + font_size = NULL, + font_weight = NULL, + padding = NULL, + max_width = NULL, + shadow = NULL, + shadow_color = NULL, + shadow_size = NULL, + position = NULL, + offset = NULL +) { + if (!is.null(preset)) { + preset <- match.arg(preset, c("light", "dark", "auto")) + } + if (!is.null(position)) { + position <- match.arg(position, c("floating", "anchored")) + } + + style <- list( + preset = preset, + background_color = background_color, + background_opacity = background_opacity, + text_color = text_color, + border_color = border_color, + border_width = border_width, + border_radius = border_radius, + font_family = font_family, + font_size = font_size, + font_weight = font_weight, + padding = padding, + max_width = max_width, + shadow = shadow, + shadow_color = shadow_color, + shadow_size = shadow_size, + position = position, + offset = offset + ) + + style <- style[!vapply(style, is.null, logical(1))] + class(style) <- "mapgl_tooltip_style" + style +} + +#' @rdname tooltip_style +#' @export +popup_style <- function( + preset = NULL, + background_color = NULL, + background_opacity = NULL, + text_color = NULL, + border_color = NULL, + border_width = NULL, + border_radius = NULL, + font_family = NULL, + font_size = NULL, + font_weight = NULL, + padding = NULL, + max_width = NULL, + shadow = NULL, + shadow_color = NULL, + shadow_size = NULL, + position = NULL, + offset = NULL +) { + tooltip_style( + preset = preset, + background_color = background_color, + background_opacity = background_opacity, + text_color = text_color, + border_color = border_color, + border_width = border_width, + border_radius = border_radius, + font_family = font_family, + font_size = font_size, + font_weight = font_weight, + padding = padding, + max_width = max_width, + shadow = shadow, + shadow_color = shadow_color, + shadow_size = shadow_size, + position = position, + offset = offset + ) +} + +# Built-in light/dark presets (Egor Kotov's flowmap.css values, generalized). +mapgl_tooltip_style_preset <- function(name) { + switch( + name, + light = list( + background_color = "rgba(255, 255, 255, 0.96)", + text_color = "#222222", + border_color = "rgba(0, 0, 0, 0.12)", + border_width = 1, + border_radius = 4, + shadow = TRUE, + shadow_color = "rgba(0, 0, 0, 0.16)", + shadow_size = 8, + padding = 8 + ), + dark = list( + background_color = "rgba(35, 35, 35, 0.94)", + text_color = "#ffffff", + border_color = "rgba(255, 255, 255, 0.12)", + border_width = 1, + border_radius = 4, + shadow = TRUE, + shadow_color = "rgba(0, 0, 0, 0.4)", + shadow_size = 8, + padding = 8 + ), + NULL + ) +} + +# Resolve a tooltip/popup style argument (NULL, a preset string, or a +# tooltip_style()/popup_style() object) into a plain serialized spec for JS. +# `dark_mode` resolves an "auto" preset (flowmap passes its resolved dark mode; +# ordinary layers default to light). +mapgl_normalize_tooltip_style <- function(x, dark_mode = FALSE, arg = "tooltip_style") { + if (is.null(x)) { + return(NULL) + } + if (is.character(x) && length(x) == 1 && !is.na(x)) { + x <- tooltip_style(preset = x) + } + if (!inherits(x, "mapgl_tooltip_style")) { + rlang::abort(paste0( + "`", + arg, + "` must be a preset string (\"light\", \"dark\", or \"auto\") or a ", + "`tooltip_style()`/`popup_style()` object." + )) + } + + preset <- x$preset + base <- list() + if (!is.null(preset)) { + if (identical(preset, "auto")) { + preset <- if (isTRUE(dark_mode)) "dark" else "light" + } + base <- mapgl_tooltip_style_preset(preset) + if (is.null(base)) { + rlang::abort(sprintf("Unknown tooltip style preset \"%s\".", preset)) + } + } + + overrides <- x[setdiff(names(x), "preset")] + spec <- utils::modifyList(base, overrides) + if (length(spec) == 0) { + return(NULL) + } + spec +} + diff --git a/R/utils.R b/R/utils.R index 94218257..8191e296 100644 --- a/R/utils.R +++ b/R/utils.R @@ -572,3 +572,35 @@ legend_style <- function( class(style_list) <- "mapgl_legend_style" return(style_list) } + +# Internal function to invoke a method on a map proxy +mapgl_invoke_method <- function(map, type, ...) { + args <- list(...) + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type, map = map$map_side), args) + ) + ) + } else { + proxy_class <- if (inherits(map, "mapboxgl_proxy")) "mapboxgl-proxy" else + "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type), args) + ) + ) + } + } + return(map) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index ce3f8345..d0db0bd2 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -64,6 +64,14 @@ reference: - add_symbol_layer - add_view + - title: "Flow Maps" + desc: "Functions to add and customize origin-destination flow maps" + contents: + - add_flowmap + - set_flowmap_filter + - set_flowmap_settings + - flowmap_color_schemes + - title: "Data Sources" desc: "Functions to add different types of data sources" contents: @@ -92,6 +100,9 @@ reference: - add_screenshot_control - add_coordinates_control - add_control + - add_slider_control + - update_slider_control + - as_time_property - clear_controls - title: "Legends" @@ -130,6 +141,8 @@ reference: - get_column - concat - number_format + - tooltip_style + - popup_style - cluster_options - palette_to_lut @@ -227,3 +240,9 @@ reference: - story_leaflet - story_section - on_section + + - title: "Datasets" + desc: "Bundled example datasets" + contents: + - bixi_locations + - bixi_flows diff --git a/data-raw/flowmap-vendor/README.md b/data-raw/flowmap-vendor/README.md new file mode 100644 index 00000000..62933937 --- /dev/null +++ b/data-raw/flowmap-vendor/README.md @@ -0,0 +1,85 @@ +# FlowmapGL Vendoring + +This directory contains the reproducible npm workspace used to build the +vendored FlowmapGL browser asset shipped with mapgl. + +## Package Developer Workflow + +Most R package development does not need to touch FlowmapGL vendoring. The +package ships the already-built browser asset in +`inst/htmlwidgets/lib/flowmap-gl/`. + +Do not hand-edit files under `inst/htmlwidgets/lib/flowmap-gl/`. They are +generated outputs from this vendoring workspace. + +Run `check` before committing when you changed any FlowmapGL vendoring input, +or when you want to verify the checked-in asset still matches this workspace: + +```sh +data-raw/flowmap-vendor/build-flowmap.sh check +``` + +Run `build` only when intentionally regenerating the vendored FlowmapGL files, +for example after: + +- changing a pinned npm package version in `package.json` +- changing the FlowmapGL bundle entry point in `entry.js` +- changing a patch under `patches/` +- changing metadata or notice generation in `scripts/generate-vendor-metadata.mjs` +- refreshing the npm lockfile intentionally + +Run from the repository root: + +```sh +data-raw/flowmap-vendor/build-flowmap.sh build +data-raw/flowmap-vendor/build-flowmap.sh check +``` + +The build command runs `npm ci`, applies every `patches/*.patch` with +`git apply --check` first, bundles `entry.js` with esbuild, and writes: + +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js.map` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js.map` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json` +- `LICENSE.note` + +The check command rebuilds those files in a temporary directory and fails if +the committed copies differ. + +Commit the vendoring workspace files, the generated files under +`inst/htmlwidgets/lib/flowmap-gl/`, and any tests that verify those outputs. +Do not commit `data-raw/flowmap-vendor/node_modules/`; it is recreated by +`npm ci`. + +The normal supported source for FlowmapGL is the npm release pinned in +`package.json` and `package-lock.json`. The manifest records package tarball +integrity values, npm `gitHead` values where available, and the SHA256 of the +generated browser bundle. + +## Local FlowmapGL Patch + +mapgl adds `flow_temporal_scale_domain` for temporal flowmaps. FlowmapGL 9.3.0 +only supports viewport-adaptive scaling, so mapgl carries +`patches/flowmap-temporal-scale-domain.patch` until upstream provides a native +temporal scale-domain control. + +`adaptiveScalesEnabled` remains spatial: when enabled, scale domains are limited +to flows with endpoints in the current viewport. `temporalScaleDomain` is +temporal: `"selected"` uses selected-time flows for width/color domains and +`"all"` uses all-time flows for comparable widths/colors across time. + +## Patch Failures + +If patch application fails after bumping FlowmapGL, inspect upstream for native +temporal scale-domain support. + +- If upstream supports it, remove the local patch and wire mapgl to the upstream + prop. +- If upstream does not support it, rebase the patch against the new + `FlowmapSelectors` and `FlowmapLayer` internals. + +The acceptance invariant is: rendered flows may remain time-filtered, but +width/color domains must use selected-time flows for `"selected"` and all-time +flows for `"all"`. diff --git a/data-raw/flowmap-vendor/build-flowmap.sh b/data-raw/flowmap-vendor/build-flowmap.sh new file mode 100755 index 00000000..d882dfe4 --- /dev/null +++ b/data-raw/flowmap-vendor/build-flowmap.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +set -euo pipefail + +VENDOR_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT_DIR="$(cd "$VENDOR_DIR/../.." && pwd)" +OUTPUT_DIR="$ROOT_DIR/inst/htmlwidgets/lib/flowmap-gl" +LICENSE_NOTE_PATH="$ROOT_DIR/LICENSE.note" +COMMAND="${1:-build}" +BUNDLE_NAME="flowmap-gl-bundle.min.js" +DEBUG_BUNDLE_NAME="flowmap-gl-bundle.js" +MANIFEST_NAME="flowmap-gl-vendor-manifest.json" +GENERATED_FILES=( + "$DEBUG_BUNDLE_NAME" + "$DEBUG_BUNDLE_NAME.map" + "$BUNDLE_NAME" + "$BUNDLE_NAME.map" + "$MANIFEST_NAME" +) + +usage() { + cat <<'EOF' +Usage: data-raw/flowmap-vendor/build-flowmap.sh [build|check] + +Commands: + build Rebuild the committed FlowmapGL bundle, manifest, and license note. + check Rebuild in a temporary directory and fail if committed outputs differ. +EOF +} + +build_outputs() { + local output_dir="$1" + local license_note_path="$2" + + cd "$VENDOR_DIR" + npm ci --silent + apply_patches + + mkdir -p "$output_dir" + npx esbuild entry.js \ + --bundle \ + --format=iife \ + --outfile="$output_dir/$DEBUG_BUNDLE_NAME" \ + --sourcemap \ + --sources-content=true + normalize_sourcemap "$output_dir/$DEBUG_BUNDLE_NAME.map" + + npx esbuild entry.js \ + --bundle \ + --format=iife \ + --outfile="$output_dir/$BUNDLE_NAME" \ + --minify \ + --sourcemap \ + --sources-content=true + normalize_sourcemap "$output_dir/$BUNDLE_NAME.map" + + node scripts/generate-vendor-metadata.mjs "$output_dir" "$license_note_path" +} + +normalize_sourcemap() { + local sourcemap_path="$1" + + node - "$sourcemap_path" <<'NODE' +const {readFileSync, writeFileSync} = require('node:fs'); + +const sourcemapPath = process.argv[2]; +const marker = 'data-raw/flowmap-vendor/'; +const sourcemap = JSON.parse(readFileSync(sourcemapPath, 'utf8')); + +sourcemap.sources = sourcemap.sources.map((source) => { + const markerIndex = source.indexOf(marker); + if (markerIndex >= 0) { + return source.slice(markerIndex + marker.length); + } + return source; +}); + +writeFileSync(sourcemapPath, `${JSON.stringify(sourcemap)}\n`); +NODE +} + +apply_patches() { + local patches=() + shopt -s nullglob + patches=("$VENDOR_DIR"/patches/*.patch) + shopt -u nullglob + + if ((${#patches[@]} == 0)); then + return 0 + fi + + for patch in "${patches[@]}"; do + git -C "$ROOT_DIR" apply --check --directory="data-raw/flowmap-vendor" "$patch" + done + + for patch in "${patches[@]}"; do + git -C "$ROOT_DIR" apply --directory="data-raw/flowmap-vendor" "$patch" + done +} + +case "$COMMAND" in + build) + build_outputs "$OUTPUT_DIR" "$LICENSE_NOTE_PATH" + ls -lh "$OUTPUT_DIR/$DEBUG_BUNDLE_NAME" "$OUTPUT_DIR/$BUNDLE_NAME" + ;; + check) + TMP_DIR="$(mktemp -d)" + cleanup() { + rm -rf "$TMP_DIR" + } + trap cleanup EXIT + + build_outputs "$TMP_DIR" "$TMP_DIR/LICENSE.note" + for file in "${GENERATED_FILES[@]}"; do + diff -u "$OUTPUT_DIR/$file" "$TMP_DIR/$file" + done + diff -u "$LICENSE_NOTE_PATH" "$TMP_DIR/LICENSE.note" + ;; + -h|--help|help) + usage + ;; + *) + usage >&2 + exit 2 + ;; +esac diff --git a/data-raw/flowmap-vendor/entry.js b/data-raw/flowmap-vendor/entry.js new file mode 100644 index 00000000..1dae7df6 --- /dev/null +++ b/data-raw/flowmap-vendor/entry.js @@ -0,0 +1,9 @@ +import {Deck} from '@deck.gl/core'; +import {MapboxOverlay} from '@deck.gl/mapbox'; +import {FlowmapLayer} from '@flowmap.gl/layers'; + +window.FlowmapGL = { + Deck, + FlowmapLayer, + MapboxOverlay +}; diff --git a/data-raw/flowmap-vendor/package-lock.json b/data-raw/flowmap-vendor/package-lock.json new file mode 100644 index 00000000..a0371e4f --- /dev/null +++ b/data-raw/flowmap-vendor/package-lock.json @@ -0,0 +1,1193 @@ +{ + "name": "mapgl-flowmap-vendor", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mapgl-flowmap-vendor", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@deck.gl/core": "9.3.2", + "@deck.gl/layers": "9.3.2", + "@deck.gl/mapbox": "9.3.2", + "@flowmap.gl/data": "9.3.0", + "@flowmap.gl/layers": "9.3.0", + "@luma.gl/core": "9.3.3", + "@luma.gl/engine": "9.3.3", + "@luma.gl/shadertools": "9.3.3", + "esbuild": "0.28.0" + } + }, + "node_modules/@deck.gl/core": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@deck.gl/core/-/core-9.3.2.tgz", + "integrity": "sha512-32Va3np0Zdlz/LBNtDWCs4EkKqdHmXcbGmVp4+7i1Cpdza8y8CFmJs2VPOmSX1fwHvNCGkAZV/SFZOfDb2INsg==", + "license": "MIT", + "dependencies": { + "@loaders.gl/core": "^4.4.1", + "@loaders.gl/images": "^4.4.1", + "@luma.gl/core": "^9.3.3", + "@luma.gl/engine": "^9.3.3", + "@luma.gl/shadertools": "^9.3.3", + "@luma.gl/webgl": "^9.3.3", + "@math.gl/core": "^4.1.0", + "@math.gl/sun": "^4.1.0", + "@math.gl/types": "^4.1.0", + "@math.gl/web-mercator": "^4.1.0", + "@probe.gl/env": "^4.1.1", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1", + "@types/offscreencanvas": "^2019.6.4", + "gl-matrix": "^3.0.0", + "mjolnir.js": "^3.0.0" + } + }, + "node_modules/@deck.gl/layers": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@deck.gl/layers/-/layers-9.3.2.tgz", + "integrity": "sha512-TeVfhQ/cQU1oTlTn16mCp7268d1uBJ6dwfgmKXThe2TzW9hql3iJaxbYTKg2phDg5YSiGmeEOpXbeBh59jyUcA==", + "license": "MIT", + "dependencies": { + "@loaders.gl/images": "^4.4.1", + "@loaders.gl/schema": "^4.4.1", + "@luma.gl/shadertools": "^9.3.3", + "@mapbox/tiny-sdf": "^2.0.5", + "@math.gl/core": "^4.1.0", + "@math.gl/polygon": "^4.1.0", + "@math.gl/web-mercator": "^4.1.0", + "earcut": "^2.2.4" + }, + "peerDependencies": { + "@deck.gl/core": "~9.3.0", + "@loaders.gl/core": "^4.4.1", + "@luma.gl/core": "~9.3.3", + "@luma.gl/engine": "~9.3.3" + } + }, + "node_modules/@deck.gl/mapbox": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@deck.gl/mapbox/-/mapbox-9.3.2.tgz", + "integrity": "sha512-+T9pJwsOXwjUxyGN6oiBMfIs28VtDIG1V1Rqz4qqn4TjjNEFFw+xO0olJIg8FO5IAqw2OtePdsrMj0tX8tHdGQ==", + "license": "MIT", + "dependencies": { + "@math.gl/web-mercator": "^4.1.0" + }, + "peerDependencies": { + "@deck.gl/core": "~9.3.0", + "@luma.gl/core": "~9.3.3", + "@math.gl/web-mercator": "^4.1.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", + "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", + "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", + "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", + "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", + "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", + "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", + "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", + "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", + "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", + "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", + "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", + "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", + "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", + "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", + "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", + "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", + "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", + "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", + "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", + "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", + "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", + "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", + "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", + "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", + "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@flowmap.gl/data": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@flowmap.gl/data/-/data-9.3.0.tgz", + "integrity": "sha512-1a4EZJdK13q5Mj3bVurFSpuYVBLSaByJJ9B4LMd7XvuD/ovB6JArDjdJetsA9jVHdA89lZli7f8ALX+oek+WtA==", + "license": "Apache-2.0", + "dependencies": { + "d3-array": "^3.2.4", + "d3-color": "^3.1.0", + "d3-geo": "^3.1.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-scale-chromatic": "^3.1.0", + "d3-time": "^3.1.0", + "d3-time-format": "^4.1.0", + "kdbush": "^4.0.2", + "reselect": "^5.1.1", + "seedrandom": "^3.0.5" + } + }, + "node_modules/@flowmap.gl/layers": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@flowmap.gl/layers/-/layers-9.3.0.tgz", + "integrity": "sha512-kARLb28BYK58O4iuiZK0IdNO+W1EX4+MaLbufRU1O0LTMM0Aoe2lET7y4QcrOifQT0dV6cAjzjw4GDnbogOxJg==", + "license": "Apache-2.0", + "dependencies": { + "@flowmap.gl/data": "^9.3.0" + }, + "peerDependencies": { + "@deck.gl/core": "^9.0.0", + "@deck.gl/layers": "^9.0.0", + "@luma.gl/core": "^9.0.0", + "@luma.gl/engine": "^9.0.0", + "@luma.gl/shadertools": "^9.0.0" + } + }, + "node_modules/@loaders.gl/core": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/core/-/core-4.4.2.tgz", + "integrity": "sha512-DZmsTwxdKh3q+mS1vSOW2EXFgwxZ4nIBte4H5g6e4VyQoQ6jAOkk0M6V+Asgy/eqjGTNjhfBA1HIkyBl0A9hcA==", + "license": "MIT", + "dependencies": { + "@loaders.gl/loader-utils": "4.4.2", + "@loaders.gl/schema": "4.4.2", + "@loaders.gl/schema-utils": "4.4.2", + "@loaders.gl/worker-utils": "4.4.2", + "@probe.gl/log": "^4.1.1" + } + }, + "node_modules/@loaders.gl/images": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/images/-/images-4.4.2.tgz", + "integrity": "sha512-b+1keNvPlyLniWtX4ZaThz2dF2aohi8Q+OEsDF2hJNZYyZJOqP9b/72UhlVk+inxTJfTLRBNARs2TJ2ssBlelg==", + "license": "MIT", + "dependencies": { + "@loaders.gl/loader-utils": "4.4.2" + }, + "peerDependencies": { + "@loaders.gl/core": "~4.4.0" + } + }, + "node_modules/@loaders.gl/loader-utils": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/loader-utils/-/loader-utils-4.4.2.tgz", + "integrity": "sha512-kqwBbyRC7rrQVsnJyKeoaig9hxaa5oj91OKqWm27HPuVn4q2dD67SEhiG0ND62eRp0tLY6jTqEcI5kDzHBZ6MA==", + "license": "MIT", + "dependencies": { + "@loaders.gl/schema": "4.4.2", + "@loaders.gl/worker-utils": "4.4.2", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1" + } + }, + "node_modules/@loaders.gl/schema": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema/-/schema-4.4.2.tgz", + "integrity": "sha512-mJTZehTHIFl8ed+03nebuPAMnLP8Yp00DKTzCnKT2HNy/uV4+Sw+GrGIuhPHGU8tdQmtBXRURGM2ZxUAxMfGKg==", + "license": "MIT", + "dependencies": { + "@types/geojson": "^7946.0.7", + "apache-arrow": ">= 17.0.0" + } + }, + "node_modules/@loaders.gl/schema-utils": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema-utils/-/schema-utils-4.4.2.tgz", + "integrity": "sha512-yYYRD/POBEO72rhIyLASrqKUUhfIOQuFk/fgInN6Td2qvFgsHbo5UaCM4sTqVUWwNxNvXDQi8ezpbnCa/yi+OQ==", + "license": "MIT", + "dependencies": { + "@loaders.gl/schema": "4.4.2", + "@types/geojson": "^7946.0.7", + "apache-arrow": ">= 17.0.0" + }, + "peerDependencies": { + "@loaders.gl/core": "~4.4.0" + } + }, + "node_modules/@loaders.gl/worker-utils": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/worker-utils/-/worker-utils-4.4.2.tgz", + "integrity": "sha512-oiZ0SoC1QKrOkhYPlVZ6Q06CtmuFRyZw2rwzmT08ZyaGtOArIJHDjlhxzwWiv+6fdws47Ub5uIGsdI1Ab1xYsA==", + "license": "MIT", + "peerDependencies": { + "@loaders.gl/core": "~4.4.0" + } + }, + "node_modules/@luma.gl/core": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/core/-/core-9.3.3.tgz", + "integrity": "sha512-jCFm2htvrVpcXIy85TBTF1ROgMfknKnfw2OH+Vydr41hiCFd6nqr79gM3f2uhaNkal0BghFNqF3qDioKiUWtew==", + "license": "MIT", + "dependencies": { + "@math.gl/types": "^4.1.0", + "@probe.gl/env": "^4.1.1", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1", + "@types/offscreencanvas": "^2019.7.3" + } + }, + "node_modules/@luma.gl/engine": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/engine/-/engine-9.3.3.tgz", + "integrity": "sha512-StmMTzUcUlpKMU3wvWU48A6OQyphptD9zVGBsSkK6iHIBdtBKlOcmqRkyfvRouo8JHtlrnoJDHLVKhxorwhGAg==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "^4.1.0", + "@math.gl/types": "^4.1.0", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1" + }, + "peerDependencies": { + "@luma.gl/core": "~9.3.0", + "@luma.gl/shadertools": "~9.3.0" + } + }, + "node_modules/@luma.gl/shadertools": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/shadertools/-/shadertools-9.3.3.tgz", + "integrity": "sha512-4ZfG4/Utix951vqyiG/JIx+Eg+GMNwOxgr/07/i0gf7bK1gJZIEQ5BxVcDw4MCQfdoVlGPGzl0cQKbdqBvaCAQ==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "^4.1.0", + "@math.gl/types": "^4.1.0" + }, + "peerDependencies": { + "@luma.gl/core": "~9.3.0" + } + }, + "node_modules/@luma.gl/webgl": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/webgl/-/webgl-9.3.3.tgz", + "integrity": "sha512-X+aavdP5o6VFHSA0es9gKZTT145jfcFbhKJt/gwJrptnKNoIW4+Y37ZEpCo1AzAnr+FQCxjgcM2kOCpoWMfSVA==", + "license": "MIT", + "dependencies": { + "@math.gl/types": "^4.1.0", + "@probe.gl/env": "^4.1.1" + }, + "peerDependencies": { + "@luma.gl/core": "~9.3.0" + } + }, + "node_modules/@mapbox/tiny-sdf": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz", + "integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==", + "license": "BSD-2-Clause" + }, + "node_modules/@math.gl/core": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/core/-/core-4.1.0.tgz", + "integrity": "sha512-FrdHBCVG3QdrworwrUSzXIaK+/9OCRLscxI2OUy6sLOHyHgBMyfnEGs99/m3KNvs+95BsnQLWklVfpKfQzfwKA==", + "license": "MIT", + "dependencies": { + "@math.gl/types": "4.1.0" + } + }, + "node_modules/@math.gl/polygon": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/polygon/-/polygon-4.1.0.tgz", + "integrity": "sha512-YA/9PzaCRHbIP5/0E9uTYrqe+jsYTQoqoDWhf6/b0Ixz8bPZBaGDEafLg3z7ffBomZLacUty9U3TlPjqMtzPjA==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "4.1.0" + } + }, + "node_modules/@math.gl/sun": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/sun/-/sun-4.1.0.tgz", + "integrity": "sha512-i3q6OCBLSZ5wgZVhXg+X7gsjY/TUtuFW/2KBiq/U1ypLso3S4sEykoU/MGjxUv1xiiGtr+v8TeMbO1OBIh/HmA==", + "license": "MIT" + }, + "node_modules/@math.gl/types": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/types/-/types-4.1.0.tgz", + "integrity": "sha512-clYZdHcmRvMzVK5fjeDkQlHUzXQSNdZ7s4xOqC3nJPgz4C/TZkUecTo9YS4PruZqtDda/ag4erndP0MIn40dGA==", + "license": "MIT" + }, + "node_modules/@math.gl/web-mercator": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/web-mercator/-/web-mercator-4.1.0.tgz", + "integrity": "sha512-HZo3vO5GCMkXJThxRJ5/QYUYRr3XumfT8CzNNCwoJfinxy5NtKUd7dusNTXn7yJ40UoB8FMIwkVwNlqaiRZZAw==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "4.1.0" + } + }, + "node_modules/@probe.gl/env": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@probe.gl/env/-/env-4.1.1.tgz", + "integrity": "sha512-+68seNDMVsEegRB47pFA/Ws1Fjy8agcFYXxzorKToyPcD6zd+gZ5uhwoLd7TzsSw6Ydns//2KEszWn+EnNHTbA==", + "license": "MIT" + }, + "node_modules/@probe.gl/log": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@probe.gl/log/-/log-4.1.1.tgz", + "integrity": "sha512-kcZs9BT44pL7hS1OkRGKYRXI/SN9KejUlPD+BY40DguRLzdC5tLG/28WGMyfKdn/51GT4a0p+0P8xvDn1Ez+Kg==", + "license": "MIT", + "dependencies": { + "@probe.gl/env": "4.1.1" + } + }, + "node_modules/@probe.gl/stats": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@probe.gl/stats/-/stats-4.1.1.tgz", + "integrity": "sha512-4VpAyMHOqydSvPlEyHwXaE+AkIdR03nX+Qhlxsk2D/IW4OVmDZgIsvJB1cDzyEEtcfKcnaEbfXeiPgejBceT6g==", + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.23", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@types/command-line-args": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.3.tgz", + "integrity": "sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==", + "license": "MIT" + }, + "node_modules/@types/command-line-usage": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.4.tgz", + "integrity": "sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==", + "license": "MIT" + }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.12.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz", + "integrity": "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/offscreencanvas": { + "version": "2019.7.3", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz", + "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==", + "license": "MIT" + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/apache-arrow": { + "version": "21.1.0", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.1.0.tgz", + "integrity": "sha512-kQrYLxhC+NTVVZ4CCzGF6L/uPVOzJmD1T3XgbiUnP7oTeVFOFgEUu6IKNwCDkpFoBVqDKQivlX4RUFqqnWFlEA==", + "license": "Apache-2.0", + "dependencies": { + "@swc/helpers": "^0.5.11", + "@types/command-line-args": "^5.2.3", + "@types/command-line-usage": "^5.0.4", + "@types/node": "^24.0.3", + "command-line-args": "^6.0.1", + "command-line-usage": "^7.0.1", + "flatbuffers": "^25.1.24", + "json-bignum": "^0.0.3", + "tslib": "^2.6.2" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/array-back": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.3.tgz", + "integrity": "sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk-template": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "license": "MIT", + "dependencies": { + "chalk": "^4.1.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/command-line-args": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-6.0.2.tgz", + "integrity": "sha512-AIjYVxrV9X752LmPDLbVYv8aMCuHPSLZJXEo2qo/xJfv+NYhaZ4sMSF01rM+gHPaMgvPM0l5D/F+Qx+i2WfSmQ==", + "license": "MIT", + "dependencies": { + "array-back": "^6.2.3", + "find-replace": "^5.0.2", + "lodash.camelcase": "^4.3.0", + "typical": "^7.3.0" + }, + "engines": { + "node": ">=12.20" + }, + "peerDependencies": { + "@75lb/nature": "latest" + }, + "peerDependenciesMeta": { + "@75lb/nature": { + "optional": true + } + } + }, + "node_modules/command-line-usage": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.4.tgz", + "integrity": "sha512-85UdvzTNx/+s5CkSgBm/0hzP80RFHAa7PsfeADE5ezZF3uHz3/Tqj9gIKGT9PTtpycc3Ua64T0oVulGfKxzfqg==", + "license": "MIT", + "dependencies": { + "array-back": "^6.2.2", + "chalk-template": "^0.4.0", + "table-layout": "^4.1.1", + "typical": "^7.3.0" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-interpolate": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/earcut": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/earcut/-/earcut-2.2.4.tgz", + "integrity": "sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==", + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.0", + "@esbuild/android-arm": "0.28.0", + "@esbuild/android-arm64": "0.28.0", + "@esbuild/android-x64": "0.28.0", + "@esbuild/darwin-arm64": "0.28.0", + "@esbuild/darwin-x64": "0.28.0", + "@esbuild/freebsd-arm64": "0.28.0", + "@esbuild/freebsd-x64": "0.28.0", + "@esbuild/linux-arm": "0.28.0", + "@esbuild/linux-arm64": "0.28.0", + "@esbuild/linux-ia32": "0.28.0", + "@esbuild/linux-loong64": "0.28.0", + "@esbuild/linux-mips64el": "0.28.0", + "@esbuild/linux-ppc64": "0.28.0", + "@esbuild/linux-riscv64": "0.28.0", + "@esbuild/linux-s390x": "0.28.0", + "@esbuild/linux-x64": "0.28.0", + "@esbuild/netbsd-arm64": "0.28.0", + "@esbuild/netbsd-x64": "0.28.0", + "@esbuild/openbsd-arm64": "0.28.0", + "@esbuild/openbsd-x64": "0.28.0", + "@esbuild/openharmony-arm64": "0.28.0", + "@esbuild/sunos-x64": "0.28.0", + "@esbuild/win32-arm64": "0.28.0", + "@esbuild/win32-ia32": "0.28.0", + "@esbuild/win32-x64": "0.28.0" + } + }, + "node_modules/find-replace": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-5.0.2.tgz", + "integrity": "sha512-Y45BAiE3mz2QsrN2fb5QEtO4qb44NcS7en/0y9PEVsg351HsLeVclP8QPMH79Le9sH3rs5RSwJu99W0WPZO43Q==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@75lb/nature": "latest" + }, + "peerDependenciesMeta": { + "@75lb/nature": { + "optional": true + } + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/gl-matrix": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz", + "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==", + "license": "MIT" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/json-bignum": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/kdbush": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz", + "integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==", + "license": "ISC" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" + }, + "node_modules/mjolnir.js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mjolnir.js/-/mjolnir.js-3.0.0.tgz", + "integrity": "sha512-siX3YCG7N2HnmN1xMH3cK4JkUZJhbkhRFJL+G5N1vH0mh1t5088rJknIoqDFWDIU6NPGvRRgLnYW3ZHjSMEBLA==", + "license": "MIT" + }, + "node_modules/reselect": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz", + "integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==", + "license": "MIT" + }, + "node_modules/seedrandom": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==", + "license": "MIT" + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/table-layout": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz", + "integrity": "sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==", + "license": "MIT", + "dependencies": { + "array-back": "^6.2.2", + "wordwrapjs": "^5.1.0" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/typical": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.3.0.tgz", + "integrity": "sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/wordwrapjs": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.1.tgz", + "integrity": "sha512-0yweIbkINJodk27gX9LBGMzyQdBDan3s/dEAiwBOj+Mf0PPyWL6/rikalkv8EeD0E8jm4o5RXEOrFTP3NXbhJg==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + } + } +} diff --git a/data-raw/flowmap-vendor/package.json b/data-raw/flowmap-vendor/package.json new file mode 100644 index 00000000..9d0d8fae --- /dev/null +++ b/data-raw/flowmap-vendor/package.json @@ -0,0 +1,23 @@ +{ + "name": "mapgl-flowmap-vendor", + "version": "1.0.0", + "private": true, + "description": "Reproducible vendoring workspace for the mapgl FlowmapGL browser bundle.", + "license": "MIT", + "type": "module", + "scripts": { + "build": "./build-flowmap.sh build", + "check": "./build-flowmap.sh check" + }, + "dependencies": { + "@deck.gl/core": "9.3.2", + "@deck.gl/layers": "9.3.2", + "@deck.gl/mapbox": "9.3.2", + "@flowmap.gl/data": "9.3.0", + "@flowmap.gl/layers": "9.3.0", + "@luma.gl/core": "9.3.3", + "@luma.gl/engine": "9.3.3", + "@luma.gl/shadertools": "9.3.3", + "esbuild": "0.28.0" + } +} diff --git a/data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch b/data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch new file mode 100644 index 00000000..886d79e3 --- /dev/null +++ b/data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch @@ -0,0 +1,263 @@ +diff --git a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts +index 92cc7ab..746013c 100644 +--- a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts ++++ b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts +@@ -1,6 +1,6 @@ + import { ScaleLinear } from 'd3-scale'; + import FlowmapAggregateAccessors from './FlowmapAggregateAccessors'; +-import { FlowmapState } from './FlowmapState'; ++import { FlowmapState, TemporalScaleDomain } from './FlowmapState'; + import { ClusterIndex, LocationWeightGetter } from './cluster/ClusterIndex'; + import { ColorsRGBA, DiffColorsRGBA } from './colors'; + import { TimeGranularityKey } from './time'; +@@ -25,6 +25,8 @@ export default class FlowmapSelectors, F extends R + getZoom: (state: FlowmapState, props: FlowmapData) => number | undefined; + getViewport: (state: FlowmapState, props: FlowmapData) => ViewportProps; + getSelectedTimeRange: (state: FlowmapState, props: FlowmapData) => [Date, Date] | undefined; ++ getSelectedTimeRanges: (state: FlowmapState, props: FlowmapData) => [Date, Date][] | undefined; ++ getTemporalScaleDomain: Selector; + getColorScheme: Selector; + getDarkMode: Selector; + getFadeEnabled: Selector; +@@ -134,7 +136,9 @@ export default class FlowmapSelectors, F extends R + memoize: typeof import("reselect").weakMapMemoize; + }; + getUnknownLocations: Selector | undefined>; ++ getSortedAggregatedFlows: Selector; + getSortedAggregatedFilteredFlows: Selector; ++ getFlowsForScaleDomain: Selector; + getExpandedSelectedLocationsSet: Selector | undefined>; + getTotalCountsByTime: Selector; + getMaxLocationCircleSize: Selector; +diff --git a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js +index 3892964..0ba65cf 100644 +--- a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js ++++ b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js +@@ -33,6 +33,8 @@ export default class FlowmapSelectors { + this.getZoom = (state, props) => state.viewport.zoom; + this.getViewport = (state, props) => state.viewport; + this.getSelectedTimeRange = (state, props) => state.filter?.selectedTimeRange; ++ this.getSelectedTimeRanges = (state, props) => state.filter?.selectedTimeRanges; ++ this.getTemporalScaleDomain = (state, props) => state.settings.temporalScaleDomain; + this.getColorScheme = (state, props) => state.settings.colorScheme; + this.getDarkMode = (state, props) => state.settings.darkMode; + this.getFadeEnabled = (state, props) => state.settings.fadeEnabled; +@@ -131,17 +133,19 @@ export default class FlowmapSelectors { + const { interval } = timeGranularity; + return [timeExtent[0], interval.offset(interval.floor(timeExtent[1]), 1)]; + }); +- this.getSortedFlowsForKnownLocationsFilteredByTime = createSelector(this.getSortedFlowsForKnownLocations, this.getTimeExtent, this.getSelectedTimeRange, (flows, timeExtent, timeRange) => { ++ this.getSortedFlowsForKnownLocationsFilteredByTime = createSelector(this.getSortedFlowsForKnownLocations, this.getTimeExtent, this.getSelectedTimeRange, this.getSelectedTimeRanges, (flows, timeExtent, timeRange, timeRanges) => { + if (!flows) + return undefined; +- if (!timeExtent || +- !timeRange || +- (timeExtent[0] === timeRange[0] && timeExtent[1] === timeRange[1])) { ++ const selectedRanges = Array.isArray(timeRanges) && timeRanges.length > 0 ? timeRanges : timeRange ? [timeRange] : null; ++ if (!timeExtent || !selectedRanges || selectedRanges.length === 0) { ++ return flows; ++ } ++ if (selectedRanges.length === 1 && timeExtent[0] === selectedRanges[0][0] && timeExtent[1] === selectedRanges[0][1]) { + return flows; + } + return flows.filter((flow) => { + const time = this.accessors.getFlowTime(flow); +- return time && timeRange[0] <= time && time < timeRange[1]; ++ return time && selectedRanges.some((range) => range[0] <= time && time < range[1]); + }); + }); + this.getLocationsHavingFlows = createSelector(this.getSortedFlowsForKnownLocations, this.getLocations, (flows, locations) => { +@@ -296,6 +300,19 @@ export default class FlowmapSelectors { + } + return missing; + }); ++ this.getSortedAggregatedFlows = createSelector(this.getClusterIndex, this.getClusteringEnabled, this.getSortedFlowsForKnownLocations, this.getClusterZoom, (clusterTree, isClusteringEnabled, flows, clusterZoom) => { ++ if (!flows) ++ return undefined; ++ let aggregated; ++ if (isClusteringEnabled && clusterTree && clusterZoom != null) { ++ aggregated = clusterTree.aggregateFlows(flows, clusterZoom, this.accessors.getFlowmapDataAccessors()); ++ } ++ else { ++ aggregated = aggregateFlows(flows, this.accessors.getFlowmapDataAccessors()); ++ } ++ aggregated.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); ++ return aggregated; ++ }); + this.getSortedAggregatedFilteredFlows = createSelector(this.getClusterIndex, this.getClusteringEnabled, this.getSortedFlowsForKnownLocationsFilteredByTime, this.getClusterZoom, this.getTimeExtent, (clusterTree, isClusteringEnabled, flows, clusterZoom, timeExtent) => { + if (!flows) + return undefined; +@@ -314,6 +331,9 @@ export default class FlowmapSelectors { + aggregated.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); + return aggregated; + }); ++ this.getFlowsForScaleDomain = createSelector(this.getTemporalScaleDomain, this.getSortedAggregatedFlows, this.getSortedAggregatedFilteredFlows, (temporalScaleDomain, allFlows, selectedFlows) => { ++ return temporalScaleDomain === 'all' ? allFlows : selectedFlows; ++ }); + this.getExpandedSelectedLocationsSet = createSelector(this.getClusteringEnabled, this.getSelectedLocationsSet, this.getClusterIndex, (clusteringEnabled, selectedLocations, clusterIndex) => { + if (!selectedLocations || !clusterIndex) { + return selectedLocations; +@@ -497,7 +517,7 @@ export default class FlowmapSelectors { + // we need ascending for rendering + return picked.reverse(); + }); +- this._getFlowMagnitudeExtent = createSelector(this.getSortedAggregatedFilteredFlows, this.getSelectedLocationsSet, this.getLocationFilterMode, (flows, selectedLocationsSet, locationFilterMode) => { ++ this._getFlowMagnitudeExtent = createSelector(this.getFlowsForScaleDomain, this.getSelectedLocationsSet, this.getLocationFilterMode, (flows, selectedLocationsSet, locationFilterMode) => { + if (!flows) + return undefined; + let rv = undefined; +@@ -519,10 +539,31 @@ export default class FlowmapSelectors { + } + return rv; + }); +- this._getAdaptiveFlowMagnitudeExtent = createSelector(this.getFlowsForFlowmapLayer, (flows) => { +- if (!flows) ++ this._getAdaptiveFlowMagnitudeExtent = createSelector(this.getFlowsForScaleDomain, this.getLocationIdsInViewport, this.getSelectedLocationsSet, this.getLocationFilterMode, this.getMaxTopFlowsDisplayNum, this.getFlowEndpointsInViewportMode, (flows, locationIdsInViewport, selectedLocationsSet, locationFilterMode, maxTopFlowsDisplayNum, flowEndpointsInViewportMode) => { ++ if (!flows || !locationIdsInViewport) + return undefined; +- const rv = extent(flows, this.accessors.getFlowMagnitude); ++ const picked = []; ++ let pickedCount = 0; ++ for (const flow of flows) { ++ const origin = this.accessors.getFlowOriginId(flow); ++ const dest = this.accessors.getFlowDestId(flow); ++ const originInView = locationIdsInViewport.has(origin); ++ const destInView = locationIdsInViewport.has(dest); ++ const isInViewport = flowEndpointsInViewportMode === 'both' ++ ? originInView && destInView ++ : originInView || destInView; ++ if (isInViewport) { ++ if (this.isFlowInSelection(flow, selectedLocationsSet, locationFilterMode)) { ++ if (origin !== dest) { ++ picked.push(flow); ++ pickedCount++; ++ } ++ } ++ } ++ if (pickedCount > maxTopFlowsDisplayNum) ++ break; ++ } ++ const rv = extent(picked, this.accessors.getFlowMagnitude); + return rv[0] !== undefined && rv[1] !== undefined ? rv : undefined; + }); + this.getFlowMagnitudeExtent = (state, props) => { +@@ -613,8 +654,8 @@ export default class FlowmapSelectors { + this.getLocationOrClusterByIdGetter = createSelector(this.getClusterIndex, this.getLocationsById, (clusterIndex, locationsById) => { + return (id) => clusterIndex?.getClusterById(id) ?? locationsById?.get(id); + }); +- this.getLayersData = createSelector(this.getLocationsForFlowmapLayer, this.getFlowsForFlowmapLayer, this.getFlowmapColorsRGBA, this.getLocationsForFlowmapLayerById, this.getLocationIdsInViewport, this.getInCircleSizeGetter, this.getOutCircleSizeGetter, this.getFlowThicknessScale, this.getViewport, this.getFlowLinesRenderingMode, this.getLocationLabelsEnabled, (locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, flowLinesRenderingMode, locationLabelsEnabled) => { +- return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, flowLinesRenderingMode, locationLabelsEnabled); ++ this.getLayersData = createSelector(this.getLocationsForFlowmapLayer, this.getFlowsForFlowmapLayer, this.getFlowmapColorsRGBA, this.getLocationsForFlowmapLayerById, this.getLocationIdsInViewport, this.getInCircleSizeGetter, this.getOutCircleSizeGetter, this.getFlowThicknessScale, this.getFlowMagnitudeExtent, this.getViewport, this.getFlowLinesRenderingMode, this.getLocationLabelsEnabled, (locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled) => { ++ return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled); + }); + this.accessors = new FlowmapAggregateAccessors(accessors); + this.setAccessors(accessors); +@@ -634,17 +675,17 @@ export default class FlowmapSelectors { + const getInCircleSize = this.getInCircleSizeGetter(state, props); + const getOutCircleSize = this.getOutCircleSizeGetter(state, props); + const flowThicknessScale = this.getFlowThicknessScale(state, props); ++ const flowMagnitudeExtent = this.getFlowMagnitudeExtent(state, props); + const locationLabelsEnabled = this.getLocationLabelsEnabled(state, props); + const viewport = this.getViewport(state, props); +- return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, state.settings.flowLinesRenderingMode, locationLabelsEnabled); ++ return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, state.settings.flowLinesRenderingMode, locationLabelsEnabled); + } +- _prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, flowLinesRenderingMode, locationLabelsEnabled) { ++ _prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled) { + if (!locations) + locations = []; + if (!flows) + flows = []; + const { getFlowOriginId, getFlowDestId, getFlowMagnitude, getLocationId, getLocationLon, getLocationLat, getLocationName, } = this.accessors; +- const flowMagnitudeExtent = extent(flows, (f) => getFlowMagnitude(f)); + const flowColorScale = getFlowColorScale(flowmapColors, flowMagnitudeExtent, flowLinesRenderingMode === 'animated-straight'); + // Using a generator here helps to avoid creating intermediary arrays + const circlePositions = Float64Array.from((function* () { +diff --git a/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts b/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts +index 185b0ee..aeb99db 100644 +--- a/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts ++++ b/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts +@@ -1,9 +1,11 @@ + import { FlowLinesRenderingMode, LocationFilterMode, ViewportProps } from './types'; + export type FlowEndpointsInViewportMode = 'any' | 'both'; ++export type TemporalScaleDomain = 'selected' | 'all'; + export interface FilterState { + selectedLocations?: (string | number)[]; + locationFilterMode?: LocationFilterMode; + selectedTimeRange?: [Date, Date]; ++ selectedTimeRanges?: [Date, Date][]; + } + export interface SettingsState { + flowLinesRenderingMode: FlowLinesRenderingMode; +@@ -20,6 +22,7 @@ export interface SettingsState { + fadeAmount: number; + colorScheme: string | string[] | undefined; + highlightColor: string | number[]; ++ temporalScaleDomain: TemporalScaleDomain; + maxTopFlowsDisplayNum: number; + flowEndpointsInViewportMode: FlowEndpointsInViewportMode; + } +diff --git a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts +index 3dacdf9..65351d1 100644 +--- a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts ++++ b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts +@@ -1,5 +1,5 @@ + import { CompositeLayer } from '@deck.gl/core'; +-import { FilterState, FlowEndpointsInViewportMode, FlowLinesLayerAttributes, FlowLinesRenderingMode, FlowmapAggregateAccessors, FlowmapData, FlowmapDataAccessors, FlowmapDataProvider, LayersData } from '@flowmap.gl/data'; ++import { FilterState, FlowEndpointsInViewportMode, FlowLinesLayerAttributes, FlowLinesRenderingMode, FlowmapAggregateAccessors, FlowmapData, FlowmapDataAccessors, FlowmapDataProvider, LayersData, TemporalScaleDomain } from '@flowmap.gl/data'; + import { FlowmapLayerPickingInfo, LayerProps } from './types'; + export type FlowmapLayerProps, F extends Record> = { + data?: FlowmapData; +@@ -22,6 +22,7 @@ export type FlowmapLayerProps, F extends Record | undefined, event: SourceEvent) => void; +@@ -68,6 +69,7 @@ export default class FlowmapLayer, F extends Recor + clusteringAuto: boolean; + clusteringLevel: undefined; + adaptiveScalesEnabled: boolean; ++ temporalScaleDomain: string; + flowLineThicknessScale: number; + flowLineCurviness: number; + colorScheme: string; +diff --git a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js +index 404c7ed..7606439 100644 +--- a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js ++++ b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js +@@ -28,6 +28,7 @@ const PROPS_TO_CAUSE_LAYER_DATA_UPDATE = [ + 'fadeAmount', + 'colorScheme', + 'highlightColor', ++ 'temporalScaleDomain', + 'maxTopFlowsDisplayNum', + 'flowEndpointsInViewportMode', + ]; +@@ -171,7 +172,7 @@ class FlowmapLayer extends CompositeLayer { + _getSettingsState() { + const props = this.typedProps; + const defaults = FlowmapLayer.defaultProps; +- const { locationsEnabled, locationTotalsEnabled, locationLabelsEnabled, adaptiveScalesEnabled, flowLinesRenderingMode, clusteringEnabled, clusteringLevel, fadeEnabled, fadeOpacityEnabled, clusteringAuto, darkMode, fadeAmount, colorScheme, highlightColor, maxTopFlowsDisplayNum, flowEndpointsInViewportMode, } = props; ++ const { locationsEnabled, locationTotalsEnabled, locationLabelsEnabled, adaptiveScalesEnabled, flowLinesRenderingMode, clusteringEnabled, clusteringLevel, fadeEnabled, fadeOpacityEnabled, clusteringAuto, darkMode, fadeAmount, colorScheme, highlightColor, temporalScaleDomain, maxTopFlowsDisplayNum, flowEndpointsInViewportMode, } = props; + return { + locationsEnabled: locationsEnabled ?? defaults.locationsEnabled, + locationTotalsEnabled: locationTotalsEnabled ?? defaults.locationTotalsEnabled, +@@ -187,6 +188,7 @@ class FlowmapLayer extends CompositeLayer { + fadeAmount: fadeAmount ?? defaults.fadeAmount, + colorScheme, + highlightColor: highlightColor ?? defaults.highlightColor, ++ temporalScaleDomain: temporalScaleDomain ?? defaults.temporalScaleDomain, + maxTopFlowsDisplayNum: maxTopFlowsDisplayNum ?? defaults.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: (flowEndpointsInViewportMode ?? + defaults.flowEndpointsInViewportMode), +@@ -490,6 +492,7 @@ FlowmapLayer.defaultProps = { + clusteringAuto: true, + clusteringLevel: undefined, + adaptiveScalesEnabled: true, ++ temporalScaleDomain: 'selected', + flowLineThicknessScale: 1, + flowLineCurviness: 1, + colorScheme: 'Teal', diff --git a/data-raw/flowmap-vendor/scripts/generate-vendor-metadata.mjs b/data-raw/flowmap-vendor/scripts/generate-vendor-metadata.mjs new file mode 100644 index 00000000..0ad3754a --- /dev/null +++ b/data-raw/flowmap-vendor/scripts/generate-vendor-metadata.mjs @@ -0,0 +1,234 @@ +import {createHash} from 'node:crypto'; +import {access, readdir, readFile, writeFile} from 'node:fs/promises'; +import {execFileSync} from 'node:child_process'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const outputDir = process.argv[2]; +const licenseNotePath = process.argv[3]; + +if (!outputDir || !licenseNotePath) { + throw new Error( + 'Usage: node scripts/generate-vendor-metadata.mjs ' + ); +} + +const vendorDir = fileURLToPath(new URL('../', import.meta.url)); +const lockPath = path.join(vendorDir, 'package-lock.json'); +const packagePath = path.join(vendorDir, 'package.json'); +const patchesDir = path.join(vendorDir, 'patches'); +const bundleName = 'flowmap-gl-bundle.min.js'; +const manifestName = 'flowmap-gl-vendor-manifest.json'; +const additionalBundledPackages = [ + { + name: 'd3', + version: '7.9.0', + license: 'ISC', + repository: 'https://github.com/d3/d3.git' + }, + { + name: 'lil-gui', + version: '0.19.0', + license: 'MIT', + repository: 'https://github.com/georgealways/lil-gui' + } +]; +const patchPurposes = { + 'patches/flowmap-temporal-scale-domain.patch': + 'Add temporalScaleDomain so temporal flow width/color domains can use selected-time or all-time flows.' +}; + +const [lock, packageJson, bundle] = await Promise.all([ + readJson(lockPath), + readJson(packagePath), + readFile(path.join(outputDir, bundleName)) +]); +const colorSchemes = extractColorSchemes(bundle.toString('utf8')); +const patchMetadata = await getPatchMetadata(); + +const declaredDependencies = packageJson.dependencies; +const packages = await Promise.all( + Object.entries(lock.packages) + .filter(([packagePath]) => packagePath.startsWith('node_modules/')) + .map(async ([packagePath, metadata]) => { + const name = packagePath.replace(/^node_modules\//, ''); + const packageJsonPath = path.join(vendorDir, packagePath, 'package.json'); + if (!(await exists(packageJsonPath))) { + return null; + } + + const packageJson = await readJson(packageJsonPath); + return { + name, + version: metadata.version, + license: packageJson.license ?? packageJson.licenses ?? metadata.license ?? null, + integrity: metadata.integrity ?? null, + resolved: metadata.resolved ?? null, + gitHead: packageJson.gitHead ?? null, + homepage: packageJson.homepage ?? null, + repository: normalizeRepository(packageJson.repository) + }; + }) +); + +const installedPackages = packages.filter((pkg) => pkg !== null); +installedPackages.sort((a, b) => a.name.localeCompare(b.name)); + +const directPackages = Object.keys(declaredDependencies) + .sort() + .map((name) => { + const metadata = installedPackages.find((pkg) => pkg.name === name); + if (!metadata) { + throw new Error(`Missing lockfile metadata for ${name}`); + } + return metadata; + }); + +const manifest = { + schemaVersion: 1, + source: 'npm release packages', + build: { + command: 'data-raw/flowmap-vendor/build-flowmap.sh build', + node: execFileSync('node', ['--version'], {encoding: 'utf8'}).trim(), + npm: execFileSync('npm', ['--version'], {encoding: 'utf8'}).trim(), + esbuild: declaredDependencies.esbuild + }, + bundle: { + path: 'inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js', + sha256: createHash('sha256').update(bundle).digest('hex'), + bytes: bundle.byteLength + }, + patches: patchMetadata, + copyrights: { + path: 'LICENSE.note' + }, + colorSchemes: { + source: 'FlowMapGL 9.3.0 vendored bundle', + names: colorSchemes + }, + directDependencies: directPackages, + transitiveDependencies: installedPackages.filter( + (pkg) => !Object.hasOwn(declaredDependencies, pkg.name) + ) +}; + +await writeFile( + path.join(outputDir, manifestName), + `${JSON.stringify(manifest, null, 2)}\n` +); + +await writeFile(licenseNotePath, renderLicenseNote(installedPackages)); + +async function readJson(file) { + return JSON.parse(await readFile(file, 'utf8')); +} + +async function exists(file) { + try { + await access(file); + return true; + } catch { + return false; + } +} + +async function getPatchMetadata() { + if (!(await exists(patchesDir))) { + return []; + } + + const patchNames = (await readdir(patchesDir)) + .filter((name) => name.endsWith('.patch')) + .sort(); + + return Promise.all( + patchNames.map(async (name) => { + const patchPath = path.join(patchesDir, name); + const contents = await readFile(patchPath); + const relativePath = `data-raw/flowmap-vendor/patches/${name}`; + const purposeKey = `patches/${name}`; + return { + path: relativePath, + sha256: createHash('sha256').update(contents).digest('hex'), + bytes: contents.byteLength, + purpose: patchPurposes[purposeKey] ?? '' + }; + }) + ); +} + +function normalizeRepository(repository) { + if (!repository) { + return null; + } + + if (typeof repository === 'string') { + return repository; + } + + return repository.url ?? null; +} + +function extractColorSchemes(bundle) { + const match = bundle.match( + /(?:^|[;,])[$A-Z_a-z][\w$]*=\{(Blues:[\s\S]*?YlOrRd:[^}]+?)\},[$A-Z_a-z][\w$]*=Object\.keys\(/ + ); + + if (!match) { + throw new Error('Could not find FlowMapGL color schemes in the bundle'); + } + + const names = [...match[1].matchAll(/([A-Za-z][A-Za-z0-9]*):/g)].map( + (scheme) => scheme[1] + ); + + for (const required of ['Blues', 'Teal', 'Viridis', 'YlOrRd']) { + if (!names.includes(required)) { + throw new Error(`Missing expected FlowMapGL color scheme: ${required}`); + } + } + + return names; +} + +function renderLicenseNote(packages) { + return [ + 'This package as a whole is licensed under the MIT License (see LICENSE file).', + '', + 'It bundles several third-party JavaScript components. The FlowmapGL browser bundle shipped at `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js` is generated from npm release packages by `data-raw/flowmap-vendor/build-flowmap.sh build`.', + '', + 'Below are the licenses of the individual bundled components:', + '', + '| Package | Version | License | Source |', + '| --- | --- | --- | --- |', + ...renderCopyrightRows(packages), + '' + ].join('\n'); +} + +function renderCopyrightRows(packages) { + const allPackages = [...packages, ...additionalBundledPackages]; + allPackages.sort((a, b) => a.name.localeCompare(b.name)); + + return allPackages.map((pkg) => { + const license = renderLicense(pkg.license); + const source = pkg.repository ?? pkg.homepage ?? pkg.resolved ?? ''; + return `| ${pkg.name} | ${pkg.version} | ${license} | ${source} |`; + }); +} + +function renderLicense(license) { + if (!license) { + return ''; + } + + if (typeof license === 'string') { + return license; + } + + if (Array.isArray(license)) { + return license.map(renderLicense).join(', '); + } + + return license.type ?? JSON.stringify(license); +} diff --git a/data-raw/get-d3.R b/data-raw/get-d3.R new file mode 100644 index 00000000..96c507d5 --- /dev/null +++ b/data-raw/get-d3.R @@ -0,0 +1,6 @@ +# Download D3.js assets for the Time Control +dir.create("inst/htmlwidgets/lib/d3", recursive = TRUE, showWarnings = FALSE) +download.file( + "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js", + destfile = "inst/htmlwidgets/lib/d3/d3.min.js" +) diff --git a/data-raw/prepare-bixi-dataset.R b/data-raw/prepare-bixi-dataset.R new file mode 100644 index 00000000..ece1c777 --- /dev/null +++ b/data-raw/prepare-bixi-dataset.R @@ -0,0 +1,59 @@ +# data-raw/prepare-bixi-dataset.R +# Script to prepare the BIXI Montréal 2019 example dataset for the mapgl package. +# Downloads the data directly from the public Google Sheet provided by the user, +# cleans IDs and coordinates, and filters out low flows (minimum 3 trips, count > 2) to minimize footprint. + +library(readxl) +library(usethis) + +# 1. Sheet Details & Download +sheet_id <- "1qTVOzkPB7U1ySI4g4uPtVBzzEDCI8n1WXAmQeZL15fE" +xlsx_url <- paste0("https://docs.google.com/spreadsheets/d/", sheet_id, "/export?format=xlsx") + +tmp_xlsx <- tempfile(fileext = ".xlsx") +message("Downloading BIXI Montréal Google Sheet as Excel workbook...") +download.file(xlsx_url, tmp_xlsx, mode = "wb", quiet = TRUE) +message("Download complete!") + +# 2. Read Raw Sheets +locations_raw <- read_excel(tmp_xlsx, sheet = "locations") +flows_raw <- read_excel(tmp_xlsx, sheet = "flows") +unlink(tmp_xlsx) + +# Helper function to clean Excel float-like ID formatting (e.g. "4000.0" -> "4000") +clean_id <- function(x) { + num_val <- suppressWarnings(as.numeric(x)) + ifelse(!is.na(num_val) & num_val == floor(num_val), as.character(as.integer(num_val)), x) +} + +# 3. Clean Locations +message("Cleaning locations dataset...") +bixi_locations <- as.data.frame(locations_raw) +bixi_locations$id <- clean_id(bixi_locations$id) + +# 4. Clean Flows, Filter for Low Flows (count > 2), and Optimize Types +message("Cleaning and optimizing flows dataset (filtering for count > 2 to minimize package footprint)...") +bixi_flows <- as.data.frame(flows_raw) +bixi_flows$origin <- clean_id(bixi_flows$origin) +bixi_flows$dest <- clean_id(bixi_flows$dest) +bixi_flows$count <- as.integer(bixi_flows$count) + +# Clean matching (only keep flows that correspond to valid locations) +bixi_flows <- bixi_flows[bixi_flows$origin %in% bixi_locations$id & bixi_flows$dest %in% bixi_locations$id, ] + +# Filter count > 2 (retaining minimum 3 trips in an hour) +bixi_flows <- bixi_flows[bixi_flows$count > 2, ] + +# Convert origin/dest to factor types matching locations$id for optimal serialization and memory +bixi_flows$origin <- factor(bixi_flows$origin, levels = bixi_locations$id) +bixi_flows$dest <- factor(bixi_flows$dest, levels = bixi_locations$id) + +# 5. Save and Package +message("Packaging datasets into the package data/ folder using xz compression...") +usethis::use_data(bixi_locations, overwrite = TRUE, compress = "xz") +usethis::use_data(bixi_flows, overwrite = TRUE, compress = "xz") + +message("Data preparation and packaging completed successfully!") +message(" - bixi_locations: ", nrow(bixi_locations), " stations") +message(" - bixi_flows: ", nrow(bixi_flows), " flow paths (count > 2)") + diff --git a/data/bixi_flows.rda b/data/bixi_flows.rda new file mode 100644 index 00000000..000926d1 Binary files /dev/null and b/data/bixi_flows.rda differ diff --git a/data/bixi_locations.rda b/data/bixi_locations.rda new file mode 100644 index 00000000..8c05f644 Binary files /dev/null and b/data/bixi_locations.rda differ diff --git a/inst/htmlwidgets/flowmap.css b/inst/htmlwidgets/flowmap.css new file mode 100644 index 00000000..451a5828 --- /dev/null +++ b/inst/htmlwidgets/flowmap.css @@ -0,0 +1,53 @@ +.mapgl-flowmap-tooltip.mapboxgl-popup .mapboxgl-popup-content, +.mapgl-flowmap-tooltip.maplibregl-popup .maplibregl-popup-content { + font-family: + -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, + Cantarell, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.35; +} + +.mapgl-flowmap-tooltip--dark.mapboxgl-popup .mapboxgl-popup-content, +.mapgl-flowmap-tooltip--dark.maplibregl-popup .maplibregl-popup-content { + background: rgba(35, 35, 35, 0.94); + color: #fff; +} + +.mapgl-flowmap-tooltip--dark.mapboxgl-popup .mapboxgl-popup-tip, +.mapgl-flowmap-tooltip--dark.maplibregl-popup .maplibregl-popup-tip { + border-top-color: rgba(35, 35, 35, 0.94); + border-bottom-color: rgba(35, 35, 35, 0.94); +} + +.mapgl-flowmap-tooltip--light.mapboxgl-popup .mapboxgl-popup-content, +.mapgl-flowmap-tooltip--light.maplibregl-popup .maplibregl-popup-content { + background: rgba(255, 255, 255, 0.96); + color: #222; +} + +.mapgl-flowmap-example-tooltip { + position: absolute; + z-index: 5; + display: none; + max-width: 320px; + padding: 1em; + border-radius: 5px; + font-family: + -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, + Cantarell, "Helvetica Neue", Arial, sans-serif; + font-size: 10px; + line-height: 1.35; + pointer-events: none; +} + +.mapgl-flowmap-example-tooltip--dark { + background-color: rgba(150, 150, 150, 0.75); + color: #fff; +} + +.mapgl-flowmap-example-tooltip--light { + border: 1px solid rgba(0, 0, 0, 0.12); + background-color: rgba(255, 255, 255, 0.92); + color: #222; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.16); +} diff --git a/inst/htmlwidgets/flowmap.js b/inst/htmlwidgets/flowmap.js new file mode 100644 index 00000000..41364db8 --- /dev/null +++ b/inst/htmlwidgets/flowmap.js @@ -0,0 +1,1519 @@ +window.MapGLFlowmapPlugin = (function () { + const FLOWMAP_ATTRIBUTION_SELECTOR = + ".mapboxgl-ctrl-attrib-inner, .maplibregl-ctrl-attrib-inner"; + const FLOWMAP_ATTRIBUTION_LINK_SELECTOR = + 'a[data-mapgl-flowmap-attribution="true"]'; + const FLOWMAP_ATTRIBUTION_SEPARATOR_SELECTOR = + '[data-mapgl-flowmap-attribution-separator="true"]'; + const DEFAULT_LOCATION_TOOLTIP = + "{name}
Incoming trips: {totals.incomingCount}
Outgoing trips: {totals.outgoingCount}
Internal or round trips: {totals.internalCount}"; + const DEFAULT_FLOW_TOOLTIP = "{count} trips"; + + function dataframeToRows(data, HTMLWidgets) { + if (!data || Array.isArray(data) || typeof data !== "object") { + return data; + } + + if (HTMLWidgets && typeof HTMLWidgets.dataframeToD3 === "function") { + return HTMLWidgets.dataframeToD3(data); + } + + return data; + } + + function attributionNodeHasContent(node) { + if (!node) { + return false; + } + + if ( + node.nodeType === 1 && + (node.matches(FLOWMAP_ATTRIBUTION_LINK_SELECTOR) || + node.matches(FLOWMAP_ATTRIBUTION_SEPARATOR_SELECTOR)) + ) { + return false; + } + + return node.textContent && node.textContent.trim() !== ""; + } + + function hasNativeAttributionContent(attributionInner) { + for (var i = 0; i < attributionInner.childNodes.length; i++) { + if (attributionNodeHasContent(attributionInner.childNodes[i])) { + return true; + } + } + + return false; + } + + function makeFlowmapAttributionLink() { + const link = document.createElement("a"); + link.href = "https://flowmap.gl/"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.setAttribute("data-mapgl-flowmap-attribution", "true"); + link.textContent = "Flowmap.gl"; + return link; + } + + function normalizeFlowmapAttributionLink(link) { + link.href = "https://flowmap.gl/"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.setAttribute("data-mapgl-flowmap-attribution", "true"); + link.textContent = "Flowmap.gl"; + } + + function ensureFlowmapAttribution(map) { + if (!map || typeof map.getContainer !== "function") { + return; + } + + const container = map.getContainer(); + if (!container || typeof container.querySelector !== "function") { + return; + } + + const attributionInner = container.querySelector( + FLOWMAP_ATTRIBUTION_SELECTOR + ); + if (!attributionInner) { + return; + } + + const existingLinks = attributionInner.querySelectorAll( + FLOWMAP_ATTRIBUTION_LINK_SELECTOR + ); + var link = existingLinks[0] || makeFlowmapAttributionLink(); + + normalizeFlowmapAttributionLink(link); + + for (var i = 1; i < existingLinks.length; i++) { + existingLinks[i].remove(); + } + + const separators = attributionInner.querySelectorAll( + FLOWMAP_ATTRIBUTION_SEPARATOR_SELECTOR + ); + for (var j = 0; j < separators.length; j++) { + separators[j].remove(); + } + + if (attributionInner.firstChild !== link) { + attributionInner.insertBefore(link, attributionInner.firstChild); + } + + if (hasNativeAttributionContent(attributionInner)) { + const separator = document.createElement("span"); + separator.setAttribute( + "data-mapgl-flowmap-attribution-separator", + "true" + ); + separator.textContent = " | "; + attributionInner.insertBefore(separator, link.nextSibling); + } + } + + function installFlowmapAttributionRefresh(map) { + if (!map || map._mapglFlowmapAttributionRefreshInstalled) { + return; + } + + var timer = null; + const refresh = function () { + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(function () { + timer = null; + ensureFlowmapAttribution(map); + }, 50); + }; + + map._mapglFlowmapAttributionRefreshInstalled = true; + map._mapglFlowmapAttributionRefresh = refresh; + + map.on("styledata", refresh); + map.on("sourcedata", refresh); + map.on("idle", refresh); + map.once("remove", function () { + if (timer) { + clearTimeout(timer); + timer = null; + } + map.off("styledata", refresh); + map.off("sourcedata", refresh); + map.off("idle", refresh); + map._mapglFlowmapAttributionRefreshInstalled = false; + map._mapglFlowmapAttributionRefresh = null; + }); + + ensureFlowmapAttribution(map); + } + + function getTooltipStore(map) { + if (!map._mapglFlowmapTooltips) { + map._mapglFlowmapTooltips = {}; + } + return map._mapglFlowmapTooltips; + } + + function hideFlowmapTooltip(map, id) { + const store = getTooltipStore(map); + const tooltip = store[id]; + if (!tooltip) { + return; + } + if (tooltip.popup) { + tooltip.popup.remove(); + } + if (tooltip.element) { + tooltip.element.style.display = "none"; + } + } + + function hideAllFlowmapTooltips(map) { + const store = getTooltipStore(map); + Object.keys(store).forEach(function (id) { + hideFlowmapTooltip(map, id); + }); + } + + function hideOtherFlowmapTooltips(map, activeId) { + const store = getTooltipStore(map); + Object.keys(store).forEach(function (id) { + if (id !== activeId) { + hideFlowmapTooltip(map, id); + } + }); + } + + function getPopupConstructor() { + if (typeof mapboxgl !== "undefined" && mapboxgl.Popup) { + return mapboxgl.Popup; + } + if (typeof maplibregl !== "undefined" && maplibregl.Popup) { + return maplibregl.Popup; + } + return null; + } + + function escapeHTML(value) { + return String(value == null ? "" : value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } + + // Mapbox-style expression evaluator (concat / number-format / get). flowmap + // is a separate IIFE and cannot reach the bindings' copy, so it carries its + // own — keep in sync with evaluateExpression in mapboxgl.js / maplibregl.js. + function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + const operator = expression[0]; + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map(function (item) { + return evaluateExpression(item, properties); + }) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": { + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + const locale = options.locale || "en-US"; + const formatOptions = {}; + if (options.style) formatOptions.style = options.style; + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + if (options.notation) formatOptions.notation = options.notation; + if (options.compactDisplay) { + formatOptions.compactDisplay = options.compactDisplay; + } + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + return new Intl.NumberFormat(locale, formatOptions).format(value); + } + default: + return expression; + } + } + + function getPathValue(object, path) { + if (!object || !path) { + return undefined; + } + + return path.split(".").reduce(function (value, key) { + if (value == null) { + return undefined; + } + return value[key]; + }, object); + } + + // Render a {brace} template against a properties object — shared package-wide + // tooltip syntax (mirrors renderTemplate in the bindings). Dotted paths work + // because the flat property bag below also keeps the nested object. + function renderTemplate(template, properties) { + if (typeof template !== "string") { + return template; + } + return template.replace(/\{([^}]+)\}/g, function (match, path) { + const value = getPathValue(properties, path.trim()); + return value == null ? "" : escapeHTML(value); + }); + } + + // Resolve a tooltip/popup content spec: array -> expression, "{..}" -> brace + // template, string -> column-name lookup on the property bag. + function resolveTooltipContent(spec, properties) { + if (Array.isArray(spec)) { + return evaluateExpression(spec, properties); + } + if (typeof spec === "string" && spec.indexOf("{") !== -1) { + return renderTemplate(spec, properties); + } + return properties[spec]; + } + + // Build a flat property bag for a picked location/flow so templates and + // expressions can use simple keys (origin_id, dest_name, incoming, ...). The + // original nested object is preserved so dotted paths ({origin.id}, + // {totals.incomingCount}) keep resolving too. + function flowmapProps(object, objectType) { + const props = Object.assign({}, object); + if (objectType === "location") { + const totals = object.totals || {}; + props.incoming = totals.incomingCount; + props.outgoing = totals.outgoingCount; + props.internal = totals.internalCount; + } else if (objectType === "flow") { + const origin = object.origin || {}; + const dest = object.dest || {}; + props.origin_id = origin.id; + props.origin_name = origin.name; + props.dest_id = dest.id; + props.dest_name = dest.name; + } + return props; + } + + function getTooltipHTML(config, info, behavior) { + const interaction = config[behavior] || {}; + const object = info && info.object; + if (!object) { + return null; + } + + // Determine object type if missing + let objectType = object.type; + if (!objectType) { + if (object.lat != null && object.lon != null) { + objectType = "location"; + } else if (object.origin != null && object.dest != null) { + objectType = "flow"; + } + } + + if (!objectType) { + return null; + } + + // The per-type content spec is one of the package-wide tooltip forms: + // true -> the default {brace} template for this object type + // false -> disabled + // string -> a column name or {brace} template + // array -> a concat()/number_format() expression + const spec = interaction[objectType]; + if (spec == null || spec === false) { + return null; + } + + const props = flowmapProps(object, objectType); + + let html; + if (spec === true) { + const template = + objectType === "location" + ? DEFAULT_LOCATION_TOOLTIP + : DEFAULT_FLOW_TOOLTIP; + html = renderTemplate(template, props); + } else { + const resolved = resolveTooltipContent(spec, props); + html = resolved == null ? "" : String(resolved); + } + + return html || null; + } + + function getTooltipLngLat(map, info) { + if (info && info.lngLat) { + return info.lngLat; + } + if (info && Array.isArray(info.coordinate)) { + return info.coordinate; + } + + const object = info && info.object; + if (!object) { + return null; + } + + if (object.type === "location" && object.location) { + const location = object.location; + if (location.lon != null && location.lat != null) { + return [location.lon, location.lat]; + } + } + + if (object.type === "flow" && object.origin && object.dest) { + const origin = object.origin; + const dest = object.dest; + if ( + origin.lon != null && + origin.lat != null && + dest.lon != null && + dest.lat != null + ) { + return [(origin.lon + dest.lon) / 2, (origin.lat + dest.lat) / 2]; + } + } + + return null; + } + + function getTooltipPoint(map, info) { + if (info && Number.isFinite(info.x) && Number.isFinite(info.y)) { + return { x: info.x, y: info.y }; + } + + const lngLat = getTooltipLngLat(map, info); + if (lngLat && map && typeof map.project === "function") { + return map.project(lngLat); + } + + return null; + } + + function mergeClassName(base, extra) { + return extra ? base + " " + extra : base; + } + + function generateHash(str) { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash |= 0; + } + return Math.abs(hash).toString(36); + } + + function ensureCustomStyle(css, className) { + const selector = className || "mapgl-custom-" + generateHash(css); + const styleId = "style-" + selector; + if (!document.getElementById(styleId)) { + const style = document.createElement("style"); + style.id = styleId; + style.textContent = "." + selector + " { " + css + " }"; + document.head.appendChild(style); + } + return selector; + } + + // ---- tooltip/popup theming (mapgl_tooltip_style spec) ------------------- + // Mirrors tooltipStyleToClass in the bindings; flowmap additionally needs an + // inline form because its "floating" tooltip is a bare
, not a Popup. + function tooltipHexToRgba(color, alpha) { + if (typeof color !== "string" || color.charAt(0) !== "#") return color; + let h = color.slice(1); + if (h.length === 3) { + h = h.split("").map(function (c) { return c + c; }).join(""); + } + const r = parseInt(h.slice(0, 2), 16); + const g = parseInt(h.slice(2, 4), 16); + const b = parseInt(h.slice(4, 6), 16); + return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; + } + + // Returns { decls: "background:...;color:...;", background: }. + function tooltipStyleDecls(spec) { + let bg = spec.background_color; + if (bg != null && spec.background_opacity != null) { + bg = tooltipHexToRgba(bg, spec.background_opacity); + } + const d = []; + if (bg != null) d.push("background:" + bg + ";"); + if (spec.text_color != null) d.push("color:" + spec.text_color + ";"); + if (spec.border_color != null || spec.border_width != null) { + const bw = spec.border_width == null ? 1 : spec.border_width; + const bc = spec.border_color == null ? "transparent" : spec.border_color; + d.push("border:" + bw + "px solid " + bc + ";"); + } + if (spec.border_radius != null) { + d.push("border-radius:" + spec.border_radius + "px;"); + } + if (spec.font_family != null) d.push("font-family:" + spec.font_family + ";"); + if (spec.font_size != null) d.push("font-size:" + spec.font_size + "px;"); + if (spec.font_weight != null) d.push("font-weight:" + spec.font_weight + ";"); + if (spec.padding != null) d.push("padding:" + spec.padding + "px;"); + if (spec.max_width != null) { + const mw = + typeof spec.max_width === "number" ? spec.max_width + "px" : spec.max_width; + d.push("max-width:" + mw + ";"); + } + if (spec.shadow) { + const ss = spec.shadow_size == null ? 8 : spec.shadow_size; + const sc = spec.shadow_color == null ? "rgba(0, 0, 0, 0.2)" : spec.shadow_color; + d.push("box-shadow:0 2px " + ss + "px " + sc + ";"); + } + return { decls: d.join(""), background: bg }; + } + + // Scoped class for an anchored Popup (targets .popup-content + tip). + function tooltipStyleToClass(spec) { + if (!spec || typeof spec !== "object") return null; + if (!window._mapglTooltipStyleClasses) window._mapglTooltipStyleClasses = {}; + const cache = window._mapglTooltipStyleClasses; + const key = JSON.stringify(spec); + if (cache[key]) return cache[key]; + const cls = "mapgl-tooltip-style-" + (Object.keys(cache).length + 1); + const built = tooltipStyleDecls(spec); + let css = + "." + cls + " .mapboxgl-popup-content, ." + cls + + " .maplibregl-popup-content {" + built.decls + "}"; + if (built.background != null) { + css += + "." + cls + " .mapboxgl-popup-tip, ." + cls + + " .maplibregl-popup-tip {border-top-color:" + built.background + + ";border-bottom-color:" + built.background + ";}"; + } + const styleEl = document.createElement("style"); + styleEl.textContent = css; + document.head.appendChild(styleEl); + cache[key] = cls; + return cls; + } + + // Inline declarations for a floating tooltip
. + function tooltipStyleInline(spec) { + if (!spec || typeof spec !== "object") return ""; + return tooltipStyleDecls(spec).decls; + } + + function tooltipStyleOffset(spec) { + const offset = spec && spec.offset; + if (Array.isArray(offset) && offset.length >= 2) { + return [Number(offset[0]) || 0, Number(offset[1]) || 0]; + } + if (typeof offset === "number") return [offset, offset]; + return [10, 10]; + } + + function showInteractiveUI(map, config, info, behavior) { + const interaction = config[behavior]; + if (!interaction || !interaction.enabled) return; + + const html = getTooltipHTML(config, info, behavior); + if (!html) { + if (behavior === "tooltip") hideFlowmapTooltip(map, config.id); + return; + } + + const lngLat = getTooltipLngLat(map, info); + if (!lngLat) { + if (behavior === "tooltip") hideFlowmapTooltip(map, config.id); + return; + } + + // Dismiss existing interactions of other types if needed + if (behavior === "popup") { + hideFlowmapTooltip(map, config.id); + } + + // interaction.style is a mapgl_tooltip_style spec (appearance + position). + const styleSpec = interaction.style || {}; + const position = styleSpec.position || "floating"; + + if (position === "anchored") { + const Popup = getPopupConstructor(); + if (!Popup) return; + + const className = mergeClassName( + "mapgl-flowmap-tooltip", + tooltipStyleToClass(styleSpec), + ); + + const options = { + closeButton: behavior === "popup", + closeOnClick: behavior === "popup" ? false : true, + maxWidth: "400px", + className: className, + }; + + const store = getTooltipStore(map); + if (!store[config.id]) store[config.id] = {}; + + const storeKey = behavior === "popup" ? "clickPopup" : "popup"; + + if (store[config.id][storeKey]) { + store[config.id][storeKey].remove(); + } + + store[config.id][storeKey] = new Popup(options) + .setLngLat(lngLat) + .setHTML(html) + .addTo(map); + } else { + // Floating mode: a bare
styled inline from the spec. + const point = getTooltipPoint(map, info); + if (!point || !map || typeof map.getContainer !== "function") return; + + const store = getTooltipStore(map); + if (!store[config.id]) store[config.id] = {}; + + const storeKey = behavior === "popup" ? "clickElement" : "element"; + + if (!store[config.id][storeKey]) { + const element = document.createElement("div"); + element.style.position = "absolute"; + element.style.zIndex = "1000"; + map.getContainer().appendChild(element); + store[config.id][storeKey] = element; + } + + const element = store[config.id][storeKey]; + + // Base class supplies layout/positioning; the spec supplies the theme + // (background/border/etc.) as inline declarations. + element.className = "mapgl-flowmap-example-tooltip flowmap-tooltip"; + element.style.cssText = + "position:absolute;z-index:1000;" + tooltipStyleInline(styleSpec); + element.innerHTML = html; + + const offset = tooltipStyleOffset(styleSpec); + element.style.left = point.x + offset[0] + "px"; + element.style.top = point.y + offset[1] + "px"; + element.style.display = "block"; + element.style.pointerEvents = behavior === "popup" ? "auto" : "none"; + + if (behavior === "popup") { + // Delayed listener to avoid immediate dismissal from bubbling + setTimeout(() => { + const closeHandler = (e) => { + // Don't close if we clicked inside the popup element itself + if (element.contains(e.target)) return; + element.style.display = "none"; + map.off("click", closeHandler); + }; + map.on("click", closeHandler); + }, 100); + } + } + } + + function getElementOffset(options) { + const offset = options && options.offset; + if (Array.isArray(offset) && offset.length >= 2) { + return [Number(offset[0]) || 0, Number(offset[1]) || 0]; + } + if (typeof offset === "number") { + return [offset, offset]; + } + return [10, 10]; + } + + function ensureOverlay(map, interleaved, elId, settings) { + if (typeof FlowmapGL === "undefined") { + console.error("FlowmapGL is not loaded. Cannot add flowmap layers."); + return null; + } + + if (interleaved) { + // Interleaved mode (MapboxOverlay) for layer ordering (beforeId/slot) + if ( + map._mapglFlowmapOverlay && + map._mapglFlowmapOverlayInterleaved === true + ) { + return map._mapglFlowmapOverlay; + } + + // Cleanup standalone Deck if any + if (map._deckgl) { + try { + map._deckgl.finalize(); + } catch (e) {} + map._deckgl = null; + } + if (map._deckContainer) { + try { + map._deckContainer.remove(); + } catch (e) {} + map._deckContainer = null; + } + + if (map._mapglFlowmapOverlay) { + try { + map.removeControl(map._mapglFlowmapOverlay); + } catch (e) {} + } + + const overlay = new FlowmapGL.MapboxOverlay({ + interleaved: true, + layers: [], + }); + + map.addControl(overlay); + map._mapglFlowmapOverlay = overlay; + map._mapglFlowmapOverlayInterleaved = true; + + map.once("remove", function () { + map._mapglFlowmapOverlay = null; + map._mapglFlowmapLayers = []; + }); + + return overlay; + } else { + // Standalone mode: Create standalone Deck container to bypass nested control stacking context. + // This is crucial because CSS mix-blend-mode will not blend with sibling map canvas elements + // if nested deep inside Mapbox/MapLibre's .mapboxgl-control-container hierarchy. + if ( + map._deckgl && + map._mapglFlowmapOverlayInterleaved === false + ) { + // Update blending styles on the existing canvas during widget updates + // NOTE: blend must go on the canvas, not the container, to avoid + // stacking-context isolation that prevents cross-element blending. + const deckCanvas = map._deckCanvas; + if (deckCanvas) { + if (settings && settings.flowBlend) { + if (typeof settings.flowBlend === "string") { + deckCanvas.style.mixBlendMode = settings.flowBlend; + } else { + deckCanvas.style.mixBlendMode = settings.darkMode ? "screen" : "multiply"; + } + } else { + deckCanvas.style.mixBlendMode = ""; + } + } + return map._deckgl; + } + + // Cleanup MapboxOverlay if any + if (map._mapglFlowmapOverlay) { + try { + map.removeControl(map._mapglFlowmapOverlay); + } catch (e) {} + map._mapglFlowmapOverlay = null; + } + if (map._deckgl) { + try { + map._deckgl.finalize(); + } catch (e) {} + map._deckgl = null; + } + if (map._deckContainer) { + try { + map._deckContainer.remove(); + } catch (e) {} + map._deckContainer = null; + } + + const container = map.getContainer(); + + // Create overlay container div directly under map container (sibling of canvas container) + const deckContainer = document.createElement("div"); + deckContainer.id = "deck-container-" + elId; + deckContainer.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;"; + container.appendChild(deckContainer); + + // Create standalone canvas + const deckCanvas = document.createElement("canvas"); + deckCanvas.id = "deck-canvas-" + elId; + deckCanvas.style.cssText = "width:100%;height:100%;"; + deckContainer.appendChild(deckCanvas); + + map._deckContainer = deckContainer; + map._deckCanvas = deckCanvas; + + const center = map.getCenter(); + const initialViewState = { + longitude: center.lng, + latitude: center.lat, + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing() + }; + + const deckInstance = new FlowmapGL.Deck({ + canvas: deckCanvas, + controller: false, // map controls the camera + _useDevicePixels: true, + initialViewState: initialViewState, + layers: [], + getTooltip: null, + pickingRadius: 5 + }); + + // Synchronize standalone Deck viewport state with map moves + const syncViewState = () => { + const center = map.getCenter(); + deckInstance.setProps({ + viewState: { + longitude: center.lng, + latitude: center.lat, + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing() + } + }); + }; + + map.on("move", syncViewState); + map.on("moveend", syncViewState); + syncViewState(); + + // Forward mouse events from Mapbox to standalone Deck for picking / hover tooltips. + // We manually delegate hover and click events to the deck.gl sublayers, which + // automatically propagates them up to the composite FlowmapLayer. This ensures + // that the composite layer's internal highlight state is updated synchronously, + // and its async picking info enrichment is executed before calling our custom handlers. + const onMapMouseMove = (e) => { + if (!deckInstance || !map._mapglFlowmapLayers || map._mapglFlowmapLayers.length === 0) return; + const { x, y } = e.point; + try { + const info = deckInstance.pickObject({ x, y, radius: 2 }); + map.getCanvas().style.cursor = info ? "pointer" : ""; + + if (info && info.layer) { + const event = { srcEvent: e.originalEvent || e }; + info.x = x; + info.y = y; + info.lngLat = e.lngLat; + if (e.lngLat) { + info.coordinate = [e.lngLat.lng, e.lngLat.lat]; + } + if (typeof info.layer.onHover === "function") { + info.layer.onHover(info, event); + } else if (info.layer.props && typeof info.layer.props.onHover === "function") { + info.layer.props.onHover(info, event); + } + } else { + hideAllFlowmapTooltips(map); + // Also notify active flowmap layers that hover has ended, to clear highlights + map._mapglFlowmapLayers.forEach((layer) => { + if (layer.props && typeof layer.props.onHover === "function") { + layer.props.onHover({ index: -1 }, {}); + } + }); + } + } catch (err) { + // Ignore deck.gl picking errors during init / rapid movement + } + }; + + const onMapClick = (e) => { + if (!deckInstance || !map._mapglFlowmapLayers || map._mapglFlowmapLayers.length === 0) return; + const { x, y } = e.point; + try { + const info = deckInstance.pickObject({ x, y, radius: 5 }); + if (info && info.layer) { + const event = { srcEvent: e.originalEvent || e }; + info.x = x; + info.y = y; + info.lngLat = e.lngLat; + if (e.lngLat) { + info.coordinate = [e.lngLat.lng, e.lngLat.lat]; + } + if (typeof info.layer.onClick === "function") { + info.layer.onClick(info, event); + } else if (info.layer.props && typeof info.layer.props.onClick === "function") { + info.layer.props.onClick(info, event); + } + } + } catch (err) { + // Ignore deck.gl picking errors + } + }; + + if (!map._hasDeckMoveListener) { + map.on("mousemove", onMapMouseMove); + map.on("click", onMapClick); + map.on("mouseout", function () { + hideAllFlowmapTooltips(map); + // Clear hover highlights on mouseout — directly update state to avoid async delay + let needsRedraw = false; + if (map._flowmapHoverTimers) { + Object.keys(map._flowmapHoverTimers).forEach(function(id) { + if (map._flowmapHoverTimers[id]) { + clearTimeout(map._flowmapHoverTimers[id]); + map._flowmapHoverTimers[id] = null; + } + }); + } + if (map._flowmapHoveredLocation) { + Object.keys(map._flowmapHoveredLocation).forEach(function(id) { + if (map._flowmapHoveredLocation[id] !== null) { + map._flowmapHoveredLocation[id] = null; + needsRedraw = true; + } + }); + } + if (needsRedraw) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + // Also notify via layer.props for any other listeners + if (map._mapglFlowmapLayers) { + map._mapglFlowmapLayers.forEach((layer) => { + if (layer.props && typeof layer.props.onHover === "function") { + layer.props.onHover({ index: -1 }, {}); + } + }); + } + }); + map._hasDeckMoveListener = true; + } + + map._deckgl = deckInstance; + map._mapglFlowmapOverlayInterleaved = false; + + // Apply CSS Blending directly to the canvas element. + // IMPORTANT: The container must NOT have a z-index (other than auto) + // because that creates a stacking context which isolates the canvas + // and prevents mix-blend-mode from blending with the underlying map. + if (settings && settings.flowBlend) { + if (typeof settings.flowBlend === "string") { + deckCanvas.style.mixBlendMode = settings.flowBlend; + } else { + deckCanvas.style.mixBlendMode = settings.darkMode ? "screen" : "multiply"; + } + } else { + deckCanvas.style.mixBlendMode = ""; + } + + map.once("remove", function () { + if (map._deckgl) { + try { + map._deckgl.finalize(); + } catch (e) {} + map._deckgl = null; + } + if (map._deckContainer) { + try { + map._deckContainer.remove(); + } catch (e) {} + map._deckContainer = null; + } + map._mapglFlowmapLayers = []; + hideAllFlowmapTooltips(map); + }); + + return deckInstance; + } + } + + function makeLayer(config, HTMLWidgets, map, customLocations, customFlows, customPickable) { + const settings = config.settings || {}; + + // Cache converted rows on the original config's data object (for the canonical id) + const canonicalId = config._canonicalId || config.id; + const canonical = map._flowmapsConfig && map._flowmapsConfig.find(function(c) { return c.id === canonicalId; }); + const dataTarget = canonical ? canonical.data : config.data; + + if (!dataTarget._locationsRows) { + dataTarget._locationsRows = dataframeToRows(dataTarget.locations, HTMLWidgets); + } + if (!dataTarget._flowsRows) { + dataTarget._flowsRows = dataframeToRows(dataTarget.flows, HTMLWidgets); + } + + const locations = customLocations !== undefined ? customLocations : dataTarget._locationsRows; + const flows = customFlows !== undefined ? customFlows : dataTarget._flowsRows; + const isPickable = customPickable !== undefined ? customPickable : true; + // When custom flows are provided we've already done the location filtering externally + const skipLocationFilter = customFlows !== undefined; + + const layerProps = { + id: config.id, + data: { + locations: locations, + flows: flows, + }, + beforeId: config.beforeId || undefined, + slot: config.slot || undefined, + pickable: isPickable, + visible: config.visibility !== "none", + opacity: settings.opacity == null ? 1 : settings.opacity, + colorScheme: settings.colorScheme, + darkMode: settings.darkMode, + fadeAmount: settings.fadeAmount, + highlightColor: settings.highlightColor, + locationsEnabled: settings.locationsEnabled, + locationTotalsEnabled: settings.locationTotalsEnabled, + locationLabelsEnabled: settings.locationLabelsEnabled, + flowLinesRenderingMode: settings.flowLinesRenderingMode, + flowLineThicknessScale: settings.flowLineThicknessScale == null ? 1 : settings.flowLineThicknessScale, + flowLineCurviness: settings.flowLineCurviness == null ? 1 : settings.flowLineCurviness, + clusteringEnabled: settings.clusteringEnabled, + clusteringAuto: settings.clusteringAuto, + clusteringLevel: settings.clusteringLevel === null ? undefined : settings.clusteringLevel, + fadeEnabled: settings.fadeEnabled, + fadeOpacityEnabled: settings.fadeOpacityEnabled, + adaptiveScalesEnabled: settings.adaptiveScalesEnabled, + temporalScaleDomain: settings.temporalScaleDomain || "selected", + maxTopFlowsDisplayNum: settings.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: settings.flowEndpointsInViewportMode, + getLocationId: function (location) { + return location.id; + }, + getLocationLat: function (location) { + return location.lat; + }, + getLocationLon: function (location) { + return location.lon; + }, + getLocationName: function (location) { + return location.name || location.id; + }, + getFlowOriginId: function (flow) { + return flow.origin; + }, + getFlowDestId: function (flow) { + return flow.dest; + }, + getFlowMagnitude: function (flow) { + return flow.count; + }, + }; + + if (settings.timeColumn) { + layerProps.getFlowTime = function (flow) { + return flow.time ? new Date(flow.time) : undefined; + }; + } + + if (settings.selectedTimeRange) { + layerProps.filter = { + ...layerProps.filter, + selectedTimeRange: [ + new Date(settings.selectedTimeRange[0]), + new Date(settings.selectedTimeRange[1]) + ] + }; + } + + if (settings.selectedTimeRanges) { + layerProps.filter = { + ...layerProps.filter, + selectedTimeRange: null, + selectedTimeRanges: normalizeTimeRanges(settings.selectedTimeRanges) + }; + } + + // Only apply location filter on the FlowmapLayer when we haven't pre-filtered externally. + // When customFlows is provided, the caller already filtered by selected locations. + if (!skipLocationFilter) { + let selectedLocs = settings.selectedLocations; + if (settings.clickToFilter && map._flowmapSelectedLocations && map._flowmapSelectedLocations[canonicalId]) { + selectedLocs = map._flowmapSelectedLocations[canonicalId]; + } + if (selectedLocs && selectedLocs.length > 0) { + layerProps.filter = { + ...layerProps.filter, + selectedLocations: selectedLocs + }; + } + } + + if (settings.locationFilterMode) { + layerProps.filter = { + ...layerProps.filter, + locationFilterMode: settings.locationFilterMode + }; + } + + // Only attach interactive handlers on the canonical (pickable) layer. + // The originalConfig is the root config from _flowmapsConfig for closures. + const originalConfig = (map._flowmapsConfig && map._flowmapsConfig.find(function(c) { return c.id === canonicalId; })) || config; + + const hasHoverHandler = (originalConfig.tooltip && originalConfig.tooltip.enabled) || settings.hoverToHighlight; + const hasClickHandler = (originalConfig.popup && originalConfig.popup.enabled) || settings.clickToFilter; + + if (isPickable && hasHoverHandler) { + layerProps.onHover = function (info) { + if (originalConfig.tooltip && originalConfig.tooltip.enabled) { + showInteractiveUI(map, originalConfig, info, "tooltip"); + } + if (settings.hoverToHighlight) { + handleHoverInteraction(map, originalConfig, info); + } + }; + } + + if (isPickable && hasClickHandler) { + layerProps.onClick = function (info) { + if (originalConfig.popup && originalConfig.popup.enabled) { + showInteractiveUI(map, originalConfig, info, "popup"); + } + if (settings.clickToFilter) { + handleClickInteraction(map, originalConfig, info); + } + }; + } + + return makeFlowmapLayer(layerProps); + } + + function makeFlowmapLayer(layerProps) { + const layer = new FlowmapGL.FlowmapLayer(layerProps); + layer._mapglOnHover = layerProps.onHover; + layer._mapglOnClick = layerProps.onClick; + return layer; + } + + function cloneFlowmapLayer(layer, props) { + const cloneProps = Object.assign({}, props); + + if (Object.prototype.hasOwnProperty.call(layer, "_mapglOnHover")) { + cloneProps.onHover = layer._mapglOnHover; + } + if (Object.prototype.hasOwnProperty.call(layer, "_mapglOnClick")) { + cloneProps.onClick = layer._mapglOnClick; + } + + const cloned = layer.clone(cloneProps); + cloned._mapglOnHover = layer._mapglOnHover; + cloned._mapglOnClick = layer._mapglOnClick; + return cloned; + } + + function init(map, x, el, HTMLWidgets) { + if (!x.flowmaps || x.flowmaps.length === 0) { + return; + } + + if (typeof FlowmapGL === "undefined" || !FlowmapGL.FlowmapLayer) { + console.error("FlowmapGL is not loaded. Cannot add flowmap layers."); + return; + } + + installFlowmapAttributionRefresh(map); + + const interleaved = x.flowmaps.some(function (flowmap) { + return Boolean(flowmap.beforeId || flowmap.slot); + }); + + var firstFlowmap = x.flowmaps[0]; + var settings = firstFlowmap.settings || {}; + + const overlay = ensureOverlay(map, interleaved, el.id, settings); + if (!overlay) { + return; + } + + // Initialize interaction state maps + if (!map._flowmapSelectedLocations) { + map._flowmapSelectedLocations = {}; + } + if (!map._flowmapHoveredLocation) { + map._flowmapHoveredLocation = {}; + } + if (!map._flowmapHoverTimers) { + map._flowmapHoverTimers = {}; + } + map._flowmapsConfig = x.flowmaps; + map._flowmapHTMLWidgets = HTMLWidgets; + + // A set_style() wipes the basemap (and, in interleaved mode, the deck + // layers) so the flowmap must be rebuilt once the new style loads. The + // persisted _flowmapsConfig carries the current settings — including any + // slider-written selectedTimeRange — so redrawFlowmaps() restores the + // flowmap and its temporal filter by construction. Installed once per map + // and debounced because a single set_style() can emit style.load more than + // once. + if (!map._flowmapStyleReloadInstalled) { + map._flowmapStyleReloadInstalled = true; + var flowmapStyleReloadTimer = null; + map.on("style.load", function () { + if (!map._flowmapsConfig || map._flowmapsConfig.length === 0) { + return; + } + if (flowmapStyleReloadTimer) { + clearTimeout(flowmapStyleReloadTimer); + } + flowmapStyleReloadTimer = setTimeout(function () { + flowmapStyleReloadTimer = null; + if (!map._flowmapsConfig || map._flowmapsConfig.length === 0) { + return; + } + redrawFlowmaps(map, map._flowmapHTMLWidgets); + // Let listeners (e.g. a slider driving the temporal window) re-emit + // their current state after the flowmap has been rebuilt. + if (typeof map.fire === "function") { + map.fire("mapgl:flowmap-reinit"); + } + }, 50); + }); + } + + x.flowmaps.forEach(function (config) { + const id = config.id; + const cSettings = config.settings || {}; + if (map._flowmapSelectedLocations[id] === undefined) { + const initialLocs = cSettings.selectedLocations; + map._flowmapSelectedLocations[id] = Array.isArray(initialLocs) + ? [...initialLocs] + : (initialLocs ? [initialLocs] : []); + } + if (map._flowmapHoveredLocation[id] === undefined) { + map._flowmapHoveredLocation[id] = null; + } + if (map._flowmapHoverTimers[id] === undefined) { + map._flowmapHoverTimers[id] = null; + } + }); + + redrawFlowmaps(map, HTMLWidgets); + } + + function redrawFlowmaps(map, HTMLWidgets) { + if (!map._flowmapsConfig) return; + const HTMLWidgetsInstance = HTMLWidgets || map._flowmapHTMLWidgets; + const layers = []; + + map._flowmapsConfig.forEach(function (config) { + const id = config.id; + const settings = config.settings || {}; + const isVisible = config.visibility !== "none"; + + if (!isVisible) { + return; + } + + const hoverActive = settings.hoverToHighlight && map._flowmapHoveredLocation[id]; + + if (!config.data._locationsRows) { + config.data._locationsRows = dataframeToRows(config.data.locations, HTMLWidgetsInstance); + } + if (!config.data._flowsRows) { + config.data._flowsRows = dataframeToRows(config.data.flows, HTMLWidgetsInstance); + } + + let baseLocations = config.data._locationsRows; + let baseFlows = config.data._flowsRows; + + const selected = map._flowmapSelectedLocations[id] || []; + if (settings.clickToFilter && selected.length > 0) { + const selectedSet = new Set(selected.map(String)); + baseFlows = baseFlows.filter(function (flow) { + return selectedSet.has(String(flow.origin)) || selectedSet.has(String(flow.dest)); + }); + } + + if (hoverActive) { + const hovered = map._flowmapHoveredLocation[id]; + + // Build the full normal layer first, then clone it with dimmed opacity. + // Cloning reuses the FlowmapLayer's internal state and preserves handlers. + const layer = makeLayer(config, HTMLWidgetsInstance, map, baseLocations, baseFlows); + const dimOpacity = (settings.opacity == null ? 1.0 : settings.opacity) * 0.15; + const baseLayer = cloneFlowmapLayer(layer, { + id: id + "-dim", + opacity: dimOpacity, + pickable: true // Keep pickable so hover events pass through to handlers + }); + layers.push(baseLayer); + + let highlightFlows = []; + let highlightLocations = []; + const connectedLocationIds = new Set(); + + if (hovered.type === "location") { + const hoveredId = String(hovered.id); + connectedLocationIds.add(hoveredId); + highlightFlows = baseFlows.filter(function (flow) { + const isConnected = String(flow.origin) === hoveredId || String(flow.dest) === hoveredId; + if (isConnected) { + connectedLocationIds.add(String(flow.origin)); + connectedLocationIds.add(String(flow.dest)); + } + return isConnected; + }); + } else if (hovered.type === "flow") { + // For flow type, origin/dest IDs are in hovered.origin.id and hovered.dest.id + // (the picking info object has {type:'flow', flow:, origin:, dest:, count}) + const originId = hovered.origin ? String(hovered.origin.id) : null; + const destId = hovered.dest ? String(hovered.dest.id) : null; + if (originId && destId) { + connectedLocationIds.add(originId); + connectedLocationIds.add(destId); + highlightFlows = baseFlows.filter(function (flow) { + return String(flow.origin) === originId && String(flow.dest) === destId; + }); + } + } + + highlightLocations = baseLocations.filter(function (loc) { + return connectedLocationIds.has(String(loc.id)); + }); + + // Highlight overlay — not pickable so cursor passes through to dim base layer. + const hlLayerSettings = Object.assign({}, settings, { + opacity: settings.opacity == null ? 1.0 : settings.opacity, + clusteringEnabled: false // disable clustering so small highlight sets render correctly + }); + const highlightLayerConfig = { + _canonicalId: id, + id: id + "-highlight", + data: config.data, + settings: hlLayerSettings, + visibility: config.visibility, + beforeId: config.beforeId, + slot: config.slot, + tooltip: null, + popup: null, + }; + + const highlightLayer = makeLayer( + highlightLayerConfig, + HTMLWidgetsInstance, + map, + highlightLocations, + highlightFlows, + false // not pickable + ); + layers.push(highlightLayer); + } else { + const normalLayer = makeLayer(config, HTMLWidgetsInstance, map, baseLocations, baseFlows); + layers.push(normalLayer); + } + }); + + map._mapglFlowmapLayers = layers; + const overlay = map._mapglFlowmapOverlay || map._deckgl; + if (overlay) { + overlay.setProps({ layers: layers }); + } + } + + function handleHoverInteraction(map, config, info) { + const id = config.id; + const settings = config.settings || {}; + const hoveredObject = info && info.object; + + if (map._flowmapHoverTimers[id]) { + clearTimeout(map._flowmapHoverTimers[id]); + map._flowmapHoverTimers[id] = null; + } + + if (hoveredObject) { + const objectType = hoveredObject.type; // 'location' or 'flow' — set by FlowmapLayer + + if (objectType === "location" || objectType === "flow") { + const currentHovered = map._flowmapHoveredLocation[id]; + let isSame = false; + if (currentHovered && currentHovered.type === objectType) { + if (objectType === "location") { + isSame = String(currentHovered.id) === String(hoveredObject.id); + } else { + // For flows: use origin.id / dest.id from the enriched location objects + const curOrig = currentHovered.origin && String(currentHovered.origin.id); + const curDest = currentHovered.dest && String(currentHovered.dest.id); + const newOrig = hoveredObject.origin && String(hoveredObject.origin.id); + const newDest = hoveredObject.dest && String(hoveredObject.dest.id); + isSame = curOrig === newOrig && curDest === newDest; + } + } + + if (!isSame) { + const delay = settings.hoverHighlightDelay != null ? settings.hoverHighlightDelay : 500; + if (delay > 0) { + map._flowmapHoverTimers[id] = setTimeout(function () { + map._flowmapHoveredLocation[id] = hoveredObject; + map._flowmapHoverTimers[id] = null; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + }, delay); + } else { + map._flowmapHoveredLocation[id] = hoveredObject; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + } + return; + } + } + + // Mouse left the element — clear pending timer and reset highlight + if (map._flowmapHoveredLocation[id] !== null) { + map._flowmapHoveredLocation[id] = null; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + } + + function handleClickInteraction(map, config, info) { + const id = config.id; + const clickedObject = info && info.object; + if (!clickedObject) { + return; + } + + const objectType = clickedObject.type; // 'location' or 'flow' + + if (objectType === "location") { + const locId = clickedObject.id; + const selected = map._flowmapSelectedLocations[id] || []; + const index = selected.indexOf(locId); + let newSelected; + if (index > -1) { + // Deselect + newSelected = selected.filter(function(s) { return s !== locId; }); + } else { + // Select — copy to avoid mutation + newSelected = selected.concat([locId]); + } + map._flowmapSelectedLocations[id] = newSelected; + // Clear hover highlight when selection changes + if (map._flowmapHoverTimers[id]) { + clearTimeout(map._flowmapHoverTimers[id]); + map._flowmapHoverTimers[id] = null; + } + map._flowmapHoveredLocation[id] = null; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + } + + function hasLayer(map, id) { + // First check canonical config store (works even when hover replaces the layer id) + if (map && map._flowmapsConfig) { + return map._flowmapsConfig.some(function (c) { return c.id === id; }); + } + return Boolean( + map && + map._mapglFlowmapLayers && + map._mapglFlowmapLayers.some(function (layer) { + return layer.id === id; + }), + ); + } + + function getVisibility(map, id) { + if (!map._flowmapsConfig) return undefined; + const config = map._flowmapsConfig.find(function (c) { + return c.id === id; + }); + return config ? (config.visibility === "none" ? "none" : "visible") : undefined; + } + + function setVisibility(map, id, visibility) { + if (!map._flowmapsConfig) { + return false; + } + let found = false; + map._flowmapsConfig.forEach(function (config) { + if (config.id === id) { + config.visibility = visibility; + if (visibility === "none") { + hideFlowmapTooltip(map, id); + } + found = true; + } + }); + if (found) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + return true; + } + return false; + } + + function setFilter(map, id, filter) { + if (!map._flowmapsConfig) { + return false; + } + let found = false; + map._flowmapsConfig.forEach(function (config) { + if (config.id === id) { + if (!config.settings) { + config.settings = {}; + } + Object.assign(config.settings, filter); + + if (filter.selectedLocations) { + map._flowmapSelectedLocations[id] = filter.selectedLocations; + } + + found = true; + } + }); + if (found) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + return true; + } + return false; + } + + function normalizeTimeRanges(ranges) { + if (!Array.isArray(ranges)) { + return null; + } + + return ranges + .filter(function (range) { + return Array.isArray(range) && range.length === 2; + }) + .map(function (range) { + return [new Date(range[0]), new Date(range[1])]; + }); + } + + function setSettings(map, id, settings) { + if (!map._flowmapsConfig) { + return false; + } + let found = false; + map._flowmapsConfig.forEach(function (config) { + if (config.id === id) { + if (!config.settings) { + config.settings = {}; + } + Object.assign(config.settings, settings); + found = true; + } + }); + if (found) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + return true; + } + return false; + } + + return { + init: init, + hasLayer: hasLayer, + getVisibility: getVisibility, + setVisibility: setVisibility, + setFilter: setFilter, + setSettings: setSettings, + }; +})(); diff --git a/inst/htmlwidgets/lib/d3/d3.min.js b/inst/htmlwidgets/lib/d3/d3.min.js new file mode 100644 index 00000000..33bb8802 --- /dev/null +++ b/inst/htmlwidgets/lib/d3/d3.min.js @@ -0,0 +1,2 @@ +// https://d3js.org v7.9.0 Copyright 2010-2023 Mike Bostock +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).d3=t.d3||{})}(this,(function(t){"use strict";function n(t,n){return null==t||null==n?NaN:tn?1:t>=n?0:NaN}function e(t,n){return null==t||null==n?NaN:nt?1:n>=t?0:NaN}function r(t){let r,o,a;function u(t,n,e=0,i=t.length){if(e>>1;o(t[r],n)<0?e=r+1:i=r}while(en(t(e),r),a=(n,e)=>t(n)-e):(r=t===n||t===e?t:i,o=t,a=t),{left:u,center:function(t,n,e=0,r=t.length){const i=u(t,n,e,r-1);return i>e&&a(t[i-1],n)>-a(t[i],n)?i-1:i},right:function(t,n,e=0,i=t.length){if(e>>1;o(t[r],n)<=0?e=r+1:i=r}while(e{n(t,e,(r<<=2)+0,(i<<=2)+0,o<<=2),n(t,e,r+1,i+1,o),n(t,e,r+2,i+2,o),n(t,e,r+3,i+3,o)}}));function d(t){return function(n,e,r=e){if(!((e=+e)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:i,width:o,height:a}=n;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((a=Math.floor(void 0!==a?a:i.length/o))>=0))throw new RangeError("invalid height");if(!o||!a||!e&&!r)return n;const u=e&&t(e),c=r&&t(r),f=i.slice();return u&&c?(p(u,f,i,o,a),p(u,i,f,o,a),p(u,f,i,o,a),g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)):u?(p(u,i,f,o,a),p(u,f,i,o,a),p(u,i,f,o,a)):c&&(g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)),n}}function p(t,n,e,r,i){for(let o=0,a=r*i;o{if(!((o-=a)>=i))return;let u=t*r[i];const c=a*t;for(let t=i,n=i+c;t{if(!((a-=u)>=o))return;let c=n*i[o];const f=u*n,s=f+u;for(let t=o,n=o+f;t=n&&++e;else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(i=+i)>=i&&++e}return e}function _(t){return 0|t.length}function b(t){return!(t>0)}function m(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function x(t,n){let e,r=0,i=0,o=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(e=n-i,i+=e/++r,o+=e*(n-i));else{let a=-1;for(let u of t)null!=(u=n(u,++a,t))&&(u=+u)>=u&&(e=u-i,i+=e/++r,o+=e*(u-i))}if(r>1)return o/(r-1)}function w(t,n){const e=x(t,n);return e?Math.sqrt(e):e}function M(t,n){let e,r;if(void 0===n)for(const n of t)null!=n&&(void 0===e?n>=n&&(e=r=n):(e>n&&(e=n),r=o&&(e=r=o):(e>o&&(e=o),r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}class InternMap extends Map{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const[n,e]of t)this.set(n,e)}get(t){return super.get(A(this,t))}has(t){return super.has(A(this,t))}set(t,n){return super.set(S(this,t),n)}delete(t){return super.delete(E(this,t))}}class InternSet extends Set{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const n of t)this.add(n)}has(t){return super.has(A(this,t))}add(t){return super.add(S(this,t))}delete(t){return super.delete(E(this,t))}}function A({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):e}function S({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):(t.set(r,e),e)}function E({_intern:t,_key:n},e){const r=n(e);return t.has(r)&&(e=t.get(r),t.delete(r)),e}function N(t){return null!==t&&"object"==typeof t?t.valueOf():t}function k(t){return t}function C(t,...n){return F(t,k,k,n)}function P(t,...n){return F(t,Array.from,k,n)}function z(t,n){for(let e=1,r=n.length;et.pop().map((([n,e])=>[...t,n,e]))));return t}function $(t,n,...e){return F(t,k,n,e)}function D(t,n,...e){return F(t,Array.from,n,e)}function R(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function F(t,n,e,r){return function t(i,o){if(o>=r.length)return e(i);const a=new InternMap,u=r[o++];let c=-1;for(const t of i){const n=u(t,++c,i),e=a.get(n);e?e.push(t):a.set(n,[t])}for(const[n,e]of a)a.set(n,t(e,o));return n(a)}(t,0)}function q(t,n){return Array.from(n,(n=>t[n]))}function U(t,...n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[e]=n;if(e&&2!==e.length||n.length>1){const r=Uint32Array.from(t,((t,n)=>n));return n.length>1?(n=n.map((n=>t.map(n))),r.sort(((t,e)=>{for(const r of n){const n=O(r[t],r[e]);if(n)return n}}))):(e=t.map(e),r.sort(((t,n)=>O(e[t],e[n])))),q(t,r)}return t.sort(I(e))}function I(t=n){if(t===n)return O;if("function"!=typeof t)throw new TypeError("compare is not a function");return(n,e)=>{const r=t(n,e);return r||0===r?r:(0===t(e,e))-(0===t(n,n))}}function O(t,n){return(null==t||!(t>=t))-(null==n||!(n>=n))||(tn?1:0)}var B=Array.prototype.slice;function Y(t){return()=>t}const L=Math.sqrt(50),j=Math.sqrt(10),H=Math.sqrt(2);function X(t,n,e){const r=(n-t)/Math.max(0,e),i=Math.floor(Math.log10(r)),o=r/Math.pow(10,i),a=o>=L?10:o>=j?5:o>=H?2:1;let u,c,f;return i<0?(f=Math.pow(10,-i)/a,u=Math.round(t*f),c=Math.round(n*f),u/fn&&--c,f=-f):(f=Math.pow(10,i)*a,u=Math.round(t/f),c=Math.round(n/f),u*fn&&--c),c0))return[];if((t=+t)===(n=+n))return[t];const r=n=i))return[];const u=o-i+1,c=new Array(u);if(r)if(a<0)for(let t=0;t0?(t=Math.floor(t/i)*i,n=Math.ceil(n/i)*i):i<0&&(t=Math.ceil(t*i)/i,n=Math.floor(n*i)/i),r=i}}function K(t){return Math.max(1,Math.ceil(Math.log(v(t))/Math.LN2)+1)}function Q(){var t=k,n=M,e=K;function r(r){Array.isArray(r)||(r=Array.from(r));var i,o,a,u=r.length,c=new Array(u);for(i=0;i=h)if(t>=h&&n===M){const t=V(l,h,e);isFinite(t)&&(t>0?h=(Math.floor(h/t)+1)*t:t<0&&(h=(Math.ceil(h*-t)+1)/-t))}else d.pop()}for(var p=d.length,g=0,y=p;d[g]<=l;)++g;for(;d[y-1]>h;)--y;(g||y0?d[i-1]:l,v.x1=i0)for(i=0;i=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e=i)&&(e=i)}return e}function tt(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e=o)&&(e=o,r=i);return r}function nt(t,n){let e;if(void 0===n)for(const n of t)null!=n&&(e>n||void 0===e&&n>=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e>i||void 0===e&&i>=i)&&(e=i)}return e}function et(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e>n||void 0===e&&n>=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e>o||void 0===e&&o>=o)&&(e=o,r=i);return r}function rt(t,n,e=0,r=1/0,i){if(n=Math.floor(n),e=Math.floor(Math.max(0,e)),r=Math.floor(Math.min(t.length-1,r)),!(e<=n&&n<=r))return t;for(i=void 0===i?O:I(i);r>e;){if(r-e>600){const o=r-e+1,a=n-e+1,u=Math.log(o),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(o-c)/o)*(a-o/2<0?-1:1);rt(t,n,Math.max(e,Math.floor(n-a*c/o+f)),Math.min(r,Math.floor(n+(o-a)*c/o+f)),i)}const o=t[n];let a=e,u=r;for(it(t,e,n),i(t[r],o)>0&&it(t,e,r);a0;)--u}0===i(t[e],o)?it(t,e,u):(++u,it(t,u,r)),u<=n&&(e=u+1),n<=u&&(r=u-1)}return t}function it(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function ot(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)>0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)>0:0===e(n,n))&&(r=n,i=!0);return r}function at(t,n,e){if(t=Float64Array.from(function*(t,n){if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(yield n);else{let e=-1;for(let r of t)null!=(r=n(r,++e,t))&&(r=+r)>=r&&(yield r)}}(t,e)),(r=t.length)&&!isNaN(n=+n)){if(n<=0||r<2)return nt(t);if(n>=1)return J(t);var r,i=(r-1)*n,o=Math.floor(i),a=J(rt(t,o).subarray(0,o+1));return a+(nt(t.subarray(o+1))-a)*(i-o)}}function ut(t,n,e=o){if((r=t.length)&&!isNaN(n=+n)){if(n<=0||r<2)return+e(t[0],0,t);if(n>=1)return+e(t[r-1],r-1,t);var r,i=(r-1)*n,a=Math.floor(i),u=+e(t[a],a,t);return u+(+e(t[a+1],a+1,t)-u)*(i-a)}}function ct(t,n,e=o){if(!isNaN(n=+n)){if(r=Float64Array.from(t,((n,r)=>o(e(t[r],r,t)))),n<=0)return et(r);if(n>=1)return tt(r);var r,i=Uint32Array.from(t,((t,n)=>n)),a=r.length-1,u=Math.floor(a*n);return rt(i,u,0,a,((t,n)=>O(r[t],r[n]))),(u=ot(i.subarray(0,u+1),(t=>r[t])))>=0?u:-1}}function ft(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}function st(t,n){return[t,n]}function lt(t,n,e){t=+t,n=+n,e=(i=arguments.length)<2?(n=t,t=0,1):i<3?1:+e;for(var r=-1,i=0|Math.max(0,Math.ceil((n-t)/e)),o=new Array(i);++r+t(n)}function kt(t,n){return n=Math.max(0,t.bandwidth()-2*n)/2,t.round()&&(n=Math.round(n)),e=>+t(e)+n}function Ct(){return!this.__axis}function Pt(t,n){var e=[],r=null,i=null,o=6,a=6,u=3,c="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,f=t===xt||t===Tt?-1:1,s=t===Tt||t===wt?"x":"y",l=t===xt||t===Mt?St:Et;function h(h){var d=null==r?n.ticks?n.ticks.apply(n,e):n.domain():r,p=null==i?n.tickFormat?n.tickFormat.apply(n,e):mt:i,g=Math.max(o,0)+u,y=n.range(),v=+y[0]+c,_=+y[y.length-1]+c,b=(n.bandwidth?kt:Nt)(n.copy(),c),m=h.selection?h.selection():h,x=m.selectAll(".domain").data([null]),w=m.selectAll(".tick").data(d,n).order(),M=w.exit(),T=w.enter().append("g").attr("class","tick"),A=w.select("line"),S=w.select("text");x=x.merge(x.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),w=w.merge(T),A=A.merge(T.append("line").attr("stroke","currentColor").attr(s+"2",f*o)),S=S.merge(T.append("text").attr("fill","currentColor").attr(s,f*g).attr("dy",t===xt?"0em":t===Mt?"0.71em":"0.32em")),h!==m&&(x=x.transition(h),w=w.transition(h),A=A.transition(h),S=S.transition(h),M=M.transition(h).attr("opacity",At).attr("transform",(function(t){return isFinite(t=b(t))?l(t+c):this.getAttribute("transform")})),T.attr("opacity",At).attr("transform",(function(t){var n=this.parentNode.__axis;return l((n&&isFinite(n=n(t))?n:b(t))+c)}))),M.remove(),x.attr("d",t===Tt||t===wt?a?"M"+f*a+","+v+"H"+c+"V"+_+"H"+f*a:"M"+c+","+v+"V"+_:a?"M"+v+","+f*a+"V"+c+"H"+_+"V"+f*a:"M"+v+","+c+"H"+_),w.attr("opacity",1).attr("transform",(function(t){return l(b(t)+c)})),A.attr(s+"2",f*o),S.attr(s,f*g).text(p),m.filter(Ct).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===wt?"start":t===Tt?"end":"middle"),m.each((function(){this.__axis=b}))}return h.scale=function(t){return arguments.length?(n=t,h):n},h.ticks=function(){return e=Array.from(arguments),h},h.tickArguments=function(t){return arguments.length?(e=null==t?[]:Array.from(t),h):e.slice()},h.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),h):r&&r.slice()},h.tickFormat=function(t){return arguments.length?(i=t,h):i},h.tickSize=function(t){return arguments.length?(o=a=+t,h):o},h.tickSizeInner=function(t){return arguments.length?(o=+t,h):o},h.tickSizeOuter=function(t){return arguments.length?(a=+t,h):a},h.tickPadding=function(t){return arguments.length?(u=+t,h):u},h.offset=function(t){return arguments.length?(c=+t,h):c},h}var zt={value:()=>{}};function $t(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),a=-1,u=o.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++a0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),Ut.hasOwnProperty(n)?{space:Ut[n],local:t}:t}function Ot(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===qt&&n.documentElement.namespaceURI===qt?n.createElement(t):n.createElementNS(e,t)}}function Bt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Yt(t){var n=It(t);return(n.local?Bt:Ot)(n)}function Lt(){}function jt(t){return null==t?Lt:function(){return this.querySelector(t)}}function Ht(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function Xt(){return[]}function Gt(t){return null==t?Xt:function(){return this.querySelectorAll(t)}}function Vt(t){return function(){return this.matches(t)}}function Wt(t){return function(n){return n.matches(t)}}var Zt=Array.prototype.find;function Kt(){return this.firstElementChild}var Qt=Array.prototype.filter;function Jt(){return Array.from(this.children)}function tn(t){return new Array(t.length)}function nn(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function en(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;un?1:t>=n?0:NaN}function cn(t){return function(){this.removeAttribute(t)}}function fn(t){return function(){this.removeAttributeNS(t.space,t.local)}}function sn(t,n){return function(){this.setAttribute(t,n)}}function ln(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function hn(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function dn(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function pn(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function gn(t){return function(){this.style.removeProperty(t)}}function yn(t,n,e){return function(){this.style.setProperty(t,n,e)}}function vn(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function _n(t,n){return t.style.getPropertyValue(n)||pn(t).getComputedStyle(t,null).getPropertyValue(n)}function bn(t){return function(){delete this[t]}}function mn(t,n){return function(){this[t]=n}}function xn(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function wn(t){return t.trim().split(/^|\s+/)}function Mn(t){return t.classList||new Tn(t)}function Tn(t){this._node=t,this._names=wn(t.getAttribute("class")||"")}function An(t,n){for(var e=Mn(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Gn=[null];function Vn(t,n){this._groups=t,this._parents=n}function Wn(){return new Vn([[document.documentElement]],Gn)}function Zn(t){return"string"==typeof t?new Vn([[document.querySelector(t)]],[document.documentElement]):new Vn([[t]],Gn)}Vn.prototype=Wn.prototype={constructor:Vn,select:function(t){"function"!=typeof t&&(t=jt(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=m&&(m=b+1);!(_=y[m])&&++m=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=un);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?gn:"function"==typeof n?vn:yn)(t,n,null==e?"":e)):_n(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?bn:"function"==typeof n?xn:mn)(t,n)):this.node()[t]},classed:function(t,n){var e=wn(t+"");if(arguments.length<2){for(var r=Mn(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?Ln:Yn,r=0;r()=>t;function fe(t,{sourceEvent:n,subject:e,target:r,identifier:i,active:o,x:a,y:u,dx:c,dy:f,dispatch:s}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},subject:{value:e,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:f,enumerable:!0,configurable:!0},_:{value:s}})}function se(t){return!t.ctrlKey&&!t.button}function le(){return this.parentNode}function he(t,n){return null==n?{x:t.x,y:t.y}:n}function de(){return navigator.maxTouchPoints||"ontouchstart"in this}function pe(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function ge(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function ye(){}fe.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var ve=.7,_e=1/ve,be="\\s*([+-]?\\d+)\\s*",me="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",xe="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",we=/^#([0-9a-f]{3,8})$/,Me=new RegExp(`^rgb\\(${be},${be},${be}\\)$`),Te=new RegExp(`^rgb\\(${xe},${xe},${xe}\\)$`),Ae=new RegExp(`^rgba\\(${be},${be},${be},${me}\\)$`),Se=new RegExp(`^rgba\\(${xe},${xe},${xe},${me}\\)$`),Ee=new RegExp(`^hsl\\(${me},${xe},${xe}\\)$`),Ne=new RegExp(`^hsla\\(${me},${xe},${xe},${me}\\)$`),ke={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Ce(){return this.rgb().formatHex()}function Pe(){return this.rgb().formatRgb()}function ze(t){var n,e;return t=(t+"").trim().toLowerCase(),(n=we.exec(t))?(e=n[1].length,n=parseInt(n[1],16),6===e?$e(n):3===e?new qe(n>>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?De(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?De(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=Me.exec(t))?new qe(n[1],n[2],n[3],1):(n=Te.exec(t))?new qe(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Ae.exec(t))?De(n[1],n[2],n[3],n[4]):(n=Se.exec(t))?De(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Ee.exec(t))?Le(n[1],n[2]/100,n[3]/100,1):(n=Ne.exec(t))?Le(n[1],n[2]/100,n[3]/100,n[4]):ke.hasOwnProperty(t)?$e(ke[t]):"transparent"===t?new qe(NaN,NaN,NaN,0):null}function $e(t){return new qe(t>>16&255,t>>8&255,255&t,1)}function De(t,n,e,r){return r<=0&&(t=n=e=NaN),new qe(t,n,e,r)}function Re(t){return t instanceof ye||(t=ze(t)),t?new qe((t=t.rgb()).r,t.g,t.b,t.opacity):new qe}function Fe(t,n,e,r){return 1===arguments.length?Re(t):new qe(t,n,e,null==r?1:r)}function qe(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Ue(){return`#${Ye(this.r)}${Ye(this.g)}${Ye(this.b)}`}function Ie(){const t=Oe(this.opacity);return`${1===t?"rgb(":"rgba("}${Be(this.r)}, ${Be(this.g)}, ${Be(this.b)}${1===t?")":`, ${t})`}`}function Oe(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Be(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Ye(t){return((t=Be(t))<16?"0":"")+t.toString(16)}function Le(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Xe(t,n,e,r)}function je(t){if(t instanceof Xe)return new Xe(t.h,t.s,t.l,t.opacity);if(t instanceof ye||(t=ze(t)),!t)return new Xe;if(t instanceof Xe)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e0&&c<1?0:a,new Xe(a,u,c,t.opacity)}function He(t,n,e,r){return 1===arguments.length?je(t):new Xe(t,n,e,null==r?1:r)}function Xe(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Ge(t){return(t=(t||0)%360)<0?t+360:t}function Ve(t){return Math.max(0,Math.min(1,t||0))}function We(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}pe(ye,ze,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ce,formatHex:Ce,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return je(this).formatHsl()},formatRgb:Pe,toString:Pe}),pe(qe,Fe,ge(ye,{brighter(t){return t=null==t?_e:Math.pow(_e,t),new qe(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?ve:Math.pow(ve,t),new qe(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new qe(Be(this.r),Be(this.g),Be(this.b),Oe(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Ue,formatHex:Ue,formatHex8:function(){return`#${Ye(this.r)}${Ye(this.g)}${Ye(this.b)}${Ye(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Ie,toString:Ie})),pe(Xe,He,ge(ye,{brighter(t){return t=null==t?_e:Math.pow(_e,t),new Xe(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?ve:Math.pow(ve,t),new Xe(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new qe(We(t>=240?t-240:t+120,i,r),We(t,i,r),We(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Xe(Ge(this.h),Ve(this.s),Ve(this.l),Oe(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Oe(this.opacity);return`${1===t?"hsl(":"hsla("}${Ge(this.h)}, ${100*Ve(this.s)}%, ${100*Ve(this.l)}%${1===t?")":`, ${t})`}`}}));const Ze=Math.PI/180,Ke=180/Math.PI,Qe=.96422,Je=1,tr=.82521,nr=4/29,er=6/29,rr=3*er*er,ir=er*er*er;function or(t){if(t instanceof ur)return new ur(t.l,t.a,t.b,t.opacity);if(t instanceof pr)return gr(t);t instanceof qe||(t=Re(t));var n,e,r=lr(t.r),i=lr(t.g),o=lr(t.b),a=cr((.2225045*r+.7168786*i+.0606169*o)/Je);return r===i&&i===o?n=e=a:(n=cr((.4360747*r+.3850649*i+.1430804*o)/Qe),e=cr((.0139322*r+.0971045*i+.7141733*o)/tr)),new ur(116*a-16,500*(n-a),200*(a-e),t.opacity)}function ar(t,n,e,r){return 1===arguments.length?or(t):new ur(t,n,e,null==r?1:r)}function ur(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function cr(t){return t>ir?Math.pow(t,1/3):t/rr+nr}function fr(t){return t>er?t*t*t:rr*(t-nr)}function sr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function lr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function hr(t){if(t instanceof pr)return new pr(t.h,t.c,t.l,t.opacity);if(t instanceof ur||(t=or(t)),0===t.a&&0===t.b)return new pr(NaN,0=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r()=>t;function Cr(t,n){return function(e){return t+e*n}}function Pr(t,n){var e=n-t;return e?Cr(t,e>180||e<-180?e-360*Math.round(e/360):e):kr(isNaN(t)?n:t)}function zr(t){return 1==(t=+t)?$r:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):kr(isNaN(n)?e:n)}}function $r(t,n){var e=n-t;return e?Cr(t,e):kr(isNaN(t)?n:t)}var Dr=function t(n){var e=zr(n);function r(t,n){var r=e((t=Fe(t)).r,(n=Fe(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=$r(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function Rr(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;eo&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:Yr(e,r)})),o=Hr.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:Yr(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:Yr(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:Yr(t,e)},{i:u-2,x:Yr(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e=0&&n._call.call(void 0,t),n=n._next;--yi}function Ci(){xi=(mi=Mi.now())+wi,yi=vi=0;try{ki()}finally{yi=0,function(){var t,n,e=pi,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:pi=n);gi=t,zi(r)}(),xi=0}}function Pi(){var t=Mi.now(),n=t-mi;n>bi&&(wi-=n,mi=t)}function zi(t){yi||(vi&&(vi=clearTimeout(vi)),t-xi>24?(t<1/0&&(vi=setTimeout(Ci,t-Mi.now()-wi)),_i&&(_i=clearInterval(_i))):(_i||(mi=Mi.now(),_i=setInterval(Pi,bi)),yi=1,Ti(Ci)))}function $i(t,n,e){var r=new Ei;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Ei.prototype=Ni.prototype={constructor:Ei,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?Ai():+e)+(null==n?0:+n),this._next||gi===this||(gi?gi._next=this:pi=this,gi=this),this._call=t,this._time=e,zi()},stop:function(){this._call&&(this._call=null,this._time=1/0,zi())}};var Di=$t("start","end","cancel","interrupt"),Ri=[],Fi=0,qi=1,Ui=2,Ii=3,Oi=4,Bi=5,Yi=6;function Li(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=qi,e.timer.restart(a,e.delay,e.time),e.delay<=t&&a(t-e.delay)}function a(o){var f,s,l,h;if(e.state!==qi)return c();for(f in i)if((h=i[f]).name===e.name){if(h.state===Ii)return $i(a);h.state===Oi?(h.state=Yi,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+fFi)throw new Error("too late; already scheduled");return e}function Hi(t,n){var e=Xi(t,n);if(e.state>Ii)throw new Error("too late; already running");return e}function Xi(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Gi(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>Ui&&e.state=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?ji:Hi;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}(e,t,n))},attr:function(t,n){var e=It(t),r="transform"===e?ni:Ki;return this.attrTween(t,"function"==typeof n?(e.local?ro:eo)(e,r,Zi(this,"attr."+t,n)):null==n?(e.local?Ji:Qi)(e):(e.local?no:to)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=It(t);return this.tween(e,(r.local?io:oo)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?ti:Ki;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=_n(this,t),a=(this.style.removeProperty(t),_n(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,lo(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=_n(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=_n(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,Zi(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=Hi(this,t),f=c.on,s=null==c.value[a]?o||(o=lo(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=_n(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(Zi(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Xi(this.node(),e).tween,o=0,a=i.length;o()=>t;function Qo(t,{sourceEvent:n,target:e,selection:r,mode:i,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:i,enumerable:!0,configurable:!0},_:{value:o}})}function Jo(t){t.preventDefault(),t.stopImmediatePropagation()}var ta={name:"drag"},na={name:"space"},ea={name:"handle"},ra={name:"center"};const{abs:ia,max:oa,min:aa}=Math;function ua(t){return[+t[0],+t[1]]}function ca(t){return[ua(t[0]),ua(t[1])]}var fa={name:"x",handles:["w","e"].map(va),input:function(t,n){return null==t?null:[[+t[0],n[0][1]],[+t[1],n[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},sa={name:"y",handles:["n","s"].map(va),input:function(t,n){return null==t?null:[[n[0][0],+t[0]],[n[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},la={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(va),input:function(t){return null==t?null:ca(t)},output:function(t){return t}},ha={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},da={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},pa={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},ga={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},ya={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function va(t){return{type:t}}function _a(t){return!t.ctrlKey&&!t.button}function ba(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function ma(){return navigator.maxTouchPoints||"ontouchstart"in this}function xa(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function wa(t){var n,e=ba,r=_a,i=ma,o=!0,a=$t("start","brush","end"),u=6;function c(n){var e=n.property("__brush",g).selectAll(".overlay").data([va("overlay")]);e.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",ha.overlay).merge(e).each((function(){var t=xa(this).extent;Zn(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),n.selectAll(".selection").data([va("selection")]).enter().append("rect").attr("class","selection").attr("cursor",ha.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=n.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return ha[t.type]})),n.each(f).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",h).filter(i).on("touchstart.brush",h).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function f(){var t=Zn(this),n=xa(this).selection;n?(t.selectAll(".selection").style("display",null).attr("x",n[0][0]).attr("y",n[0][1]).attr("width",n[1][0]-n[0][0]).attr("height",n[1][1]-n[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?n[1][0]-u/2:n[0][0]-u/2})).attr("y",(function(t){return"s"===t.type[0]?n[1][1]-u/2:n[0][1]-u/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?n[1][0]-n[0][0]+u:u})).attr("height",(function(t){return"e"===t.type||"w"===t.type?n[1][1]-n[0][1]+u:u}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function s(t,n,e){var r=t.__brush.emitter;return!r||e&&r.clean?new l(t,n,e):r}function l(t,n,e){this.that=t,this.args=n,this.state=t.__brush,this.active=0,this.clean=e}function h(e){if((!n||e.touches)&&r.apply(this,arguments)){var i,a,u,c,l,h,d,p,g,y,v,_=this,b=e.target.__data__.type,m="selection"===(o&&e.metaKey?b="overlay":b)?ta:o&&e.altKey?ra:ea,x=t===sa?null:ga[b],w=t===fa?null:ya[b],M=xa(_),T=M.extent,A=M.selection,S=T[0][0],E=T[0][1],N=T[1][0],k=T[1][1],C=0,P=0,z=x&&w&&o&&e.shiftKey,$=Array.from(e.touches||[e],(t=>{const n=t.identifier;return(t=ne(t,_)).point0=t.slice(),t.identifier=n,t}));Gi(_);var D=s(_,arguments,!0).beforestart();if("overlay"===b){A&&(g=!0);const n=[$[0],$[1]||$[0]];M.selection=A=[[i=t===sa?S:aa(n[0][0],n[1][0]),u=t===fa?E:aa(n[0][1],n[1][1])],[l=t===sa?N:oa(n[0][0],n[1][0]),d=t===fa?k:oa(n[0][1],n[1][1])]],$.length>1&&I(e)}else i=A[0][0],u=A[0][1],l=A[1][0],d=A[1][1];a=i,c=u,h=l,p=d;var R=Zn(_).attr("pointer-events","none"),F=R.selectAll(".overlay").attr("cursor",ha[b]);if(e.touches)D.moved=U,D.ended=O;else{var q=Zn(e.view).on("mousemove.brush",U,!0).on("mouseup.brush",O,!0);o&&q.on("keydown.brush",(function(t){switch(t.keyCode){case 16:z=x&&w;break;case 18:m===ea&&(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=ra,I(t));break;case 32:m!==ea&&m!==ra||(x<0?l=h-C:x>0&&(i=a-C),w<0?d=p-P:w>0&&(u=c-P),m=na,F.attr("cursor",ha.selection),I(t));break;default:return}Jo(t)}),!0).on("keyup.brush",(function(t){switch(t.keyCode){case 16:z&&(y=v=z=!1,I(t));break;case 18:m===ra&&(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=ea,I(t));break;case 32:m===na&&(t.altKey?(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=ra):(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=ea),F.attr("cursor",ha[b]),I(t));break;default:return}Jo(t)}),!0),ae(e.view)}f.call(_),D.start(e,m.name)}function U(t){for(const n of t.changedTouches||[t])for(const t of $)t.identifier===n.identifier&&(t.cur=ne(n,_));if(z&&!y&&!v&&1===$.length){const t=$[0];ia(t.cur[0]-t[0])>ia(t.cur[1]-t[1])?v=!0:y=!0}for(const t of $)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);g=!0,Jo(t),I(t)}function I(t){const n=$[0],e=n.point0;var r;switch(C=n[0]-e[0],P=n[1]-e[1],m){case na:case ta:x&&(C=oa(S-i,aa(N-l,C)),a=i+C,h=l+C),w&&(P=oa(E-u,aa(k-d,P)),c=u+P,p=d+P);break;case ea:$[1]?(x&&(a=oa(S,aa(N,$[0][0])),h=oa(S,aa(N,$[1][0])),x=1),w&&(c=oa(E,aa(k,$[0][1])),p=oa(E,aa(k,$[1][1])),w=1)):(x<0?(C=oa(S-i,aa(N-i,C)),a=i+C,h=l):x>0&&(C=oa(S-l,aa(N-l,C)),a=i,h=l+C),w<0?(P=oa(E-u,aa(k-u,P)),c=u+P,p=d):w>0&&(P=oa(E-d,aa(k-d,P)),c=u,p=d+P));break;case ra:x&&(a=oa(S,aa(N,i-C*x)),h=oa(S,aa(N,l+C*x))),w&&(c=oa(E,aa(k,u-P*w)),p=oa(E,aa(k,d+P*w)))}ht+e))}function za(t,n){var e=0,r=null,i=null,o=null;function a(a){var u,c=a.length,f=new Array(c),s=Pa(0,c),l=new Array(c*c),h=new Array(c),d=0;a=Float64Array.from({length:c*c},n?(t,n)=>a[n%c][n/c|0]:(t,n)=>a[n/c|0][n%c]);for(let n=0;nr(f[t],f[n])));for(const e of s){const r=n;if(t){const t=Pa(1+~c,c).filter((t=>t<0?a[~t*c+e]:a[e*c+t]));i&&t.sort(((t,n)=>i(t<0?-a[~t*c+e]:a[e*c+t],n<0?-a[~n*c+e]:a[e*c+n])));for(const r of t)if(r<0){(l[~r*c+e]||(l[~r*c+e]={source:null,target:null})).target={index:e,startAngle:n,endAngle:n+=a[~r*c+e]*d,value:a[~r*c+e]}}else{(l[e*c+r]||(l[e*c+r]={source:null,target:null})).source={index:e,startAngle:n,endAngle:n+=a[e*c+r]*d,value:a[e*c+r]}}h[e]={index:e,startAngle:r,endAngle:n,value:f[e]}}else{const t=Pa(0,c).filter((t=>a[e*c+t]||a[t*c+e]));i&&t.sort(((t,n)=>i(a[e*c+t],a[e*c+n])));for(const r of t){let t;if(e=0))throw new Error(`invalid digits: ${t}`);if(n>15)return qa;const e=10**n;return function(t){this._+=t[0];for(let n=1,r=t.length;nRa)if(Math.abs(s*u-c*f)>Ra&&i){let h=e-o,d=r-a,p=u*u+c*c,g=h*h+d*d,y=Math.sqrt(p),v=Math.sqrt(l),_=i*Math.tan(($a-Math.acos((p+l-g)/(2*y*v)))/2),b=_/v,m=_/y;Math.abs(b-1)>Ra&&this._append`L${t+b*f},${n+b*s}`,this._append`A${i},${i},0,0,${+(s*h>f*d)},${this._x1=t+m*u},${this._y1=n+m*c}`}else this._append`L${this._x1=t},${this._y1=n}`;else;}arc(t,n,e,r,i,o){if(t=+t,n=+n,o=!!o,(e=+e)<0)throw new Error(`negative radius: ${e}`);let a=e*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;null===this._x1?this._append`M${c},${f}`:(Math.abs(this._x1-c)>Ra||Math.abs(this._y1-f)>Ra)&&this._append`L${c},${f}`,e&&(l<0&&(l=l%Da+Da),l>Fa?this._append`A${e},${e},0,1,${s},${t-a},${n-u}A${e},${e},0,1,${s},${this._x1=c},${this._y1=f}`:l>Ra&&this._append`A${e},${e},0,${+(l>=$a)},${s},${this._x1=t+e*Math.cos(i)},${this._y1=n+e*Math.sin(i)}`)}rect(t,n,e,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${e=+e}v${+r}h${-e}Z`}toString(){return this._}};function Ia(){return new Ua}Ia.prototype=Ua.prototype;var Oa=Array.prototype.slice;function Ba(t){return function(){return t}}function Ya(t){return t.source}function La(t){return t.target}function ja(t){return t.radius}function Ha(t){return t.startAngle}function Xa(t){return t.endAngle}function Ga(){return 0}function Va(){return 10}function Wa(t){var n=Ya,e=La,r=ja,i=ja,o=Ha,a=Xa,u=Ga,c=null;function f(){var f,s=n.apply(this,arguments),l=e.apply(this,arguments),h=u.apply(this,arguments)/2,d=Oa.call(arguments),p=+r.apply(this,(d[0]=s,d)),g=o.apply(this,d)-Ea,y=a.apply(this,d)-Ea,v=+i.apply(this,(d[0]=l,d)),_=o.apply(this,d)-Ea,b=a.apply(this,d)-Ea;if(c||(c=f=Ia()),h>Ca&&(Ma(y-g)>2*h+Ca?y>g?(g+=h,y-=h):(g-=h,y+=h):g=y=(g+y)/2,Ma(b-_)>2*h+Ca?b>_?(_+=h,b-=h):(_-=h,b+=h):_=b=(_+b)/2),c.moveTo(p*Ta(g),p*Aa(g)),c.arc(0,0,p,g,y),g!==_||y!==b)if(t){var m=v-+t.apply(this,arguments),x=(_+b)/2;c.quadraticCurveTo(0,0,m*Ta(_),m*Aa(_)),c.lineTo(v*Ta(x),v*Aa(x)),c.lineTo(m*Ta(b),m*Aa(b))}else c.quadraticCurveTo(0,0,v*Ta(_),v*Aa(_)),c.arc(0,0,v,_,b);if(c.quadraticCurveTo(0,0,p*Ta(g),p*Aa(g)),c.closePath(),f)return c=null,f+""||null}return t&&(f.headRadius=function(n){return arguments.length?(t="function"==typeof n?n:Ba(+n),f):t}),f.radius=function(t){return arguments.length?(r=i="function"==typeof t?t:Ba(+t),f):r},f.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:Ba(+t),f):r},f.targetRadius=function(t){return arguments.length?(i="function"==typeof t?t:Ba(+t),f):i},f.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:Ba(+t),f):o},f.endAngle=function(t){return arguments.length?(a="function"==typeof t?t:Ba(+t),f):a},f.padAngle=function(t){return arguments.length?(u="function"==typeof t?t:Ba(+t),f):u},f.source=function(t){return arguments.length?(n=t,f):n},f.target=function(t){return arguments.length?(e=t,f):e},f.context=function(t){return arguments.length?(c=null==t?null:t,f):c},f}var Za=Array.prototype.slice;function Ka(t,n){return t-n}var Qa=t=>()=>t;function Ja(t,n){for(var e,r=-1,i=n.length;++rr!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function nu(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function eu(){}var ru=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function iu(){var t=1,n=1,e=K,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(Ka);else{const e=M(t,ou);for(n=G(...Z(e[0],e[1],n),n);n[n.length-1]>=e[1];)n.pop();for(;n[1]o(t,n)))}function o(e,i){const o=null==i?NaN:+i;if(isNaN(o))throw new Error(`invalid value: ${i}`);var u=[],c=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=au(e[0],r),ru[f<<1].forEach(p);for(;++o=r,ru[s<<2].forEach(p);for(;++o0?u.push([t]):c.push(t)})),c.forEach((function(t){for(var n,e=0,r=u.length;e0&&o0&&a=0&&o>=0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?Qa(Za.call(t)):Qa(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:eu,i):r===u},i}function ou(t){return isFinite(t)?t:NaN}function au(t,n){return null!=t&&+t>=n}function uu(t){return null==t||isNaN(t=+t)?-1/0:t}function cu(t,n,e,r){const i=r-n,o=e-n,a=isFinite(i)||isFinite(o)?i/o:Math.sign(i)/Math.sign(o);return isNaN(a)?t:t+a-.5}function fu(t){return t[0]}function su(t){return t[1]}function lu(){return 1}const hu=134217729,du=33306690738754706e-32;function pu(t,n,e,r,i){let o,a,u,c,f=n[0],s=r[0],l=0,h=0;s>f==s>-f?(o=f,f=n[++l]):(o=s,s=r[++h]);let d=0;if(lf==s>-f?(a=f+o,u=o-(a-f),f=n[++l]):(a=s+o,u=o-(a-s),s=r[++h]),o=a,0!==u&&(i[d++]=u);lf==s>-f?(a=o+f,c=a-o,u=o-(a-c)+(f-c),f=n[++l]):(a=o+s,c=a-o,u=o-(a-c)+(s-c),s=r[++h]),o=a,0!==u&&(i[d++]=u);for(;l=33306690738754716e-32*f?c:-function(t,n,e,r,i,o,a){let u,c,f,s,l,h,d,p,g,y,v,_,b,m,x,w,M,T;const A=t-i,S=e-i,E=n-o,N=r-o;m=A*N,h=hu*A,d=h-(h-A),p=A-d,h=hu*N,g=h-(h-N),y=N-g,x=p*y-(m-d*g-p*g-d*y),w=E*S,h=hu*E,d=h-(h-E),p=E-d,h=hu*S,g=h-(h-S),y=S-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,_u[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,_u[1]=b-(v+l)+(l-w),T=_+v,l=T-_,_u[2]=_-(T-l)+(v-l),_u[3]=T;let k=function(t,n){let e=n[0];for(let r=1;r=C||-k>=C)return k;if(l=t-A,u=t-(A+l)+(l-i),l=e-S,f=e-(S+l)+(l-i),l=n-E,c=n-(E+l)+(l-o),l=r-N,s=r-(N+l)+(l-o),0===u&&0===c&&0===f&&0===s)return k;if(C=vu*a+du*Math.abs(k),k+=A*s+N*u-(E*f+S*c),k>=C||-k>=C)return k;m=u*N,h=hu*u,d=h-(h-u),p=u-d,h=hu*N,g=h-(h-N),y=N-g,x=p*y-(m-d*g-p*g-d*y),w=c*S,h=hu*c,d=h-(h-c),p=c-d,h=hu*S,g=h-(h-S),y=S-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,wu[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,wu[1]=b-(v+l)+(l-w),T=_+v,l=T-_,wu[2]=_-(T-l)+(v-l),wu[3]=T;const P=pu(4,_u,4,wu,bu);m=A*s,h=hu*A,d=h-(h-A),p=A-d,h=hu*s,g=h-(h-s),y=s-g,x=p*y-(m-d*g-p*g-d*y),w=E*f,h=hu*E,d=h-(h-E),p=E-d,h=hu*f,g=h-(h-f),y=f-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,wu[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,wu[1]=b-(v+l)+(l-w),T=_+v,l=T-_,wu[2]=_-(T-l)+(v-l),wu[3]=T;const z=pu(P,bu,4,wu,mu);m=u*s,h=hu*u,d=h-(h-u),p=u-d,h=hu*s,g=h-(h-s),y=s-g,x=p*y-(m-d*g-p*g-d*y),w=c*f,h=hu*c,d=h-(h-c),p=c-d,h=hu*f,g=h-(h-f),y=f-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,wu[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,wu[1]=b-(v+l)+(l-w),T=_+v,l=T-_,wu[2]=_-(T-l)+(v-l),wu[3]=T;const $=pu(z,mu,4,wu,xu);return xu[$-1]}(t,n,e,r,i,o,f)}const Tu=Math.pow(2,-52),Au=new Uint32Array(512);class Su{static from(t,n=zu,e=$u){const r=t.length,i=new Float64Array(2*r);for(let o=0;o>1;if(n>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const e=Math.max(2*n-5,0);this._triangles=new Uint32Array(3*e),this._halfedges=new Int32Array(3*e),this._hashSize=Math.ceil(Math.sqrt(n)),this._hullPrev=new Uint32Array(n),this._hullNext=new Uint32Array(n),this._hullTri=new Uint32Array(n),this._hullHash=new Int32Array(this._hashSize),this._ids=new Uint32Array(n),this._dists=new Float64Array(n),this.update()}update(){const{coords:t,_hullPrev:n,_hullNext:e,_hullTri:r,_hullHash:i}=this,o=t.length>>1;let a=1/0,u=1/0,c=-1/0,f=-1/0;for(let n=0;nc&&(c=e),r>f&&(f=r),this._ids[n]=n}const s=(a+c)/2,l=(u+f)/2;let h,d,p;for(let n=0,e=1/0;n0&&(d=n,e=r)}let v=t[2*d],_=t[2*d+1],b=1/0;for(let n=0;nr&&(n[e++]=i,r=o)}return this.hull=n.subarray(0,e),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Mu(g,y,v,_,m,x)<0){const t=d,n=v,e=_;d=p,v=m,_=x,p=t,m=n,x=e}const w=function(t,n,e,r,i,o){const a=e-t,u=r-n,c=i-t,f=o-n,s=a*a+u*u,l=c*c+f*f,h=.5/(a*f-u*c),d=t+(f*s-u*l)*h,p=n+(a*l-c*s)*h;return{x:d,y:p}}(g,y,v,_,m,x);this._cx=w.x,this._cy=w.y;for(let n=0;n0&&Math.abs(f-o)<=Tu&&Math.abs(s-a)<=Tu)continue;if(o=f,a=s,c===h||c===d||c===p)continue;let l=0;for(let t=0,n=this._hashKey(f,s);t=0;)if(y=g,y===l){y=-1;break}if(-1===y)continue;let v=this._addTriangle(y,c,e[y],-1,-1,r[y]);r[c]=this._legalize(v+2),r[y]=v,M++;let _=e[y];for(;g=e[_],Mu(f,s,t[2*_],t[2*_+1],t[2*g],t[2*g+1])<0;)v=this._addTriangle(_,c,g,r[c],-1,r[_]),r[c]=this._legalize(v+2),e[_]=_,M--,_=g;if(y===l)for(;g=n[y],Mu(f,s,t[2*g],t[2*g+1],t[2*y],t[2*y+1])<0;)v=this._addTriangle(g,c,y,-1,r[y],r[g]),this._legalize(v+2),r[g]=v,e[y]=y,M--,y=g;this._hullStart=n[c]=y,e[y]=n[_]=c,e[c]=_,i[this._hashKey(f,s)]=c,i[this._hashKey(t[2*y],t[2*y+1])]=y}this.hull=new Uint32Array(M);for(let t=0,n=this._hullStart;t0?3-e:1+e)/4}(t-this._cx,n-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:n,_halfedges:e,coords:r}=this;let i=0,o=0;for(;;){const a=e[t],u=t-t%3;if(o=u+(t+2)%3,-1===a){if(0===i)break;t=Au[--i];continue}const c=a-a%3,f=u+(t+1)%3,s=c+(a+2)%3,l=n[o],h=n[t],d=n[f],p=n[s];if(Nu(r[2*l],r[2*l+1],r[2*h],r[2*h+1],r[2*d],r[2*d+1],r[2*p],r[2*p+1])){n[t]=p,n[a]=l;const r=e[s];if(-1===r){let n=this._hullStart;do{if(this._hullTri[n]===s){this._hullTri[n]=t;break}n=this._hullPrev[n]}while(n!==this._hullStart)}this._link(t,r),this._link(a,e[o]),this._link(o,s);const u=c+(a+1)%3;i=e&&n[t[a]]>o;)t[a+1]=t[a--];t[a+1]=r}else{let i=e+1,o=r;Pu(t,e+r>>1,i),n[t[e]]>n[t[r]]&&Pu(t,e,r),n[t[i]]>n[t[r]]&&Pu(t,i,r),n[t[e]]>n[t[i]]&&Pu(t,e,i);const a=t[i],u=n[a];for(;;){do{i++}while(n[t[i]]u);if(o=o-e?(Cu(t,n,i,r),Cu(t,n,e,o-1)):(Cu(t,n,e,o-1),Cu(t,n,i,r))}}function Pu(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function zu(t){return t[0]}function $u(t){return t[1]}const Du=1e-6;class Ru{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,n){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,n){this._+=`L${this._x1=+t},${this._y1=+n}`}arc(t,n,e){const r=(t=+t)+(e=+e),i=n=+n;if(e<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${i}`:(Math.abs(this._x1-r)>Du||Math.abs(this._y1-i)>Du)&&(this._+="L"+r+","+i),e&&(this._+=`A${e},${e},0,1,1,${t-e},${n}A${e},${e},0,1,1,${this._x1=r},${this._y1=i}`)}rect(t,n,e,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${+e}v${+r}h${-e}Z`}value(){return this._||null}}class Fu{constructor(){this._=[]}moveTo(t,n){this._.push([t,n])}closePath(){this._.push(this._[0].slice())}lineTo(t,n){this._.push([t,n])}value(){return this._.length?this._:null}}class qu{constructor(t,[n,e,r,i]=[0,0,960,500]){if(!((r=+r)>=(n=+n)&&(i=+i)>=(e=+e)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=n,this.ymax=i,this.ymin=e,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:n,triangles:e},vectors:r}=this;let i,o;const a=this.circumcenters=this._circumcenters.subarray(0,e.length/3*2);for(let r,u,c=0,f=0,s=e.length;c1;)i-=2;for(let t=2;t0){if(n>=this.ymax)return null;(i=(this.ymax-n)/r)0){if(t>=this.xmax)return null;(i=(this.xmax-t)/e)this.xmax?2:0)|(nthis.ymax?8:0)}_simplify(t){if(t&&t.length>4){for(let n=0;n2&&function(t){const{triangles:n,coords:e}=t;for(let t=0;t1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:n.length/2},((t,n)=>n)).sort(((t,e)=>n[2*t]-n[2*e]||n[2*t+1]-n[2*e+1]));const t=this.collinear[0],e=this.collinear[this.collinear.length-1],r=[n[2*t],n[2*t+1],n[2*e],n[2*e+1]],i=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,e=n.length/2;t0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],o[r[0]]=1,2===r.length&&(o[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]))}voronoi(t){return new qu(this,t)}*neighbors(t){const{inedges:n,hull:e,_hullIndex:r,halfedges:i,triangles:o,collinear:a}=this;if(a){const n=a.indexOf(t);return n>0&&(yield a[n-1]),void(n=0&&i!==e&&i!==r;)e=i;return i}_step(t,n,e){const{inedges:r,hull:i,_hullIndex:o,halfedges:a,triangles:u,points:c}=this;if(-1===r[t]||!c.length)return(t+1)%(c.length>>1);let f=t,s=Iu(n-c[2*t],2)+Iu(e-c[2*t+1],2);const l=r[t];let h=l;do{let r=u[h];const l=Iu(n-c[2*r],2)+Iu(e-c[2*r+1],2);if(l9999?"+"+Ku(n,6):Ku(n,4))+"-"+Ku(t.getUTCMonth()+1,2)+"-"+Ku(t.getUTCDate(),2)+(o?"T"+Ku(e,2)+":"+Ku(r,2)+":"+Ku(i,2)+"."+Ku(o,3)+"Z":i?"T"+Ku(e,2)+":"+Ku(r,2)+":"+Ku(i,2)+"Z":r||e?"T"+Ku(e,2)+":"+Ku(r,2)+"Z":"")}function Ju(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return Hu;if(f)return f=!1,ju;var n,r,i=a;if(t.charCodeAt(i)===Xu){for(;a++=o?c=!0:(r=t.charCodeAt(a++))===Gu?f=!0:r===Vu&&(f=!0,t.charCodeAt(a)===Gu&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;amc(n,e).then((n=>(new DOMParser).parseFromString(n,t)))}var Sc=Ac("application/xml"),Ec=Ac("text/html"),Nc=Ac("image/svg+xml");function kc(t,n,e,r){if(isNaN(n)||isNaN(e))return t;var i,o,a,u,c,f,s,l,h,d=t._root,p={data:r},g=t._x0,y=t._y0,v=t._x1,_=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function Cc(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function Pc(t){return t[0]}function zc(t){return t[1]}function $c(t,n,e){var r=new Dc(null==n?Pc:n,null==e?zc:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Dc(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function Rc(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var Fc=$c.prototype=Dc.prototype;function qc(t){return function(){return t}}function Uc(t){return 1e-6*(t()-.5)}function Ic(t){return t.x+t.vx}function Oc(t){return t.y+t.vy}function Bc(t){return t.index}function Yc(t,n){var e=t.get(n);if(!e)throw new Error("node not found: "+n);return e}Fc.copy=function(){var t,n,e=new Dc(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=Rc(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=Rc(n));return e},Fc.add=function(t){const n=+this._x.call(null,t),e=+this._y.call(null,t);return kc(this.cover(n,e),n,e,t)},Fc.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;es&&(s=r),il&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;et||t>=i||r>n||n>=o;)switch(u=(nh||(o=c.y0)>d||(a=c.x1)=v)<<1|t>=y)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,g.data),b=n-+this._y.call(null,g.data),m=_*_+b*b;if(m=(u=(p+y)/2))?p=u:y=u,(s=a>=(c=(g+v)/2))?g=c:v=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},Fc.removeAll=function(t){for(var n=0,e=t.length;n1?r[0]+r.slice(2):r,+t.slice(e+1)]}function Zc(t){return(t=Wc(Math.abs(t)))?t[1]:NaN}var Kc,Qc=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Jc(t){if(!(n=Qc.exec(t)))throw new Error("invalid format: "+t);var n;return new tf({fill:n[1],align:n[2],sign:n[3],symbol:n[4],zero:n[5],width:n[6],comma:n[7],precision:n[8]&&n[8].slice(1),trim:n[9],type:n[10]})}function tf(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function nf(t,n){var e=Wc(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}Jc.prototype=tf.prototype,tf.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var ef={"%":(t,n)=>(100*t).toFixed(n),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,n)=>t.toExponential(n),f:(t,n)=>t.toFixed(n),g:(t,n)=>t.toPrecision(n),o:t=>Math.round(t).toString(8),p:(t,n)=>nf(100*t,n),r:nf,s:function(t,n){var e=Wc(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(Kc=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+Wc(t,Math.max(0,n+o-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function rf(t){return t}var of,af=Array.prototype.map,uf=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function cf(t){var n,e,r=void 0===t.grouping||void 0===t.thousands?rf:(n=af.call(t.grouping,Number),e=t.thousands+"",function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}),i=void 0===t.currency?"":t.currency[0]+"",o=void 0===t.currency?"":t.currency[1]+"",a=void 0===t.decimal?".":t.decimal+"",u=void 0===t.numerals?rf:function(t){return function(n){return n.replace(/[0-9]/g,(function(n){return t[+n]}))}}(af.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",f=void 0===t.minus?"−":t.minus+"",s=void 0===t.nan?"NaN":t.nan+"";function l(t){var n=(t=Jc(t)).fill,e=t.align,l=t.sign,h=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,v=t.trim,_=t.type;"n"===_?(g=!0,_="g"):ef[_]||(void 0===y&&(y=12),v=!0,_="g"),(d||"0"===n&&"="===e)&&(d=!0,n="0",e="=");var b="$"===h?i:"#"===h&&/[boxX]/.test(_)?"0"+_.toLowerCase():"",m="$"===h?o:/[%p]/.test(_)?c:"",x=ef[_],w=/[defgprs%]/.test(_);function M(t){var i,o,c,h=b,M=m;if("c"===_)M=x(t)+M,t="";else{var T=(t=+t)<0||1/t<0;if(t=isNaN(t)?s:x(Math.abs(t),y),v&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),T&&0==+t&&"+"!==l&&(T=!1),h=(T?"("===l?l:f:"-"===l||"("===l?"":l)+h,M=("s"===_?uf[8+Kc/3]:"")+M+(T&&"("===l?")":""),w)for(i=-1,o=t.length;++i(c=t.charCodeAt(i))||c>57){M=(46===c?a+t.slice(i+1):t.slice(i))+M,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var A=h.length+t.length+M.length,S=A>1)+h+t+M+S.slice(A);break;default:t=S+h+t+M}return u(t)}return y=void 0===y?6:/[gprs]/.test(_)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),M.toString=function(){return t+""},M}return{format:l,formatPrefix:function(t,n){var e=l(((t=Jc(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(Zc(n)/3))),i=Math.pow(10,-r),o=uf[8+r/3];return function(t){return e(i*t)+o}}}}function ff(n){return of=cf(n),t.format=of.format,t.formatPrefix=of.formatPrefix,of}function sf(t){return Math.max(0,-Zc(Math.abs(t)))}function lf(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(Zc(n)/3)))-Zc(Math.abs(t)))}function hf(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,Zc(n)-Zc(t))+1}t.format=void 0,t.formatPrefix=void 0,ff({thousands:",",grouping:[3],currency:["$",""]});var df=1e-6,pf=1e-12,gf=Math.PI,yf=gf/2,vf=gf/4,_f=2*gf,bf=180/gf,mf=gf/180,xf=Math.abs,wf=Math.atan,Mf=Math.atan2,Tf=Math.cos,Af=Math.ceil,Sf=Math.exp,Ef=Math.hypot,Nf=Math.log,kf=Math.pow,Cf=Math.sin,Pf=Math.sign||function(t){return t>0?1:t<0?-1:0},zf=Math.sqrt,$f=Math.tan;function Df(t){return t>1?0:t<-1?gf:Math.acos(t)}function Rf(t){return t>1?yf:t<-1?-yf:Math.asin(t)}function Ff(t){return(t=Cf(t/2))*t}function qf(){}function Uf(t,n){t&&Of.hasOwnProperty(t.type)&&Of[t.type](t,n)}var If={Feature:function(t,n){Uf(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,o=Tf(n=(n*=mf)/2+vf),a=Cf(n),u=Vf*a,c=Gf*o+u*Tf(i),f=u*r*Cf(i);as.add(Mf(f,c)),Xf=t,Gf=o,Vf=a}function ds(t){return[Mf(t[1],t[0]),Rf(t[2])]}function ps(t){var n=t[0],e=t[1],r=Tf(e);return[r*Tf(n),r*Cf(n),Cf(e)]}function gs(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function ys(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function vs(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function _s(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function bs(t){var n=zf(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var ms,xs,ws,Ms,Ts,As,Ss,Es,Ns,ks,Cs,Ps,zs,$s,Ds,Rs,Fs={point:qs,lineStart:Is,lineEnd:Os,polygonStart:function(){Fs.point=Bs,Fs.lineStart=Ys,Fs.lineEnd=Ls,rs=new T,cs.polygonStart()},polygonEnd:function(){cs.polygonEnd(),Fs.point=qs,Fs.lineStart=Is,Fs.lineEnd=Os,as<0?(Wf=-(Kf=180),Zf=-(Qf=90)):rs>df?Qf=90:rs<-df&&(Zf=-90),os[0]=Wf,os[1]=Kf},sphere:function(){Wf=-(Kf=180),Zf=-(Qf=90)}};function qs(t,n){is.push(os=[Wf=t,Kf=t]),nQf&&(Qf=n)}function Us(t,n){var e=ps([t*mf,n*mf]);if(es){var r=ys(es,e),i=ys([r[1],-r[0],0],r);bs(i),i=ds(i);var o,a=t-Jf,u=a>0?1:-1,c=i[0]*bf*u,f=xf(a)>180;f^(u*JfQf&&(Qf=o):f^(u*Jf<(c=(c+360)%360-180)&&cQf&&(Qf=n)),f?tjs(Wf,Kf)&&(Kf=t):js(t,Kf)>js(Wf,Kf)&&(Wf=t):Kf>=Wf?(tKf&&(Kf=t)):t>Jf?js(Wf,t)>js(Wf,Kf)&&(Kf=t):js(t,Kf)>js(Wf,Kf)&&(Wf=t)}else is.push(os=[Wf=t,Kf=t]);nQf&&(Qf=n),es=e,Jf=t}function Is(){Fs.point=Us}function Os(){os[0]=Wf,os[1]=Kf,Fs.point=qs,es=null}function Bs(t,n){if(es){var e=t-Jf;rs.add(xf(e)>180?e+(e>0?360:-360):e)}else ts=t,ns=n;cs.point(t,n),Us(t,n)}function Ys(){cs.lineStart()}function Ls(){Bs(ts,ns),cs.lineEnd(),xf(rs)>df&&(Wf=-(Kf=180)),os[0]=Wf,os[1]=Kf,es=null}function js(t,n){return(n-=t)<0?n+360:n}function Hs(t,n){return t[0]-n[0]}function Xs(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:ngf&&(t-=Math.round(t/_f)*_f),[t,n]}function ul(t,n,e){return(t%=_f)?n||e?ol(fl(t),sl(n,e)):fl(t):n||e?sl(n,e):al}function cl(t){return function(n,e){return xf(n+=t)>gf&&(n-=Math.round(n/_f)*_f),[n,e]}}function fl(t){var n=cl(t);return n.invert=cl(-t),n}function sl(t,n){var e=Tf(t),r=Cf(t),i=Tf(n),o=Cf(n);function a(t,n){var a=Tf(n),u=Tf(t)*a,c=Cf(t)*a,f=Cf(n),s=f*e+u*r;return[Mf(c*i-s*o,u*e-f*r),Rf(s*i+c*o)]}return a.invert=function(t,n){var a=Tf(n),u=Tf(t)*a,c=Cf(t)*a,f=Cf(n),s=f*i-c*o;return[Mf(c*i+f*o,u*e+s*r),Rf(s*e-u*r)]},a}function ll(t){function n(n){return(n=t(n[0]*mf,n[1]*mf))[0]*=bf,n[1]*=bf,n}return t=ul(t[0]*mf,t[1]*mf,t.length>2?t[2]*mf:0),n.invert=function(n){return(n=t.invert(n[0]*mf,n[1]*mf))[0]*=bf,n[1]*=bf,n},n}function hl(t,n,e,r,i,o){if(e){var a=Tf(n),u=Cf(n),c=r*e;null==i?(i=n+r*_f,o=n-c/2):(i=dl(a,i),o=dl(a,o),(r>0?io)&&(i+=r*_f));for(var f,s=i;r>0?s>o:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function gl(t,n){return xf(t[0]-n[0])=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function _l(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,E=S*A,N=E>gf,k=y*w;if(c.add(Mf(k*S*Cf(E),v*M+k*Tf(E))),a+=N?A+S*_f:A,N^p>=e^m>=e){var C=ys(ps(d),ps(b));bs(C);var P=ys(o,C);bs(P);var z=(N^A>=0?-1:1)*Rf(P[2]);(r>z||r===z&&(C[0]||C[1]))&&(u+=N^A>=0?1:-1)}}return(a<-df||a0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(wl))}return h}}function wl(t){return t.length>1}function Ml(t,n){return((t=t.x)[0]<0?t[1]-yf-df:yf-t[1])-((n=n.x)[0]<0?n[1]-yf-df:yf-n[1])}al.invert=al;var Tl=xl((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?gf:-gf,c=xf(o-e);xf(c-gf)0?yf:-yf),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=gf&&(xf(e-i)df?wf((Cf(n)*(o=Tf(r))*Cf(e)-Cf(r)*(i=Tf(n))*Cf(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*yf,r.point(-gf,i),r.point(0,i),r.point(gf,i),r.point(gf,0),r.point(gf,-i),r.point(0,-i),r.point(-gf,-i),r.point(-gf,0),r.point(-gf,i);else if(xf(t[0]-n[0])>df){var o=t[0]0,i=xf(n)>df;function o(t,e){return Tf(t)*Tf(e)>n}function a(t,e,r){var i=[1,0,0],o=ys(ps(t),ps(e)),a=gs(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=ys(i,o),h=_s(i,f);vs(h,_s(o,s));var d=l,p=gs(h,d),g=gs(d,d),y=p*p-g*(gs(h,h)-1);if(!(y<0)){var v=zf(y),_=_s(d,(-p-v)/g);if(vs(_,h),_=ds(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x0^_[1]<(xf(_[0]-m)gf^(m<=_[0]&&_[0]<=x)){var S=_s(d,(-p+v)/g);return vs(S,h),[_,ds(S)]}}}function u(n,e){var i=r?t:gf-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return xl(o,(function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],g=o(l,h),y=r?g?0:u(l,h):g?u(l+(l<0?gf:-gf),h):0;if(!n&&(f=c=g)&&t.lineStart(),g!==c&&(!(d=a(n,p))||gl(n,d)||gl(p,d))&&(p[2]=1),g!==c)s=0,g?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1],2),t.lineEnd()),n=d;else if(i&&n&&r^g){var v;y&e||!(v=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1],3)))}!g||n&&gl(n,p)||t.point(p[0],p[1]),n=p,c=g,e=y},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}}),(function(n,r,i,o){hl(o,t,e,i,n,r)}),r?[0,-t]:[-gf,t-gf])}var Sl,El,Nl,kl,Cl=1e9,Pl=-Cl;function zl(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return xf(r[0]-t)0?0:3:xf(r[0]-e)0?2:1:xf(r[1]-n)0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,g,y,v,_,b=a,m=pl(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);v=!0,y=!1,p=g=NaN},lineEnd:function(){c&&(M(l,h),d&&y&&m.rejoin(),c.push(m.result()));x.point=w,y&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;er&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=ft(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&vl(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),v)l=o,h=a,d=u,v=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&y)b.point(o,a);else{var c=[p=Math.max(Pl,Math.min(Cl,p)),g=Math.max(Pl,Math.min(Cl,g))],m=[o=Math.max(Pl,Math.min(Cl,o)),a=Math.max(Pl,Math.min(Cl,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a0)){if(a/=h,h<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(y||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,g=a,y=u}return x}}var $l={sphere:qf,point:qf,lineStart:function(){$l.point=Rl,$l.lineEnd=Dl},lineEnd:qf,polygonStart:qf,polygonEnd:qf};function Dl(){$l.point=$l.lineEnd=qf}function Rl(t,n){El=t*=mf,Nl=Cf(n*=mf),kl=Tf(n),$l.point=Fl}function Fl(t,n){t*=mf;var e=Cf(n*=mf),r=Tf(n),i=xf(t-El),o=Tf(i),a=r*Cf(i),u=kl*e-Nl*r*o,c=Nl*e+kl*r*o;Sl.add(Mf(zf(a*a+u*u),c)),El=t,Nl=e,kl=r}function ql(t){return Sl=new T,Lf(t,$l),+Sl}var Ul=[null,null],Il={type:"LineString",coordinates:Ul};function Ol(t,n){return Ul[0]=t,Ul[1]=n,ql(Il)}var Bl={Feature:function(t,n){return Ll(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r0&&(i=Ol(t[o],t[o-1]))>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))df})).map(c)).concat(lt(Af(o/d)*d,i,d).filter((function(t){return xf(t%g)>df})).map(f))}return v.lines=function(){return _().map((function(t){return{type:"LineString",coordinates:t}}))},v.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},v.extent=function(t){return arguments.length?v.extentMajor(t).extentMinor(t):v.extentMinor()},v.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),v.precision(y)):[[r,u],[e,a]]},v.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),v.precision(y)):[[n,o],[t,i]]},v.step=function(t){return arguments.length?v.stepMajor(t).stepMinor(t):v.stepMinor()},v.stepMajor=function(t){return arguments.length?(p=+t[0],g=+t[1],v):[p,g]},v.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],v):[h,d]},v.precision=function(h){return arguments.length?(y=+h,c=Wl(o,i,90),f=Zl(n,t,y),s=Wl(u,a,90),l=Zl(r,e,y),v):y},v.extentMajor([[-180,-90+df],[180,90-df]]).extentMinor([[-180,-80-df],[180,80+df]])}var Ql,Jl,th,nh,eh=t=>t,rh=new T,ih=new T,oh={point:qf,lineStart:qf,lineEnd:qf,polygonStart:function(){oh.lineStart=ah,oh.lineEnd=fh},polygonEnd:function(){oh.lineStart=oh.lineEnd=oh.point=qf,rh.add(xf(ih)),ih=new T},result:function(){var t=rh/2;return rh=new T,t}};function ah(){oh.point=uh}function uh(t,n){oh.point=ch,Ql=th=t,Jl=nh=n}function ch(t,n){ih.add(nh*t-th*n),th=t,nh=n}function fh(){ch(Ql,Jl)}var sh=oh,lh=1/0,hh=lh,dh=-lh,ph=dh,gh={point:function(t,n){tdh&&(dh=t);nph&&(ph=n)},lineStart:qf,lineEnd:qf,polygonStart:qf,polygonEnd:qf,result:function(){var t=[[lh,hh],[dh,ph]];return dh=ph=-(hh=lh=1/0),t}};var yh,vh,_h,bh,mh=gh,xh=0,wh=0,Mh=0,Th=0,Ah=0,Sh=0,Eh=0,Nh=0,kh=0,Ch={point:Ph,lineStart:zh,lineEnd:Rh,polygonStart:function(){Ch.lineStart=Fh,Ch.lineEnd=qh},polygonEnd:function(){Ch.point=Ph,Ch.lineStart=zh,Ch.lineEnd=Rh},result:function(){var t=kh?[Eh/kh,Nh/kh]:Sh?[Th/Sh,Ah/Sh]:Mh?[xh/Mh,wh/Mh]:[NaN,NaN];return xh=wh=Mh=Th=Ah=Sh=Eh=Nh=kh=0,t}};function Ph(t,n){xh+=t,wh+=n,++Mh}function zh(){Ch.point=$h}function $h(t,n){Ch.point=Dh,Ph(_h=t,bh=n)}function Dh(t,n){var e=t-_h,r=n-bh,i=zf(e*e+r*r);Th+=i*(_h+t)/2,Ah+=i*(bh+n)/2,Sh+=i,Ph(_h=t,bh=n)}function Rh(){Ch.point=Ph}function Fh(){Ch.point=Uh}function qh(){Ih(yh,vh)}function Uh(t,n){Ch.point=Ih,Ph(yh=_h=t,vh=bh=n)}function Ih(t,n){var e=t-_h,r=n-bh,i=zf(e*e+r*r);Th+=i*(_h+t)/2,Ah+=i*(bh+n)/2,Sh+=i,Eh+=(i=bh*t-_h*n)*(_h+t),Nh+=i*(bh+n),kh+=3*i,Ph(_h=t,bh=n)}var Oh=Ch;function Bh(t){this._context=t}Bh.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,_f)}},result:qf};var Yh,Lh,jh,Hh,Xh,Gh=new T,Vh={point:qf,lineStart:function(){Vh.point=Wh},lineEnd:function(){Yh&&Zh(Lh,jh),Vh.point=qf},polygonStart:function(){Yh=!0},polygonEnd:function(){Yh=null},result:function(){var t=+Gh;return Gh=new T,t}};function Wh(t,n){Vh.point=Zh,Lh=Hh=t,jh=Xh=n}function Zh(t,n){Hh-=t,Xh-=n,Gh.add(zf(Hh*Hh+Xh*Xh)),Hh=t,Xh=n}var Kh=Vh;let Qh,Jh,td,nd;class ed{constructor(t){this._append=null==t?rd:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return rd;if(n!==Qh){const t=10**n;Qh=n,Jh=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&g--){var m=a+h,x=u+d,w=c+p,M=zf(m*m+x*x+w*w),T=Rf(w/=M),A=xf(xf(w)-1)n||xf((v*k+_*C)/b-.5)>.3||a*h+u*d+c*p2?t[2]%360*mf:0,k()):[y*bf,v*bf,_*bf]},E.angle=function(t){return arguments.length?(b=t%360*mf,k()):b*bf},E.reflectX=function(t){return arguments.length?(m=t?-1:1,k()):m<0},E.reflectY=function(t){return arguments.length?(x=t?-1:1,k()):x<0},E.precision=function(t){return arguments.length?(a=dd(u,S=t*t),C()):zf(S)},E.fitExtent=function(t,n){return ud(E,t,n)},E.fitSize=function(t,n){return cd(E,t,n)},E.fitWidth=function(t,n){return fd(E,t,n)},E.fitHeight=function(t,n){return sd(E,t,n)},function(){return n=t.apply(this,arguments),E.invert=n.invert&&N,k()}}function _d(t){var n=0,e=gf/3,r=vd(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*mf,e=t[1]*mf):[n*bf,e*bf]},i}function bd(t,n){var e=Cf(t),r=(e+Cf(n))/2;if(xf(r)0?n<-yf+df&&(n=-yf+df):n>yf-df&&(n=yf-df);var e=i/kf(Nd(n),r);return[e*Cf(r*t),i-e*Tf(r*t)]}return o.invert=function(t,n){var e=i-n,o=Pf(r)*zf(t*t+e*e),a=Mf(t,xf(e))*Pf(e);return e*r<0&&(a-=gf*Pf(t)*Pf(e)),[a/r,2*wf(kf(i/o,1/r))-yf]},o}function Cd(t,n){return[t,n]}function Pd(t,n){var e=Tf(t),r=t===n?Cf(t):(e-Tf(n))/(n-t),i=e/r+t;if(xf(r)=0;)n+=e[r].value;else n=1;t.value=n}function Gd(t,n){t instanceof Map?(t=[void 0,t],void 0===n&&(n=Wd)):void 0===n&&(n=Vd);for(var e,r,i,o,a,u=new Qd(t),c=[u];e=c.pop();)if((i=n(e.data))&&(a=(i=Array.from(i)).length))for(e.children=i,o=a-1;o>=0;--o)c.push(r=i[o]=new Qd(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(Kd)}function Vd(t){return t.children}function Wd(t){return Array.isArray(t)?t[1]:null}function Zd(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function Kd(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function Qd(t){this.data=t,this.depth=this.height=0,this.parent=null}function Jd(t){return null==t?null:tp(t)}function tp(t){if("function"!=typeof t)throw new Error;return t}function np(){return 0}function ep(t){return function(){return t}}qd.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(zd+$d*i+o*(Dd+Rd*i))-n)/(zd+3*$d*i+o*(7*Dd+9*Rd*i)))*r)*i*i,!(xf(e)df&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},Od.invert=Md(Rf),Bd.invert=Md((function(t){return 2*wf(t)})),Yd.invert=function(t,n){return[-n,2*wf(Sf(t))-yf]},Qd.prototype=Gd.prototype={constructor:Qd,count:function(){return this.eachAfter(Xd)},each:function(t,n){let e=-1;for(const r of this)t.call(n,r,++e,this);return this},eachAfter:function(t,n){for(var e,r,i,o=this,a=[o],u=[],c=-1;o=a.pop();)if(u.push(o),e=o.children)for(r=0,i=e.length;r=0;--r)o.push(e[r]);return this},find:function(t,n){let e=-1;for(const r of this)if(t.call(n,r,++e,this))return r},sum:function(t){return this.eachAfter((function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e}))},sort:function(t){return this.eachBefore((function(n){n.children&&n.children.sort(t)}))},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;t=e.pop(),n=r.pop();for(;t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(n){n.children||t.push(n)})),t},links:function(){var t=this,n=[];return t.each((function(e){e!==t&&n.push({source:e.parent,target:e})})),n},copy:function(){return Gd(this).eachBefore(Zd)},[Symbol.iterator]:function*(){var t,n,e,r,i=this,o=[i];do{for(t=o.reverse(),o=[];i=t.pop();)if(yield i,n=i.children)for(e=0,r=n.length;e(t=(rp*t+ip)%op)/op}function up(t,n){for(var e,r,i=0,o=(t=function(t,n){let e,r,i=t.length;for(;i;)r=n()*i--|0,e=t[i],t[i]=t[r],t[r]=e;return t}(Array.from(t),n)).length,a=[];i0&&e*e>r*r+i*i}function lp(t,n){for(var e=0;e1e-6?(E+Math.sqrt(E*E-4*S*N))/(2*S):N/E);return{x:r+w+M*k,y:i+T+A*k,r:k}}function gp(t,n,e){var r,i,o,a,u=t.x-n.x,c=t.y-n.y,f=u*u+c*c;f?(i=n.r+e.r,i*=i,a=t.r+e.r,i>(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function yp(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function vp(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function _p(t){this._=t,this.next=null,this.previous=null}function bp(t,n){if(!(o=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var e,r,i,o,a,u,c,f,s,l,h;if((e=t[0]).x=0,e.y=0,!(o>1))return e.r;if(r=t[1],e.x=-r.r,r.x=e.r,r.y=0,!(o>2))return e.r+r.r;gp(r,e,i=t[2]),e=new _p(e),r=new _p(r),i=new _p(i),e.next=i.previous=r,r.next=e.previous=i,i.next=r.previous=e;t:for(c=3;c1&&!zp(t,n););return t.slice(0,n)}function zp(t,n){if("/"===t[n]){let e=0;for(;n>0&&"\\"===t[--n];)++e;if(!(1&e))return!0}return!1}function $p(t,n){return t.parent===n.parent?1:2}function Dp(t){var n=t.children;return n?n[0]:t.t}function Rp(t){var n=t.children;return n?n[n.length-1]:t.t}function Fp(t,n,e){var r=e/(n.i-t.i);n.c-=r,n.s+=e,t.c+=r,n.z+=e,n.m+=e}function qp(t,n,e){return t.a.parent===n.parent?t.a:e}function Up(t,n){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=n}function Ip(t,n,e,r,i){for(var o,a=t.children,u=-1,c=a.length,f=t.value&&(i-e)/t.value;++uh&&(h=u),y=s*s*g,(d=Math.max(h/y,y/l))>p){s-=u;break}p=d}v.push(a={value:s,dice:c1?n:1)},e}(Op);var Lp=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l1?n:1)},e}(Op);function jp(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])}function Hp(t,n){return t[0]-n[0]||t[1]-n[1]}function Xp(t){const n=t.length,e=[0,1];let r,i=2;for(r=2;r1&&jp(t[e[i-2]],t[e[i-1]],t[r])<=0;)--i;e[i++]=r}return e.slice(0,i)}var Gp=Math.random,Vp=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(Gp),Wp=function t(n){function e(t,e){return arguments.length<2&&(e=t,t=0),t=Math.floor(t),e=Math.floor(e)-t,function(){return Math.floor(n()*e+t)}}return e.source=t,e}(Gp),Zp=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(Gp),Kp=function t(n){var e=Zp.source(n);function r(){var t=e.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Gp),Qp=function t(n){function e(t){return(t=+t)<=0?()=>0:function(){for(var e=0,r=t;r>1;--r)e+=n();return e+r*n()}}return e.source=t,e}(Gp),Jp=function t(n){var e=Qp.source(n);function r(t){if(0==(t=+t))return n;var r=e(t);return function(){return r()/t}}return r.source=t,r}(Gp),tg=function t(n){function e(t){return function(){return-Math.log1p(-n())/t}}return e.source=t,e}(Gp),ng=function t(n){function e(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-n(),t)}}return e.source=t,e}(Gp),eg=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(n()+t)}}return e.source=t,e}(Gp),rg=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-n())/t)})}return e.source=t,e}(Gp),ig=function t(n){var e=Zp.source(n)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-n())*r;var i=(t<1?t+1:t)-1/3,o=1/(3*Math.sqrt(i)),a=t<1?()=>Math.pow(n(),1/t):()=>1;return function(){do{do{var t=e(),u=1+o*t}while(u<=0);u*=u*u;var c=1-n()}while(c>=1-.0331*t*t*t*t&&Math.log(c)>=.5*t*t+i*(1-u+Math.log(u)));return i*u*a()*r}}return r.source=t,r}(Gp),og=function t(n){var e=ig.source(n);function r(t,n){var r=e(t),i=e(n);return function(){var t=r();return 0===t?0:t/(t+i())}}return r.source=t,r}(Gp),ag=function t(n){var e=rg.source(n),r=og.source(n);function i(t,n){return t=+t,(n=+n)>=1?()=>t:n<=0?()=>0:function(){for(var i=0,o=t,a=n;o*a>16&&o*(1-a)>16;){var u=Math.floor((o+1)*a),c=r(u,o-u+1)();c<=a?(i+=u,o-=u,a=(a-c)/(1-c)):(o=u-1,a/=c)}for(var f=a<.5,s=e(f?a:1-a),l=s(),h=0;l<=o;++h)l+=s();return i+(f?h:o-h)}}return i.source=t,i}(Gp),ug=function t(n){function e(t,e,r){var i;return 0==(t=+t)?i=t=>-Math.log(t):(t=1/t,i=n=>Math.pow(n,t)),e=null==e?0:+e,r=null==r?1:+r,function(){return e+r*i(-Math.log1p(-n()))}}return e.source=t,e}(Gp),cg=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){return t+e*Math.tan(Math.PI*n())}}return e.source=t,e}(Gp),fg=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){var r=n();return t+e*Math.log(r/(1-r))}}return e.source=t,e}(Gp),sg=function t(n){var e=ig.source(n),r=ag.source(n);function i(t){return function(){for(var i=0,o=t;o>16;){var a=Math.floor(.875*o),u=e(a)();if(u>o)return i+r(a-1,o/u)();i+=a,o-=u}for(var c=-Math.log1p(-n()),f=0;c<=o;++f)c-=Math.log1p(-n());return i+f}}return i.source=t,i}(Gp);const lg=1/4294967296;function hg(t,n){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(n).domain(t)}return this}function dg(t,n){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof n?this.interpolator(n):this.range(n)}return this}const pg=Symbol("implicit");function gg(){var t=new InternMap,n=[],e=[],r=pg;function i(i){let o=t.get(i);if(void 0===o){if(r!==pg)return r;t.set(i,o=n.push(i)-1)}return e[o%e.length]}return i.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new InternMap;for(const r of e)t.has(r)||t.set(r,n.push(r)-1);return i},i.range=function(t){return arguments.length?(e=Array.from(t),i):e.slice()},i.unknown=function(t){return arguments.length?(r=t,i):r},i.copy=function(){return gg(n,e).unknown(r)},hg.apply(i,arguments),i}function yg(){var t,n,e=gg().unknown(void 0),r=e.domain,i=e.range,o=0,a=1,u=!1,c=0,f=0,s=.5;function l(){var e=r().length,l=an&&(e=t,t=n,n=e),function(e){return Math.max(t,Math.min(n,e))}}(a[0],a[t-1])),r=t>2?Mg:wg,i=o=null,l}function l(n){return null==n||isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),Yr)))(e)))},l.domain=function(t){return arguments.length?(a=Array.from(t,_g),s()):a.slice()},l.range=function(t){return arguments.length?(u=Array.from(t),s()):u.slice()},l.rangeRound=function(t){return u=Array.from(t),c=Vr,s()},l.clamp=function(t){return arguments.length?(f=!!t||mg,s()):f!==mg},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function Sg(){return Ag()(mg,mg)}function Eg(n,e,r,i){var o,a=W(n,e,r);switch((i=Jc(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=lf(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=hf(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=sf(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function Ng(t){var n=t.domain;return t.ticks=function(t){var e=n();return G(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return Eg(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i,o=n(),a=0,u=o.length-1,c=o[a],f=o[u],s=10;for(f0;){if((i=V(c,f,e))===r)return o[a]=c,o[u]=f,n(o);if(i>0)c=Math.floor(c/i)*i,f=Math.ceil(f/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,f=Math.floor(f*i)/i}r=i}return t},t}function kg(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a-t(-n,e)}function Fg(n){const e=n(Cg,Pg),r=e.domain;let i,o,a=10;function u(){return i=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),n=>Math.log(n)/t)}(a),o=function(t){return 10===t?Dg:t===Math.E?Math.exp:n=>Math.pow(t,n)}(a),r()[0]<0?(i=Rg(i),o=Rg(o),n(zg,$g)):n(Cg,Pg),e}return e.base=function(t){return arguments.length?(a=+t,u()):a},e.domain=function(t){return arguments.length?(r(t),u()):r()},e.ticks=t=>{const n=r();let e=n[0],u=n[n.length-1];const c=u0){for(;l<=h;++l)for(f=1;fu)break;p.push(s)}}else for(;l<=h;++l)for(f=a-1;f>=1;--f)if(s=l>0?f/o(-l):f*o(l),!(su)break;p.push(s)}2*p.length{if(null==n&&(n=10),null==r&&(r=10===a?"s":","),"function"!=typeof r&&(a%1||null!=(r=Jc(r)).precision||(r.trim=!0),r=t.format(r)),n===1/0)return r;const u=Math.max(1,a*n/e.ticks().length);return t=>{let n=t/o(Math.round(i(t)));return n*ar(kg(r(),{floor:t=>o(Math.floor(i(t))),ceil:t=>o(Math.ceil(i(t)))})),e}function qg(t){return function(n){return Math.sign(n)*Math.log1p(Math.abs(n/t))}}function Ug(t){return function(n){return Math.sign(n)*Math.expm1(Math.abs(n))*t}}function Ig(t){var n=1,e=t(qg(n),Ug(n));return e.constant=function(e){return arguments.length?t(qg(n=+e),Ug(n)):n},Ng(e)}function Og(t){return function(n){return n<0?-Math.pow(-n,t):Math.pow(n,t)}}function Bg(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function Yg(t){return t<0?-t*t:t*t}function Lg(t){var n=t(mg,mg),e=1;return n.exponent=function(n){return arguments.length?1===(e=+n)?t(mg,mg):.5===e?t(Bg,Yg):t(Og(e),Og(1/e)):e},Ng(n)}function jg(){var t=Lg(Ag());return t.copy=function(){return Tg(t,jg()).exponent(t.exponent())},hg.apply(t,arguments),t}function Hg(t){return Math.sign(t)*t*t}const Xg=new Date,Gg=new Date;function Vg(t,n,e,r){function i(n){return t(n=0===arguments.length?new Date:new Date(+n)),n}return i.floor=n=>(t(n=new Date(+n)),n),i.ceil=e=>(t(e=new Date(e-1)),n(e,1),t(e),e),i.round=t=>{const n=i(t),e=i.ceil(t);return t-n(n(t=new Date(+t),null==e?1:Math.floor(e)),t),i.range=(e,r,o)=>{const a=[];if(e=i.ceil(e),o=null==o?1:Math.floor(o),!(e0))return a;let u;do{a.push(u=new Date(+e)),n(e,o),t(e)}while(uVg((n=>{if(n>=n)for(;t(n),!e(n);)n.setTime(n-1)}),((t,r)=>{if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););})),e&&(i.count=(n,r)=>(Xg.setTime(+n),Gg.setTime(+r),t(Xg),t(Gg),Math.floor(e(Xg,Gg))),i.every=t=>(t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?n=>r(n)%t==0:n=>i.count(0,n)%t==0):i:null)),i}const Wg=Vg((()=>{}),((t,n)=>{t.setTime(+t+n)}),((t,n)=>n-t));Wg.every=t=>(t=Math.floor(t),isFinite(t)&&t>0?t>1?Vg((n=>{n.setTime(Math.floor(n/t)*t)}),((n,e)=>{n.setTime(+n+e*t)}),((n,e)=>(e-n)/t)):Wg:null);const Zg=Wg.range,Kg=1e3,Qg=6e4,Jg=36e5,ty=864e5,ny=6048e5,ey=2592e6,ry=31536e6,iy=Vg((t=>{t.setTime(t-t.getMilliseconds())}),((t,n)=>{t.setTime(+t+n*Kg)}),((t,n)=>(n-t)/Kg),(t=>t.getUTCSeconds())),oy=iy.range,ay=Vg((t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Kg)}),((t,n)=>{t.setTime(+t+n*Qg)}),((t,n)=>(n-t)/Qg),(t=>t.getMinutes())),uy=ay.range,cy=Vg((t=>{t.setUTCSeconds(0,0)}),((t,n)=>{t.setTime(+t+n*Qg)}),((t,n)=>(n-t)/Qg),(t=>t.getUTCMinutes())),fy=cy.range,sy=Vg((t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Kg-t.getMinutes()*Qg)}),((t,n)=>{t.setTime(+t+n*Jg)}),((t,n)=>(n-t)/Jg),(t=>t.getHours())),ly=sy.range,hy=Vg((t=>{t.setUTCMinutes(0,0,0)}),((t,n)=>{t.setTime(+t+n*Jg)}),((t,n)=>(n-t)/Jg),(t=>t.getUTCHours())),dy=hy.range,py=Vg((t=>t.setHours(0,0,0,0)),((t,n)=>t.setDate(t.getDate()+n)),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qg)/ty),(t=>t.getDate()-1)),gy=py.range,yy=Vg((t=>{t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+n)}),((t,n)=>(n-t)/ty),(t=>t.getUTCDate()-1)),vy=yy.range,_y=Vg((t=>{t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+n)}),((t,n)=>(n-t)/ty),(t=>Math.floor(t/ty))),by=_y.range;function my(t){return Vg((n=>{n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)}),((t,n)=>{t.setDate(t.getDate()+7*n)}),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qg)/ny))}const xy=my(0),wy=my(1),My=my(2),Ty=my(3),Ay=my(4),Sy=my(5),Ey=my(6),Ny=xy.range,ky=wy.range,Cy=My.range,Py=Ty.range,zy=Ay.range,$y=Sy.range,Dy=Ey.range;function Ry(t){return Vg((n=>{n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+7*n)}),((t,n)=>(n-t)/ny))}const Fy=Ry(0),qy=Ry(1),Uy=Ry(2),Iy=Ry(3),Oy=Ry(4),By=Ry(5),Yy=Ry(6),Ly=Fy.range,jy=qy.range,Hy=Uy.range,Xy=Iy.range,Gy=Oy.range,Vy=By.range,Wy=Yy.range,Zy=Vg((t=>{t.setDate(1),t.setHours(0,0,0,0)}),((t,n)=>{t.setMonth(t.getMonth()+n)}),((t,n)=>n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())),(t=>t.getMonth())),Ky=Zy.range,Qy=Vg((t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCMonth(t.getUTCMonth()+n)}),((t,n)=>n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())),(t=>t.getUTCMonth())),Jy=Qy.range,tv=Vg((t=>{t.setMonth(0,1),t.setHours(0,0,0,0)}),((t,n)=>{t.setFullYear(t.getFullYear()+n)}),((t,n)=>n.getFullYear()-t.getFullYear()),(t=>t.getFullYear()));tv.every=t=>isFinite(t=Math.floor(t))&&t>0?Vg((n=>{n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)}),((n,e)=>{n.setFullYear(n.getFullYear()+e*t)})):null;const nv=tv.range,ev=Vg((t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n)}),((t,n)=>n.getUTCFullYear()-t.getUTCFullYear()),(t=>t.getUTCFullYear()));ev.every=t=>isFinite(t=Math.floor(t))&&t>0?Vg((n=>{n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)}),((n,e)=>{n.setUTCFullYear(n.getUTCFullYear()+e*t)})):null;const rv=ev.range;function iv(t,n,e,i,o,a){const u=[[iy,1,Kg],[iy,5,5e3],[iy,15,15e3],[iy,30,3e4],[a,1,Qg],[a,5,3e5],[a,15,9e5],[a,30,18e5],[o,1,Jg],[o,3,108e5],[o,6,216e5],[o,12,432e5],[i,1,ty],[i,2,1728e5],[e,1,ny],[n,1,ey],[n,3,7776e6],[t,1,ry]];function c(n,e,i){const o=Math.abs(e-n)/i,a=r((([,,t])=>t)).right(u,o);if(a===u.length)return t.every(W(n/ry,e/ry,i));if(0===a)return Wg.every(Math.max(W(n,e,i),1));const[c,f]=u[o/u[a-1][2]=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:k_,s:C_,S:Zv,u:Kv,U:Qv,V:t_,w:n_,W:e_,x:null,X:null,y:r_,Y:o_,Z:u_,"%":N_},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:c_,e:c_,f:d_,g:T_,G:S_,H:f_,I:s_,j:l_,L:h_,m:p_,M:g_,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:k_,s:C_,S:y_,u:v_,U:__,V:m_,w:x_,W:w_,x:null,X:null,y:M_,Y:A_,Z:E_,"%":N_},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p.get(r[0].toLowerCase()),e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h.get(r[0].toLowerCase()),e+r[0].length):-1},b:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=_.get(r[0].toLowerCase()),e+r[0].length):-1},B:function(t,n,e){var r=g.exec(n.slice(e));return r?(t.m=y.get(r[0].toLowerCase()),e+r[0].length):-1},c:function(t,e,r){return T(t,n,e,r)},d:zv,e:zv,f:Uv,g:Nv,G:Ev,H:Dv,I:Dv,j:$v,L:qv,m:Pv,M:Rv,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s.get(r[0].toLowerCase()),e+r[0].length):-1},q:Cv,Q:Ov,s:Bv,S:Fv,u:Mv,U:Tv,V:Av,w:wv,W:Sv,x:function(t,n,r){return T(t,e,n,r)},X:function(t,n,e){return T(t,r,n,e)},y:Nv,Y:Ev,Z:kv,"%":Iv};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=sv(lv(o.y,0,1))).getUTCDay(),r=i>4||0===i?qy.ceil(r):qy(r),r=yy.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=fv(lv(o.y,0,1))).getDay(),r=i>4||0===i?wy.ceil(r):wy(r),r=py.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?sv(lv(o.y,0,1)).getUTCDay():fv(lv(o.y,0,1)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,sv(o)):fv(o)}}function T(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in pv?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",!1);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t+="",!0);return n.toString=function(){return t},n}}}var dv,pv={"-":"",_:" ",0:"0"},gv=/^\s*\d+/,yv=/^%/,vv=/[\\^$*+?|[\]().{}]/g;function _v(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o[t.toLowerCase(),n])))}function wv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.w=+r[0],e+r[0].length):-1}function Mv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.u=+r[0],e+r[0].length):-1}function Tv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.U=+r[0],e+r[0].length):-1}function Av(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.V=+r[0],e+r[0].length):-1}function Sv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.W=+r[0],e+r[0].length):-1}function Ev(t,n,e){var r=gv.exec(n.slice(e,e+4));return r?(t.y=+r[0],e+r[0].length):-1}function Nv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),e+r[0].length):-1}function kv(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function Cv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.q=3*r[0]-3,e+r[0].length):-1}function Pv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function zv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function $v(t,n,e){var r=gv.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function Dv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function Rv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Fv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function qv(t,n,e){var r=gv.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function Uv(t,n,e){var r=gv.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Iv(t,n,e){var r=yv.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Ov(t,n,e){var r=gv.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function Bv(t,n,e){var r=gv.exec(n.slice(e));return r?(t.s=+r[0],e+r[0].length):-1}function Yv(t,n){return _v(t.getDate(),n,2)}function Lv(t,n){return _v(t.getHours(),n,2)}function jv(t,n){return _v(t.getHours()%12||12,n,2)}function Hv(t,n){return _v(1+py.count(tv(t),t),n,3)}function Xv(t,n){return _v(t.getMilliseconds(),n,3)}function Gv(t,n){return Xv(t,n)+"000"}function Vv(t,n){return _v(t.getMonth()+1,n,2)}function Wv(t,n){return _v(t.getMinutes(),n,2)}function Zv(t,n){return _v(t.getSeconds(),n,2)}function Kv(t){var n=t.getDay();return 0===n?7:n}function Qv(t,n){return _v(xy.count(tv(t)-1,t),n,2)}function Jv(t){var n=t.getDay();return n>=4||0===n?Ay(t):Ay.ceil(t)}function t_(t,n){return t=Jv(t),_v(Ay.count(tv(t),t)+(4===tv(t).getDay()),n,2)}function n_(t){return t.getDay()}function e_(t,n){return _v(wy.count(tv(t)-1,t),n,2)}function r_(t,n){return _v(t.getFullYear()%100,n,2)}function i_(t,n){return _v((t=Jv(t)).getFullYear()%100,n,2)}function o_(t,n){return _v(t.getFullYear()%1e4,n,4)}function a_(t,n){var e=t.getDay();return _v((t=e>=4||0===e?Ay(t):Ay.ceil(t)).getFullYear()%1e4,n,4)}function u_(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+_v(n/60|0,"0",2)+_v(n%60,"0",2)}function c_(t,n){return _v(t.getUTCDate(),n,2)}function f_(t,n){return _v(t.getUTCHours(),n,2)}function s_(t,n){return _v(t.getUTCHours()%12||12,n,2)}function l_(t,n){return _v(1+yy.count(ev(t),t),n,3)}function h_(t,n){return _v(t.getUTCMilliseconds(),n,3)}function d_(t,n){return h_(t,n)+"000"}function p_(t,n){return _v(t.getUTCMonth()+1,n,2)}function g_(t,n){return _v(t.getUTCMinutes(),n,2)}function y_(t,n){return _v(t.getUTCSeconds(),n,2)}function v_(t){var n=t.getUTCDay();return 0===n?7:n}function __(t,n){return _v(Fy.count(ev(t)-1,t),n,2)}function b_(t){var n=t.getUTCDay();return n>=4||0===n?Oy(t):Oy.ceil(t)}function m_(t,n){return t=b_(t),_v(Oy.count(ev(t),t)+(4===ev(t).getUTCDay()),n,2)}function x_(t){return t.getUTCDay()}function w_(t,n){return _v(qy.count(ev(t)-1,t),n,2)}function M_(t,n){return _v(t.getUTCFullYear()%100,n,2)}function T_(t,n){return _v((t=b_(t)).getUTCFullYear()%100,n,2)}function A_(t,n){return _v(t.getUTCFullYear()%1e4,n,4)}function S_(t,n){var e=t.getUTCDay();return _v((t=e>=4||0===e?Oy(t):Oy.ceil(t)).getUTCFullYear()%1e4,n,4)}function E_(){return"+0000"}function N_(){return"%"}function k_(t){return+t}function C_(t){return Math.floor(+t/1e3)}function P_(n){return dv=hv(n),t.timeFormat=dv.format,t.timeParse=dv.parse,t.utcFormat=dv.utcFormat,t.utcParse=dv.utcParse,dv}t.timeFormat=void 0,t.timeParse=void 0,t.utcFormat=void 0,t.utcParse=void 0,P_({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var z_="%Y-%m-%dT%H:%M:%S.%LZ";var $_=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat(z_),D_=$_;var R_=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse(z_),F_=R_;function q_(t){return new Date(t)}function U_(t){return t instanceof Date?+t:+new Date(+t)}function I_(t,n,e,r,i,o,a,u,c,f){var s=Sg(),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),g=f("%I:%M"),y=f("%I %p"),v=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y");function x(t){return(c(t)Fr(t[t.length-1]),ib=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(H_),ob=rb(ib),ab=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(H_),ub=rb(ab),cb=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(H_),fb=rb(cb),sb=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(H_),lb=rb(sb),hb=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(H_),db=rb(hb),pb=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(H_),gb=rb(pb),yb=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(H_),vb=rb(yb),_b=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(H_),bb=rb(_b),mb=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(H_),xb=rb(mb),wb=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(H_),Mb=rb(wb),Tb=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(H_),Ab=rb(Tb),Sb=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(H_),Eb=rb(Sb),Nb=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(H_),kb=rb(Nb),Cb=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(H_),Pb=rb(Cb),zb=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(H_),$b=rb(zb),Db=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(H_),Rb=rb(Db),Fb=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(H_),qb=rb(Fb),Ub=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(H_),Ib=rb(Ub),Ob=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(H_),Bb=rb(Ob),Yb=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(H_),Lb=rb(Yb),jb=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(H_),Hb=rb(jb),Xb=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(H_),Gb=rb(Xb),Vb=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(H_),Wb=rb(Vb),Zb=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(H_),Kb=rb(Zb),Qb=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(H_),Jb=rb(Qb),tm=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(H_),nm=rb(tm),em=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(H_),rm=rb(em);var im=hi(Tr(300,.5,0),Tr(-240,.5,1)),om=hi(Tr(-100,.75,.35),Tr(80,1.5,.8)),am=hi(Tr(260,.75,.35),Tr(80,1.5,.8)),um=Tr();var cm=Fe(),fm=Math.PI/3,sm=2*Math.PI/3;function lm(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}}var hm=lm(H_("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),dm=lm(H_("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),pm=lm(H_("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),gm=lm(H_("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function ym(t){return function(){return t}}const vm=Math.abs,_m=Math.atan2,bm=Math.cos,mm=Math.max,xm=Math.min,wm=Math.sin,Mm=Math.sqrt,Tm=1e-12,Am=Math.PI,Sm=Am/2,Em=2*Am;function Nm(t){return t>=1?Sm:t<=-1?-Sm:Math.asin(t)}function km(t){let n=3;return t.digits=function(e){if(!arguments.length)return n;if(null==e)n=null;else{const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);n=t}return t},()=>new Ua(n)}function Cm(t){return t.innerRadius}function Pm(t){return t.outerRadius}function zm(t){return t.startAngle}function $m(t){return t.endAngle}function Dm(t){return t&&t.padAngle}function Rm(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/Mm(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,g=r+l,y=(h+p)/2,v=(d+g)/2,_=p-h,b=g-d,m=_*_+b*b,x=i-o,w=h*g-p*d,M=(b<0?-1:1)*Mm(mm(0,x*x*m-w*w)),T=(w*b-_*M)/m,A=(-w*_-b*M)/m,S=(w*b+_*M)/m,E=(-w*_+b*M)/m,N=T-y,k=A-v,C=S-y,P=E-v;return N*N+k*k>C*C+P*P&&(T=S,A=E),{cx:T,cy:A,x01:-s,y01:-l,x11:T*(i/x-1),y11:A*(i/x-1)}}var Fm=Array.prototype.slice;function qm(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function Um(t){this._context=t}function Im(t){return new Um(t)}function Om(t){return t[0]}function Bm(t){return t[1]}function Ym(t,n){var e=ym(!0),r=null,i=Im,o=null,a=km(u);function u(u){var c,f,s,l=(u=qm(u)).length,h=!1;for(null==r&&(o=i(s=a())),c=0;c<=l;++c)!(c=l;--h)u.point(v[h],_[h]);u.lineEnd(),u.areaEnd()}y&&(v[s]=+t(d,s,f),_[s]=+n(d,s,f),u.point(r?+r(d,s,f):v[s],e?+e(d,s,f):_[s]))}if(p)return u=null,p+""||null}function s(){return Ym().defined(i).curve(a).context(o)}return t="function"==typeof t?t:void 0===t?Om:ym(+t),n="function"==typeof n?n:ym(void 0===n?0:+n),e="function"==typeof e?e:void 0===e?Bm:ym(+e),f.x=function(n){return arguments.length?(t="function"==typeof n?n:ym(+n),r=null,f):t},f.x0=function(n){return arguments.length?(t="function"==typeof n?n:ym(+n),f):t},f.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:ym(+t),f):r},f.y=function(t){return arguments.length?(n="function"==typeof t?t:ym(+t),e=null,f):n},f.y0=function(t){return arguments.length?(n="function"==typeof t?t:ym(+t),f):n},f.y1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:ym(+t),f):e},f.lineX0=f.lineY0=function(){return s().x(t).y(n)},f.lineY1=function(){return s().x(t).y(e)},f.lineX1=function(){return s().x(r).y(n)},f.defined=function(t){return arguments.length?(i="function"==typeof t?t:ym(!!t),f):i},f.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),f):a},f.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),f):o},f}function jm(t,n){return nt?1:n>=t?0:NaN}function Hm(t){return t}Um.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Xm=Vm(Im);function Gm(t){this._curve=t}function Vm(t){function n(n){return new Gm(t(n))}return n._curve=t,n}function Wm(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(Vm(t)):n()._curve},t}function Zm(){return Wm(Ym().curve(Xm))}function Km(){var t=Lm().curve(Xm),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Wm(e())},delete t.lineX0,t.lineEndAngle=function(){return Wm(r())},delete t.lineX1,t.lineInnerRadius=function(){return Wm(i())},delete t.lineY0,t.lineOuterRadius=function(){return Wm(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(Vm(t)):n()._curve},t}function Qm(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}Gm.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};class Jm{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n)}this._x0=t,this._y0=n}}class tx{constructor(t){this._context=t}lineStart(){this._point=0}lineEnd(){}point(t,n){if(t=+t,n=+n,0===this._point)this._point=1;else{const e=Qm(this._x0,this._y0),r=Qm(this._x0,this._y0=(this._y0+n)/2),i=Qm(t,this._y0),o=Qm(t,n);this._context.moveTo(...e),this._context.bezierCurveTo(...r,...i,...o)}this._x0=t,this._y0=n}}function nx(t){return new Jm(t,!0)}function ex(t){return new Jm(t,!1)}function rx(t){return new tx(t)}function ix(t){return t.source}function ox(t){return t.target}function ax(t){let n=ix,e=ox,r=Om,i=Bm,o=null,a=null,u=km(c);function c(){let c;const f=Fm.call(arguments),s=n.apply(this,f),l=e.apply(this,f);if(null==o&&(a=t(c=u())),a.lineStart(),f[0]=s,a.point(+r.apply(this,f),+i.apply(this,f)),f[0]=l,a.point(+r.apply(this,f),+i.apply(this,f)),a.lineEnd(),c)return a=null,c+""||null}return c.source=function(t){return arguments.length?(n=t,c):n},c.target=function(t){return arguments.length?(e=t,c):e},c.x=function(t){return arguments.length?(r="function"==typeof t?t:ym(+t),c):r},c.y=function(t){return arguments.length?(i="function"==typeof t?t:ym(+t),c):i},c.context=function(n){return arguments.length?(null==n?o=a=null:a=t(o=n),c):o},c}const ux=Mm(3);var cx={draw(t,n){const e=.59436*Mm(n+xm(n/28,.75)),r=e/2,i=r*ux;t.moveTo(0,e),t.lineTo(0,-e),t.moveTo(-i,-r),t.lineTo(i,r),t.moveTo(-i,r),t.lineTo(i,-r)}},fx={draw(t,n){const e=Mm(n/Am);t.moveTo(e,0),t.arc(0,0,e,0,Em)}},sx={draw(t,n){const e=Mm(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}};const lx=Mm(1/3),hx=2*lx;var dx={draw(t,n){const e=Mm(n/hx),r=e*lx;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},px={draw(t,n){const e=.62625*Mm(n);t.moveTo(0,-e),t.lineTo(e,0),t.lineTo(0,e),t.lineTo(-e,0),t.closePath()}},gx={draw(t,n){const e=.87559*Mm(n-xm(n/7,2));t.moveTo(-e,0),t.lineTo(e,0),t.moveTo(0,e),t.lineTo(0,-e)}},yx={draw(t,n){const e=Mm(n),r=-e/2;t.rect(r,r,e,e)}},vx={draw(t,n){const e=.4431*Mm(n);t.moveTo(e,e),t.lineTo(e,-e),t.lineTo(-e,-e),t.lineTo(-e,e),t.closePath()}};const _x=wm(Am/10)/wm(7*Am/10),bx=wm(Em/10)*_x,mx=-bm(Em/10)*_x;var xx={draw(t,n){const e=Mm(.8908130915292852*n),r=bx*e,i=mx*e;t.moveTo(0,-e),t.lineTo(r,i);for(let n=1;n<5;++n){const o=Em*n/5,a=bm(o),u=wm(o);t.lineTo(u*e,-a*e),t.lineTo(a*r-u*i,u*r+a*i)}t.closePath()}};const wx=Mm(3);var Mx={draw(t,n){const e=-Mm(n/(3*wx));t.moveTo(0,2*e),t.lineTo(-wx*e,-e),t.lineTo(wx*e,-e),t.closePath()}};const Tx=Mm(3);var Ax={draw(t,n){const e=.6824*Mm(n),r=e/2,i=e*Tx/2;t.moveTo(0,-e),t.lineTo(i,r),t.lineTo(-i,r),t.closePath()}};const Sx=-.5,Ex=Mm(3)/2,Nx=1/Mm(12),kx=3*(Nx/2+1);var Cx={draw(t,n){const e=Mm(n/kx),r=e/2,i=e*Nx,o=r,a=e*Nx+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(Sx*r-Ex*i,Ex*r+Sx*i),t.lineTo(Sx*o-Ex*a,Ex*o+Sx*a),t.lineTo(Sx*u-Ex*c,Ex*u+Sx*c),t.lineTo(Sx*r+Ex*i,Sx*i-Ex*r),t.lineTo(Sx*o+Ex*a,Sx*a-Ex*o),t.lineTo(Sx*u+Ex*c,Sx*c-Ex*u),t.closePath()}},Px={draw(t,n){const e=.6189*Mm(n-xm(n/6,1.7));t.moveTo(-e,-e),t.lineTo(e,e),t.moveTo(-e,e),t.lineTo(e,-e)}};const zx=[fx,sx,dx,yx,xx,Mx,Cx],$x=[fx,gx,Px,Ax,cx,vx,px];function Dx(){}function Rx(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function Fx(t){this._context=t}function qx(t){this._context=t}function Ux(t){this._context=t}function Ix(t,n){this._basis=new Fx(t),this._beta=n}Fx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Rx(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Rx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},qx.prototype={areaStart:Dx,areaEnd:Dx,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:Rx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},Ux.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:Rx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},Ix.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var Ox=function t(n){function e(t){return 1===n?new Fx(t):new Ix(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function Bx(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function Yx(t,n){this._context=t,this._k=(1-n)/6}Yx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Bx(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:Bx(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Lx=function t(n){function e(t){return new Yx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function jx(t,n){this._context=t,this._k=(1-n)/6}jx.prototype={areaStart:Dx,areaEnd:Dx,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Bx(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Hx=function t(n){function e(t){return new jx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Xx(t,n){this._context=t,this._k=(1-n)/6}Xx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Bx(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Gx=function t(n){function e(t){return new Xx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Vx(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>Tm){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>Tm){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function Wx(t,n){this._context=t,this._alpha=n}Wx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:Vx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Zx=function t(n){function e(t){return n?new Wx(t,n):new Yx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Kx(t,n){this._context=t,this._alpha=n}Kx.prototype={areaStart:Dx,areaEnd:Dx,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Vx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Qx=function t(n){function e(t){return n?new Kx(t,n):new jx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Jx(t,n){this._context=t,this._alpha=n}Jx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Vx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var tw=function t(n){function e(t){return n?new Jx(t,n):new Xx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function nw(t){this._context=t}function ew(t){return t<0?-1:1}function rw(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(ew(o)+ew(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function iw(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function ow(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function aw(t){this._context=t}function uw(t){this._context=new cw(t)}function cw(t){this._context=t}function fw(t){this._context=t}function sw(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o=0;)e[n]=n;return e}function pw(t,n){return t[n]}function gw(t){const n=[];return n.key=t,n}function yw(t){var n=t.map(vw);return dw(t).sort((function(t,e){return n[t]-n[e]}))}function vw(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++eo&&(o=n,r=e);return r}function _w(t){var n=t.map(bw);return dw(t).sort((function(t,e){return n[t]-n[e]}))}function bw(t){for(var n,e=0,r=-1,i=t.length;++r=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}};var mw=t=>()=>t;function xw(t,{sourceEvent:n,target:e,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function ww(t,n,e){this.k=t,this.x=n,this.y=e}ww.prototype={constructor:ww,scale:function(t){return 1===t?this:new ww(this.k*t,this.x,this.y)},translate:function(t,n){return 0===t&0===n?this:new ww(this.k,this.x+this.k*t,this.y+this.k*n)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Mw=new ww(1,0,0);function Tw(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Mw;return t.__zoom}function Aw(t){t.stopImmediatePropagation()}function Sw(t){t.preventDefault(),t.stopImmediatePropagation()}function Ew(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function Nw(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function kw(){return this.__zoom||Mw}function Cw(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function Pw(){return navigator.maxTouchPoints||"ontouchstart"in this}function zw(t,n,e){var r=t.invertX(n[0][0])-e[0][0],i=t.invertX(n[1][0])-e[1][0],o=t.invertY(n[0][1])-e[0][1],a=t.invertY(n[1][1])-e[1][1];return t.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}Tw.prototype=ww.prototype,t.Adder=T,t.Delaunay=Lu,t.FormatSpecifier=tf,t.InternMap=InternMap,t.InternSet=InternSet,t.Node=Qd,t.Path=Ua,t.Voronoi=qu,t.ZoomTransform=ww,t.active=function(t,n){var e,r,i=t.__transition;if(i)for(r in n=null==n?null:n+"",i)if((e=i[r]).state>qi&&e.name===n)return new po([[t]],Zo,n,+r);return null},t.arc=function(){var t=Cm,n=Pm,e=ym(0),r=null,i=zm,o=$m,a=Dm,u=null,c=km(f);function f(){var f,s,l=+t.apply(this,arguments),h=+n.apply(this,arguments),d=i.apply(this,arguments)-Sm,p=o.apply(this,arguments)-Sm,g=vm(p-d),y=p>d;if(u||(u=f=c()),hTm)if(g>Em-Tm)u.moveTo(h*bm(d),h*wm(d)),u.arc(0,0,h,d,p,!y),l>Tm&&(u.moveTo(l*bm(p),l*wm(p)),u.arc(0,0,l,p,d,y));else{var v,_,b=d,m=p,x=d,w=p,M=g,T=g,A=a.apply(this,arguments)/2,S=A>Tm&&(r?+r.apply(this,arguments):Mm(l*l+h*h)),E=xm(vm(h-l)/2,+e.apply(this,arguments)),N=E,k=E;if(S>Tm){var C=Nm(S/l*wm(A)),P=Nm(S/h*wm(A));(M-=2*C)>Tm?(x+=C*=y?1:-1,w-=C):(M=0,x=w=(d+p)/2),(T-=2*P)>Tm?(b+=P*=y?1:-1,m-=P):(T=0,b=m=(d+p)/2)}var z=h*bm(b),$=h*wm(b),D=l*bm(w),R=l*wm(w);if(E>Tm){var F,q=h*bm(m),U=h*wm(m),I=l*bm(x),O=l*wm(x);if(g1?0:t<-1?Am:Math.acos(t)}((B*L+Y*j)/(Mm(B*B+Y*Y)*Mm(L*L+j*j)))/2),X=Mm(F[0]*F[0]+F[1]*F[1]);N=xm(E,(l-X)/(H-1)),k=xm(E,(h-X)/(H+1))}else N=k=0}T>Tm?k>Tm?(v=Rm(I,O,z,$,h,k,y),_=Rm(q,U,D,R,h,k,y),u.moveTo(v.cx+v.x01,v.cy+v.y01),kTm&&M>Tm?N>Tm?(v=Rm(D,R,q,U,l,-N,y),_=Rm(z,$,I,O,l,-N,y),u.lineTo(v.cx+v.x01,v.cy+v.y01),N=0))throw new RangeError("invalid r");let e=t.length;if(!((e=Math.floor(e))>=0))throw new RangeError("invalid length");if(!e||!n)return t;const r=y(n),i=t.slice();return r(t,i,0,e,1),r(i,t,0,e,1),r(t,i,0,e,1),t},t.blur2=l,t.blurImage=h,t.brush=function(){return wa(la)},t.brushSelection=function(t){var n=t.__brush;return n?n.dim.output(n.selection):null},t.brushX=function(){return wa(fa)},t.brushY=function(){return wa(sa)},t.buffer=function(t,n){return fetch(t,n).then(_c)},t.chord=function(){return za(!1,!1)},t.chordDirected=function(){return za(!0,!1)},t.chordTranspose=function(){return za(!1,!0)},t.cluster=function(){var t=Ld,n=1,e=1,r=!1;function i(i){var o,a=0;i.eachAfter((function(n){var e=n.children;e?(n.x=function(t){return t.reduce(jd,0)/t.length}(e),n.y=function(t){return 1+t.reduce(Hd,0)}(e)):(n.x=o?a+=t(n,o):0,n.y=0,o=n)}));var u=function(t){for(var n;n=t.children;)t=n[0];return t}(i),c=function(t){for(var n;n=t.children;)t=n[n.length-1];return t}(i),f=u.x-t(u,c)/2,s=c.x+t(c,u)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*n,t.y=(i.y-t.y)*e}:function(t){t.x=(t.x-f)/(s-f)*n,t.y=(1-(i.y?t.y/i.y:1))*e})}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.color=ze,t.contourDensity=function(){var t=fu,n=su,e=lu,r=960,i=500,o=20,a=2,u=3*o,c=r+2*u>>a,f=i+2*u>>a,s=Qa(20);function h(r){var i=new Float32Array(c*f),s=Math.pow(2,-a),h=-1;for(const o of r){var d=(t(o,++h,r)+u)*s,p=(n(o,h,r)+u)*s,g=+e(o,h,r);if(g&&d>=0&&d=0&&pt*r)))(n).map(((t,n)=>(t.value=+e[n],p(t))))}function p(t){return t.coordinates.forEach(g),t}function g(t){t.forEach(y)}function y(t){t.forEach(v)}function v(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function _(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,d}return d.contours=function(t){var n=h(t),e=iu().size([c,f]),r=Math.pow(2,2*a),i=t=>{t=+t;var i=p(e.contour(n,t*r));return i.value=t,i};return Object.defineProperty(i,"max",{get:()=>J(n)/r}),i},d.x=function(n){return arguments.length?(t="function"==typeof n?n:Qa(+n),d):t},d.y=function(t){return arguments.length?(n="function"==typeof t?t:Qa(+t),d):n},d.weight=function(t){return arguments.length?(e="function"==typeof t?t:Qa(+t),d):e},d.size=function(t){if(!arguments.length)return[r,i];var n=+t[0],e=+t[1];if(!(n>=0&&e>=0))throw new Error("invalid size");return r=n,i=e,_()},d.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),_()},d.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?Qa(Za.call(t)):Qa(t),d):s},d.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=(Math.sqrt(4*t*t+1)-1)/2,_()},d},t.contours=iu,t.count=v,t.create=function(t){return Zn(Yt(t).call(document.documentElement))},t.creator=Yt,t.cross=function(...t){const n="function"==typeof t[t.length-1]&&function(t){return n=>t(...n)}(t.pop()),e=(t=t.map(m)).map(_),r=t.length-1,i=new Array(r+1).fill(0),o=[];if(r<0||e.some(b))return o;for(;;){o.push(i.map(((n,e)=>t[e][n])));let a=r;for(;++i[a]===e[a];){if(0===a)return n?o.map(n):o;i[a--]=0}}},t.csv=wc,t.csvFormat=rc,t.csvFormatBody=ic,t.csvFormatRow=ac,t.csvFormatRows=oc,t.csvFormatValue=uc,t.csvParse=nc,t.csvParseRows=ec,t.cubehelix=Tr,t.cumsum=function(t,n){var e=0,r=0;return Float64Array.from(t,void 0===n?t=>e+=+t||0:i=>e+=+n(i,r++,t)||0)},t.curveBasis=function(t){return new Fx(t)},t.curveBasisClosed=function(t){return new qx(t)},t.curveBasisOpen=function(t){return new Ux(t)},t.curveBumpX=nx,t.curveBumpY=ex,t.curveBundle=Ox,t.curveCardinal=Lx,t.curveCardinalClosed=Hx,t.curveCardinalOpen=Gx,t.curveCatmullRom=Zx,t.curveCatmullRomClosed=Qx,t.curveCatmullRomOpen=tw,t.curveLinear=Im,t.curveLinearClosed=function(t){return new nw(t)},t.curveMonotoneX=function(t){return new aw(t)},t.curveMonotoneY=function(t){return new uw(t)},t.curveNatural=function(t){return new fw(t)},t.curveStep=function(t){return new lw(t,.5)},t.curveStepAfter=function(t){return new lw(t,1)},t.curveStepBefore=function(t){return new lw(t,0)},t.descending=e,t.deviation=w,t.difference=function(t,...n){t=new InternSet(t);for(const e of n)for(const n of e)t.delete(n);return t},t.disjoint=function(t,n){const e=n[Symbol.iterator](),r=new InternSet;for(const n of t){if(r.has(n))return!1;let t,i;for(;({value:t,done:i}=e.next())&&!i;){if(Object.is(n,t))return!1;r.add(t)}}return!0},t.dispatch=$t,t.drag=function(){var t,n,e,r,i=se,o=le,a=he,u=de,c={},f=$t("start","drag","end"),s=0,l=0;function h(t){t.on("mousedown.drag",d).filter(u).on("touchstart.drag",y).on("touchmove.drag",v,ee).on("touchend.drag touchcancel.drag",_).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(a,u){if(!r&&i.call(this,a,u)){var c=b(this,o.call(this,a,u),a,u,"mouse");c&&(Zn(a.view).on("mousemove.drag",p,re).on("mouseup.drag",g,re),ae(a.view),ie(a),e=!1,t=a.clientX,n=a.clientY,c("start",a))}}function p(r){if(oe(r),!e){var i=r.clientX-t,o=r.clientY-n;e=i*i+o*o>l}c.mouse("drag",r)}function g(t){Zn(t.view).on("mousemove.drag mouseup.drag",null),ue(t.view,e),oe(t),c.mouse("end",t)}function y(t,n){if(i.call(this,t,n)){var e,r,a=t.changedTouches,u=o.call(this,t,n),c=a.length;for(e=0;e+t,t.easePoly=wo,t.easePolyIn=mo,t.easePolyInOut=wo,t.easePolyOut=xo,t.easeQuad=_o,t.easeQuadIn=function(t){return t*t},t.easeQuadInOut=_o,t.easeQuadOut=function(t){return t*(2-t)},t.easeSin=Ao,t.easeSinIn=function(t){return 1==+t?1:1-Math.cos(t*To)},t.easeSinInOut=Ao,t.easeSinOut=function(t){return Math.sin(t*To)},t.every=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(!n(r,++e,t))return!1;return!0},t.extent=M,t.fcumsum=function(t,n){const e=new T;let r=-1;return Float64Array.from(t,void 0===n?t=>e.add(+t||0):i=>e.add(+n(i,++r,t)||0))},t.filter=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");const e=[];let r=-1;for(const i of t)n(i,++r,t)&&e.push(i);return e},t.flatGroup=function(t,...n){return z(P(t,...n),n)},t.flatRollup=function(t,n,...e){return z(D(t,n,...e),e)},t.forceCenter=function(t,n){var e,r=1;function i(){var i,o,a=e.length,u=0,c=0;for(i=0;if+p||os+p||ac.index){var g=f-u.x-u.vx,y=s-u.y-u.vy,v=g*g+y*y;vt.r&&(t.r=t[n].r)}function c(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r[u(t,n,r),t])));for(a=0,i=new Array(f);a=u)){(t.data!==n||t.next)&&(0===l&&(p+=(l=Uc(e))*l),0===h&&(p+=(h=Uc(e))*h),p(t=(Lc*t+jc)%Hc)/Hc}();function l(){h(),f.call("tick",n),e1?(null==e?u.delete(t):u.set(t,p(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=qc(.1);function o(t){for(var i,o=0,a=n.length;o=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++ejs(r[0],r[1])&&(r[1]=i[1]),js(i[0],r[1])>js(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=js(r[1],i[0]))>a&&(a=u,Wf=i[0],Kf=r[1])}return is=os=null,Wf===1/0||Zf===1/0?[[NaN,NaN],[NaN,NaN]]:[[Wf,Zf],[Kf,Qf]]},t.geoCentroid=function(t){ms=xs=ws=Ms=Ts=As=Ss=Es=0,Ns=new T,ks=new T,Cs=new T,Lf(t,Gs);var n=+Ns,e=+ks,r=+Cs,i=Ef(n,e,r);return i=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new ed(i)),a},a.projection(t).digits(i).context(n)},t.geoProjection=yd,t.geoProjectionMutator=vd,t.geoRotation=ll,t.geoStereographic=function(){return yd(Bd).scale(250).clipAngle(142)},t.geoStereographicRaw=Bd,t.geoStream=Lf,t.geoTransform=function(t){return{stream:id(t)}},t.geoTransverseMercator=function(){var t=Ed(Yd),n=t.center,e=t.rotate;return t.center=function(t){return arguments.length?n([-t[1],t[0]]):[(t=n())[1],-t[0]]},t.rotate=function(t){return arguments.length?e([t[0],t[1],t.length>2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=Yd,t.gray=function(t,n){return new ur(t,0,0,null==n?1:n)},t.greatest=ot,t.greatestIndex=function(t,e=n){if(1===e.length)return tt(t,e);let r,i=-1,o=-1;for(const n of t)++o,(i<0?0===e(n,n):e(n,r)>0)&&(r=n,i=o);return i},t.group=C,t.groupSort=function(t,e,r){return(2!==e.length?U($(t,e,r),(([t,e],[r,i])=>n(e,i)||n(t,r))):U(C(t,r),(([t,r],[i,o])=>e(r,o)||n(t,i)))).map((([t])=>t))},t.groups=P,t.hcl=dr,t.hierarchy=Gd,t.histogram=Q,t.hsl=He,t.html=Ec,t.image=function(t,n){return new Promise((function(e,r){var i=new Image;for(var o in n)i[o]=n[o];i.onerror=r,i.onload=function(){e(i)},i.src=t}))},t.index=function(t,...n){return F(t,k,R,n)},t.indexes=function(t,...n){return F(t,Array.from,R,n)},t.interpolate=Gr,t.interpolateArray=function(t,n){return(Ir(n)?Ur:Or)(t,n)},t.interpolateBasis=Er,t.interpolateBasisClosed=Nr,t.interpolateBlues=Gb,t.interpolateBrBG=ob,t.interpolateBuGn=Mb,t.interpolateBuPu=Ab,t.interpolateCividis=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"},t.interpolateCool=am,t.interpolateCubehelix=li,t.interpolateCubehelixDefault=im,t.interpolateCubehelixLong=hi,t.interpolateDate=Br,t.interpolateDiscrete=function(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}},t.interpolateGnBu=Eb,t.interpolateGreens=Wb,t.interpolateGreys=Kb,t.interpolateHcl=ci,t.interpolateHclLong=fi,t.interpolateHsl=oi,t.interpolateHslLong=ai,t.interpolateHue=function(t,n){var e=Pr(+t,+n);return function(t){var n=e(t);return n-360*Math.floor(n/360)}},t.interpolateInferno=pm,t.interpolateLab=function(t,n){var e=$r((t=ar(t)).l,(n=ar(n)).l),r=$r(t.a,n.a),i=$r(t.b,n.b),o=$r(t.opacity,n.opacity);return function(n){return t.l=e(n),t.a=r(n),t.b=i(n),t.opacity=o(n),t+""}},t.interpolateMagma=dm,t.interpolateNumber=Yr,t.interpolateNumberArray=Ur,t.interpolateObject=Lr,t.interpolateOrRd=kb,t.interpolateOranges=rm,t.interpolatePRGn=ub,t.interpolatePiYG=fb,t.interpolatePlasma=gm,t.interpolatePuBu=$b,t.interpolatePuBuGn=Pb,t.interpolatePuOr=lb,t.interpolatePuRd=Rb,t.interpolatePurples=Jb,t.interpolateRainbow=function(t){(t<0||t>1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return um.h=360*t-100,um.s=1.5-1.5*n,um.l=.8-.9*n,um+""},t.interpolateRdBu=db,t.interpolateRdGy=gb,t.interpolateRdPu=qb,t.interpolateRdYlBu=vb,t.interpolateRdYlGn=bb,t.interpolateReds=nm,t.interpolateRgb=Dr,t.interpolateRgbBasis=Fr,t.interpolateRgbBasisClosed=qr,t.interpolateRound=Vr,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,cm.r=255*(n=Math.sin(t))*n,cm.g=255*(n=Math.sin(t+fm))*n,cm.b=255*(n=Math.sin(t+sm))*n,cm+""},t.interpolateSpectral=xb,t.interpolateString=Xr,t.interpolateTransformCss=ti,t.interpolateTransformSvg=ni,t.interpolateTurbo=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"},t.interpolateViridis=hm,t.interpolateWarm=om,t.interpolateYlGn=Bb,t.interpolateYlGnBu=Ib,t.interpolateYlOrBr=Lb,t.interpolateYlOrRd=Hb,t.interpolateZoom=ri,t.interrupt=Gi,t.intersection=function(t,...n){t=new InternSet(t),n=n.map(vt);t:for(const e of t)for(const r of n)if(!r.has(e)){t.delete(e);continue t}return t},t.interval=function(t,n,e){var r=new Ei,i=n;return null==n?(r.restart(t,n,e),r):(r._restart=r.restart,r.restart=function(t,n,e){n=+n,e=null==e?Ai():+e,r._restart((function o(a){a+=i,r._restart(o,i+=n,e),t(a)}),n,e)},r.restart(t,n,e),r)},t.isoFormat=D_,t.isoParse=F_,t.json=function(t,n){return fetch(t,n).then(Tc)},t.lab=ar,t.lch=function(t,n,e,r){return 1===arguments.length?hr(t):new pr(e,n,t,null==r?1:r)},t.least=function(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)<0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)<0:0===e(n,n))&&(r=n,i=!0);return r},t.leastIndex=ht,t.line=Ym,t.lineRadial=Zm,t.link=ax,t.linkHorizontal=function(){return ax(nx)},t.linkRadial=function(){const t=ax(rx);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.linkVertical=function(){return ax(ex)},t.local=Qn,t.map=function(t,n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof n)throw new TypeError("mapper is not a function");return Array.from(t,((e,r)=>n(e,r,t)))},t.matcher=Vt,t.max=J,t.maxIndex=tt,t.mean=function(t,n){let e=0,r=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(++e,r+=n);else{let i=-1;for(let o of t)null!=(o=n(o,++i,t))&&(o=+o)>=o&&(++e,r+=o)}if(e)return r/e},t.median=function(t,n){return at(t,.5,n)},t.medianIndex=function(t,n){return ct(t,.5,n)},t.merge=ft,t.min=nt,t.minIndex=et,t.mode=function(t,n){const e=new InternMap;if(void 0===n)for(let n of t)null!=n&&n>=n&&e.set(n,(e.get(n)||0)+1);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&i>=i&&e.set(i,(e.get(i)||0)+1)}let r,i=0;for(const[t,n]of e)n>i&&(i=n,r=t);return r},t.namespace=It,t.namespaces=Ut,t.nice=Z,t.now=Ai,t.pack=function(){var t=null,n=1,e=1,r=np;function i(i){const o=ap();return i.x=n/2,i.y=e/2,t?i.eachBefore(xp(t)).eachAfter(wp(r,.5,o)).eachBefore(Mp(1)):i.eachBefore(xp(mp)).eachAfter(wp(np,1,o)).eachAfter(wp(r,i.r/Math.min(n,e),o)).eachBefore(Mp(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=Jd(n),i):t},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:ep(+t),i):r},i},t.packEnclose=function(t){return up(t,ap())},t.packSiblings=function(t){return bp(t,ap()),t},t.pairs=function(t,n=st){const e=[];let r,i=!1;for(const o of t)i&&e.push(n(r,o)),r=o,i=!0;return e},t.partition=function(){var t=1,n=1,e=0,r=!1;function i(i){var o=i.height+1;return i.x0=i.y0=e,i.x1=t,i.y1=n/o,i.eachBefore(function(t,n){return function(r){r.children&&Ap(r,r.x0,t*(r.depth+1)/n,r.x1,t*(r.depth+2)/n);var i=r.x0,o=r.y0,a=r.x1-e,u=r.y1-e;a0&&(d+=l);for(null!=n?p.sort((function(t,e){return n(g[t],g[e])})):null!=e&&p.sort((function(t,n){return e(a[t],a[n])})),u=0,f=d?(v-h*b)/d:0;u0?l*f:0)+b,g[c]={data:a[c],index:u,value:l,startAngle:y,endAngle:s,padAngle:_};return g}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:ym(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:ym(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:ym(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:ym(+t),a):o},a},t.piecewise=di,t.pointRadial=Qm,t.pointer=ne,t.pointers=function(t,n){return t.target&&(t=te(t),void 0===n&&(n=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>ne(t,n)))},t.polygonArea=function(t){for(var n,e=-1,r=t.length,i=t[r-1],o=0;++eu!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonHull=function(t){if((e=t.length)<3)return null;var n,e,r=new Array(e),i=new Array(e);for(n=0;n=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;n(n=1664525*n+1013904223|0,lg*(n>>>0))},t.randomLogNormal=Kp,t.randomLogistic=fg,t.randomNormal=Zp,t.randomPareto=ng,t.randomPoisson=sg,t.randomUniform=Vp,t.randomWeibull=ug,t.range=lt,t.rank=function(t,e=n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let r=Array.from(t);const i=new Float64Array(r.length);2!==e.length&&(r=r.map(e),e=n);const o=(t,n)=>e(r[t],r[n]);let a,u;return(t=Uint32Array.from(r,((t,n)=>n))).sort(e===n?(t,n)=>O(r[t],r[n]):I(o)),t.forEach(((t,n)=>{const e=o(t,void 0===a?t:a);e>=0?((void 0===a||e>0)&&(a=t,u=n),i[t]=u):i[t]=NaN})),i},t.reduce=function(t,n,e){if("function"!=typeof n)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let i,o,a=-1;if(arguments.length<3){if(({done:i,value:e}=r.next()),i)return;++a}for(;({done:i,value:o}=r.next()),!i;)e=n(e,o,++a,t);return e},t.reverse=function(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()},t.rgb=Fe,t.ribbon=function(){return Wa()},t.ribbonArrow=function(){return Wa(Va)},t.rollup=$,t.rollups=D,t.scaleBand=yg,t.scaleDiverging=function t(){var n=Ng(L_()(mg));return n.copy=function(){return B_(n,t())},dg.apply(n,arguments)},t.scaleDivergingLog=function t(){var n=Fg(L_()).domain([.1,1,10]);return n.copy=function(){return B_(n,t()).base(n.base())},dg.apply(n,arguments)},t.scaleDivergingPow=j_,t.scaleDivergingSqrt=function(){return j_.apply(null,arguments).exponent(.5)},t.scaleDivergingSymlog=function t(){var n=Ig(L_());return n.copy=function(){return B_(n,t()).constant(n.constant())},dg.apply(n,arguments)},t.scaleIdentity=function t(n){var e;function r(t){return null==t||isNaN(t=+t)?e:t}return r.invert=r,r.domain=r.range=function(t){return arguments.length?(n=Array.from(t,_g),r):n.slice()},r.unknown=function(t){return arguments.length?(e=t,r):e},r.copy=function(){return t(n).unknown(e)},n=arguments.length?Array.from(n,_g):[0,1],Ng(r)},t.scaleImplicit=pg,t.scaleLinear=function t(){var n=Sg();return n.copy=function(){return Tg(n,t())},hg.apply(n,arguments),Ng(n)},t.scaleLog=function t(){const n=Fg(Ag()).domain([1,10]);return n.copy=()=>Tg(n,t()).base(n.base()),hg.apply(n,arguments),n},t.scaleOrdinal=gg,t.scalePoint=function(){return vg(yg.apply(null,arguments).paddingInner(1))},t.scalePow=jg,t.scaleQuantile=function t(){var e,r=[],i=[],o=[];function a(){var t=0,n=Math.max(1,i.length);for(o=new Array(n-1);++t0?o[n-1]:r[0],n=i?[o[i-1],r]:[o[n-1],o[n]]},u.unknown=function(t){return arguments.length?(n=t,u):u},u.thresholds=function(){return o.slice()},u.copy=function(){return t().domain([e,r]).range(a).unknown(n)},hg.apply(Ng(u),arguments)},t.scaleRadial=function t(){var n,e=Sg(),r=[0,1],i=!1;function o(t){var r=function(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}(e(t));return isNaN(r)?n:i?Math.round(r):r}return o.invert=function(t){return e.invert(Hg(t))},o.domain=function(t){return arguments.length?(e.domain(t),o):e.domain()},o.range=function(t){return arguments.length?(e.range((r=Array.from(t,_g)).map(Hg)),o):r.slice()},o.rangeRound=function(t){return o.range(t).round(!0)},o.round=function(t){return arguments.length?(i=!!t,o):i},o.clamp=function(t){return arguments.length?(e.clamp(t),o):e.clamp()},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t(e.domain(),r).round(i).clamp(e.clamp()).unknown(n)},hg.apply(o,arguments),Ng(o)},t.scaleSequential=function t(){var n=Ng(O_()(mg));return n.copy=function(){return B_(n,t())},dg.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Fg(O_()).domain([1,10]);return n.copy=function(){return B_(n,t()).base(n.base())},dg.apply(n,arguments)},t.scaleSequentialPow=Y_,t.scaleSequentialQuantile=function t(){var e=[],r=mg;function i(t){if(null!=t&&!isNaN(t=+t))return r((s(e,t,1)-1)/(e.length-1))}return i.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(n),i},i.interpolator=function(t){return arguments.length?(r=t,i):r},i.range=function(){return e.map(((t,n)=>r(n/(e.length-1))))},i.quantiles=function(t){return Array.from({length:t+1},((n,r)=>at(e,r/t)))},i.copy=function(){return t(r).domain(e)},dg.apply(i,arguments)},t.scaleSequentialSqrt=function(){return Y_.apply(null,arguments).exponent(.5)},t.scaleSequentialSymlog=function t(){var n=Ig(O_());return n.copy=function(){return B_(n,t()).constant(n.constant())},dg.apply(n,arguments)},t.scaleSqrt=function(){return jg.apply(null,arguments).exponent(.5)},t.scaleSymlog=function t(){var n=Ig(Ag());return n.copy=function(){return Tg(n,t()).constant(n.constant())},hg.apply(n,arguments)},t.scaleThreshold=function t(){var n,e=[.5],r=[0,1],i=1;function o(t){return null!=t&&t<=t?r[s(e,t,0,i)]:n}return o.domain=function(t){return arguments.length?(e=Array.from(t),i=Math.min(e.length,r.length-1),o):e.slice()},o.range=function(t){return arguments.length?(r=Array.from(t),i=Math.min(e.length,r.length-1),o):r.slice()},o.invertExtent=function(t){var n=r.indexOf(t);return[e[n-1],e[n]]},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t().domain(e).range(r).unknown(n)},hg.apply(o,arguments)},t.scaleTime=function(){return hg.apply(I_(uv,cv,tv,Zy,xy,py,sy,ay,iy,t.timeFormat).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)},t.scaleUtc=function(){return hg.apply(I_(ov,av,ev,Qy,Fy,yy,hy,cy,iy,t.utcFormat).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)},t.scan=function(t,n){const e=ht(t,n);return e<0?void 0:e},t.schemeAccent=G_,t.schemeBlues=Xb,t.schemeBrBG=ib,t.schemeBuGn=wb,t.schemeBuPu=Tb,t.schemeCategory10=X_,t.schemeDark2=V_,t.schemeGnBu=Sb,t.schemeGreens=Vb,t.schemeGreys=Zb,t.schemeObservable10=W_,t.schemeOrRd=Nb,t.schemeOranges=em,t.schemePRGn=ab,t.schemePaired=Z_,t.schemePastel1=K_,t.schemePastel2=Q_,t.schemePiYG=cb,t.schemePuBu=zb,t.schemePuBuGn=Cb,t.schemePuOr=sb,t.schemePuRd=Db,t.schemePurples=Qb,t.schemeRdBu=hb,t.schemeRdGy=pb,t.schemeRdPu=Fb,t.schemeRdYlBu=yb,t.schemeRdYlGn=_b,t.schemeReds=tm,t.schemeSet1=J_,t.schemeSet2=tb,t.schemeSet3=nb,t.schemeSpectral=mb,t.schemeTableau10=eb,t.schemeYlGn=Ob,t.schemeYlGnBu=Ub,t.schemeYlOrBr=Yb,t.schemeYlOrRd=jb,t.select=Zn,t.selectAll=function(t){return"string"==typeof t?new Vn([document.querySelectorAll(t)],[document.documentElement]):new Vn([Ht(t)],Gn)},t.selection=Wn,t.selector=jt,t.selectorAll=Gt,t.shuffle=dt,t.shuffler=pt,t.some=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(n(r,++e,t))return!0;return!1},t.sort=U,t.stack=function(){var t=ym([]),n=dw,e=hw,r=pw;function i(i){var o,a,u=Array.from(t.apply(this,arguments),gw),c=u.length,f=-1;for(const t of i)for(o=0,++f;o0)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):(r[0]=0,r[1]=i)},t.stackOffsetExpand=function(t,n){if((r=t.length)>0){for(var e,r,i,o=0,a=t[0].length;o0){for(var e,r=0,i=t[n[0]],o=i.length;r0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;afunction(t){t=`${t}`;let n=t.length;zp(t,n-1)&&!zp(t,n-2)&&(t=t.slice(0,-1));return"/"===t[0]?t:`/${t}`}(t(n,e,r)))),e=n.map(Pp),i=new Set(n).add("");for(const t of e)i.has(t)||(i.add(t),n.push(t),e.push(Pp(t)),h.push(Np));d=(t,e)=>n[e],p=(t,n)=>e[n]}for(a=0,i=h.length;a=0&&(f=h[t]).data===Np;--t)f.data=null}if(u.parent=Sp,u.eachBefore((function(t){t.depth=t.parent.depth+1,--i})).eachBefore(Kd),u.parent=null,i>0)throw new Error("cycle");return u}return r.id=function(t){return arguments.length?(n=Jd(t),r):n},r.parentId=function(t){return arguments.length?(e=Jd(t),r):e},r.path=function(n){return arguments.length?(t=Jd(n),r):t},r},t.style=_n,t.subset=function(t,n){return _t(n,t)},t.sum=function(t,n){let e=0;if(void 0===n)for(let n of t)(n=+n)&&(e+=n);else{let r=-1;for(let i of t)(i=+n(i,++r,t))&&(e+=i)}return e},t.superset=_t,t.svg=Nc,t.symbol=function(t,n){let e=null,r=km(i);function i(){let i;if(e||(e=i=r()),t.apply(this,arguments).draw(e,+n.apply(this,arguments)),i)return e=null,i+""||null}return t="function"==typeof t?t:ym(t||fx),n="function"==typeof n?n:ym(void 0===n?64:+n),i.type=function(n){return arguments.length?(t="function"==typeof n?n:ym(n),i):t},i.size=function(t){return arguments.length?(n="function"==typeof t?t:ym(+t),i):n},i.context=function(t){return arguments.length?(e=null==t?null:t,i):e},i},t.symbolAsterisk=cx,t.symbolCircle=fx,t.symbolCross=sx,t.symbolDiamond=dx,t.symbolDiamond2=px,t.symbolPlus=gx,t.symbolSquare=yx,t.symbolSquare2=vx,t.symbolStar=xx,t.symbolTimes=Px,t.symbolTriangle=Mx,t.symbolTriangle2=Ax,t.symbolWye=Cx,t.symbolX=Px,t.symbols=zx,t.symbolsFill=zx,t.symbolsStroke=$x,t.text=mc,t.thresholdFreedmanDiaconis=function(t,n,e){const r=v(t),i=at(t,.75)-at(t,.25);return r&&i?Math.ceil((e-n)/(2*i*Math.pow(r,-1/3))):1},t.thresholdScott=function(t,n,e){const r=v(t),i=w(t);return r&&i?Math.ceil((e-n)*Math.cbrt(r)/(3.49*i)):1},t.thresholdSturges=K,t.tickFormat=Eg,t.tickIncrement=V,t.tickStep=W,t.ticks=G,t.timeDay=py,t.timeDays=gy,t.timeFormatDefaultLocale=P_,t.timeFormatLocale=hv,t.timeFriday=Sy,t.timeFridays=$y,t.timeHour=sy,t.timeHours=ly,t.timeInterval=Vg,t.timeMillisecond=Wg,t.timeMilliseconds=Zg,t.timeMinute=ay,t.timeMinutes=uy,t.timeMonday=wy,t.timeMondays=ky,t.timeMonth=Zy,t.timeMonths=Ky,t.timeSaturday=Ey,t.timeSaturdays=Dy,t.timeSecond=iy,t.timeSeconds=oy,t.timeSunday=xy,t.timeSundays=Ny,t.timeThursday=Ay,t.timeThursdays=zy,t.timeTickInterval=cv,t.timeTicks=uv,t.timeTuesday=My,t.timeTuesdays=Cy,t.timeWednesday=Ty,t.timeWednesdays=Py,t.timeWeek=xy,t.timeWeeks=Ny,t.timeYear=tv,t.timeYears=nv,t.timeout=$i,t.timer=Ni,t.timerFlush=ki,t.transition=go,t.transpose=gt,t.tree=function(){var t=$p,n=1,e=1,r=null;function i(i){var c=function(t){for(var n,e,r,i,o,a=new Up(t,0),u=[a];n=u.pop();)if(r=n._.children)for(n.children=new Array(o=r.length),i=o-1;i>=0;--i)u.push(e=n.children[i]=new Up(r[i],i)),e.parent=n;return(a.parent=new Up(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore((function(t){t.xs.x&&(s=t),t.depth>l.depth&&(l=t)}));var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),g=e/(l.depth||1);i.eachBefore((function(t){t.x=(t.x+d)*p,t.y=t.depth*g}))}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=Rp(u),o=Dp(o),u&&o;)c=Dp(c),(a=Rp(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(Fp(qp(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!Rp(a)&&(a.t=u,a.m+=l-s),o&&!Dp(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=Yp,n=!1,e=1,r=1,i=[0],o=np,a=np,u=np,c=np,f=np;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(Tp),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}var l=f[n],h=r/2+l,d=n+1,p=e-1;for(;d>>1;f[g]c-o){var _=r?(i*v+a*y)/r:a;t(n,d,y,i,o,_,c),t(d,e,v,_,o,a,c)}else{var b=r?(o*v+c*y)/r:c;t(n,d,y,i,o,a,b),t(d,e,v,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=Ap,t.treemapResquarify=Lp,t.treemapSlice=Ip,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?Ip:Ap)(t,n,e,r,i)},t.treemapSquarify=Yp,t.tsv=Mc,t.tsvFormat=lc,t.tsvFormatBody=hc,t.tsvFormatRow=pc,t.tsvFormatRows=dc,t.tsvFormatValue=gc,t.tsvParse=fc,t.tsvParseRows=sc,t.union=function(...t){const n=new InternSet;for(const e of t)for(const t of e)n.add(t);return n},t.unixDay=_y,t.unixDays=by,t.utcDay=yy,t.utcDays=vy,t.utcFriday=By,t.utcFridays=Vy,t.utcHour=hy,t.utcHours=dy,t.utcMillisecond=Wg,t.utcMilliseconds=Zg,t.utcMinute=cy,t.utcMinutes=fy,t.utcMonday=qy,t.utcMondays=jy,t.utcMonth=Qy,t.utcMonths=Jy,t.utcSaturday=Yy,t.utcSaturdays=Wy,t.utcSecond=iy,t.utcSeconds=oy,t.utcSunday=Fy,t.utcSundays=Ly,t.utcThursday=Oy,t.utcThursdays=Gy,t.utcTickInterval=av,t.utcTicks=ov,t.utcTuesday=Uy,t.utcTuesdays=Hy,t.utcWednesday=Iy,t.utcWednesdays=Xy,t.utcWeek=Fy,t.utcWeeks=Ly,t.utcYear=ev,t.utcYears=rv,t.variance=x,t.version="7.9.0",t.window=pn,t.xml=Sc,t.zip=function(){return gt(arguments)},t.zoom=function(){var t,n,e,r=Ew,i=Nw,o=zw,a=Cw,u=Pw,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=ri,h=$t("start","zoom","end"),d=500,p=150,g=0,y=10;function v(t){t.property("__zoom",kw).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",A).on("dblclick.zoom",S).filter(u).on("touchstart.zoom",E).on("touchmove.zoom",N).on("touchend.zoom touchcancel.zoom",k).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function _(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new ww(n,t.x,t.y)}function b(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new ww(t.k,r,i)}function m(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function x(t,n,e,r){t.on("start.zoom",(function(){w(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){w(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,o=arguments,a=w(t,o).event(r),u=i.apply(t,o),c=null==e?m(u):"function"==typeof e?e.apply(t,o):e,f=Math.max(u[1][0]-u[0][0],u[1][1]-u[0][1]),s=t.__zoom,h="function"==typeof n?n.apply(t,o):n,d=l(s.invert(c).concat(f/s.k),h.invert(c).concat(f/h.k));return function(t){if(1===t)t=h;else{var n=d(t),e=f/n[2];t=new ww(e,c[0]-n[0]*e,c[1]-n[1]*e)}a.zoom(null,t)}}))}function w(t,n,e){return!e&&t.__zooming||new M(t,n)}function M(t,n){this.that=t,this.args=n,this.active=0,this.sourceEvent=null,this.extent=i.apply(t,n),this.taps=0}function T(t,...n){if(r.apply(this,arguments)){var e=w(this,n).event(t),i=this.__zoom,u=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,a.apply(this,arguments)))),s=ne(t);if(e.wheel)e.mouse[0][0]===s[0]&&e.mouse[0][1]===s[1]||(e.mouse[1]=i.invert(e.mouse[0]=s)),clearTimeout(e.wheel);else{if(i.k===u)return;e.mouse=[s,i.invert(s)],Gi(this),e.start()}Sw(t),e.wheel=setTimeout((function(){e.wheel=null,e.end()}),p),e.zoom("mouse",o(b(_(i,u),e.mouse[0],e.mouse[1]),e.extent,f))}}function A(t,...n){if(!e&&r.apply(this,arguments)){var i=t.currentTarget,a=w(this,n,!0).event(t),u=Zn(t.view).on("mousemove.zoom",(function(t){if(Sw(t),!a.moved){var n=t.clientX-s,e=t.clientY-l;a.moved=n*n+e*e>g}a.event(t).zoom("mouse",o(b(a.that.__zoom,a.mouse[0]=ne(t,i),a.mouse[1]),a.extent,f))}),!0).on("mouseup.zoom",(function(t){u.on("mousemove.zoom mouseup.zoom",null),ue(t.view,a.moved),Sw(t),a.event(t).end()}),!0),c=ne(t,i),s=t.clientX,l=t.clientY;ae(t.view),Aw(t),a.mouse=[c,this.__zoom.invert(c)],Gi(this),a.start()}}function S(t,...n){if(r.apply(this,arguments)){var e=this.__zoom,a=ne(t.changedTouches?t.changedTouches[0]:t,this),u=e.invert(a),c=e.k*(t.shiftKey?.5:2),l=o(b(_(e,c),a,u),i.apply(this,n),f);Sw(t),s>0?Zn(this).transition().duration(s).call(x,l,a,t):Zn(this).call(v.transform,l,a,t)}}function E(e,...i){if(r.apply(this,arguments)){var o,a,u,c,f=e.touches,s=f.length,l=w(this,i,e.changedTouches.length===s).event(e);for(Aw(e),a=0;a{var _2=Object.create;var Mu=Object.defineProperty;var y2=Object.getOwnPropertyDescriptor;var x2=Object.getOwnPropertyNames;var b2=Object.getPrototypeOf,T2=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var er=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zi=(t,e)=>{for(var r in e)Mu(t,r,{get:e[r],enumerable:!0})},w2=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of x2(e))!T2.call(t,n)&&n!==r&&Mu(t,n,{get:()=>e[n],enumerable:!(i=y2(e,n))||i.enumerable});return t};var S2=(t,e,r)=>(r=t!=null?_2(b2(t)):{},w2(e||!t||!t.__esModule?Mu(r,"default",{value:t,enumerable:!0}):r,t));var Qa,P2,Ja,M2,e_,Iu=P(()=>{Qa=globalThis,P2=globalThis.document||{},Ja=globalThis.process||{},M2=globalThis.console,e_=globalThis.navigator||{}});function ec(t){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,r=t||e;return!!(r&&r.indexOf("Electron")>=0)}var Ou=P(()=>{});function De(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||ec()}var Nu=P(()=>{Ou()});function Du(t){return!t&&!De()?"Node":ec(t)?"Electron":(t||e_.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown"}var t_=P(()=>{Nu();Ou();Iu()});var Lu,Rr=P(()=>{Iu();Nu();t_();Lu="4.1.1"});function Qi(t,e){if(!t)throw new Error(e||"Assertion failed")}var Fu=P(()=>{});function Bu(t){if(!t)return 0;let e;switch(typeof t){case"number":e=t;break;case"object":e=t.logLevel||t.priority||0;break;default:return 0}return Qi(Number.isFinite(e)&&e>=0),e}function r_(t){let{logLevel:e,message:r}=t;t.logLevel=Bu(e);let i=t.args?Array.from(t.args):[];for(;i.length&&i.shift()!==r;);switch(typeof e){case"string":case"function":r!==void 0&&i.unshift(r),t.message=e;break;case"object":Object.assign(t,e);break;default:}typeof t.message=="function"&&(t.message=t.message());let n=typeof t.message;return Qi(n==="string"||n==="object"),Object.assign(t,{args:i},t.opts)}var i_=P(()=>{Fu()});var oi,tc,n_=P(()=>{i_();oi=()=>{},tc=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...r){return this._log("warn",0,e,r,{once:!0})}error(e,...r){return this._log("error",0,e,r)}log(e,r,...i){return this._log("log",e,r,i)}info(e,r,...i){return this._log("info",e,r,i)}once(e,r,...i){return this._log("once",e,r,i,{once:!0})}_log(e,r,i,n,o={}){let s=r_({logLevel:r,message:i,args:this._buildArgs(r,i,n),opts:o});return this._createLogFunction(e,s,o)}_buildArgs(e,r,i){return[e,r,...i]}_createLogFunction(e,r,i){if(!this._shouldLog(r.logLevel))return oi;let n=this._getOnceTag(i.tag??r.tag??r.message);if((i.once||r.once)&&n!==void 0){if(this._onceCache.has(n))return oi;this._onceCache.add(n)}return this._emit(e,r)}_shouldLog(e){return this.getLevel()>=Bu(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}}});function O2(t){try{let e=window[t],r="__storage_test__";return e.setItem(r,r),e.removeItem(r),e}catch{return null}}var rc,o_=P(()=>{rc=class{constructor(e,r,i="sessionStorage"){this.storage=O2(i),this.id=e,this.config=r,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let r=JSON.stringify(this.config);this.storage.setItem(this.id,r)}}_loadConfiguration(){let e={};if(this.storage){let r=this.storage.getItem(this.id);e=r?JSON.parse(r):{}}return Object.assign(this.config,e),this}}});function s_(t){let e;return t<10?e=`${t.toFixed(2)}ms`:t<100?e=`${t.toFixed(1)}ms`:t<1e3?e=`${t.toFixed(0)}ms`:e=`${(t/1e3).toFixed(2)}s`,e}function a_(t,e=8){let r=Math.max(e-t.length,0);return`${" ".repeat(r)}${t}`}var c_=P(()=>{});function l_(t){return typeof t!="string"?t:(t=t.toUpperCase(),ic[t]||ic.WHITE)}function f_(t,e,r){return!De&&typeof t=="string"&&(e&&(t=`\x1B[${l_(e)}m${t}\x1B[39m`),r&&(t=`\x1B[${l_(r)+N2}m${t}\x1B[49m`)),t}var ic,N2,u_=P(()=>{Rr();(function(t){t[t.BLACK=30]="BLACK",t[t.RED=31]="RED",t[t.GREEN=32]="GREEN",t[t.YELLOW=33]="YELLOW",t[t.BLUE=34]="BLUE",t[t.MAGENTA=35]="MAGENTA",t[t.CYAN=36]="CYAN",t[t.WHITE=37]="WHITE",t[t.BRIGHT_BLACK=90]="BRIGHT_BLACK",t[t.BRIGHT_RED=91]="BRIGHT_RED",t[t.BRIGHT_GREEN=92]="BRIGHT_GREEN",t[t.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",t[t.BRIGHT_BLUE=94]="BRIGHT_BLUE",t[t.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",t[t.BRIGHT_CYAN=96]="BRIGHT_CYAN",t[t.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(ic||(ic={}));N2=10});function d_(t,e=["constructor"]){let r=Object.getPrototypeOf(t),i=Object.getOwnPropertyNames(r),n=t;for(let o of i){let s=n[o];typeof s=="function"&&(e.find(a=>o===a)||(n[o]=s.bind(t)))}}var h_=P(()=>{});function Ji(){let t;if(De()&&Qa.performance)t=Qa?.performance?.now?.();else if("hrtime"in Ja){let e=Ja?.hrtime?.();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}var p_=P(()=>{Rr()});function D2(t,e,r){if(typeof e=="string"){let i=r.time?a_(s_(r.total)):"";e=r.time?`${t}: ${i} ${e}`:`${t}: ${e}`,e=f_(e,r.color,r.background)}return e}function L2(t){for(let e in t)for(let r in t[e])return r||"untitled";return"empty"}var en,ku,Le,Uu=P(()=>{Rr();n_();o_();c_();u_();h_();Fu();p_();en={debug:De()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},ku={enabled:!0,level:0},Le=class extends tc{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Lu,this._startTs=Ji(),this._deltaTs=Ji(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new rc(`__probe-${this.id}__`,{[this.id]:ku}),this.timeStamp(`${this.id} started`),d_(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((Ji()-this._startTs).toPrecision(10))}getDelta(){return Number((Ji()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,r){this._updateConfiguration({[e]:r})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,r){if(!e)throw new Error(r||"Assertion failed")}warn(e,...r){return this._log("warn",0,e,r,{method:en.warn,once:!0})}error(e,...r){return this._log("error",0,e,r,{method:en.error})}deprecated(e,r){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${r}\` instead`)}removed(e,r){return this.error(`\`${e}\` has been removed. Use \`${r}\` instead`)}probe(e,r,...i){return this._log("log",e,r,i,{method:en.log,time:!0,once:!0})}log(e,r,...i){return this._log("log",e,r,i,{method:en.debug})}info(e,r,...i){return this._log("info",e,r,i,{method:console.info})}once(e,r,...i){return this._log("once",e,r,i,{method:en.debug||en.info,once:!0})}table(e,r,i){return r?this._log("table",e,r,i&&[i]||[],{method:console.table||oi,tag:L2(r)}):oi}time(e,r){return this._log("time",e,r,[],{method:console.time?console.time:console.info})}timeEnd(e,r){return this._log("time",e,r,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,r){return this._log("time",e,r,[],{method:console.timeStamp||oi})}group(e,r,i={collapsed:!1}){let n=(i.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,r,[],{method:n})}groupCollapsed(e,r,i={}){return this.group(e,r,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||oi})}withGroup(e,r,i){this.group(e,r)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,r){let i=r.method;Qi(i),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Ji();let n=D2(this.id,r.message,r);return i.bind(console,n,...r.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(ku),this._storage.config[this.id]}_updateConfiguration(e){let r=this._storage.config[this.id]||{...ku};this._storage.setConfiguration({[this.id]:{...r,...e}})}};Le.VERSION=Lu});var g_=P(()=>{globalThis.probe={}});var Fk,lo=P(()=>{Uu();Uu();g_();Fk=new Le({id:"@probe.gl/log"})});function po(){let t;if(typeof window<"u"&&window.performance)t=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}var rd=P(()=>{});var ai,id=P(()=>{rd();ai=class{constructor(e,r){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=e,this.type=r,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=po(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(po()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}}});var it,C_=P(()=>{id();it=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,r="count"){return this._getOrCreate({name:e,type:r})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let r of Object.values(this.stats))e(r)}getTable(){let e={};return this.forEach(r=>{e[r.name]={time:r.time||0,count:r.count||0,average:r.getAverageTime()||0,hz:r.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(r=>this._getOrCreate(r))}_getOrCreate(e){let{name:r,type:i}=e,n=this.stats[r];return n||(e instanceof ai?n=e:n=new ai(r,i),this.stats[r]=n),n}}});var go=P(()=>{C_();id();rd()});function kP(t,e){let r=t.stats,i=!1;for(let c of e)r[c]||(t.get(c),i=!0);let n=Object.keys(r).length,o=Fy.get(t);if(!i&&o?.orderedStatNames===e&&o.statCount===n)return;let s={},a=By.get(e);a||(a=new Set(e),By.set(e,a));for(let c of e)r[c]&&(s[c]=r[c]);for(let[c,l]of Object.entries(r))a.has(c)||(s[c]=l);for(let c of Object.keys(r))delete r[c];Object.assign(r,s),Fy.set(t,{orderedStatNames:e,statCount:n})}var FP,BP,Fy,By,mh,Pc,_h=P(()=>{go();FP="GPU Time and Memory",BP=["Adapter","GPU","GPU Type","GPU Backend","Frame Rate","CPU Time","GPU Time","GPU Memory","Buffer Memory","Texture Memory","Referenced Buffer Memory","Referenced Texture Memory","Swap Chain Texture"],Fy=new WeakMap,By=new WeakMap,mh=class{stats=new Map;getStats(e){return this.get(e)}get(e){this.stats.has(e)||this.stats.set(e,new it({id:e}));let r=this.stats.get(e);return e===FP&&kP(r,BP),r}},Pc=new mh});var v,ot=P(()=>{lo();v=new Le({id:"luma.gl"})});function Dt(t="id"){yh[t]=yh[t]||1;let e=yh[t]++;return`${t}-${e}`}var yh,un=P(()=>{yh={}});function $P(t,e){let r={...e};for(let i in t)t[i]!==void 0&&(r[i]=t[i]);return r}function jy(t,e){let r=t.stats,i=!1;for(let c of e)r[c]||(t.get(c),i=!0);let n=Object.keys(r).length,o=Wy.get(t);if(!i&&o?.orderedStatNames===e&&o.statCount===n)return;let s={},a=Vy.get(e);a||(a=new Set(e),Vy.set(e,a));for(let c of e)r[c]&&(s[c]=r[c]);for(let[c,l]of Object.entries(r))a.has(c)||(s[c]=l);for(let c of Object.keys(r))delete r[c];Object.assign(r,s),Wy.set(t,{orderedStatNames:e,statCount:n})}function $y(t){return t.type==="webgl"?jP:VP}function Po(t){let e=t.userData[UP];return e?.enabled?e:null}function Ir(){return globalThis.performance?.now?.()??Date.now()}function HP(t,e){let r=Po(t);if(!(!r||!r.activeDefaultFramebufferAcquireDepth))switch(r.transientCanvasResourceCreates=(r.transientCanvasResourceCreates||0)+1,e){case"Texture":r.transientCanvasTextureCreates=(r.transientCanvasTextureCreates||0)+1;break;case"TextureView":r.transientCanvasTextureViewCreates=(r.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":r.transientCanvasSamplerCreates=(r.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":r.transientCanvasFramebufferCreates=(r.transientCanvasFramebufferCreates||0)+1;break;default:break}}function YP(t){let e=Object.getPrototypeOf(t);for(;e;){let r=Object.getPrototypeOf(e);if(!r||r===k.prototype)return XP(e)||t[Symbol.toStringTag]||t.constructor.name;e=r}return t[Symbol.toStringTag]||t.constructor.name}function XP(t){let e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(t):typeof e?.value=="string"?e.value:null}var UP,ky,Uy,zy,zP,WP,VP,jP,Wy,Vy,k,we=P(()=>{un();UP="cpu-hotspot-profiler",ky="GPU Resource Counts",Uy="Resource Counts",zy="GPU Time and Memory",zP=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","ComputePasss","CommandEncoders","CommandBuffers"],WP=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","ComputePasss","CommandEncoders","CommandBuffers"],VP=zP.flatMap(t=>[`${t} Created`,`${t} Active`]),jP=WP.flatMap(t=>[`${t} Created`,`${t} Active`]),Wy=new WeakMap,Vy=new WeakMap,k=class{static defaultProps={id:"undefined",handle:void 0,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;constructor(e,r,i){if(!e)throw new Error("no device");this._device=e,this.props=$P(r,i);let n=this.props.id!=="undefined"?this.props.id:Dt(this[Symbol.toStringTag]);this.props.id=n,this.id=n,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=Po(this._device),r=e?Ir():0,i=[this._device.statsManager.getStats(ky),this._device.statsManager.getStats(Uy)],n=$y(this._device);for(let s of i)jy(s,n);let o=this.getStatsName();for(let s of i)s.get("Resources Active").decrementCount(),s.get(`${o}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(Ir()-r))}trackAllocatedMemory(e,r=this.getStatsName()){let i=Po(this._device),n=i?Ir():0,o=this._device.statsManager.getStats(zy);this.allocatedBytes>0&&this.allocatedBytesName&&(o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),o.get("GPU Memory").addCount(e),o.get(`${r} Memory`).addCount(e),i&&(i.statsBookkeepingCalls=(i.statsBookkeepingCalls||0)+1,i.statsBookkeepingTimeMs=(i.statsBookkeepingTimeMs||0)+(Ir()-n)),this.allocatedBytes=e,this.allocatedBytesName=r}trackReferencedMemory(e,r=this.getStatsName()){this.trackAllocatedMemory(e,`Referenced ${r}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let r=Po(this._device),i=r?Ir():0,n=this._device.statsManager.getStats(zy);n.get("GPU Memory").subtractCount(this.allocatedBytes),n.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),r&&(r.statsBookkeepingCalls=(r.statsBookkeepingCalls||0)+1,r.statsBookkeepingTimeMs=(r.statsBookkeepingTimeMs||0)+(Ir()-i)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),r=Po(this._device),i=r?Ir():0,n=[this._device.statsManager.getStats(ky),this._device.statsManager.getStats(Uy)],o=$y(this._device);for(let s of n)jy(s,o);for(let s of n)s.get("Resources Created").incrementCount(),s.get("Resources Active").incrementCount(),s.get(`${e}s Created`).incrementCount(),s.get(`${e}s Active`).incrementCount();r&&(r.statsBookkeepingCalls=(r.statsBookkeepingCalls||0)+1,r.statsBookkeepingTimeMs=(r.statsBookkeepingTimeMs||0)+(Ir()-i)),HP(this._device,e)}getStatsName(){return YP(this)}}});var j,Mc=P(()=>{we();j=class t extends k{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,r){let i={...r};(r.usage||0)&t.INDEX&&!r.indexType&&(r.data instanceof Uint32Array?i.indexType="uint32":r.data instanceof Uint16Array?i.indexType="uint16":r.data instanceof Uint8Array&&(i.indexType="uint8")),delete i.data,super(e,i,t.defaultProps),this.usage=i.usage||0,this.indexType=i.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,r,i){let n=null,o;ArrayBuffer.isView(e)?(n=e,o=e.buffer):o=e;let s=Math.min(e?e.byteLength:i,t.DEBUG_DATA_MAX_LENGTH);if(o===null)this.debugData=new ArrayBuffer(s);else{let a=Math.min(n?.byteOffset||0,o.byteLength),c=Math.max(0,o.byteLength-a),l=Math.min(s,c);this.debugData=new Uint8Array(o,a,l).slice().buffer}}static defaultProps={...k.defaultProps,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}});var bh,ke,xh,Ic=P(()=>{bh=class{getDataTypeInfo(e){let[r,i,n]=xh[e],o=e.includes("norm"),s=!o&&!e.startsWith("float"),a=e.startsWith("s");return{signedType:r,primitiveType:i,byteLength:n,normalized:o,integer:s,signed:a}}getNormalizedDataType(e){let r=e;switch(r){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return r}}alignTo(e,r){switch(r){case 1:return e;case 2:return e+e%2;default:return e+(4-e%4)%4}}getDataType(e){let r=ArrayBuffer.isView(e)?e.constructor:e;if(r===Uint8ClampedArray)return"uint8";let i=Object.values(xh).find(n=>r===n[4]);if(!i)throw new Error(r.name);return i[0]}getTypedArrayConstructor(e){let[,,,,r]=xh[e];return r}},ke=new bh,xh={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});var Th,or,Oc=P(()=>{Ic();Th=class{getVertexFormatInfo(e){let r;e.endsWith("-webgl")&&(e.replace("-webgl",""),r=!0);let[i,n]=e.split("x"),o=i,s=n?parseInt(n):1,a=ke.getDataTypeInfo(o),c={type:o,components:s,byteLength:a.byteLength*s,integer:a.integer,signed:a.signed,normalized:a.normalized};return r&&(c.webglOnly=!0),c}makeVertexFormat(e,r,i){let n=i?ke.getNormalizedDataType(e):e;switch(n){case"unorm8":return r===1?"unorm8":r===3?"unorm8x3-webgl":`${n}x${r}`;case"snorm8":return r===1?"snorm8":r===3?"snorm8x3-webgl":`${n}x${r}`;case"uint8":case"sint8":if(r===1||r===3)throw new Error(`size: ${r}`);return`${n}x${r}`;case"uint16":return r===1?"uint16":r===3?"uint16x3-webgl":`${n}x${r}`;case"sint16":return r===1?"sint16":r===3?"sint16x3-webgl":`${n}x${r}`;case"unorm16":return r===1?"unorm16":r===3?"unorm16x3-webgl":`${n}x${r}`;case"snorm16":return r===1?"snorm16":r===3?"snorm16x3-webgl":`${n}x${r}`;case"float16":if(r===1||r===3)throw new Error(`size: ${r}`);return`${n}x${r}`;default:return r===1?n:`${n}x${r}`}}getVertexFormatFromAttribute(e,r,i){if(!r||r>4)throw new Error(`size ${r}`);let n=r,o=ke.getDataType(e);return this.makeVertexFormat(o,n,i)}getCompatibleVertexFormat(e){let r;switch(e.primitiveType){case"f32":r="float32";break;case"i32":r="sint32";break;case"u32":r="uint32";break;case"f16":return e.components<=2?"float16x2":"float16x4"}return e.components===1?r:`${r}x${e.components}`}},or=new Th});function Rh(t){let e=Xy[t];if(!e)throw new Error(`Unsupported texture format ${t}`);return e}function Yy(){return Xy}var Ie,te,Lt,GP,Nc,wh,Dc,Sh,qP,Ah,Or,vh,Eh,Lc,Hy,KP,ZP,Xy,Ch=P(()=>{Ie="texture-compression-bc",te="texture-compression-astc",Lt="texture-compression-etc2",GP="texture-compression-etc1-webgl",Nc="texture-compression-pvrtc-webgl",wh="texture-compression-atc-webgl",Dc="float32-renderable-webgl",Sh="float16-renderable-webgl",qP="rgb9e5ufloat-renderable-webgl",Ah="snorm8-renderable-webgl",Or="norm16-webgl",vh="norm16-renderable-webgl",Eh="snorm16-renderable-webgl",Lc="float32-filterable",Hy="float16-filterable-webgl";KP={r8unorm:{},rg8unorm:{},"rgb8unorm-webgl":{},rgba8unorm:{},"rgba8unorm-srgb":{},r8snorm:{render:Ah},rg8snorm:{render:Ah},"rgb8snorm-webgl":{},rgba8snorm:{render:Ah},r8uint:{},rg8uint:{},rgba8uint:{},r8sint:{},rg8sint:{},rgba8sint:{},bgra8unorm:{},"bgra8unorm-srgb":{},r16unorm:{f:Or,render:vh},rg16unorm:{f:Or,render:vh},"rgb16unorm-webgl":{f:Or,render:!1},rgba16unorm:{f:Or,render:vh},r16snorm:{f:Or,render:Eh},rg16snorm:{f:Or,render:Eh},"rgb16snorm-webgl":{f:Or,render:!1},rgba16snorm:{f:Or,render:Eh},r16uint:{},rg16uint:{},rgba16uint:{},r16sint:{},rg16sint:{},rgba16sint:{},r16float:{render:Sh,filter:"float16-filterable-webgl"},rg16float:{render:Sh,filter:Hy},rgba16float:{render:Sh,filter:Hy},r32uint:{},rg32uint:{},rgba32uint:{},r32sint:{},rg32sint:{},rgba32sint:{},r32float:{render:Dc,filter:Lc},rg32float:{render:!1,filter:Lc},"rgb32float-webgl":{render:Dc,filter:Lc},rgba32float:{render:Dc,filter:Lc},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:qP},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Dc},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8"},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16"},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32"},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32"},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0}},ZP={"bc1-rgb-unorm-webgl":{f:Ie},"bc1-rgb-unorm-srgb-webgl":{f:Ie},"bc1-rgba-unorm":{f:Ie},"bc1-rgba-unorm-srgb":{f:Ie},"bc2-rgba-unorm":{f:Ie},"bc2-rgba-unorm-srgb":{f:Ie},"bc3-rgba-unorm":{f:Ie},"bc3-rgba-unorm-srgb":{f:Ie},"bc4-r-unorm":{f:Ie},"bc4-r-snorm":{f:Ie},"bc5-rg-unorm":{f:Ie},"bc5-rg-snorm":{f:Ie},"bc6h-rgb-ufloat":{f:Ie},"bc6h-rgb-float":{f:Ie},"bc7-rgba-unorm":{f:Ie},"bc7-rgba-unorm-srgb":{f:Ie},"etc2-rgb8unorm":{f:Lt},"etc2-rgb8unorm-srgb":{f:Lt},"etc2-rgb8a1unorm":{f:Lt},"etc2-rgb8a1unorm-srgb":{f:Lt},"etc2-rgba8unorm":{f:Lt},"etc2-rgba8unorm-srgb":{f:Lt},"eac-r11unorm":{f:Lt},"eac-r11snorm":{f:Lt},"eac-rg11unorm":{f:Lt},"eac-rg11snorm":{f:Lt},"astc-4x4-unorm":{f:te},"astc-4x4-unorm-srgb":{f:te},"astc-5x4-unorm":{f:te},"astc-5x4-unorm-srgb":{f:te},"astc-5x5-unorm":{f:te},"astc-5x5-unorm-srgb":{f:te},"astc-6x5-unorm":{f:te},"astc-6x5-unorm-srgb":{f:te},"astc-6x6-unorm":{f:te},"astc-6x6-unorm-srgb":{f:te},"astc-8x5-unorm":{f:te},"astc-8x5-unorm-srgb":{f:te},"astc-8x6-unorm":{f:te},"astc-8x6-unorm-srgb":{f:te},"astc-8x8-unorm":{f:te},"astc-8x8-unorm-srgb":{f:te},"astc-10x5-unorm":{f:te},"astc-10x5-unorm-srgb":{f:te},"astc-10x6-unorm":{f:te},"astc-10x6-unorm-srgb":{f:te},"astc-10x8-unorm":{f:te},"astc-10x8-unorm-srgb":{f:te},"astc-10x10-unorm":{f:te},"astc-10x10-unorm-srgb":{f:te},"astc-12x10-unorm":{f:te},"astc-12x10-unorm-srgb":{f:te},"astc-12x12-unorm":{f:te},"astc-12x12-unorm-srgb":{f:te},"pvrtc-rgb4unorm-webgl":{f:Nc},"pvrtc-rgba4unorm-webgl":{f:Nc},"pvrtc-rgb2unorm-webgl":{f:Nc},"pvrtc-rgba2unorm-webgl":{f:Nc},"etc1-rbg-unorm-webgl":{f:GP},"atc-rgb-unorm-webgl":{f:wh},"atc-rgba-unorm-webgl":{f:wh},"atc-rgbai-unorm-webgl":{f:wh}},Xy={...KP,...ZP}});function rM({format:t,width:e,height:r,depth:i,byteAlignment:n}){let o=Ue.getInfo(t),{bytesPerPixel:s,bytesPerBlock:a=s,blockWidth:c=1,blockHeight:l=1,compressed:f=!1}=o,u=f?Math.ceil(e/c):e,d=f?Math.ceil(r/l):r,h=u*a,p=Math.ceil(h/n)*n,g=d,m=p*g*i;return{bytesPerPixel:s,bytesPerRow:p,rowsPerImage:g,depthOrArrayLayers:i,bytesPerImage:p*g,byteLength:m}}function iM(t){let e=Rh(t),r={format:t,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},i=Gy(t),n=t.startsWith("depth")||t.startsWith("stencil"),o=i?.signed,s=i?.integer,a=i?.webgl,c=!!i?.compressed;return r.render&&=!n&&!c,r.filter&&=!n&&!o&&!s&&!a,r}function Gy(t){let e=nM(t);if(Ue.isCompressed(t)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=sM(t);let i=oM(t);i&&(e.blockWidth=i.blockWidth,e.blockHeight=i.blockHeight)}let r=e.packed?null:QP.exec(t);if(r){let[,i,n,o,s,a]=r,c=`${o}${n}`,l=ke.getDataTypeInfo(c),f=l.byteLength*8,u=i?.length??1,d=[f,u>=2?f:0,u>=3?f:0,u>=4?f:0];e={format:t,attachment:e.attachment,dataType:l.signedType,components:u,channels:i,integer:l.integer,signed:l.signed,normalized:l.normalized,bitsPerChannel:d,bytesPerPixel:l.byteLength*u,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),s==="-srgb"&&(e.srgb=!0)}return t.endsWith("-webgl")&&(e.webgl=!0),t.endsWith("-srgb")&&(e.srgb=!0),e}function nM(t){let e=Rh(t),r=e.bytesPerPixel||1,i=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,{...e,format:t,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:r,bitsPerChannel:i,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function oM(t){let r=/.*-(\d+)x(\d+)-.*/.exec(t);if(r){let[,i,n]=r;return{blockWidth:Number(i),blockHeight:Number(n)}}return t.startsWith("bc")||t.startsWith("etc1")||t.startsWith("etc2")||t.startsWith("eac")||t.startsWith("atc")?{blockWidth:4,blockHeight:4}:t.startsWith("pvrtc-rgb4")||t.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:t.startsWith("pvrtc-rgb2")||t.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function sM(t){return t.startsWith("bc1")||t.startsWith("bc4")||t.startsWith("etc1")||t.startsWith("etc2-rgb8")||t.startsWith("etc2-rgb8a1")||t.startsWith("eac-r11")||t==="atc-rgb-unorm-webgl"?8:t.startsWith("bc2")||t.startsWith("bc3")||t.startsWith("bc5")||t.startsWith("bc6h")||t.startsWith("bc7")||t.startsWith("etc2-rgba8")||t.startsWith("eac-rg11")||t.startsWith("astc")||t==="atc-rgba-unorm-webgl"||t==="atc-rgbai-unorm-webgl"?16:t.startsWith("pvrtc")?8:16}var QP,JP,eM,tM,Ph,Ue,Fc=P(()=>{Ic();Ch();QP=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,JP=["rgb","rgba","bgra"],eM=["depth","stencil"],tM=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Ph=class{isColor(e){return JP.some(r=>e.startsWith(r))}isDepthStencil(e){return eM.some(r=>e.startsWith(r))}isCompressed(e){return tM.some(r=>e.startsWith(r))}getInfo(e){return Gy(e)}getCapabilities(e){return iM(e)}computeMemoryLayout(e){return rM(e)}},Ue=new Ph});function dn(t){return typeof ImageData<"u"&&t instanceof ImageData||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof VideoFrame<"u"&&t instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas}function Mo(t){if(typeof ImageData<"u"&&t instanceof ImageData||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return{width:t.width,height:t.height};if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return{width:t.naturalWidth,height:t.naturalHeight};if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)return{width:t.videoWidth,height:t.videoHeight};if(typeof VideoFrame<"u"&&t instanceof VideoFrame)return{width:t.displayWidth,height:t.displayHeight};throw new Error("Unknown image type")}var Mh=P(()=>{});function aM(t,e){let r=Ih(t),i=e.map(Ih).filter(n=>n!==void 0);return[r,...i].filter(n=>n!==void 0)}function Ih(t){if(t!==void 0){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Error)return t.message;if(Array.isArray(t))return t.map(Ih);if(typeof t=="object"){if(cM(t)){let e=String(t);if(e!=="[object Object]")return e}return lM(t)?fM(t):t.constructor?.name||"Object"}return String(t)}}function cM(t){return"toString"in t&&typeof t.toString=="function"&&t.toString!==Object.prototype.toString}function lM(t){return"message"in t&&"type"in t}function fM(t){let e=typeof t.type=="string"?t.type:"message",r=typeof t.message=="string"?t.message:"",i=typeof t.lineNum=="number"?t.lineNum:null,n=typeof t.linePos=="number"?t.linePos:null,o=i!==null&&n!==null?` @ ${i}:${n}`:i!==null?` @ ${i}`:"";return`${e}${o}: ${r}`.trim()}function uM(t,e){return t!=null?!!t:e!==void 0?e!=="production":!1}function dM(){return uM(v.get("debug"),hM())}function hM(){let t=globalThis.process;if(t?.env)return t.env.NODE_ENV}var Io,Oo,ht,Oh=P(()=>{_h();ot();un();Mc();Oc();Fc();Mh();Ch();Io=class{};Oo=class{features;disabledFeatures;constructor(e=[],r){this.features=new Set(e),this.disabledFeatures=r||{}}*[Symbol.iterator](){yield*this.features}has(e){return!this.disabledFeatures?.[e]&&this.features.has(e)}},ht=class t{static defaultProps={id:null,powerPreference:"high-performance",failIfMajorPerformanceCaveat:!1,createCanvasContext:void 0,webgl:{},onError:(e,r)=>{},onResize:(e,r)=>{let[i,n]=e.getDevicePixelSize();v.log(1,`${e} resized => ${i}x${n}px`)()},onPositionChange:(e,r)=>{let[i,n]=e.getPosition();v.log(1,`${e} repositioned => ${i},${n}`)()},onVisibilityChange:e=>v.log(1,`${e} Visibility changed ${e.isVisible}`)(),onDevicePixelRatioChange:(e,r)=>v.log(1,`${e} DPR changed ${r.oldRatio} => ${e.devicePixelRatio}`)(),debug:dM(),debugGPUTime:!1,debugShaders:v.get("debug-shaders")||void 0,debugFramebuffers:!!v.get("debug-framebuffers"),debugFactories:!!v.get("debug-factories"),debugWebGL:!!v.get("debug-webgl"),debugSpectorJS:void 0,debugSpectorJSUrl:void 0,_reuseDevices:!1,_requestMaxLimits:!0,_cacheShaders:!0,_destroyShaders:!1,_cachePipelines:!0,_sharePipelines:!0,_destroyPipelines:!1,_initializeFeatures:!0,_disabledFeatures:{"compilation-status-async-webgl":!0},_handle:void 0};get[Symbol.toStringTag](){return"Device"}toString(){return`Device(${this.id})`}id;props;userData={};statsManager=Pc;_factories={};timestamp=0;_reused=!1;_moduleData={};_textureCaps={};_debugGPUTimeQuery=null;constructor(e){this.props={...t.defaultProps,...e},this.id=this.props.id||Dt(this[Symbol.toStringTag].toLowerCase())}getVertexFormatInfo(e){return or.getVertexFormatInfo(e)}isVertexFormatSupported(e){return!0}getTextureFormatInfo(e){return Ue.getInfo(e)}getTextureFormatCapabilities(e){let r=this._textureCaps[e];if(!r){let i=this._getDeviceTextureFormatCapabilities(e);r=this._getDeviceSpecificTextureFormatCapabilities(i),this._textureCaps[e]=r}return r}getMipLevelCount(e,r,i=1){let n=Math.max(e,r,i);return 1+Math.floor(Math.log2(n))}isExternalImage(e){return dn(e)}getExternalImageSize(e){return Mo(e)}isTextureFormatSupported(e){return this.getTextureFormatCapabilities(e).create}isTextureFormatFilterable(e){return this.getTextureFormatCapabilities(e).filter}isTextureFormatRenderable(e){return this.getTextureFormatCapabilities(e).render}isTextureFormatCompressed(e){return Ue.isCompressed(e)}getSupportedCompressedTextureFormats(){let e=[];for(let r of Object.keys(Yy()))this.isTextureFormatCompressed(r)&&this.isTextureFormatSupported(r)&&e.push(r);return e}pushDebugGroup(e){this.commandEncoder.pushDebugGroup(e)}popDebugGroup(){this.commandEncoder?.popDebugGroup()}insertDebugMarker(e){this.commandEncoder?.insertDebugMarker(e)}loseDevice(){return!1}incrementTimestamp(){return this.timestamp++}reportError(e,r,...i){if(!this.props.onError(e,r)){let o=aM(r,i);return v.error(this.type==="webgl"?"%cWebGL":"%cWebGPU","color: white; background: red; padding: 2px 6px; border-radius: 3px;",e.message,...o)}return()=>{}}debug(){if(this.props.debug)debugger;else v.once(0,`'Type luma.log.set({debug: true}) in console to enable debug breakpoints', +or create a device with the 'debug: true' prop.`)()}getDefaultCanvasContext(){if(!this.canvasContext)throw new Error("Device has no default CanvasContext. See props.createCanvasContext");return this.canvasContext}createFence(){throw new Error("createFence() not implemented")}beginRenderPass(e){return this.commandEncoder.beginRenderPass(e)}beginComputePass(e){return this.commandEncoder.beginComputePass(e)}generateMipmapsWebGPU(e){throw new Error("not implemented")}_createSharedRenderPipelineWebGL(e){throw new Error("_createSharedRenderPipelineWebGL() not implemented")}_createBindGroupLayoutWebGPU(e,r){throw new Error("_createBindGroupLayoutWebGPU() not implemented")}_createBindGroupWebGPU(e,r,i,n,o){throw new Error("_createBindGroupWebGPU() not implemented")}_supportsDebugGPUTime(){return this.features.has("timestamp-query")&&!!(this.props.debug||this.props.debugGPUTime)}_enableDebugGPUTime(e=256){if(!this._supportsDebugGPUTime())return null;if(this._debugGPUTimeQuery)return this._debugGPUTimeQuery;try{this._debugGPUTimeQuery=this.createQuerySet({type:"timestamp",count:e}),this.commandEncoder=this.createCommandEncoder({id:this.commandEncoder.props.id,timeProfilingQuerySet:this._debugGPUTimeQuery})}catch{this._debugGPUTimeQuery=null}return this._debugGPUTimeQuery}_disableDebugGPUTime(){this._debugGPUTimeQuery&&(this.commandEncoder.getTimeProfilingQuerySet()===this._debugGPUTimeQuery&&(this.commandEncoder=this.createCommandEncoder({id:this.commandEncoder.props.id})),this._debugGPUTimeQuery.destroy(),this._debugGPUTimeQuery=null)}_isDebugGPUTimeEnabled(){return this._debugGPUTimeQuery!==null}getCanvasContext(){return this.getDefaultCanvasContext()}readPixelsToArrayWebGL(e,r){throw new Error("not implemented")}readPixelsToBufferWebGL(e,r){throw new Error("not implemented")}setParametersWebGL(e){throw new Error("not implemented")}getParametersWebGL(e){throw new Error("not implemented")}withParametersWebGL(e,r){throw new Error("not implemented")}clearWebGL(e){throw new Error("not implemented")}resetWebGL(){throw new Error("not implemented")}getModuleData(e){return this._moduleData[e]||={},this._moduleData[e]}static _getCanvasContextProps(e){return e.createCanvasContext===!0?{}:e.createCanvasContext}_getDeviceTextureFormatCapabilities(e){let r=Ue.getCapabilities(e),i=o=>(typeof o=="string"?this.features.has(o):o)??!0,n=i(r.create);return{format:e,create:n,render:n&&i(r.render),filter:n&&i(r.filter),blend:n&&i(r.blend),store:n&&i(r.store)}}_normalizeBufferProps(e){(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});let r={...e};if((e.usage||0)&j.INDEX&&(e.indexType||(e.data instanceof Uint32Array?r.indexType="uint32":e.data instanceof Uint16Array?r.indexType="uint16":e.data instanceof Uint8Array&&(r.data=new Uint16Array(e.data),r.indexType="uint16")),!r.indexType))throw new Error("indices buffer content must be of type uint16 or uint32");return r}}});var pM,qy,Nh,hn,Ky=P(()=>{Oh();_h();ot();pM="set luma.log.level=1 (or higher) to trace rendering",qy="No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.",Nh=class t{static defaultProps={...ht.defaultProps,type:"best-available",adapters:void 0,waitForPageLoad:!0};stats=Pc;log=v;VERSION="9.3.3";spector;preregisteredAdapters=new Map;constructor(){if(globalThis.luma){if(globalThis.luma.VERSION!==this.VERSION)throw v.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)(),v.error("'yarn why @luma.gl/core' can help identify the source of the conflict")(),new Error("luma.gl - multiple versions detected: see console log");v.error("This version of luma.gl has already been initialized")()}v.log(1,`${this.VERSION} - ${pM}`)(),globalThis.luma=this}async createDevice(e={}){let r={...t.defaultProps,...e},i=this.selectAdapter(r.type,r.adapters);if(!i)throw new Error(qy);return r.waitForPageLoad&&await i.pageLoaded,await i.create(r)}async attachDevice(e,r){let i=this._getTypeFromHandle(e,r.adapters),n=i&&this.selectAdapter(i,r.adapters);if(!n)throw new Error(qy);return await n?.attach?.(e,r)}registerAdapters(e){for(let r of e)this.preregisteredAdapters.set(r.type,r)}getSupportedAdapters(e=[]){let r=this._getAdapterMap(e);return Array.from(r).map(([,i])=>i).filter(i=>i.isSupported?.()).map(i=>i.type)}getBestAvailableAdapterType(e=[]){let r=["webgpu","webgl","null"],i=this._getAdapterMap(e);for(let n of r)if(i.get(n)?.isSupported?.())return n;return null}selectAdapter(e,r=[]){let i=e;e==="best-available"&&(i=this.getBestAvailableAdapterType(r));let n=this._getAdapterMap(r);return i&&n.get(i)||null}enforceWebGL2(e=!0,r=[]){let n=this._getAdapterMap(r).get("webgl");n||v.warn("enforceWebGL2: webgl adapter not found")(),n?.enforceWebGL2?.(e)}setDefaultDeviceProps(e){Object.assign(t.defaultProps,e)}_getAdapterMap(e=[]){let r=new Map(this.preregisteredAdapters);for(let i of e)r.set(i.type,i);return r}_getTypeFromHandle(e,r=[]){return e instanceof WebGL2RenderingContext?"webgl":typeof GPUDevice<"u"&&e instanceof GPUDevice||e?.queue?"webgpu":e===null?"null":(e instanceof WebGLRenderingContext?v.warn("WebGL1 is not supported",e)():v.warn("Unknown handle type",e)(),null)}},hn=new Nh});function _M(){return Bc||(mM()||typeof window>"u"?Bc=Promise.resolve():Bc=new Promise(t=>window.addEventListener("load",()=>t()))),Bc}var No,gM,mM,Bc,Zy=P(()=>{Rr();No=class{get pageLoaded(){return _M()}},gM=De()&&typeof document<"u",mM=()=>gM&&document.readyState==="complete",Bc=null});var kc,Qy=P(()=>{kc=class{props;_resizeObserver;_intersectionObserver;_observeDevicePixelRatioTimeout=null;_observeDevicePixelRatioMediaQuery=null;_handleDevicePixelRatioChange=()=>this._refreshDevicePixelRatio();_trackPositionInterval=null;_started=!1;get started(){return this._started}constructor(e){this.props=e}start(){if(!(this._started||!this.props.canvas)){this._started=!0,this._intersectionObserver||=new IntersectionObserver(e=>this.props.onIntersection(e)),this._resizeObserver||=new ResizeObserver(e=>this.props.onResize(e)),this._intersectionObserver.observe(this.props.canvas);try{this._resizeObserver.observe(this.props.canvas,{box:"device-pixel-content-box"})}catch{this._resizeObserver.observe(this.props.canvas,{box:"content-box"})}this._observeDevicePixelRatioTimeout=setTimeout(()=>this._refreshDevicePixelRatio(),0),this.props.trackPosition&&this._trackPosition()}}stop(){this._started&&(this._started=!1,this._observeDevicePixelRatioTimeout&&(clearTimeout(this._observeDevicePixelRatioTimeout),this._observeDevicePixelRatioTimeout=null),this._observeDevicePixelRatioMediaQuery&&(this._observeDevicePixelRatioMediaQuery.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=null),this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null),this._resizeObserver?.disconnect(),this._intersectionObserver?.disconnect())}_refreshDevicePixelRatio(){this._started&&(this.props.onDevicePixelRatioChange(),this._observeDevicePixelRatioMediaQuery?.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._observeDevicePixelRatioMediaQuery.addEventListener("change",this._handleDevicePixelRatioChange,{once:!0}))}_trackPosition(e=100){this._trackPositionInterval||(this._trackPositionInterval=setInterval(()=>{this._started?this.props.onPositionChange():this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null)},e))}}});function Jy(){let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}}var ex=P(()=>{});function Dh(t,e){if(!t){let r=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(r,Dh),r}}function hi(t,e){return Dh(t,e),t}var Lh=P(()=>{});function yM(t){if(typeof t=="string"){let e=document.getElementById(t);if(!e)throw new Error(`${t} is not an HTML element`);return e}return t||document.body}function xM(t){let e=document.getElementById(t);if(!Nr.isHTMLCanvas(e))throw new Error("Object is not a canvas element");return e}function bM(t){let{width:e,height:r}=t,i=document.createElement("canvas");i.id=Dt("lumagl-auto-created-canvas"),i.width=e||1,i.height=r||1,i.style.width=Number.isFinite(e)?`${e}px`:"100%",i.style.height=Number.isFinite(r)?`${r}px`:"100%",t?.visible||(i.style.visibility="hidden");let n=yM(t?.container||null);return n.insertBefore(i,n.firstChild),i}function TM(t,e,r,i,n){let o=t,s=tx(o[0],e,r),a=rx(o[1],e,i,n),c=tx(o[0]+1,e,r),l=c===r-1?c:c-1;c=rx(o[1]+1,e,i,n);let f;return n?(c=c===0?c:c+1,f=a,a=c):f=c===i-1?c:c-1,{x:s,y:a,width:Math.max(l-s+1,1),height:Math.max(f-a+1,1)}}function tx(t,e,r){return Math.min(Math.round(t*e),r-1)}function rx(t,e,r,i){return i?Math.max(0,r-1-Math.round(t*e)):Math.min(Math.round(t*e),r-1)}var Nr,Fh=P(()=>{Rr();Qy();un();ex();Lh();Nr=class t{static isHTMLCanvas(e){return typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement}static isOffscreenCanvas(e){return typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas}static defaultProps={id:void 0,canvas:null,width:800,height:600,useDevicePixels:!0,autoResize:!0,container:null,visible:!0,alphaMode:"opaque",colorSpace:"srgb",trackPosition:!1};id;props;canvas;htmlCanvas;offscreenCanvas;type;initialized;isInitialized=!1;isVisible=!0;cssWidth;cssHeight;devicePixelRatio;devicePixelWidth;devicePixelHeight;drawingBufferWidth;drawingBufferHeight;_initializedResolvers=Jy();_canvasObserver;_position=[0,0];destroyed=!1;_needsDrawingBufferResize=!0;toString(){return`${this[Symbol.toStringTag]}(${this.id})`}constructor(e){this.props={...t.defaultProps,...e},e=this.props,this.initialized=this._initializedResolvers.promise,De()?e.canvas?typeof e.canvas=="string"?this.canvas=xM(e.canvas):this.canvas=e.canvas:this.canvas=bM(e):this.canvas={width:e.width||1,height:e.height||1},t.isHTMLCanvas(this.canvas)?(this.id=e.id||this.canvas.id,this.type="html-canvas",this.htmlCanvas=this.canvas):t.isOffscreenCanvas(this.canvas)?(this.id=e.id||"offscreen-canvas",this.type="offscreen-canvas",this.offscreenCanvas=this.canvas):(this.id=e.id||"node-canvas-context",this.type="node"),this.cssWidth=this.htmlCanvas?.clientWidth||this.canvas.width,this.cssHeight=this.htmlCanvas?.clientHeight||this.canvas.height,this.devicePixelWidth=this.canvas.width,this.devicePixelHeight=this.canvas.height,this.drawingBufferWidth=this.canvas.width,this.drawingBufferHeight=this.canvas.height,this.devicePixelRatio=globalThis.devicePixelRatio||1,this._position=[0,0],this._canvasObserver=new kc({canvas:this.htmlCanvas,trackPosition:this.props.trackPosition,onResize:r=>this._handleResize(r),onIntersection:r=>this._handleIntersection(r),onDevicePixelRatioChange:()=>this._observeDevicePixelRatio(),onPositionChange:()=>this.updatePosition()})}destroy(){this.destroyed||(this.destroyed=!0,this._stopObservers(),this.device=null)}setProps(e){return"useDevicePixels"in e&&(this.props.useDevicePixels=e.useDevicePixels||!1,this._updateDrawingBufferSize()),this}getCurrentFramebuffer(e){return this._resizeDrawingBufferIfNeeded(),this._getCurrentFramebuffer(e)}getCSSSize(){return[this.cssWidth,this.cssHeight]}getPosition(){return this._position}getDevicePixelSize(){return[this.devicePixelWidth,this.devicePixelHeight]}getDrawingBufferSize(){return[this.drawingBufferWidth,this.drawingBufferHeight]}getMaxDrawingBufferSize(){let e=this.device.limits.maxTextureDimension2D;return[e,e]}setDrawingBufferSize(e,r){e=Math.floor(e),r=Math.floor(r),!(this.drawingBufferWidth===e&&this.drawingBufferHeight===r)&&(this.drawingBufferWidth=e,this.drawingBufferHeight=r,this._needsDrawingBufferResize=!0)}getDevicePixelRatio(){return typeof window<"u"&&window.devicePixelRatio||1}cssToDevicePixels(e,r=!0){let i=this.cssToDeviceRatio(),[n,o]=this.getDrawingBufferSize();return TM(e,i,n,o,r)}getPixelSize(){return this.getDevicePixelSize()}getAspect(){let[e,r]=this.getDrawingBufferSize();return e>0&&r>0?e/r:1}cssToDeviceRatio(){try{let[e]=this.getDrawingBufferSize(),[r]=this.getCSSSize();return r?e/r:1}catch{return 1}}resize(e){this.setDrawingBufferSize(e.width,e.height)}_setAutoCreatedCanvasId(e){this.htmlCanvas?.id==="lumagl-auto-created-canvas"&&(this.htmlCanvas.id=e)}_startObservers(){this.destroyed||this._canvasObserver.start()}_stopObservers(){this._canvasObserver.stop()}_handleIntersection(e){if(this.destroyed)return;let r=e.find(n=>n.target===this.canvas);if(!r)return;let i=r.isIntersecting;this.isVisible!==i&&(this.isVisible=i,this.device.props.onVisibilityChange(this))}_handleResize(e){if(this.destroyed)return;let r=e.find(l=>l.target===this.canvas);if(!r)return;let i=hi(r.contentBoxSize?.[0]);this.cssWidth=i.inlineSize,this.cssHeight=i.blockSize;let n=this.getDevicePixelSize(),o=r.devicePixelContentBoxSize?.[0]?.inlineSize||i.inlineSize*devicePixelRatio,s=r.devicePixelContentBoxSize?.[0]?.blockSize||i.blockSize*devicePixelRatio,[a,c]=this.getMaxDrawingBufferSize();this.devicePixelWidth=Math.max(1,Math.min(o,a)),this.devicePixelHeight=Math.max(1,Math.min(s,c)),this._updateDrawingBufferSize(),this.device.props.onResize(this,{oldPixelSize:n})}_updateDrawingBufferSize(){if(this.props.autoResize)if(typeof this.props.useDevicePixels=="number"){let e=this.props.useDevicePixels;this.setDrawingBufferSize(this.cssWidth*e,this.cssHeight*e)}else this.props.useDevicePixels?this.setDrawingBufferSize(this.devicePixelWidth,this.devicePixelHeight):this.setDrawingBufferSize(this.cssWidth,this.cssHeight);this._initializedResolvers.resolve(),this.isInitialized=!0,this.updatePosition()}_resizeDrawingBufferIfNeeded(){this._needsDrawingBufferResize&&(this._needsDrawingBufferResize=!1,(this.drawingBufferWidth!==this.canvas.width||this.drawingBufferHeight!==this.canvas.height)&&(this.canvas.width=this.drawingBufferWidth,this.canvas.height=this.drawingBufferHeight,this._configureDevice()))}_observeDevicePixelRatio(){if(this.destroyed||!this._canvasObserver.started)return;let e=this.devicePixelRatio;this.devicePixelRatio=window.devicePixelRatio,this.updatePosition(),this.device.props.onDevicePixelRatioChange?.(this,{oldRatio:e})}updatePosition(){if(this.destroyed)return;let e=this.htmlCanvas?.getBoundingClientRect();if(e){let r=[e.left,e.top];if(this._position??=r,r[0]!==this._position[0]||r[1]!==this._position[1]){let n=this._position;this._position=r,this.device.props.onPositionChange?.(this,{oldPosition:n})}}}}});var Do,ix=P(()=>{Fh();Do=class extends Nr{static defaultProps=Nr.defaultProps}});var Lo,nx=P(()=>{Fh();Lo=class extends Nr{}});var pt,Bh=P(()=>{we();pt=class t extends k{static defaultProps={...k.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,r){r=t.normalizeProps(e,r),super(e,r,t.defaultProps)}static normalizeProps(e,r){return r}}});var wM,$,kh=P(()=>{we();Bh();ot();Fc();wM={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},$=class t extends k{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,r,i){if(r=t.normalizeProps(e,r),super(e,r,t.defaultProps),this.dimension=this.props.dimension,this.baseDimension=wM[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(r.data)){let n=e.getExternalImageSize(r.data);this.width=n?.width||1,this.height=n?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&v.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=i?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof pt?e:this.device.createSampler(e)}copyImageData(e){let{data:r,depth:i,...n}=e;this.writeData(r,{...n,depthOrArrayLayers:n.depthOrArrayLayers??i})}computeMemoryLayout(e={}){let r=this._normalizeTextureReadOptions(e),{width:i=this.width,height:n=this.height,depthOrArrayLayers:o=this.depth}=r,{format:s,byteAlignment:a}=this;return Ue.computeMemoryLayout({format:s,width:i,height:n,depth:o,byteAlignment:a})}readBuffer(e,r){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,r){throw new Error("readBuffer not implemented")}writeData(e,r){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,r){let i={...r},{width:n,height:o}=i;return typeof n=="number"&&(i.width=Math.max(1,Math.ceil(n))),typeof o=="number"&&(i.height=Math.max(1,Math.ceil(o))),i}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:r,depth:i,...n}=e,o=this._normalizeTextureWriteOptions({...n,depthOrArrayLayers:n.depthOrArrayLayers??i});return{data:r,depth:o.depthOrArrayLayers,...o}}_normalizeCopyExternalImageOptions(e){let r=t._omitUndefined(e),i=r.mipLevel??0,n=this._getMipLevelSize(i),o=this.device.getExternalImageSize(e.image),s={...t.defaultCopyExternalImageOptions,...n,...o,...r};return s.width=Math.min(s.width,n.width-s.x),s.height=Math.min(s.height,n.height-s.y),s.depth=Math.min(s.depth,n.depthOrArrayLayers-s.z),s}_normalizeTextureReadOptions(e){let r=t._omitUndefined(e),i=r.mipLevel??0,n=this._getMipLevelSize(i),o={...t.defaultTextureReadOptions,...n,...r};return o.width=Math.min(o.width,n.width-o.x),o.height=Math.min(o.height,n.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,n.depthOrArrayLayers-o.z),o}_getSupportedColorReadOptions(e){let r=this._normalizeTextureReadOptions(e),i=Ue.getInfo(this.format);switch(this._validateColorReadAspect(r),this._validateColorReadFormat(i),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return r;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let r=t._omitUndefined(e),i=r.mipLevel??0,n=this._getMipLevelSize(i),o={...t.defaultTextureWriteOptions,...n,...r};o.width=Math.min(o.width,n.width-o.x),o.height=Math.min(o.height,n.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,n.depthOrArrayLayers-o.z);let s=Ue.computeMemoryLayout({format:this.format,width:o.width,height:o.height,depth:o.depthOrArrayLayers,byteAlignment:this.byteAlignment}),a=s.bytesPerPixel*o.width;if(o.bytesPerRow=r.bytesPerRow??s.bytesPerRow,o.rowsPerImage=r.rowsPerImage??o.height,o.bytesPerRow>e),i=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),n=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:r,height:i,depthOrArrayLayers:n}}getAllocatedByteLength(){let e=0;for(let r=0;rr!==void 0))}static defaultProps={...k.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:t.SAMPLE|t.RENDER|t.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}}});var pi,ox=P(()=>{we();pi=class t extends k{get[Symbol.toStringTag](){return"TextureView"}constructor(e,r){super(e,r,t.defaultProps)}static defaultProps={...k.defaultProps,format:void 0,dimension:void 0,aspect:"all",baseMipLevel:0,mipLevelCount:void 0,baseArrayLayer:0,arrayLayerCount:void 0}}});function sx(t,e,r){let i="",n=e.split(/\r?\n/),o=t.slice().sort((s,a)=>s.lineNum-a.lineNum);switch(r?.showSourceCode||"no"){case"all":let s=0;for(let a=1;a<=n.length;a++){let c=n[a-1],l=o[s];for(c&&l&&(i+=ax(c,a,r));o.length>s&&l.lineNum===a;){let f=o[s++];f&&(i+=Uh(f,n,f.lineNum,{...r,inlineSource:!1}))}}for(;o.length>s;){let a=o[s++];a&&(i+=Uh(a,[],0,{...r,inlineSource:!1}))}return i;case"issues":case"no":for(let a of t)i+=Uh(a,n,a.lineNum,{inlineSource:r?.showSourceCode!=="no"});return i}}function Uh(t,e,r,i){if(i?.inlineSource){let o=SM(e,r),s=t.linePos>0?`${" ".repeat(t.linePos+5)}^^^ +`:"";return` +${o}${s}${t.type.toUpperCase()}: ${t.message} + +`}let n=t.type==="error"?"red":"orange";return i?.html?`
${t.type.toUpperCase()}: ${t.message}
`:`${t.type.toUpperCase()}: ${t.message}`}function SM(t,e,r){let i="";for(let n=e-2;n<=e;n++){let o=t[n-1];o!==void 0&&(i+=ax(o,e,r))}return i}function ax(t,e,r){let i=r?.html?vM(t):t;return`${AM(String(e),4)}: ${i}${r?.html?"
":` +`}`}function AM(t,e){let r="";for(let i=t.length;i",">").replaceAll('"',""").replaceAll("'","'")}var cx=P(()=>{});function EM(t){return RM(t.source)||t.id||Dt(`unnamed ${t.stage}-shader`)}function RM(t,e="unnamed"){return/#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/.exec(t)?.[1]??e}var gi,zh=P(()=>{we();un();cx();gi=class t extends k{get[Symbol.toStringTag](){return"Shader"}stage;source;compilationStatus="pending";constructor(e,r){r={...r,debugShaders:r.debugShaders||e.props.debugShaders||"errors"},super(e,{id:EM(r),...r},t.defaultProps),this.stage=this.props.stage,this.source=this.props.source}getCompilationInfoSync(){return null}getTranslatedSource(){return null}async debugShader(){let e=this.props.debugShaders;switch(e){case"never":return;case"errors":if(this.compilationStatus==="success")return;break;case"warnings":case"always":break}let r=await this.getCompilationInfo();e==="warnings"&&r?.length===0||this._displayShaderLog(r,this.id)}_displayShaderLog(e,r){if(typeof document>"u"||!document?.createElement)return;let i=r,n=`${this.stage} shader "${i}"`,o=sx(e,this.source,{showSourceCode:"all",html:!0}),s=this.getTranslatedSource(),a=document.createElement("div");a.innerHTML=`

Compilation error in ${n}

+
+
+ +
+
${o}
`,s&&(a.innerHTML+=`

Translated Source



${s}
`),a.style.top="0",a.style.left="0",a.style.background="white",a.style.position="fixed",a.style.zIndex="9999",a.style.maxWidth="100vw",a.style.maxHeight="100vh",a.style.overflowY="auto",document.body.appendChild(a),a.querySelector(".luma-compiler-log-error")?.scrollIntoView(),a.querySelector("button#close").onclick=()=>{a.remove()},a.querySelector("button#copy").onclick=()=>{navigator.clipboard.writeText(this.source)}}static defaultProps={...k.defaultProps,language:"auto",stage:void 0,source:"",sourceMap:null,entryPoint:"main",debugShaders:void 0}}});var mi,lx=P(()=>{we();kh();ot();mi=class t extends k{get[Symbol.toStringTag](){return"Framebuffer"}width;height;constructor(e,r={}){super(e,r,t.defaultProps),this.width=this.props.width,this.height=this.props.height}clone(e){let r=this.colorAttachments.map(n=>n.texture.clone(e)),i=this.depthStencilAttachment&&this.depthStencilAttachment.texture.clone(e);return this.device.createFramebuffer({...this.props,...e,colorAttachments:r,depthStencilAttachment:i})}resize(e){let r=!e;if(e){let[i,n]=Array.isArray(e)?e:[e.width,e.height];r=r||n!==this.height||i!==this.width,this.width=i,this.height=n}r&&(v.log(2,`Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)(),this.resizeAttachments(this.width,this.height))}autoCreateAttachmentTextures(){if(this.props.colorAttachments.length===0&&!this.props.depthStencilAttachment)throw new Error("Framebuffer has noattachments");this.colorAttachments=this.props.colorAttachments.map((r,i)=>{if(typeof r=="string"){let n=this.createColorTexture(r,i);return this.attachResource(n),n.view}return r instanceof $?r.view:r});let e=this.props.depthStencilAttachment;if(e)if(typeof e=="string"){let r=this.createDepthStencilTexture(e);this.attachResource(r),this.depthStencilAttachment=r.view}else e instanceof $?this.depthStencilAttachment=e.view:this.depthStencilAttachment=e}createColorTexture(e,r){return this.device.createTexture({id:`${this.id}-color-attachment-${r}`,usage:$.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height,sampler:{magFilter:"linear",minFilter:"linear"}})}createDepthStencilTexture(e){return this.device.createTexture({id:`${this.id}-depth-stencil-attachment`,usage:$.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height})}resizeAttachments(e,r){if(this.colorAttachments.forEach((i,n)=>{let o=i.texture.clone({width:e,height:r});this.destroyAttachedResource(i),this.colorAttachments[n]=o.view,this.attachResource(o.view)}),this.depthStencilAttachment){let i=this.depthStencilAttachment.texture.clone({width:e,height:r});this.destroyAttachedResource(this.depthStencilAttachment),this.depthStencilAttachment=i.view,this.attachResource(i)}this.updateAttachments()}static defaultProps={...k.defaultProps,width:1,height:1,colorAttachments:[],depthStencilAttachment:null}}});var st,Wh=P(()=>{we();st=class t extends k{get[Symbol.toStringTag](){return"RenderPipeline"}shaderLayout;bufferLayout;linkStatus="pending";hash="";sharedRenderPipeline=null;get isPending(){return this.linkStatus==="pending"||this.vs.compilationStatus==="pending"||this.fs?.compilationStatus==="pending"}get isErrored(){return this.linkStatus==="error"||this.vs.compilationStatus==="error"||this.fs?.compilationStatus==="error"}constructor(e,r){super(e,r,t.defaultProps),this.shaderLayout=this.props.shaderLayout,this.bufferLayout=this.props.bufferLayout||[],this.sharedRenderPipeline=this.props._sharedRenderPipeline||null}static defaultProps={...k.defaultProps,vs:null,vertexEntryPoint:"vertexMain",vsConstants:{},fs:null,fragmentEntryPoint:"fragmentMain",fsConstants:{},shaderLayout:null,bufferLayout:[],topology:"triangle-list",colorAttachmentFormats:void 0,depthStencilAttachmentFormat:void 0,parameters:{},varyings:void 0,bufferMode:void 0,disableWarnings:!1,_sharedRenderPipeline:void 0,bindings:void 0,bindGroups:void 0}}});var Fo,fx=P(()=>{we();Fo=class extends k{get[Symbol.toStringTag](){return"SharedRenderPipeline"}constructor(e,r){super(e,r,{...k.defaultProps,handle:void 0,vs:void 0,fs:void 0,varyings:void 0,bufferMode:void 0})}}});var Bo,ux=P(()=>{we();Bo=class t extends k{get[Symbol.toStringTag](){return"ComputePipeline"}hash="";shaderLayout;constructor(e,r){super(e,r,t.defaultProps),this.shaderLayout=r.shaderLayout}static defaultProps={...k.defaultProps,shader:void 0,entryPoint:void 0,constants:{},shaderLayout:void 0}}});var ko,dx=P(()=>{ux();Wh();ot();un();ko=class t{static defaultProps={...st.defaultProps};static getDefaultPipelineFactory(e){let r=e.getModuleData("@luma.gl/core");return r.defaultPipelineFactory||=new t(e),r.defaultPipelineFactory}device;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};_sharedRenderPipelineCache={};get[Symbol.toStringTag](){return"PipelineFactory"}toString(){return`PipelineFactory(${this.device.id})`}constructor(e){this.device=e}createRenderPipeline(e){if(!this.device.props._cachePipelines)return this.device.createRenderPipeline(e);let r={...st.defaultProps,...e},i=this._renderPipelineCache,n=this._hashRenderPipeline(r),o=i[n]?.resource;if(o)i[n].useCount++,this.device.props.debugFactories&&v.log(3,`${this}: ${i[n].resource} reused, count=${i[n].useCount}, (id=${e.id})`)();else{let s=this.device.type==="webgl"&&this.device.props._sharePipelines?this.createSharedRenderPipeline(r):void 0;o=this.device.createRenderPipeline({...r,id:r.id?`${r.id}-cached`:Dt("unnamed-cached"),_sharedRenderPipeline:s}),o.hash=n,i[n]={resource:o,useCount:1},this.device.props.debugFactories&&v.log(3,`${this}: ${o} created, count=${i[n].useCount}`)()}return o}createComputePipeline(e){if(!this.device.props._cachePipelines)return this.device.createComputePipeline(e);let r={...Bo.defaultProps,...e},i=this._computePipelineCache,n=this._hashComputePipeline(r),o=i[n]?.resource;return o?(i[n].useCount++,this.device.props.debugFactories&&v.log(3,`${this}: ${i[n].resource} reused, count=${i[n].useCount}, (id=${e.id})`)()):(o=this.device.createComputePipeline({...r,id:r.id?`${r.id}-cached`:void 0}),o.hash=n,i[n]={resource:o,useCount:1},this.device.props.debugFactories&&v.log(3,`${this}: ${o} created, count=${i[n].useCount}`)()),o}release(e){if(!this.device.props._cachePipelines){e.destroy();return}let r=this._getCache(e),i=e.hash;r[i].useCount--,r[i].useCount===0?(this._destroyPipeline(e),this.device.props.debugFactories&&v.log(3,`${this}: ${e} released and destroyed`)()):r[i].useCount<0?(v.error(`${this}: ${e} released, useCount < 0, resetting`)(),r[i].useCount=0):this.device.props.debugFactories&&v.log(3,`${this}: ${e} released, count=${r[i].useCount}`)()}createSharedRenderPipeline(e){let r=this._hashSharedRenderPipeline(e),i=this._sharedRenderPipelineCache[r];return i||(i={resource:this.device._createSharedRenderPipelineWebGL(e),useCount:0},this._sharedRenderPipelineCache[r]=i),i.useCount++,i.resource}releaseSharedRenderPipeline(e){if(!e.sharedRenderPipeline)return;let r=this._hashSharedRenderPipeline(e.sharedRenderPipeline.props),i=this._sharedRenderPipelineCache[r];i&&(i.useCount--,i.useCount===0&&(i.resource.destroy(),delete this._sharedRenderPipelineCache[r]))}_destroyPipeline(e){let r=this._getCache(e);return this.device.props._destroyPipelines?(delete r[e.hash],e.destroy(),e instanceof st&&this.releaseSharedRenderPipeline(e),!0):!1}_getCache(e){let r;if(e instanceof Bo&&(r=this._computePipelineCache),e instanceof st&&(r=this._renderPipelineCache),!r)throw new Error(`${this}`);if(!r[e.hash])throw new Error(`${this}: ${e} matched incorrect entry`);return r}_hashComputePipeline(e){let{type:r}=this.device,i=this._getHash(e.shader.source),n=this._getHash(JSON.stringify(e.shaderLayout));return`${r}/C/${i}SL${n}`}_hashRenderPipeline(e){let r=e.vs?this._getHash(e.vs.source):0,i=e.fs?this._getHash(e.fs.source):0,n=this._getWebGLVaryingHash(e),o=this._getHash(JSON.stringify(e.shaderLayout)),s=this._getHash(JSON.stringify(e.bufferLayout)),{type:a}=this.device;if(a==="webgl"){let c=this._getHash(JSON.stringify(e.parameters));return`${a}/R/${r}/${i}V${n}T${e.topology}P${c}SL${o}BL${s}`}else{let l=this._getHash(JSON.stringify({vertexEntryPoint:e.vertexEntryPoint,fragmentEntryPoint:e.fragmentEntryPoint})),f=this._getHash(JSON.stringify(e.parameters)),u=this._getWebGPUAttachmentHash(e);return`${a}/R/${r}/${i}V${n}T${e.topology}EP${l}P${f}SL${o}BL${s}A${u}`}}_hashSharedRenderPipeline(e){let r=e.vs?this._getHash(e.vs.source):0,i=e.fs?this._getHash(e.fs.source):0,n=this._getWebGLVaryingHash(e);return`webgl/S/${r}/${i}V${n}`}_getHash(e){return this._hashes[e]===void 0&&(this._hashes[e]=this._hashCounter++),this._hashes[e]}_getWebGLVaryingHash(e){let{varyings:r=[],bufferMode:i=null}=e;return this._getHash(JSON.stringify({varyings:r,bufferMode:i}))}_getWebGPUAttachmentHash(e){let r=e.colorAttachmentFormats??[this.device.preferredColorFormat],i=e.parameters?.depthWriteEnabled?e.depthStencilAttachmentFormat||this.device.preferredDepthFormat:null;return this._getHash(JSON.stringify({colorAttachmentFormats:r,depthStencilAttachmentFormat:i}))}}});var Uo,hx=P(()=>{zh();ot();Uo=class t{static defaultProps={...gi.defaultProps};static getDefaultShaderFactory(e){let r=e.getModuleData("@luma.gl/core");return r.defaultShaderFactory||=new t(e),r.defaultShaderFactory}device;_cache={};get[Symbol.toStringTag](){return"ShaderFactory"}toString(){return`${this[Symbol.toStringTag]}(${this.device.id})`}constructor(e){this.device=e}createShader(e){if(!this.device.props._cacheShaders)return this.device.createShader(e);let r=this._hashShader(e),i=this._cache[r];if(i)i.useCount++,this.device.props.debugFactories&&v.log(3,`${this}: Reusing shader ${i.resource.id} count=${i.useCount}`)();else{let n=this.device.createShader({...e,id:e.id?`${e.id}-cached`:void 0});this._cache[r]=i={resource:n,useCount:1},this.device.props.debugFactories&&v.log(3,`${this}: Created new shader ${n.id}`)()}return i.resource}release(e){if(!this.device.props._cacheShaders){e.destroy();return}let r=this._hashShader(e),i=this._cache[r];if(i)if(i.useCount--,i.useCount===0)this.device.props._destroyShaders&&(delete this._cache[r],i.resource.destroy(),this.device.props.debugFactories&&v.log(3,`${this}: Releasing shader ${e.id}, destroyed`)());else{if(i.useCount<0)throw new Error(`ShaderFactory: Shader ${e.id} released too many times`);this.device.props.debugFactories&&v.log(3,`${this}: Releasing shader ${e.id} count=${i.useCount}`)()}}_hashShader(e){return`${e.stage}:${e.source}`}}});function px(t,e,r){let i=t.bindings.find(n=>n.name===e||`${n.name.toLocaleLowerCase()}uniforms`===e.toLocaleLowerCase());return!i&&!r?.ignoreWarnings&&v.warn(`Binding ${e} not set: Not found in shader layout.`)(),i||null}function zo(t,e){if(!e)return{};if(CM(e))return Object.fromEntries(Object.entries(e).map(([n,o])=>[Number(n),{...o}]));let r={};for(let[i,n]of Object.entries(e)){let s=px(t,i)?.group??0;r[s]||={},r[s][i]=n}return r}function Uc(t){let e={};for(let r of Object.values(t))Object.assign(e,r);return e}function CM(t){let e=Object.keys(t);return e.length>0&&e.every(r=>/^\d+$/.test(r))}var gx=P(()=>{ot()});var Wo,mx=P(()=>{we();Wo=class t extends k{static defaultClearColor=[0,0,0,1];static defaultClearDepth=1;static defaultClearStencil=0;get[Symbol.toStringTag](){return"RenderPass"}constructor(e,r){r=t.normalizeProps(e,r),super(e,r,t.defaultProps)}static normalizeProps(e,r){return r}static defaultProps={...k.defaultProps,framebuffer:null,parameters:void 0,clearColor:t.defaultClearColor,clearColors:void 0,clearDepth:t.defaultClearDepth,clearStencil:t.defaultClearStencil,depthReadOnly:!1,stencilReadOnly:!1,discard:!1,occlusionQuerySet:void 0,timestampQuerySet:void 0,beginTimestampIndex:void 0,endTimestampIndex:void 0}}});var Vo,_x=P(()=>{we();Vo=class t extends k{get[Symbol.toStringTag](){return"CommandEncoder"}_timeProfilingQuerySet=null;_timeProfilingSlotCount=0;_gpuTimeMs;constructor(e,r){super(e,r,t.defaultProps),this._timeProfilingQuerySet=r.timeProfilingQuerySet??null,this._timeProfilingSlotCount=0,this._gpuTimeMs=void 0}async resolveTimeProfilingQuerySet(){if(this._gpuTimeMs=void 0,!this._timeProfilingQuerySet)return;let e=Math.floor(this._timeProfilingSlotCount/2);if(e<=0)return;let r=e*2,i=await this._timeProfilingQuerySet.readResults({firstQuery:0,queryCount:r}),n=0n;for(let o=0;o=this._timeProfilingQuerySet.props.count?r:(this._timeProfilingSlotCount+=2,{...r,timestampQuerySet:this._timeProfilingQuerySet,beginTimestampIndex:i,endTimestampIndex:i+1})}_supportsTimestampQueries(){return this.device.features.has("timestamp-query")}static defaultProps={...k.defaultProps,measureExecutionTime:void 0,timeProfilingQuerySet:void 0}}});var jo,yx=P(()=>{we();jo=class t extends k{get[Symbol.toStringTag](){return"CommandBuffer"}constructor(e,r){super(e,r,t.defaultProps)}static defaultProps={...k.defaultProps}}});function pn(t){let e=zc(t),r=OM[e];if(!r)throw new Error(`Unsupported variable shader type: ${t}`);return r}function xx(t){let e=bx(t),r=IM[e];if(!r)throw new Error(`Unsupported attribute shader type: ${t}`);let[i,n]=r,o=i==="i32"||i==="u32",s=i!=="u32",a=MM[i]*n;return{primitiveType:i,components:n,byteLength:a,integer:o,signed:s}}function PM(t,e){return e===1?t:`vec${e}<${t}>`}function bx(t){return NM[t]||t}function zc(t){return DM[t]||t}var Vh,jh,MM,IM,OM,NM,DM,Wc=P(()=>{Vh=class{getVariableShaderTypeInfo(e){return pn(e)}getAttributeShaderTypeInfo(e){return xx(e)}makeShaderAttributeType(e,r){return PM(e,r)}resolveAttributeShaderTypeAlias(e){return bx(e)}resolveVariableShaderTypeAlias(e){return zc(e)}};jh=new Vh,MM={f32:4,f16:2,i32:4,u32:4},IM={f32:["f32",1],"vec2":["f32",2],"vec3":["f32",3],"vec4":["f32",4],f16:["f16",1],"vec2":["f16",2],"vec3":["f16",3],"vec4":["f16",4],i32:["i32",1],"vec2":["i32",2],"vec3":["i32",3],"vec4":["i32",4],u32:["u32",1],"vec2":["u32",2],"vec3":["u32",3],"vec4":["u32",4]},OM={f32:{type:"f32",components:1},f16:{type:"f16",components:1},i32:{type:"i32",components:1},u32:{type:"u32",components:1},"vec2":{type:"f32",components:2},"vec3":{type:"f32",components:3},"vec4":{type:"f32",components:4},"vec2":{type:"f16",components:2},"vec3":{type:"f16",components:3},"vec4":{type:"f16",components:4},"vec2":{type:"i32",components:2},"vec3":{type:"i32",components:3},"vec4":{type:"i32",components:4},"vec2":{type:"u32",components:2},"vec3":{type:"u32",components:3},"vec4":{type:"u32",components:4},"mat2x2":{type:"f32",components:4},"mat2x3":{type:"f32",components:6},"mat2x4":{type:"f32",components:8},"mat3x2":{type:"f32",components:6},"mat3x3":{type:"f32",components:9},"mat3x4":{type:"f32",components:12},"mat4x2":{type:"f32",components:8},"mat4x3":{type:"f32",components:12},"mat4x4":{type:"f32",components:16},"mat2x2":{type:"f16",components:4},"mat2x3":{type:"f16",components:6},"mat2x4":{type:"f16",components:8},"mat3x2":{type:"f16",components:6},"mat3x3":{type:"f16",components:9},"mat3x4":{type:"f16",components:12},"mat4x2":{type:"f16",components:8},"mat4x3":{type:"f16",components:12},"mat4x4":{type:"f16",components:16},"mat2x2":{type:"i32",components:4},"mat2x3":{type:"i32",components:6},"mat2x4":{type:"i32",components:8},"mat3x2":{type:"i32",components:6},"mat3x3":{type:"i32",components:9},"mat3x4":{type:"i32",components:12},"mat4x2":{type:"i32",components:8},"mat4x3":{type:"i32",components:12},"mat4x4":{type:"i32",components:16},"mat2x2":{type:"u32",components:4},"mat2x3":{type:"u32",components:6},"mat2x4":{type:"u32",components:8},"mat3x2":{type:"u32",components:6},"mat3x3":{type:"u32",components:9},"mat3x4":{type:"u32",components:12},"mat4x2":{type:"u32",components:8},"mat4x3":{type:"u32",components:12},"mat4x4":{type:"u32",components:16}},NM={vec2i:"vec2",vec3i:"vec3",vec4i:"vec4",vec2u:"vec2",vec3u:"vec3",vec4u:"vec4",vec2f:"vec2",vec3f:"vec3",vec4f:"vec4",vec2h:"vec2",vec3h:"vec3",vec4h:"vec4"},DM={vec2i:"vec2",vec3i:"vec3",vec4i:"vec4",vec2u:"vec2",vec3u:"vec3",vec4u:"vec4",vec2f:"vec2",vec3f:"vec3",vec4f:"vec4",vec2h:"vec2",vec3h:"vec3",vec4h:"vec4",mat2x2f:"mat2x2",mat2x3f:"mat2x3",mat2x4f:"mat2x4",mat3x2f:"mat3x2",mat3x3f:"mat3x3",mat3x4f:"mat3x4",mat4x2f:"mat4x2",mat4x3f:"mat4x3",mat4x4f:"mat4x4",mat2x2i:"mat2x2",mat2x3i:"mat2x3",mat2x4i:"mat2x4",mat3x2i:"mat3x2",mat3x3i:"mat3x3",mat3x4i:"mat3x4",mat4x2i:"mat4x2",mat4x3i:"mat4x3",mat4x4i:"mat4x4",mat2x2u:"mat2x2",mat2x3u:"mat2x3",mat2x4u:"mat2x4",mat3x2u:"mat3x2",mat3x3u:"mat3x3",mat3x4u:"mat3x4",mat4x2u:"mat4x2",mat4x3u:"mat4x3",mat4x4u:"mat4x4",mat2x2h:"mat2x2",mat2x3h:"mat2x3",mat2x4h:"mat2x4",mat3x2h:"mat3x2",mat3x3h:"mat3x3",mat3x4h:"mat3x4",mat4x2h:"mat4x2",mat4x3h:"mat4x3",mat4x4h:"mat4x4"}});function Vc(t,e){let r={};for(let i of t.attributes){let n=LM(t,e,i.name);n&&(r[i.name]=n)}return r}function Tx(t,e,r=16){let i=Vc(t,e),n=new Array(r).fill(null);for(let o of Object.values(i))n[o.location]=o;return n}function LM(t,e,r){let i=FM(t,r),n=BM(e,r);if(!i)return null;let o=jh.getAttributeShaderTypeInfo(i.type),s=or.getCompatibleVertexFormat(o),a=n?.vertexFormat||s,c=or.getVertexFormatInfo(a);return{attributeName:n?.attributeName||i.name,bufferName:n?.bufferName||i.name,location:i.location,shaderType:i.type,primitiveType:o.primitiveType,shaderComponents:o.components,vertexFormat:a,bufferDataType:c.type,bufferComponents:c.components,normalized:c.normalized,integer:o.integer,stepMode:n?.stepMode||i.stepMode||"vertex",byteOffset:n?.byteOffset||0,byteStride:n?.byteStride||0}}function FM(t,e){let r=t.attributes.find(i=>i.name===e);return r||v.warn(`shader layout attribute "${e}" not present in shader`),r||null}function BM(t,e){kM(t);let r=UM(t,e);return r||(r=zM(t,e),r)?r:(v.warn(`layout for attribute "${e}" not present in buffer layout`),null)}function kM(t){for(let e of t)(e.attributes&&e.format||!e.attributes&&!e.format)&&v.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`)}function UM(t,e){for(let r of t)if(r.format&&r.name===e)return{attributeName:r.name,bufferName:e,stepMode:r.stepMode,vertexFormat:r.format,byteOffset:0,byteStride:r.byteStride||0};return null}function zM(t,e){for(let r of t){let i=r.byteStride;if(typeof r.byteStride!="number")for(let o of r.attributes||[]){let s=or.getVertexFormatInfo(o.format);i+=s.byteLength}let n=r.attributes?.find(o=>o.attribute===e);if(n)return{attributeName:n.attribute,bufferName:r.name,stepMode:r.stepMode,vertexFormat:n.format,byteOffset:n.byteOffset,byteStride:i}}return null}var $h=P(()=>{ot();Wc();Oc()});var $o,wx=P(()=>{$h();we();$o=class t extends k{static defaultProps={...k.defaultProps,shaderLayout:void 0,bufferLayout:[]};get[Symbol.toStringTag](){return"VertexArray"}maxVertexAttributes;attributeInfos;indexBuffer=null;attributes;constructor(e,r){super(e,r,t.defaultProps),this.maxVertexAttributes=e.limits.maxVertexAttributes,this.attributes=new Array(this.maxVertexAttributes).fill(null),this.attributeInfos=Tx(r.shaderLayout,r.bufferLayout,this.maxVertexAttributes)}setConstantWebGL(e,r){this.device.reportError(new Error("constant attributes not supported"),this)()}}});var Ho,Sx=P(()=>{we();Ho=class t extends k{static defaultProps={...k.defaultProps,layout:void 0,buffers:{}};get[Symbol.toStringTag](){return"TransformFeedback"}constructor(e,r){super(e,r,t.defaultProps)}}});var Yo,Ax=P(()=>{we();Yo=class t extends k{get[Symbol.toStringTag](){return"QuerySet"}constructor(e,r){super(e,r,t.defaultProps)}static defaultProps={...k.defaultProps,type:void 0,count:void 0}}});var Xo,vx=P(()=>{we();Xo=class t extends k{static defaultProps={...k.defaultProps};get[Symbol.toStringTag](){return"Fence"}constructor(e,r={}){super(e,r,t.defaultProps)}}});function Ft(t,e){switch(e){case 1:return t;case 2:return t+t%2;default:return t+(4-t%4)%4}}function Go(t){let[,,,,e]=WM[t];return e}var WM,Hh=P(()=>{WM={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});function Rx(t,e={}){let r={...t},i=e.layout??"std140",n={},o=0;for(let[s,a]of Object.entries(r))o=Yh(n,s,a,o,i);return o=Ft(o,Dr(r,i)),{layout:i,byteLength:o*4,uniformTypes:r,fields:n}}function qo(t,e){let r=zc(t),i=pn(r),n=/^mat(\d)x(\d)<.+>$/.exec(r);if(n){let s=Number(n[1]),a=Number(n[2]),c=Ex(a,r,i.type,e),l=jM(c.size,c.alignment,e);return{alignment:c.alignment,size:s*l,components:s*a,columns:s,rows:a,columnStride:l,shaderType:r,type:i.type}}let o=/^vec(\d)<.+>$/.exec(r);return o?Ex(Number(o[1]),r,i.type,e):{alignment:1,size:1,components:1,columns:1,rows:1,columnStride:1,shaderType:r,type:i.type}}function Xh(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Yh(t,e,r,i,n){if(typeof r=="string"){let o=qo(r,n),s=Ft(i,o.alignment);return t[e]={offset:s,...o},s+o.size}if(Array.isArray(r)){if(Array.isArray(r[0]))throw new Error(`Nested arrays are not supported for ${e}`);let o=r[0],s=r[1],a=Px(o,n),c=Ft(i,Dr(r,n));for(let l=0;l{Hh();Wc()});function qh(t){return(!jc||jc.byteLength{});function HM(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function gn(t){return Array.isArray(t)?t.length===0||typeof t[0]=="number":HM(t)}var Qh=P(()=>{});function YM(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&!ArrayBuffer.isView(t)}function XM(t,e,r){return Array.prototype.slice.call(t,e,r)}var $c,Ix=P(()=>{Zh();Qh();ot();Gh();$c=class{layout;constructor(e){this.layout=e}has(e){return!!this.layout.fields[e]}get(e){let r=this.layout.fields[e];return r?{offset:r.offset,size:r.size}:void 0}getFlatUniformValues(e){let r={};for(let[i,n]of Object.entries(e)){let o=this.layout.uniformTypes[i];o?this._flattenCompositeValue(r,i,o,n):this.layout.fields[i]&&(r[i]=n)}return r}getData(e){let r=qh(this.layout.byteLength);new Uint8Array(r,0,this.layout.byteLength).fill(0);let i={i32:new Int32Array(r),u32:new Uint32Array(r),f32:new Float32Array(r),f16:new Uint16Array(r)},n=this.getFlatUniformValues(e);for(let[o,s]of Object.entries(n))this._writeLeafValue(i,o,s);return new Uint8Array(r,0,this.layout.byteLength)}_flattenCompositeValue(e,r,i,n){if(n!==void 0){if(typeof i=="string"||this.layout.fields[r]){e[r]=n;return}if(Array.isArray(i)){let o=i[0],s=i[1];if(Array.isArray(o))throw new Error(`Nested arrays are not supported for ${r}`);if(typeof o=="string"&&gn(n)){this._flattenPackedArray(e,r,o,s,n);return}if(!Array.isArray(n)){v.warn(`Unsupported uniform array value for ${r}:`,n)();return}for(let a=0;a=s.length)break;c===1?e[`${r}[${l}]`]=Number(s[f]):e[`${r}[${l}]`]=XM(o,f,f+c)}}_writeLeafValue(e,r,i){let n=this.layout.fields[r];if(!n){v.warn(`Uniform ${r} not found in layout`)();return}let{type:o,components:s,columns:a,rows:c,offset:l,columnStride:f}=n,u=e[o];if(s===1){u[l]=Number(i);return}let d=i;if(a===1){for(let p=0;po)return!1;for(let s=0;s{Qh();GM=128});var Hc,Lx=P(()=>{Dx();Hc=class{name;uniforms={};modifiedUniforms={};modified=!0;bindingLayout={};needsRedraw="initialized";constructor(e){if(this.name=e?.name||"unnamed",e?.name&&e?.shaderLayout){let r=e?.shaderLayout.bindings?.find(n=>n.type==="uniform"&&n.name===e?.name);if(!r)throw new Error(e?.name);let i=r;for(let n of i.uniforms||[])this.bindingLayout[n.name]=n}}setUniforms(e){for(let[r,i]of Object.entries(e))this._setUniform(r,i),this.needsRedraw||this.setNeedsRedraw(`${this.name}.${r}=${i}`)}setNeedsRedraw(e){this.needsRedraw=this.needsRedraw||e}getAllUniforms(){return this.modifiedUniforms={},this.needsRedraw=!1,this.uniforms||{}}_setUniform(e,r){Ox(this.uniforms[e],r)||(this.uniforms[e]=Nx(r),this.modifiedUniforms[e]=!0,this.modified=!0)}}});function KM(t){return t.type==="webgpu"?"wgsl-uniform":"std140"}var qM,Ko,Fx=P(()=>{Mc();ot();Gh();Lx();Ix();qM=1024,Ko=class{device;uniformBlocks=new Map;shaderBlockLayouts=new Map;shaderBlockWriters=new Map;uniformBuffers=new Map;constructor(e,r){this.device=e;for(let[i,n]of Object.entries(r)){let o=i,s=Rx(n.uniformTypes??{},{layout:n.layout??KM(e)}),a=new $c(s);this.shaderBlockLayouts.set(o,s),this.shaderBlockWriters.set(o,a);let c=new Hc({name:i});c.setUniforms(a.getFlatUniformValues(n.defaultUniforms||{})),this.uniformBlocks.set(o,c)}}destroy(){for(let e of this.uniformBuffers.values())e.destroy()}setUniforms(e){for(let[r,i]of Object.entries(e)){let n=r,s=this.shaderBlockWriters.get(n)?.getFlatUniformValues(i||{});this.uniformBlocks.get(n)?.setUniforms(s||{})}this.updateUniformBuffers()}getUniformBufferByteLength(e){let r=this.shaderBlockLayouts.get(e)?.byteLength||0;return Math.max(r,qM)}getUniformBufferData(e){let r=this.uniformBlocks.get(e)?.getAllUniforms()||{};return this.shaderBlockWriters.get(e)?.getData(r)||new Uint8Array(0)}createUniformBuffer(e,r){r&&this.setUniforms(r);let i=this.getUniformBufferByteLength(e),n=this.device.createBuffer({usage:j.UNIFORM|j.COPY_DST,byteLength:i}),o=this.getUniformBufferData(e);return n.write(o),n}getManagedUniformBuffer(e){if(!this.uniformBuffers.get(e)){let r=this.getUniformBufferByteLength(e),i=this.device.createBuffer({usage:j.UNIFORM|j.COPY_DST,byteLength:r});this.uniformBuffers.set(e,i)}return this.uniformBuffers.get(e)}updateUniformBuffers(){let e=!1;for(let r of this.uniformBlocks.keys()){let i=this.updateUniformBuffer(r);e||=i}return e&&v.log(3,`UniformStore.updateUniformBuffers(): ${e}`)(),e}updateUniformBuffer(e){let r=this.uniformBlocks.get(e),i=this.uniformBuffers.get(e),n=!1;if(i&&r?.needsRedraw){n||=r.needsRedraw;let o=this.getUniformBufferData(e);i=this.uniformBuffers.get(e),i?.write(o);let s=this.uniformBlocks.get(e)?.getAllUniforms();v.log(4,`Writing to uniform buffer ${String(e)}`,o,s)()}return n}}});var z=P(()=>{Ky();Zy();Oh();ix();nx();Mc();kh();ox();zh();Bh();lx();Wh();fx();dx();hx();mx();_x();yx();wx();Sx();Ax();vx();Fx();Ic();Hh();Wc();Oc();Fc();Mh();ot();gx();Lh();Zh();$h()});var Vr,Jb=P(()=>{(function(t){t[t.DEPTH_BUFFER_BIT=256]="DEPTH_BUFFER_BIT",t[t.STENCIL_BUFFER_BIT=1024]="STENCIL_BUFFER_BIT",t[t.COLOR_BUFFER_BIT=16384]="COLOR_BUFFER_BIT",t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t[t.ZERO=0]="ZERO",t[t.ONE=1]="ONE",t[t.SRC_COLOR=768]="SRC_COLOR",t[t.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",t[t.SRC_ALPHA=770]="SRC_ALPHA",t[t.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",t[t.DST_ALPHA=772]="DST_ALPHA",t[t.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",t[t.DST_COLOR=774]="DST_COLOR",t[t.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",t[t.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE",t[t.CONSTANT_COLOR=32769]="CONSTANT_COLOR",t[t.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",t[t.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",t[t.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",t[t.FUNC_ADD=32774]="FUNC_ADD",t[t.FUNC_SUBTRACT=32778]="FUNC_SUBTRACT",t[t.FUNC_REVERSE_SUBTRACT=32779]="FUNC_REVERSE_SUBTRACT",t[t.BLEND_EQUATION=32777]="BLEND_EQUATION",t[t.BLEND_EQUATION_RGB=32777]="BLEND_EQUATION_RGB",t[t.BLEND_EQUATION_ALPHA=34877]="BLEND_EQUATION_ALPHA",t[t.BLEND_DST_RGB=32968]="BLEND_DST_RGB",t[t.BLEND_SRC_RGB=32969]="BLEND_SRC_RGB",t[t.BLEND_DST_ALPHA=32970]="BLEND_DST_ALPHA",t[t.BLEND_SRC_ALPHA=32971]="BLEND_SRC_ALPHA",t[t.BLEND_COLOR=32773]="BLEND_COLOR",t[t.ARRAY_BUFFER_BINDING=34964]="ARRAY_BUFFER_BINDING",t[t.ELEMENT_ARRAY_BUFFER_BINDING=34965]="ELEMENT_ARRAY_BUFFER_BINDING",t[t.LINE_WIDTH=2849]="LINE_WIDTH",t[t.ALIASED_POINT_SIZE_RANGE=33901]="ALIASED_POINT_SIZE_RANGE",t[t.ALIASED_LINE_WIDTH_RANGE=33902]="ALIASED_LINE_WIDTH_RANGE",t[t.CULL_FACE_MODE=2885]="CULL_FACE_MODE",t[t.FRONT_FACE=2886]="FRONT_FACE",t[t.DEPTH_RANGE=2928]="DEPTH_RANGE",t[t.DEPTH_WRITEMASK=2930]="DEPTH_WRITEMASK",t[t.DEPTH_CLEAR_VALUE=2931]="DEPTH_CLEAR_VALUE",t[t.DEPTH_FUNC=2932]="DEPTH_FUNC",t[t.STENCIL_CLEAR_VALUE=2961]="STENCIL_CLEAR_VALUE",t[t.STENCIL_FUNC=2962]="STENCIL_FUNC",t[t.STENCIL_FAIL=2964]="STENCIL_FAIL",t[t.STENCIL_PASS_DEPTH_FAIL=2965]="STENCIL_PASS_DEPTH_FAIL",t[t.STENCIL_PASS_DEPTH_PASS=2966]="STENCIL_PASS_DEPTH_PASS",t[t.STENCIL_REF=2967]="STENCIL_REF",t[t.STENCIL_VALUE_MASK=2963]="STENCIL_VALUE_MASK",t[t.STENCIL_WRITEMASK=2968]="STENCIL_WRITEMASK",t[t.STENCIL_BACK_FUNC=34816]="STENCIL_BACK_FUNC",t[t.STENCIL_BACK_FAIL=34817]="STENCIL_BACK_FAIL",t[t.STENCIL_BACK_PASS_DEPTH_FAIL=34818]="STENCIL_BACK_PASS_DEPTH_FAIL",t[t.STENCIL_BACK_PASS_DEPTH_PASS=34819]="STENCIL_BACK_PASS_DEPTH_PASS",t[t.STENCIL_BACK_REF=36003]="STENCIL_BACK_REF",t[t.STENCIL_BACK_VALUE_MASK=36004]="STENCIL_BACK_VALUE_MASK",t[t.STENCIL_BACK_WRITEMASK=36005]="STENCIL_BACK_WRITEMASK",t[t.VIEWPORT=2978]="VIEWPORT",t[t.SCISSOR_BOX=3088]="SCISSOR_BOX",t[t.COLOR_CLEAR_VALUE=3106]="COLOR_CLEAR_VALUE",t[t.COLOR_WRITEMASK=3107]="COLOR_WRITEMASK",t[t.UNPACK_ALIGNMENT=3317]="UNPACK_ALIGNMENT",t[t.PACK_ALIGNMENT=3333]="PACK_ALIGNMENT",t[t.MAX_TEXTURE_SIZE=3379]="MAX_TEXTURE_SIZE",t[t.MAX_VIEWPORT_DIMS=3386]="MAX_VIEWPORT_DIMS",t[t.SUBPIXEL_BITS=3408]="SUBPIXEL_BITS",t[t.RED_BITS=3410]="RED_BITS",t[t.GREEN_BITS=3411]="GREEN_BITS",t[t.BLUE_BITS=3412]="BLUE_BITS",t[t.ALPHA_BITS=3413]="ALPHA_BITS",t[t.DEPTH_BITS=3414]="DEPTH_BITS",t[t.STENCIL_BITS=3415]="STENCIL_BITS",t[t.POLYGON_OFFSET_UNITS=10752]="POLYGON_OFFSET_UNITS",t[t.POLYGON_OFFSET_FACTOR=32824]="POLYGON_OFFSET_FACTOR",t[t.TEXTURE_BINDING_2D=32873]="TEXTURE_BINDING_2D",t[t.SAMPLE_BUFFERS=32936]="SAMPLE_BUFFERS",t[t.SAMPLES=32937]="SAMPLES",t[t.SAMPLE_COVERAGE_VALUE=32938]="SAMPLE_COVERAGE_VALUE",t[t.SAMPLE_COVERAGE_INVERT=32939]="SAMPLE_COVERAGE_INVERT",t[t.COMPRESSED_TEXTURE_FORMATS=34467]="COMPRESSED_TEXTURE_FORMATS",t[t.VENDOR=7936]="VENDOR",t[t.RENDERER=7937]="RENDERER",t[t.VERSION=7938]="VERSION",t[t.IMPLEMENTATION_COLOR_READ_TYPE=35738]="IMPLEMENTATION_COLOR_READ_TYPE",t[t.IMPLEMENTATION_COLOR_READ_FORMAT=35739]="IMPLEMENTATION_COLOR_READ_FORMAT",t[t.BROWSER_DEFAULT_WEBGL=37444]="BROWSER_DEFAULT_WEBGL",t[t.STATIC_DRAW=35044]="STATIC_DRAW",t[t.STREAM_DRAW=35040]="STREAM_DRAW",t[t.DYNAMIC_DRAW=35048]="DYNAMIC_DRAW",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.BUFFER_SIZE=34660]="BUFFER_SIZE",t[t.BUFFER_USAGE=34661]="BUFFER_USAGE",t[t.CURRENT_VERTEX_ATTRIB=34342]="CURRENT_VERTEX_ATTRIB",t[t.VERTEX_ATTRIB_ARRAY_ENABLED=34338]="VERTEX_ATTRIB_ARRAY_ENABLED",t[t.VERTEX_ATTRIB_ARRAY_SIZE=34339]="VERTEX_ATTRIB_ARRAY_SIZE",t[t.VERTEX_ATTRIB_ARRAY_STRIDE=34340]="VERTEX_ATTRIB_ARRAY_STRIDE",t[t.VERTEX_ATTRIB_ARRAY_TYPE=34341]="VERTEX_ATTRIB_ARRAY_TYPE",t[t.VERTEX_ATTRIB_ARRAY_NORMALIZED=34922]="VERTEX_ATTRIB_ARRAY_NORMALIZED",t[t.VERTEX_ATTRIB_ARRAY_POINTER=34373]="VERTEX_ATTRIB_ARRAY_POINTER",t[t.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING=34975]="VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",t[t.CULL_FACE=2884]="CULL_FACE",t[t.FRONT=1028]="FRONT",t[t.BACK=1029]="BACK",t[t.FRONT_AND_BACK=1032]="FRONT_AND_BACK",t[t.BLEND=3042]="BLEND",t[t.DEPTH_TEST=2929]="DEPTH_TEST",t[t.DITHER=3024]="DITHER",t[t.POLYGON_OFFSET_FILL=32823]="POLYGON_OFFSET_FILL",t[t.SAMPLE_ALPHA_TO_COVERAGE=32926]="SAMPLE_ALPHA_TO_COVERAGE",t[t.SAMPLE_COVERAGE=32928]="SAMPLE_COVERAGE",t[t.SCISSOR_TEST=3089]="SCISSOR_TEST",t[t.STENCIL_TEST=2960]="STENCIL_TEST",t[t.NO_ERROR=0]="NO_ERROR",t[t.INVALID_ENUM=1280]="INVALID_ENUM",t[t.INVALID_VALUE=1281]="INVALID_VALUE",t[t.INVALID_OPERATION=1282]="INVALID_OPERATION",t[t.OUT_OF_MEMORY=1285]="OUT_OF_MEMORY",t[t.CONTEXT_LOST_WEBGL=37442]="CONTEXT_LOST_WEBGL",t[t.CW=2304]="CW",t[t.CCW=2305]="CCW",t[t.DONT_CARE=4352]="DONT_CARE",t[t.FASTEST=4353]="FASTEST",t[t.NICEST=4354]="NICEST",t[t.GENERATE_MIPMAP_HINT=33170]="GENERATE_MIPMAP_HINT",t[t.BYTE=5120]="BYTE",t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.SHORT=5122]="SHORT",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.INT=5124]="INT",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.FLOAT=5126]="FLOAT",t[t.DOUBLE=5130]="DOUBLE",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.ALPHA=6406]="ALPHA",t[t.RGB=6407]="RGB",t[t.RGBA=6408]="RGBA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.FRAGMENT_SHADER=35632]="FRAGMENT_SHADER",t[t.VERTEX_SHADER=35633]="VERTEX_SHADER",t[t.COMPILE_STATUS=35713]="COMPILE_STATUS",t[t.DELETE_STATUS=35712]="DELETE_STATUS",t[t.LINK_STATUS=35714]="LINK_STATUS",t[t.VALIDATE_STATUS=35715]="VALIDATE_STATUS",t[t.ATTACHED_SHADERS=35717]="ATTACHED_SHADERS",t[t.ACTIVE_ATTRIBUTES=35721]="ACTIVE_ATTRIBUTES",t[t.ACTIVE_UNIFORMS=35718]="ACTIVE_UNIFORMS",t[t.MAX_VERTEX_ATTRIBS=34921]="MAX_VERTEX_ATTRIBS",t[t.MAX_VERTEX_UNIFORM_VECTORS=36347]="MAX_VERTEX_UNIFORM_VECTORS",t[t.MAX_VARYING_VECTORS=36348]="MAX_VARYING_VECTORS",t[t.MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661]="MAX_COMBINED_TEXTURE_IMAGE_UNITS",t[t.MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660]="MAX_VERTEX_TEXTURE_IMAGE_UNITS",t[t.MAX_TEXTURE_IMAGE_UNITS=34930]="MAX_TEXTURE_IMAGE_UNITS",t[t.MAX_FRAGMENT_UNIFORM_VECTORS=36349]="MAX_FRAGMENT_UNIFORM_VECTORS",t[t.SHADER_TYPE=35663]="SHADER_TYPE",t[t.SHADING_LANGUAGE_VERSION=35724]="SHADING_LANGUAGE_VERSION",t[t.CURRENT_PROGRAM=35725]="CURRENT_PROGRAM",t[t.NEVER=512]="NEVER",t[t.LESS=513]="LESS",t[t.EQUAL=514]="EQUAL",t[t.LEQUAL=515]="LEQUAL",t[t.GREATER=516]="GREATER",t[t.NOTEQUAL=517]="NOTEQUAL",t[t.GEQUAL=518]="GEQUAL",t[t.ALWAYS=519]="ALWAYS",t[t.KEEP=7680]="KEEP",t[t.REPLACE=7681]="REPLACE",t[t.INCR=7682]="INCR",t[t.DECR=7683]="DECR",t[t.INVERT=5386]="INVERT",t[t.INCR_WRAP=34055]="INCR_WRAP",t[t.DECR_WRAP=34056]="DECR_WRAP",t[t.NEAREST=9728]="NEAREST",t[t.LINEAR=9729]="LINEAR",t[t.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",t[t.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",t[t.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",t[t.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR",t[t.TEXTURE_MAG_FILTER=10240]="TEXTURE_MAG_FILTER",t[t.TEXTURE_MIN_FILTER=10241]="TEXTURE_MIN_FILTER",t[t.TEXTURE_WRAP_S=10242]="TEXTURE_WRAP_S",t[t.TEXTURE_WRAP_T=10243]="TEXTURE_WRAP_T",t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE=5890]="TEXTURE",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_BINDING_CUBE_MAP=34068]="TEXTURE_BINDING_CUBE_MAP",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t[t.MAX_CUBE_MAP_TEXTURE_SIZE=34076]="MAX_CUBE_MAP_TEXTURE_SIZE",t[t.TEXTURE0=33984]="TEXTURE0",t[t.ACTIVE_TEXTURE=34016]="ACTIVE_TEXTURE",t[t.REPEAT=10497]="REPEAT",t[t.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t[t.TEXTURE_WIDTH=4096]="TEXTURE_WIDTH",t[t.TEXTURE_HEIGHT=4097]="TEXTURE_HEIGHT",t[t.FLOAT_VEC2=35664]="FLOAT_VEC2",t[t.FLOAT_VEC3=35665]="FLOAT_VEC3",t[t.FLOAT_VEC4=35666]="FLOAT_VEC4",t[t.INT_VEC2=35667]="INT_VEC2",t[t.INT_VEC3=35668]="INT_VEC3",t[t.INT_VEC4=35669]="INT_VEC4",t[t.BOOL=35670]="BOOL",t[t.BOOL_VEC2=35671]="BOOL_VEC2",t[t.BOOL_VEC3=35672]="BOOL_VEC3",t[t.BOOL_VEC4=35673]="BOOL_VEC4",t[t.FLOAT_MAT2=35674]="FLOAT_MAT2",t[t.FLOAT_MAT3=35675]="FLOAT_MAT3",t[t.FLOAT_MAT4=35676]="FLOAT_MAT4",t[t.SAMPLER_2D=35678]="SAMPLER_2D",t[t.SAMPLER_CUBE=35680]="SAMPLER_CUBE",t[t.LOW_FLOAT=36336]="LOW_FLOAT",t[t.MEDIUM_FLOAT=36337]="MEDIUM_FLOAT",t[t.HIGH_FLOAT=36338]="HIGH_FLOAT",t[t.LOW_INT=36339]="LOW_INT",t[t.MEDIUM_INT=36340]="MEDIUM_INT",t[t.HIGH_INT=36341]="HIGH_INT",t[t.FRAMEBUFFER=36160]="FRAMEBUFFER",t[t.RENDERBUFFER=36161]="RENDERBUFFER",t[t.RGBA4=32854]="RGBA4",t[t.RGB5_A1=32855]="RGB5_A1",t[t.RGB565=36194]="RGB565",t[t.DEPTH_COMPONENT16=33189]="DEPTH_COMPONENT16",t[t.STENCIL_INDEX=6401]="STENCIL_INDEX",t[t.STENCIL_INDEX8=36168]="STENCIL_INDEX8",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t[t.RENDERBUFFER_WIDTH=36162]="RENDERBUFFER_WIDTH",t[t.RENDERBUFFER_HEIGHT=36163]="RENDERBUFFER_HEIGHT",t[t.RENDERBUFFER_INTERNAL_FORMAT=36164]="RENDERBUFFER_INTERNAL_FORMAT",t[t.RENDERBUFFER_RED_SIZE=36176]="RENDERBUFFER_RED_SIZE",t[t.RENDERBUFFER_GREEN_SIZE=36177]="RENDERBUFFER_GREEN_SIZE",t[t.RENDERBUFFER_BLUE_SIZE=36178]="RENDERBUFFER_BLUE_SIZE",t[t.RENDERBUFFER_ALPHA_SIZE=36179]="RENDERBUFFER_ALPHA_SIZE",t[t.RENDERBUFFER_DEPTH_SIZE=36180]="RENDERBUFFER_DEPTH_SIZE",t[t.RENDERBUFFER_STENCIL_SIZE=36181]="RENDERBUFFER_STENCIL_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE=36048]="FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",t[t.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME=36049]="FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL=36050]="FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE=36051]="FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",t[t.COLOR_ATTACHMENT0=36064]="COLOR_ATTACHMENT0",t[t.DEPTH_ATTACHMENT=36096]="DEPTH_ATTACHMENT",t[t.STENCIL_ATTACHMENT=36128]="STENCIL_ATTACHMENT",t[t.DEPTH_STENCIL_ATTACHMENT=33306]="DEPTH_STENCIL_ATTACHMENT",t[t.NONE=0]="NONE",t[t.FRAMEBUFFER_COMPLETE=36053]="FRAMEBUFFER_COMPLETE",t[t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054]="FRAMEBUFFER_INCOMPLETE_ATTACHMENT",t[t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055]="FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",t[t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057]="FRAMEBUFFER_INCOMPLETE_DIMENSIONS",t[t.FRAMEBUFFER_UNSUPPORTED=36061]="FRAMEBUFFER_UNSUPPORTED",t[t.FRAMEBUFFER_BINDING=36006]="FRAMEBUFFER_BINDING",t[t.RENDERBUFFER_BINDING=36007]="RENDERBUFFER_BINDING",t[t.READ_FRAMEBUFFER=36008]="READ_FRAMEBUFFER",t[t.DRAW_FRAMEBUFFER=36009]="DRAW_FRAMEBUFFER",t[t.MAX_RENDERBUFFER_SIZE=34024]="MAX_RENDERBUFFER_SIZE",t[t.INVALID_FRAMEBUFFER_OPERATION=1286]="INVALID_FRAMEBUFFER_OPERATION",t[t.UNPACK_FLIP_Y_WEBGL=37440]="UNPACK_FLIP_Y_WEBGL",t[t.UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441]="UNPACK_PREMULTIPLY_ALPHA_WEBGL",t[t.UNPACK_COLORSPACE_CONVERSION_WEBGL=37443]="UNPACK_COLORSPACE_CONVERSION_WEBGL",t[t.READ_BUFFER=3074]="READ_BUFFER",t[t.UNPACK_ROW_LENGTH=3314]="UNPACK_ROW_LENGTH",t[t.UNPACK_SKIP_ROWS=3315]="UNPACK_SKIP_ROWS",t[t.UNPACK_SKIP_PIXELS=3316]="UNPACK_SKIP_PIXELS",t[t.PACK_ROW_LENGTH=3330]="PACK_ROW_LENGTH",t[t.PACK_SKIP_ROWS=3331]="PACK_SKIP_ROWS",t[t.PACK_SKIP_PIXELS=3332]="PACK_SKIP_PIXELS",t[t.TEXTURE_BINDING_3D=32874]="TEXTURE_BINDING_3D",t[t.UNPACK_SKIP_IMAGES=32877]="UNPACK_SKIP_IMAGES",t[t.UNPACK_IMAGE_HEIGHT=32878]="UNPACK_IMAGE_HEIGHT",t[t.MAX_3D_TEXTURE_SIZE=32883]="MAX_3D_TEXTURE_SIZE",t[t.MAX_ELEMENTS_VERTICES=33e3]="MAX_ELEMENTS_VERTICES",t[t.MAX_ELEMENTS_INDICES=33001]="MAX_ELEMENTS_INDICES",t[t.MAX_TEXTURE_LOD_BIAS=34045]="MAX_TEXTURE_LOD_BIAS",t[t.MAX_FRAGMENT_UNIFORM_COMPONENTS=35657]="MAX_FRAGMENT_UNIFORM_COMPONENTS",t[t.MAX_VERTEX_UNIFORM_COMPONENTS=35658]="MAX_VERTEX_UNIFORM_COMPONENTS",t[t.MAX_ARRAY_TEXTURE_LAYERS=35071]="MAX_ARRAY_TEXTURE_LAYERS",t[t.MIN_PROGRAM_TEXEL_OFFSET=35076]="MIN_PROGRAM_TEXEL_OFFSET",t[t.MAX_PROGRAM_TEXEL_OFFSET=35077]="MAX_PROGRAM_TEXEL_OFFSET",t[t.MAX_VARYING_COMPONENTS=35659]="MAX_VARYING_COMPONENTS",t[t.FRAGMENT_SHADER_DERIVATIVE_HINT=35723]="FRAGMENT_SHADER_DERIVATIVE_HINT",t[t.RASTERIZER_DISCARD=35977]="RASTERIZER_DISCARD",t[t.VERTEX_ARRAY_BINDING=34229]="VERTEX_ARRAY_BINDING",t[t.MAX_VERTEX_OUTPUT_COMPONENTS=37154]="MAX_VERTEX_OUTPUT_COMPONENTS",t[t.MAX_FRAGMENT_INPUT_COMPONENTS=37157]="MAX_FRAGMENT_INPUT_COMPONENTS",t[t.MAX_SERVER_WAIT_TIMEOUT=37137]="MAX_SERVER_WAIT_TIMEOUT",t[t.MAX_ELEMENT_INDEX=36203]="MAX_ELEMENT_INDEX",t[t.RED=6403]="RED",t[t.RGB8=32849]="RGB8",t[t.RGBA8=32856]="RGBA8",t[t.RGB10_A2=32857]="RGB10_A2",t[t.TEXTURE_3D=32879]="TEXTURE_3D",t[t.TEXTURE_WRAP_R=32882]="TEXTURE_WRAP_R",t[t.TEXTURE_MIN_LOD=33082]="TEXTURE_MIN_LOD",t[t.TEXTURE_MAX_LOD=33083]="TEXTURE_MAX_LOD",t[t.TEXTURE_BASE_LEVEL=33084]="TEXTURE_BASE_LEVEL",t[t.TEXTURE_MAX_LEVEL=33085]="TEXTURE_MAX_LEVEL",t[t.TEXTURE_COMPARE_MODE=34892]="TEXTURE_COMPARE_MODE",t[t.TEXTURE_COMPARE_FUNC=34893]="TEXTURE_COMPARE_FUNC",t[t.SRGB=35904]="SRGB",t[t.SRGB8=35905]="SRGB8",t[t.SRGB8_ALPHA8=35907]="SRGB8_ALPHA8",t[t.COMPARE_REF_TO_TEXTURE=34894]="COMPARE_REF_TO_TEXTURE",t[t.RGBA32F=34836]="RGBA32F",t[t.RGB32F=34837]="RGB32F",t[t.RGBA16F=34842]="RGBA16F",t[t.RGB16F=34843]="RGB16F",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_BINDING_2D_ARRAY=35869]="TEXTURE_BINDING_2D_ARRAY",t[t.R11F_G11F_B10F=35898]="R11F_G11F_B10F",t[t.RGB9_E5=35901]="RGB9_E5",t[t.RGBA32UI=36208]="RGBA32UI",t[t.RGB32UI=36209]="RGB32UI",t[t.RGBA16UI=36214]="RGBA16UI",t[t.RGB16UI=36215]="RGB16UI",t[t.RGBA8UI=36220]="RGBA8UI",t[t.RGB8UI=36221]="RGB8UI",t[t.RGBA32I=36226]="RGBA32I",t[t.RGB32I=36227]="RGB32I",t[t.RGBA16I=36232]="RGBA16I",t[t.RGB16I=36233]="RGB16I",t[t.RGBA8I=36238]="RGBA8I",t[t.RGB8I=36239]="RGB8I",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.R8=33321]="R8",t[t.RG8=33323]="RG8",t[t.R16F=33325]="R16F",t[t.R32F=33326]="R32F",t[t.RG16F=33327]="RG16F",t[t.RG32F=33328]="RG32F",t[t.R8I=33329]="R8I",t[t.R8UI=33330]="R8UI",t[t.R16I=33331]="R16I",t[t.R16UI=33332]="R16UI",t[t.R32I=33333]="R32I",t[t.R32UI=33334]="R32UI",t[t.RG8I=33335]="RG8I",t[t.RG8UI=33336]="RG8UI",t[t.RG16I=33337]="RG16I",t[t.RG16UI=33338]="RG16UI",t[t.RG32I=33339]="RG32I",t[t.RG32UI=33340]="RG32UI",t[t.R8_SNORM=36756]="R8_SNORM",t[t.RG8_SNORM=36757]="RG8_SNORM",t[t.RGB8_SNORM=36758]="RGB8_SNORM",t[t.RGBA8_SNORM=36759]="RGBA8_SNORM",t[t.RGB10_A2UI=36975]="RGB10_A2UI",t[t.TEXTURE_IMMUTABLE_FORMAT=37167]="TEXTURE_IMMUTABLE_FORMAT",t[t.TEXTURE_IMMUTABLE_LEVELS=33503]="TEXTURE_IMMUTABLE_LEVELS",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.HALF_FLOAT=5131]="HALF_FLOAT",t[t.RG=33319]="RG",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.INT_2_10_10_10_REV=36255]="INT_2_10_10_10_REV",t[t.CURRENT_QUERY=34917]="CURRENT_QUERY",t[t.QUERY_RESULT=34918]="QUERY_RESULT",t[t.QUERY_RESULT_AVAILABLE=34919]="QUERY_RESULT_AVAILABLE",t[t.ANY_SAMPLES_PASSED=35887]="ANY_SAMPLES_PASSED",t[t.ANY_SAMPLES_PASSED_CONSERVATIVE=36202]="ANY_SAMPLES_PASSED_CONSERVATIVE",t[t.MAX_DRAW_BUFFERS=34852]="MAX_DRAW_BUFFERS",t[t.DRAW_BUFFER0=34853]="DRAW_BUFFER0",t[t.DRAW_BUFFER1=34854]="DRAW_BUFFER1",t[t.DRAW_BUFFER2=34855]="DRAW_BUFFER2",t[t.DRAW_BUFFER3=34856]="DRAW_BUFFER3",t[t.DRAW_BUFFER4=34857]="DRAW_BUFFER4",t[t.DRAW_BUFFER5=34858]="DRAW_BUFFER5",t[t.DRAW_BUFFER6=34859]="DRAW_BUFFER6",t[t.DRAW_BUFFER7=34860]="DRAW_BUFFER7",t[t.DRAW_BUFFER8=34861]="DRAW_BUFFER8",t[t.DRAW_BUFFER9=34862]="DRAW_BUFFER9",t[t.DRAW_BUFFER10=34863]="DRAW_BUFFER10",t[t.DRAW_BUFFER11=34864]="DRAW_BUFFER11",t[t.DRAW_BUFFER12=34865]="DRAW_BUFFER12",t[t.DRAW_BUFFER13=34866]="DRAW_BUFFER13",t[t.DRAW_BUFFER14=34867]="DRAW_BUFFER14",t[t.DRAW_BUFFER15=34868]="DRAW_BUFFER15",t[t.MAX_COLOR_ATTACHMENTS=36063]="MAX_COLOR_ATTACHMENTS",t[t.COLOR_ATTACHMENT1=36065]="COLOR_ATTACHMENT1",t[t.COLOR_ATTACHMENT2=36066]="COLOR_ATTACHMENT2",t[t.COLOR_ATTACHMENT3=36067]="COLOR_ATTACHMENT3",t[t.COLOR_ATTACHMENT4=36068]="COLOR_ATTACHMENT4",t[t.COLOR_ATTACHMENT5=36069]="COLOR_ATTACHMENT5",t[t.COLOR_ATTACHMENT6=36070]="COLOR_ATTACHMENT6",t[t.COLOR_ATTACHMENT7=36071]="COLOR_ATTACHMENT7",t[t.COLOR_ATTACHMENT8=36072]="COLOR_ATTACHMENT8",t[t.COLOR_ATTACHMENT9=36073]="COLOR_ATTACHMENT9",t[t.COLOR_ATTACHMENT10=36074]="COLOR_ATTACHMENT10",t[t.COLOR_ATTACHMENT11=36075]="COLOR_ATTACHMENT11",t[t.COLOR_ATTACHMENT12=36076]="COLOR_ATTACHMENT12",t[t.COLOR_ATTACHMENT13=36077]="COLOR_ATTACHMENT13",t[t.COLOR_ATTACHMENT14=36078]="COLOR_ATTACHMENT14",t[t.COLOR_ATTACHMENT15=36079]="COLOR_ATTACHMENT15",t[t.SAMPLER_3D=35679]="SAMPLER_3D",t[t.SAMPLER_2D_SHADOW=35682]="SAMPLER_2D_SHADOW",t[t.SAMPLER_2D_ARRAY=36289]="SAMPLER_2D_ARRAY",t[t.SAMPLER_2D_ARRAY_SHADOW=36292]="SAMPLER_2D_ARRAY_SHADOW",t[t.SAMPLER_CUBE_SHADOW=36293]="SAMPLER_CUBE_SHADOW",t[t.INT_SAMPLER_2D=36298]="INT_SAMPLER_2D",t[t.INT_SAMPLER_3D=36299]="INT_SAMPLER_3D",t[t.INT_SAMPLER_CUBE=36300]="INT_SAMPLER_CUBE",t[t.INT_SAMPLER_2D_ARRAY=36303]="INT_SAMPLER_2D_ARRAY",t[t.UNSIGNED_INT_SAMPLER_2D=36306]="UNSIGNED_INT_SAMPLER_2D",t[t.UNSIGNED_INT_SAMPLER_3D=36307]="UNSIGNED_INT_SAMPLER_3D",t[t.UNSIGNED_INT_SAMPLER_CUBE=36308]="UNSIGNED_INT_SAMPLER_CUBE",t[t.UNSIGNED_INT_SAMPLER_2D_ARRAY=36311]="UNSIGNED_INT_SAMPLER_2D_ARRAY",t[t.MAX_SAMPLES=36183]="MAX_SAMPLES",t[t.SAMPLER_BINDING=35097]="SAMPLER_BINDING",t[t.PIXEL_PACK_BUFFER=35051]="PIXEL_PACK_BUFFER",t[t.PIXEL_UNPACK_BUFFER=35052]="PIXEL_UNPACK_BUFFER",t[t.PIXEL_PACK_BUFFER_BINDING=35053]="PIXEL_PACK_BUFFER_BINDING",t[t.PIXEL_UNPACK_BUFFER_BINDING=35055]="PIXEL_UNPACK_BUFFER_BINDING",t[t.COPY_READ_BUFFER=36662]="COPY_READ_BUFFER",t[t.COPY_WRITE_BUFFER=36663]="COPY_WRITE_BUFFER",t[t.COPY_READ_BUFFER_BINDING=36662]="COPY_READ_BUFFER_BINDING",t[t.COPY_WRITE_BUFFER_BINDING=36663]="COPY_WRITE_BUFFER_BINDING",t[t.FLOAT_MAT2x3=35685]="FLOAT_MAT2x3",t[t.FLOAT_MAT2x4=35686]="FLOAT_MAT2x4",t[t.FLOAT_MAT3x2=35687]="FLOAT_MAT3x2",t[t.FLOAT_MAT3x4=35688]="FLOAT_MAT3x4",t[t.FLOAT_MAT4x2=35689]="FLOAT_MAT4x2",t[t.FLOAT_MAT4x3=35690]="FLOAT_MAT4x3",t[t.UNSIGNED_INT_VEC2=36294]="UNSIGNED_INT_VEC2",t[t.UNSIGNED_INT_VEC3=36295]="UNSIGNED_INT_VEC3",t[t.UNSIGNED_INT_VEC4=36296]="UNSIGNED_INT_VEC4",t[t.UNSIGNED_NORMALIZED=35863]="UNSIGNED_NORMALIZED",t[t.SIGNED_NORMALIZED=36764]="SIGNED_NORMALIZED",t[t.VERTEX_ATTRIB_ARRAY_INTEGER=35069]="VERTEX_ATTRIB_ARRAY_INTEGER",t[t.VERTEX_ATTRIB_ARRAY_DIVISOR=35070]="VERTEX_ATTRIB_ARRAY_DIVISOR",t[t.TRANSFORM_FEEDBACK_BUFFER_MODE=35967]="TRANSFORM_FEEDBACK_BUFFER_MODE",t[t.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS=35968]="MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS",t[t.TRANSFORM_FEEDBACK_VARYINGS=35971]="TRANSFORM_FEEDBACK_VARYINGS",t[t.TRANSFORM_FEEDBACK_BUFFER_START=35972]="TRANSFORM_FEEDBACK_BUFFER_START",t[t.TRANSFORM_FEEDBACK_BUFFER_SIZE=35973]="TRANSFORM_FEEDBACK_BUFFER_SIZE",t[t.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN=35976]="TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN",t[t.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS=35978]="MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS",t[t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS=35979]="MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",t[t.INTERLEAVED_ATTRIBS=35980]="INTERLEAVED_ATTRIBS",t[t.SEPARATE_ATTRIBS=35981]="SEPARATE_ATTRIBS",t[t.TRANSFORM_FEEDBACK_BUFFER=35982]="TRANSFORM_FEEDBACK_BUFFER",t[t.TRANSFORM_FEEDBACK_BUFFER_BINDING=35983]="TRANSFORM_FEEDBACK_BUFFER_BINDING",t[t.TRANSFORM_FEEDBACK=36386]="TRANSFORM_FEEDBACK",t[t.TRANSFORM_FEEDBACK_PAUSED=36387]="TRANSFORM_FEEDBACK_PAUSED",t[t.TRANSFORM_FEEDBACK_ACTIVE=36388]="TRANSFORM_FEEDBACK_ACTIVE",t[t.TRANSFORM_FEEDBACK_BINDING=36389]="TRANSFORM_FEEDBACK_BINDING",t[t.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING=33296]="FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING",t[t.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE=33297]="FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE",t[t.FRAMEBUFFER_ATTACHMENT_RED_SIZE=33298]="FRAMEBUFFER_ATTACHMENT_RED_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE=33299]="FRAMEBUFFER_ATTACHMENT_GREEN_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE=33300]="FRAMEBUFFER_ATTACHMENT_BLUE_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE=33301]="FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE=33302]="FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE=33303]="FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE",t[t.FRAMEBUFFER_DEFAULT=33304]="FRAMEBUFFER_DEFAULT",t[t.DEPTH24_STENCIL8=35056]="DEPTH24_STENCIL8",t[t.DRAW_FRAMEBUFFER_BINDING=36006]="DRAW_FRAMEBUFFER_BINDING",t[t.READ_FRAMEBUFFER_BINDING=36010]="READ_FRAMEBUFFER_BINDING",t[t.RENDERBUFFER_SAMPLES=36011]="RENDERBUFFER_SAMPLES",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER=36052]="FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER",t[t.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE=36182]="FRAMEBUFFER_INCOMPLETE_MULTISAMPLE",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t[t.UNIFORM_BUFFER_BINDING=35368]="UNIFORM_BUFFER_BINDING",t[t.UNIFORM_BUFFER_START=35369]="UNIFORM_BUFFER_START",t[t.UNIFORM_BUFFER_SIZE=35370]="UNIFORM_BUFFER_SIZE",t[t.MAX_VERTEX_UNIFORM_BLOCKS=35371]="MAX_VERTEX_UNIFORM_BLOCKS",t[t.MAX_FRAGMENT_UNIFORM_BLOCKS=35373]="MAX_FRAGMENT_UNIFORM_BLOCKS",t[t.MAX_COMBINED_UNIFORM_BLOCKS=35374]="MAX_COMBINED_UNIFORM_BLOCKS",t[t.MAX_UNIFORM_BUFFER_BINDINGS=35375]="MAX_UNIFORM_BUFFER_BINDINGS",t[t.MAX_UNIFORM_BLOCK_SIZE=35376]="MAX_UNIFORM_BLOCK_SIZE",t[t.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS=35377]="MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS",t[t.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS=35379]="MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS",t[t.UNIFORM_BUFFER_OFFSET_ALIGNMENT=35380]="UNIFORM_BUFFER_OFFSET_ALIGNMENT",t[t.ACTIVE_UNIFORM_BLOCKS=35382]="ACTIVE_UNIFORM_BLOCKS",t[t.UNIFORM_TYPE=35383]="UNIFORM_TYPE",t[t.UNIFORM_SIZE=35384]="UNIFORM_SIZE",t[t.UNIFORM_BLOCK_INDEX=35386]="UNIFORM_BLOCK_INDEX",t[t.UNIFORM_OFFSET=35387]="UNIFORM_OFFSET",t[t.UNIFORM_ARRAY_STRIDE=35388]="UNIFORM_ARRAY_STRIDE",t[t.UNIFORM_MATRIX_STRIDE=35389]="UNIFORM_MATRIX_STRIDE",t[t.UNIFORM_IS_ROW_MAJOR=35390]="UNIFORM_IS_ROW_MAJOR",t[t.UNIFORM_BLOCK_BINDING=35391]="UNIFORM_BLOCK_BINDING",t[t.UNIFORM_BLOCK_DATA_SIZE=35392]="UNIFORM_BLOCK_DATA_SIZE",t[t.UNIFORM_BLOCK_ACTIVE_UNIFORMS=35394]="UNIFORM_BLOCK_ACTIVE_UNIFORMS",t[t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES=35395]="UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES",t[t.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER=35396]="UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER",t[t.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER=35398]="UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER",t[t.OBJECT_TYPE=37138]="OBJECT_TYPE",t[t.SYNC_CONDITION=37139]="SYNC_CONDITION",t[t.SYNC_STATUS=37140]="SYNC_STATUS",t[t.SYNC_FLAGS=37141]="SYNC_FLAGS",t[t.SYNC_FENCE=37142]="SYNC_FENCE",t[t.SYNC_GPU_COMMANDS_COMPLETE=37143]="SYNC_GPU_COMMANDS_COMPLETE",t[t.UNSIGNALED=37144]="UNSIGNALED",t[t.SIGNALED=37145]="SIGNALED",t[t.ALREADY_SIGNALED=37146]="ALREADY_SIGNALED",t[t.TIMEOUT_EXPIRED=37147]="TIMEOUT_EXPIRED",t[t.CONDITION_SATISFIED=37148]="CONDITION_SATISFIED",t[t.WAIT_FAILED=37149]="WAIT_FAILED",t[t.SYNC_FLUSH_COMMANDS_BIT=1]="SYNC_FLUSH_COMMANDS_BIT",t[t.COLOR=6144]="COLOR",t[t.DEPTH=6145]="DEPTH",t[t.STENCIL=6146]="STENCIL",t[t.MIN=32775]="MIN",t[t.MAX=32776]="MAX",t[t.DEPTH_COMPONENT24=33190]="DEPTH_COMPONENT24",t[t.STREAM_READ=35041]="STREAM_READ",t[t.STREAM_COPY=35042]="STREAM_COPY",t[t.STATIC_READ=35045]="STATIC_READ",t[t.STATIC_COPY=35046]="STATIC_COPY",t[t.DYNAMIC_READ=35049]="DYNAMIC_READ",t[t.DYNAMIC_COPY=35050]="DYNAMIC_COPY",t[t.DEPTH_COMPONENT32F=36012]="DEPTH_COMPONENT32F",t[t.DEPTH32F_STENCIL8=36013]="DEPTH32F_STENCIL8",t[t.INVALID_INDEX=4294967295]="INVALID_INDEX",t[t.TIMEOUT_IGNORED=-1]="TIMEOUT_IGNORED",t[t.MAX_CLIENT_WAIT_TIMEOUT_WEBGL=37447]="MAX_CLIENT_WAIT_TIMEOUT_WEBGL",t[t.UNMASKED_VENDOR_WEBGL=37445]="UNMASKED_VENDOR_WEBGL",t[t.UNMASKED_RENDERER_WEBGL=37446]="UNMASKED_RENDERER_WEBGL",t[t.MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047]="MAX_TEXTURE_MAX_ANISOTROPY_EXT",t[t.TEXTURE_MAX_ANISOTROPY_EXT=34046]="TEXTURE_MAX_ANISOTROPY_EXT",t[t.R16_EXT=33322]="R16_EXT",t[t.RG16_EXT=33324]="RG16_EXT",t[t.RGB16_EXT=32852]="RGB16_EXT",t[t.RGBA16_EXT=32859]="RGBA16_EXT",t[t.R16_SNORM_EXT=36760]="R16_SNORM_EXT",t[t.RG16_SNORM_EXT=36761]="RG16_SNORM_EXT",t[t.RGB16_SNORM_EXT=36762]="RGB16_SNORM_EXT",t[t.RGBA16_SNORM_EXT=36763]="RGBA16_SNORM_EXT",t[t.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT1_EXT=33777]="COMPRESSED_RGBA_S3TC_DXT1_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT3_EXT=33778]="COMPRESSED_RGBA_S3TC_DXT3_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",t[t.COMPRESSED_SRGB_S3TC_DXT1_EXT=35916]="COMPRESSED_SRGB_S3TC_DXT1_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917]="COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918]="COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919]="COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT",t[t.COMPRESSED_RED_RGTC1_EXT=36283]="COMPRESSED_RED_RGTC1_EXT",t[t.COMPRESSED_SIGNED_RED_RGTC1_EXT=36284]="COMPRESSED_SIGNED_RED_RGTC1_EXT",t[t.COMPRESSED_RED_GREEN_RGTC2_EXT=36285]="COMPRESSED_RED_GREEN_RGTC2_EXT",t[t.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT=36286]="COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT",t[t.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",t[t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=36493]="COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT",t[t.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT=36494]="COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT",t[t.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT=36495]="COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT",t[t.COMPRESSED_R11_EAC=37488]="COMPRESSED_R11_EAC",t[t.COMPRESSED_SIGNED_R11_EAC=37489]="COMPRESSED_SIGNED_R11_EAC",t[t.COMPRESSED_RG11_EAC=37490]="COMPRESSED_RG11_EAC",t[t.COMPRESSED_SIGNED_RG11_EAC=37491]="COMPRESSED_SIGNED_RG11_EAC",t[t.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",t[t.COMPRESSED_RGBA8_ETC2_EAC=37493]="COMPRESSED_RGBA8_ETC2_EAC",t[t.COMPRESSED_SRGB8_ETC2=37494]="COMPRESSED_SRGB8_ETC2",t[t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37495]="COMPRESSED_SRGB8_ALPHA8_ETC2_EAC",t[t.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37496]="COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2",t[t.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37497]="COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2",t[t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",t[t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",t[t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841]="COMPRESSED_RGB_PVRTC_2BPPV1_IMG",t[t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843]="COMPRESSED_RGBA_PVRTC_2BPPV1_IMG",t[t.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",t[t.COMPRESSED_RGB_ATC_WEBGL=35986]="COMPRESSED_RGB_ATC_WEBGL",t[t.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35986]="COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL",t[t.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798]="COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL",t[t.COMPRESSED_RGBA_ASTC_4x4_KHR=37808]="COMPRESSED_RGBA_ASTC_4x4_KHR",t[t.COMPRESSED_RGBA_ASTC_5x4_KHR=37809]="COMPRESSED_RGBA_ASTC_5x4_KHR",t[t.COMPRESSED_RGBA_ASTC_5x5_KHR=37810]="COMPRESSED_RGBA_ASTC_5x5_KHR",t[t.COMPRESSED_RGBA_ASTC_6x5_KHR=37811]="COMPRESSED_RGBA_ASTC_6x5_KHR",t[t.COMPRESSED_RGBA_ASTC_6x6_KHR=37812]="COMPRESSED_RGBA_ASTC_6x6_KHR",t[t.COMPRESSED_RGBA_ASTC_8x5_KHR=37813]="COMPRESSED_RGBA_ASTC_8x5_KHR",t[t.COMPRESSED_RGBA_ASTC_8x6_KHR=37814]="COMPRESSED_RGBA_ASTC_8x6_KHR",t[t.COMPRESSED_RGBA_ASTC_8x8_KHR=37815]="COMPRESSED_RGBA_ASTC_8x8_KHR",t[t.COMPRESSED_RGBA_ASTC_10x5_KHR=37816]="COMPRESSED_RGBA_ASTC_10x5_KHR",t[t.COMPRESSED_RGBA_ASTC_10x6_KHR=37817]="COMPRESSED_RGBA_ASTC_10x6_KHR",t[t.COMPRESSED_RGBA_ASTC_10x8_KHR=37818]="COMPRESSED_RGBA_ASTC_10x8_KHR",t[t.COMPRESSED_RGBA_ASTC_10x10_KHR=37819]="COMPRESSED_RGBA_ASTC_10x10_KHR",t[t.COMPRESSED_RGBA_ASTC_12x10_KHR=37820]="COMPRESSED_RGBA_ASTC_12x10_KHR",t[t.COMPRESSED_RGBA_ASTC_12x12_KHR=37821]="COMPRESSED_RGBA_ASTC_12x12_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840]="COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841]="COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842]="COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843]="COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844]="COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852]="COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853]="COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR",t[t.QUERY_COUNTER_BITS_EXT=34916]="QUERY_COUNTER_BITS_EXT",t[t.CURRENT_QUERY_EXT=34917]="CURRENT_QUERY_EXT",t[t.QUERY_RESULT_EXT=34918]="QUERY_RESULT_EXT",t[t.QUERY_RESULT_AVAILABLE_EXT=34919]="QUERY_RESULT_AVAILABLE_EXT",t[t.TIME_ELAPSED_EXT=35007]="TIME_ELAPSED_EXT",t[t.TIMESTAMP_EXT=36392]="TIMESTAMP_EXT",t[t.GPU_DISJOINT_EXT=36795]="GPU_DISJOINT_EXT",t[t.COMPLETION_STATUS_KHR=37297]="COMPLETION_STATUS_KHR",t[t.DEPTH_CLAMP_EXT=34383]="DEPTH_CLAMP_EXT",t[t.FIRST_VERTEX_CONVENTION_WEBGL=36429]="FIRST_VERTEX_CONVENTION_WEBGL",t[t.LAST_VERTEX_CONVENTION_WEBGL=36430]="LAST_VERTEX_CONVENTION_WEBGL",t[t.PROVOKING_VERTEX_WEBL=36431]="PROVOKING_VERTEX_WEBL",t[t.POLYGON_MODE_WEBGL=2880]="POLYGON_MODE_WEBGL",t[t.POLYGON_OFFSET_LINE_WEBGL=10754]="POLYGON_OFFSET_LINE_WEBGL",t[t.LINE_WEBGL=6913]="LINE_WEBGL",t[t.FILL_WEBGL=6914]="FILL_WEBGL",t[t.MAX_CLIP_DISTANCES_WEBGL=3378]="MAX_CLIP_DISTANCES_WEBGL",t[t.MAX_CULL_DISTANCES_WEBGL=33529]="MAX_CULL_DISTANCES_WEBGL",t[t.MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL=33530]="MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL",t[t.CLIP_DISTANCE0_WEBGL=12288]="CLIP_DISTANCE0_WEBGL",t[t.CLIP_DISTANCE1_WEBGL=12289]="CLIP_DISTANCE1_WEBGL",t[t.CLIP_DISTANCE2_WEBGL=12290]="CLIP_DISTANCE2_WEBGL",t[t.CLIP_DISTANCE3_WEBGL=12291]="CLIP_DISTANCE3_WEBGL",t[t.CLIP_DISTANCE4_WEBGL=12292]="CLIP_DISTANCE4_WEBGL",t[t.CLIP_DISTANCE5_WEBGL=12293]="CLIP_DISTANCE5_WEBGL",t[t.CLIP_DISTANCE6_WEBGL=12294]="CLIP_DISTANCE6_WEBGL",t[t.CLIP_DISTANCE7_WEBGL=12295]="CLIP_DISTANCE7_WEBGL",t[t.POLYGON_OFFSET_CLAMP_EXT=36379]="POLYGON_OFFSET_CLAMP_EXT",t[t.LOWER_LEFT_EXT=36001]="LOWER_LEFT_EXT",t[t.UPPER_LEFT_EXT=36002]="UPPER_LEFT_EXT",t[t.NEGATIVE_ONE_TO_ONE_EXT=37726]="NEGATIVE_ONE_TO_ONE_EXT",t[t.ZERO_TO_ONE_EXT=37727]="ZERO_TO_ONE_EXT",t[t.CLIP_ORIGIN_EXT=37724]="CLIP_ORIGIN_EXT",t[t.CLIP_DEPTH_MODE_EXT=37725]="CLIP_DEPTH_MODE_EXT",t[t.SRC1_COLOR_WEBGL=35065]="SRC1_COLOR_WEBGL",t[t.SRC1_ALPHA_WEBGL=34185]="SRC1_ALPHA_WEBGL",t[t.ONE_MINUS_SRC1_COLOR_WEBGL=35066]="ONE_MINUS_SRC1_COLOR_WEBGL",t[t.ONE_MINUS_SRC1_ALPHA_WEBGL=35067]="ONE_MINUS_SRC1_ALPHA_WEBGL",t[t.MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL=35068]="MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL",t[t.MIRROR_CLAMP_TO_EDGE_EXT=34627]="MIRROR_CLAMP_TO_EDGE_EXT"})(Vr||(Vr={}))});var e1=P(()=>{Jb()});function t1(t=!0){let e=HTMLCanvasElement.prototype;if(!t&&e.originalGetContext){e.getContext=e.originalGetContext,e.originalGetContext=void 0;return}e.originalGetContext=e.getContext,e.getContext=function(r,i){if(r==="webgl"||r==="experimental-webgl"){let n=this.originalGetContext("webgl2",i);return n instanceof HTMLElement&&E4(n),n}return this.originalGetContext(r,i)}}function E4(t){t.getExtension("EXT_color_buffer_float");let e={...w4,WEBGL_disjoint_timer_query:t.getExtension("EXT_disjoint_timer_query_webgl2"),WEBGL_draw_buffers:S4(t),OES_vertex_array_object:A4(t),ANGLE_instanced_arrays:v4(t)},r=t.getExtension;t.getExtension=function(n){let o=r.call(t,n);return o||(n in e?e[n]:null)};let i=t.getSupportedExtensions;t.getSupportedExtensions=function(){return(i.apply(t)||[])?.concat(Object.keys(e))}}var w4,S4,A4,v4,r1=P(()=>{w4={WEBGL_depth_texture:{UNSIGNED_INT_24_8_WEBGL:34042},OES_element_index_uint:{},OES_texture_float:{},OES_texture_half_float:{HALF_FLOAT_OES:5131},EXT_color_buffer_float:{},OES_standard_derivatives:{FRAGMENT_SHADER_DERIVATIVE_HINT_OES:35723},EXT_frag_depth:{},EXT_blend_minmax:{MIN_EXT:32775,MAX_EXT:32776},EXT_shader_texture_lod:{}},S4=t=>({drawBuffersWEBGL(e){return t.drawBuffers(e)},COLOR_ATTACHMENT0_WEBGL:36064,COLOR_ATTACHMENT1_WEBGL:36065,COLOR_ATTACHMENT2_WEBGL:36066,COLOR_ATTACHMENT3_WEBGL:36067}),A4=t=>({VERTEX_ARRAY_BINDING_OES:34229,createVertexArrayOES(){return t.createVertexArray()},deleteVertexArrayOES(e){return t.deleteVertexArray(e)},isVertexArrayOES(e){return t.isVertexArray(e)},bindVertexArrayOES(e){return t.bindVertexArray(e)}}),v4=t=>({VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:35070,drawArraysInstancedANGLE(...e){return t.drawArraysInstanced(...e)},drawElementsInstancedANGLE(...e){return t.drawElementsInstanced(...e)},vertexAttribDivisorANGLE(...e){return t.vertexAttribDivisor(...e)}})});async function Rl(t,e){let r=document.getElementsByTagName("head")[0];if(!r)throw new Error("loadScript");let i=document.createElement("script");return i.setAttribute("type","text/javascript"),i.setAttribute("src",t),e&&(i.id=e),new Promise((n,o)=>{i.onload=n,i.onerror=s=>o(new Error(`Unable to load script '${t}': ${s}`)),r.appendChild(i)})}var zp=P(()=>{});function Ii(t){let e=t.luma||{_polyfilled:!1,extensions:{},softwareRenderer:!1};return e._polyfilled??=!1,e.extensions||={},t.luma=e,e}var Cl=P(()=>{});async function n1(t){if(!globalThis.SPECTOR)try{await Rl(t.debugSpectorJSUrl||Pl.debugSpectorJSUrl)}catch(e){v.warn(String(e))}}function o1(t){if(t={...Pl,...t},!t.debugSpectorJS)return null;if(!Qe&&globalThis.SPECTOR&&!globalThis.luma?.spector){v.probe(R4,"SPECTOR found and initialized. Start with `luma.spector.displayUI()`")();let{Spector:e}=globalThis.SPECTOR;Qe=new e,globalThis.luma&&(globalThis.luma.spector=Qe)}if(!Qe)return null;if(i1||(i1=!0,Qe.spyCanvases(),Qe?.onCaptureStarted.add(e=>v.info("Spector capture started:",e)()),Qe?.onCapture.add(e=>{v.info("Spector capture complete:",e)(),Qe?.getResultUI(),Qe?.resultView.display(),Qe?.resultView.addCapture(e)})),t.gl){let e=t.gl,r=Ii(e),i=r.device;Qe?.startCapture(t.gl,500),r.device=i,new Promise(n=>setTimeout(n,2e3)).then(n=>{v.info("Spector capture stopped after 2 seconds")(),Qe?.stopCapture()})}return Qe}var R4,Qe,i1,Pl,Wp=P(()=>{z();zp();Cl();R4=1,Qe=null,i1=!1,Pl={debugSpectorJS:v.get("debug-spectorjs"),debugSpectorJSUrl:"https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js",gl:void 0}});function a1(t){return t.luma=t.luma||{},t.luma}async function c1(){De()&&!globalThis.WebGLDebugUtils&&(globalThis.global=globalThis.global||globalThis,globalThis.global.module={},await Rl(C4))}function l1(t,e={}){return e.debugWebGL||e.traceWebGL?M4(t,e):P4(t)}function P4(t){let e=a1(t);return e.realContext?e.realContext:t}function M4(t,e){if(!globalThis.WebGLDebugUtils)return v.warn("webgl-debug not loaded")(),t;let r=a1(t);if(r.debugContext)return r.debugContext;globalThis.WebGLDebugUtils.init({...Vr,...t});let i=globalThis.WebGLDebugUtils.makeDebugContext(t,I4.bind(null,e),O4.bind(null,e));for(let s in Vr)!(s in i)&&typeof Vr[s]=="number"&&(i[s]=Vr[s]);class n{}Object.setPrototypeOf(i,Object.getPrototypeOf(t)),Object.setPrototypeOf(n,i);let o=Object.create(n);return r.realContext=t,r.debugContext=o,o.luma=r,o.debug=!0,o}function s1(t,e){e=Array.from(e).map(i=>i===void 0?"undefined":i);let r=globalThis.WebGLDebugUtils.glFunctionArgsToString(t,e);return r=`${r.slice(0,100)}${r.length>100?"...":""}`,`gl.${t}(${r})`}function I4(t,e,r,i){i=Array.from(i).map(a=>a===void 0?"undefined":a);let n=globalThis.WebGLDebugUtils.glEnumToString(e),o=globalThis.WebGLDebugUtils.glFunctionArgsToString(r,i),s=`${n} in gl.${r}(${o})`;v.error("%cWebGL","color: white; background: red; padding: 2px 6px; border-radius: 3px;",s)();debugger;throw new Error(s)}function O4(t,e,r){let i="";t.traceWebGL&&v.level>=1&&(i=s1(e,r),v.info(1,"%cWebGL","color: white; background: blue; padding: 2px 6px; border-radius: 3px;",i)());for(let n of r)if(n===void 0){i=i||s1(e,r);debugger}}var C4,Vp=P(()=>{z();e1();Rr();zp();C4="https://unpkg.com/webgl-debug@2.0.1/index.js"});function jp(t){return Array.isArray(t)||ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fe(t,e,r){return e[t]!==void 0?e[t]:r[t]}var Ls,pe,f1,Je,u1,Ds,d1,h1,$p,Vt,Hp,p1,Yp=P(()=>{Ls={3042:!1,32773:new Float32Array([0,0,0,0]),32777:32774,34877:32774,32969:1,32968:0,32971:1,32970:0,3106:new Float32Array([0,0,0,0]),3107:[!0,!0,!0,!0],2884:!1,2885:1029,2929:!1,2931:1,2932:513,2928:new Float32Array([0,1]),2930:!0,3024:!0,35725:null,36006:null,36007:null,34229:null,34964:null,2886:2305,33170:4352,2849:1,32823:!1,32824:0,10752:0,32926:!1,32928:!1,32938:1,32939:!1,3089:!1,3088:new Int32Array([0,0,1024,1024]),2960:!1,2961:0,2968:4294967295,36005:4294967295,2962:519,2967:0,2963:4294967295,34816:519,36003:0,36004:4294967295,2964:7680,2965:7680,2966:7680,34817:7680,34818:7680,34819:7680,2978:[0,0,1024,1024],36389:null,36662:null,36663:null,35053:null,35055:null,35723:4352,36010:null,35977:!1,3333:4,3317:4,37440:!1,37441:!1,37443:37444,3330:0,3332:0,3331:0,3314:0,32878:0,3316:0,3315:0,32877:0},pe=(t,e,r)=>e?t.enable(r):t.disable(r),f1=(t,e,r)=>t.hint(r,e),Je=(t,e,r)=>t.pixelStorei(r,e),u1=(t,e,r)=>{let i=r===36006?36009:36008;return t.bindFramebuffer(i,e)},Ds=(t,e,r)=>{let n={34964:34962,36662:36662,36663:36663,35053:35051,35055:35052}[r];t.bindBuffer(n,e)};d1={3042:pe,32773:(t,e)=>t.blendColor(...e),32777:"blendEquation",34877:"blendEquation",32969:"blendFunc",32968:"blendFunc",32971:"blendFunc",32970:"blendFunc",3106:(t,e)=>t.clearColor(...e),3107:(t,e)=>t.colorMask(...e),2884:pe,2885:(t,e)=>t.cullFace(e),2929:pe,2931:(t,e)=>t.clearDepth(e),2932:(t,e)=>t.depthFunc(e),2928:(t,e)=>t.depthRange(...e),2930:(t,e)=>t.depthMask(e),3024:pe,35723:f1,35725:(t,e)=>t.useProgram(e),36007:(t,e)=>t.bindRenderbuffer(36161,e),36389:(t,e)=>t.bindTransformFeedback?.(36386,e),34229:(t,e)=>t.bindVertexArray(e),36006:u1,36010:u1,34964:Ds,36662:Ds,36663:Ds,35053:Ds,35055:Ds,2886:(t,e)=>t.frontFace(e),33170:f1,2849:(t,e)=>t.lineWidth(e),32823:pe,32824:"polygonOffset",10752:"polygonOffset",35977:pe,32926:pe,32928:pe,32938:"sampleCoverage",32939:"sampleCoverage",3089:pe,3088:(t,e)=>t.scissor(...e),2960:pe,2961:(t,e)=>t.clearStencil(e),2968:(t,e)=>t.stencilMaskSeparate(1028,e),36005:(t,e)=>t.stencilMaskSeparate(1029,e),2962:"stencilFuncFront",2967:"stencilFuncFront",2963:"stencilFuncFront",34816:"stencilFuncBack",36003:"stencilFuncBack",36004:"stencilFuncBack",2964:"stencilOpFront",2965:"stencilOpFront",2966:"stencilOpFront",34817:"stencilOpBack",34818:"stencilOpBack",34819:"stencilOpBack",2978:(t,e)=>t.viewport(...e),34383:pe,10754:pe,12288:pe,12289:pe,12290:pe,12291:pe,12292:pe,12293:pe,12294:pe,12295:pe,3333:Je,3317:Je,37440:Je,37441:Je,37443:Je,3330:Je,3332:Je,3331:Je,3314:Je,32878:Je,3316:Je,3315:Je,32877:Je,framebuffer:(t,e)=>{let r=e&&"handle"in e?e.handle:e;return t.bindFramebuffer(36160,r)},blend:(t,e)=>e?t.enable(3042):t.disable(3042),blendColor:(t,e)=>t.blendColor(...e),blendEquation:(t,e)=>{let r=typeof e=="number"?[e,e]:e;t.blendEquationSeparate(...r)},blendFunc:(t,e)=>{let r=e?.length===2?[...e,...e]:e;t.blendFuncSeparate(...r)},clearColor:(t,e)=>t.clearColor(...e),clearDepth:(t,e)=>t.clearDepth(e),clearStencil:(t,e)=>t.clearStencil(e),colorMask:(t,e)=>t.colorMask(...e),cull:(t,e)=>e?t.enable(2884):t.disable(2884),cullFace:(t,e)=>t.cullFace(e),depthTest:(t,e)=>e?t.enable(2929):t.disable(2929),depthFunc:(t,e)=>t.depthFunc(e),depthMask:(t,e)=>t.depthMask(e),depthRange:(t,e)=>t.depthRange(...e),dither:(t,e)=>e?t.enable(3024):t.disable(3024),derivativeHint:(t,e)=>{t.hint(35723,e)},frontFace:(t,e)=>t.frontFace(e),mipmapHint:(t,e)=>t.hint(33170,e),lineWidth:(t,e)=>t.lineWidth(e),polygonOffsetFill:(t,e)=>e?t.enable(32823):t.disable(32823),polygonOffset:(t,e)=>t.polygonOffset(...e),sampleCoverage:(t,e)=>t.sampleCoverage(e[0],e[1]||!1),scissorTest:(t,e)=>e?t.enable(3089):t.disable(3089),scissor:(t,e)=>t.scissor(...e),stencilTest:(t,e)=>e?t.enable(2960):t.disable(2960),stencilMask:(t,e)=>{e=jp(e)?e:[e,e];let[r,i]=e;t.stencilMaskSeparate(1028,r),t.stencilMaskSeparate(1029,i)},stencilFunc:(t,e)=>{e=jp(e)&&e.length===3?[...e,...e]:e;let[r,i,n,o,s,a]=e;t.stencilFuncSeparate(1028,r,i,n),t.stencilFuncSeparate(1029,o,s,a)},stencilOp:(t,e)=>{e=jp(e)&&e.length===3?[...e,...e]:e;let[r,i,n,o,s,a]=e;t.stencilOpSeparate(1028,r,i,n),t.stencilOpSeparate(1029,o,s,a)},viewport:(t,e)=>t.viewport(...e)};h1={blendEquation:(t,e,r)=>t.blendEquationSeparate(fe(32777,e,r),fe(34877,e,r)),blendFunc:(t,e,r)=>t.blendFuncSeparate(fe(32969,e,r),fe(32968,e,r),fe(32971,e,r),fe(32970,e,r)),polygonOffset:(t,e,r)=>t.polygonOffset(fe(32824,e,r),fe(10752,e,r)),sampleCoverage:(t,e,r)=>t.sampleCoverage(fe(32938,e,r),fe(32939,e,r)),stencilFuncFront:(t,e,r)=>t.stencilFuncSeparate(1028,fe(2962,e,r),fe(2967,e,r),fe(2963,e,r)),stencilFuncBack:(t,e,r)=>t.stencilFuncSeparate(1029,fe(34816,e,r),fe(36003,e,r),fe(36004,e,r)),stencilOpFront:(t,e,r)=>t.stencilOpSeparate(1028,fe(2964,e,r),fe(2965,e,r),fe(2966,e,r)),stencilOpBack:(t,e,r)=>t.stencilOpSeparate(1029,fe(34817,e,r),fe(34818,e,r),fe(34819,e,r))},$p={enable:(t,e)=>t({[e]:!0}),disable:(t,e)=>t({[e]:!1}),pixelStorei:(t,e,r)=>t({[e]:r}),hint:(t,e,r)=>t({[e]:r}),useProgram:(t,e)=>t({35725:e}),bindRenderbuffer:(t,e,r)=>t({36007:r}),bindTransformFeedback:(t,e,r)=>t({36389:r}),bindVertexArray:(t,e)=>t({34229:e}),bindFramebuffer:(t,e,r)=>{switch(e){case 36160:return t({36006:r,36010:r});case 36009:return t({36006:r});case 36008:return t({36010:r});default:return null}},bindBuffer:(t,e,r)=>{let i={34962:[34964],36662:[36662],36663:[36663],35051:[35053],35052:[35055]}[e];return i?t({[i]:r}):{valueChanged:!0}},blendColor:(t,e,r,i,n)=>t({32773:new Float32Array([e,r,i,n])}),blendEquation:(t,e)=>t({32777:e,34877:e}),blendEquationSeparate:(t,e,r)=>t({32777:e,34877:r}),blendFunc:(t,e,r)=>t({32969:e,32968:r,32971:e,32970:r}),blendFuncSeparate:(t,e,r,i,n)=>t({32969:e,32968:r,32971:i,32970:n}),clearColor:(t,e,r,i,n)=>t({3106:new Float32Array([e,r,i,n])}),clearDepth:(t,e)=>t({2931:e}),clearStencil:(t,e)=>t({2961:e}),colorMask:(t,e,r,i,n)=>t({3107:[e,r,i,n]}),cullFace:(t,e)=>t({2885:e}),depthFunc:(t,e)=>t({2932:e}),depthRange:(t,e,r)=>t({2928:new Float32Array([e,r])}),depthMask:(t,e)=>t({2930:e}),frontFace:(t,e)=>t({2886:e}),lineWidth:(t,e)=>t({2849:e}),polygonOffset:(t,e,r)=>t({32824:e,10752:r}),sampleCoverage:(t,e,r)=>t({32938:e,32939:r}),scissor:(t,e,r,i,n)=>t({3088:new Int32Array([e,r,i,n])}),stencilMask:(t,e)=>t({2968:e,36005:e}),stencilMaskSeparate:(t,e,r)=>t({[e===1028?2968:36005]:r}),stencilFunc:(t,e,r,i)=>t({2962:e,2967:r,2963:i,34816:e,36003:r,36004:i}),stencilFuncSeparate:(t,e,r,i,n)=>t({[e===1028?2962:34816]:r,[e===1028?2967:36003]:i,[e===1028?2963:36004]:n}),stencilOp:(t,e,r,i)=>t({2964:e,2965:r,2966:i,34817:e,34818:r,34819:i}),stencilOpSeparate:(t,e,r,i,n)=>t({[e===1028?2964:34817]:r,[e===1028?2965:34818]:i,[e===1028?2966:34819]:n}),viewport:(t,e,r,i,n)=>t({2978:[e,r,i,n]})},Vt=(t,e)=>t.isEnabled(e),Hp={3042:Vt,2884:Vt,2929:Vt,3024:Vt,32823:Vt,32926:Vt,32928:Vt,3089:Vt,2960:Vt,35977:Vt},p1=new Set([34016,36388,36387,35983,35368,34965,35739,35738,3074,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34866,34867,34868,35097,32873,35869,32874,34068])});function bt(t,e){if(N4(e))return;let r={};for(let n in e){let o=Number(n),s=d1[n];s&&(typeof s=="string"?r[s]=!0:s(t,e[n],o))}let i=t.lumaState?.cache;if(i)for(let n in r){let o=h1[n];o(t,e,i)}}function Ml(t,e=Ls){if(typeof e=="number"){let n=e,o=Hp[n];return o?o(t,n):t.getParameter(n)}let r=Array.isArray(e)?e:Object.keys(e),i={};for(let n of r){let o=Hp[n];i[n]=o?o(t,Number(n)):t.getParameter(Number(n))}return i}function g1(t){bt(t,Ls)}function N4(t){for(let e in t)return!1;return!0}var Nn=P(()=>{Yp()});function _1(t,e){if(t===e)return!0;if(m1(t)&&m1(e)&&t.length===e.length){for(let r=0;r{});function x1(t,e){let r=t[e].bind(t);t[e]=function(n){if(n===void 0||p1.has(n))return r(n);let o=Tt.get(t);return n in o.cache||(o.cache[n]=r(n)),o.enable?o.cache[n]:r(n)},Object.defineProperty(t[e],"name",{value:`${e}-from-cache`,configurable:!1})}function D4(t,e,r){if(!t[e])return;let i=t[e].bind(t);t[e]=function(...o){let s=Tt.get(t),{valueChanged:a,oldValue:c}=r(s._updateCache,...o);return a&&i(...o),c},Object.defineProperty(t[e],"name",{value:`${e}-to-cache`,configurable:!1})}function L4(t){let e=t.useProgram.bind(t);t.useProgram=function(i){let n=Tt.get(t);n.program!==i&&(e(i),n.program=i)}}var Tt,Xp=P(()=>{Nn();y1();Yp();Tt=class{static get(e){return e.lumaState}gl;program=null;stateStack=[];enable=!0;cache=null;log;initialized=!1;constructor(e,r){this.gl=e,this.log=r?.log||(()=>{}),this._updateCache=this._updateCache.bind(this),Object.seal(this)}push(e={}){this.stateStack.push({})}pop(){let e=this.stateStack[this.stateStack.length-1];bt(this.gl,e),this.stateStack.pop()}trackState(e,r){if(this.cache=r?.copyState?Ml(e):Object.assign({},Ls),this.initialized)throw new Error("WebGLStateTracker");this.initialized=!0,this.gl.lumaState=this,L4(e);for(let i in $p){let n=$p[i];D4(e,i,n)}x1(e,"getParameter"),x1(e,"isEnabled")}_updateCache(e){let r=!1,i,n=this.stateStack.length>0?this.stateStack[this.stateStack.length-1]:null;for(let o in e){let s=e[o],a=this.cache[o];_1(s,a)||(r=!0,i=a,n&&!(o in n)&&(n[o]=a),this.cache[o]=s)}return{valueChanged:r,oldValue:i}}}});function b1(t,e,r){let i="",n=c=>{let l=c.statusMessage;l&&(i||=l)};t.addEventListener("webglcontextcreationerror",n,!1);let o=r.failIfMajorPerformanceCaveat!==!0,s={preserveDrawingBuffer:!0,...r,failIfMajorPerformanceCaveat:!0},a=null;try{a||=t.getContext("webgl2",s),!a&&s.failIfMajorPerformanceCaveat&&(i||="Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow.");let c=!1;if(!a&&o&&(s.failIfMajorPerformanceCaveat=!1,a=t.getContext("webgl2",s),c=!0),a||(a=t.getContext("webgl",{}),a&&(a=null,i||="Your browser only supports WebGL1")),!a)throw i||="Your browser does not support WebGL",new Error(`Failed to create WebGL context: ${i}`);let l=Ii(a);l.softwareRenderer=c;let{onContextLost:f,onContextRestored:u}=e;return t.addEventListener("webglcontextlost",d=>f(d),!1),t.addEventListener("webglcontextrestored",d=>u(d),!1),a}finally{t.removeEventListener("webglcontextcreationerror",n,!1)}}var T1=P(()=>{Cl()});function wt(t,e,r){return r[e]===void 0&&(r[e]=t.getExtension(e)||null),r[e]}var Fs=P(()=>{});function w1(t,e){let r=t.getParameter(7936),i=t.getParameter(7937);wt(t,"WEBGL_debug_renderer_info",e);let n=e.WEBGL_debug_renderer_info,o=t.getParameter(n?n.UNMASKED_VENDOR_WEBGL:7936),s=t.getParameter(n?n.UNMASKED_RENDERER_WEBGL:7937),a=o||r,c=s||i,l=t.getParameter(7938),f=S1(a,c),u=F4(a,c),d=B4(a,c);return{type:"webgl",gpu:f,gpuType:d,gpuBackend:u,vendor:a,renderer:c,version:l,shadingLanguage:"glsl",shadingLanguageVersion:300}}function S1(t,e){return/NVIDIA/i.exec(t)||/NVIDIA/i.exec(e)?"nvidia":/INTEL/i.exec(t)||/INTEL/i.exec(e)?"intel":/Apple/i.exec(t)||/Apple/i.exec(e)?"apple":/AMD/i.exec(t)||/AMD/i.exec(e)||/ATI/i.exec(t)||/ATI/i.exec(e)?"amd":/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e)?"software":"unknown"}function F4(t,e){return/Metal/i.exec(t)||/Metal/i.exec(e)?"metal":/ANGLE/i.exec(t)||/ANGLE/i.exec(e)?"opengl":"unknown"}function B4(t,e){if(/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e))return"cpu";switch(S1(t,e)){case"apple":return k4(t,e)?"integrated":"unknown";case"intel":return"integrated";case"software":return"cpu";case"unknown":return"unknown";default:return"discrete"}}function k4(t,e){return/Apple (M\d|A\d|GPU)/i.test(`${t} ${e}`)}var A1=P(()=>{Fs()});function Il(t){switch(t){case"uint8":return 5121;case"sint8":return 5120;case"unorm8":return 5121;case"snorm8":return 5120;case"uint16":return 5123;case"sint16":return 5122;case"unorm16":return 5123;case"snorm16":return 5122;case"uint32":return 5125;case"sint32":return 5124;case"float16":return 5131;case"float32":return 5126}throw new Error(String(t))}var Gp=P(()=>{});function R1(t){return t in Nl}function Jp(t,e,r){return C1(t,e,r,new Set)}function C1(t,e,r,i){let n=Nl[e];if(!n||i.has(e))return!1;i.add(e);let o=(n.features||[]).every(s=>C1(t,s,r,i));return i.delete(e),o?(n.extensions||[]).every(s=>!!wt(t,s,r)):!1}function P1(t,e,r){let i=e.create,n=Dl[e.format];n?.gl===void 0&&(i=!1),n?.x&&(i=i&&!!wt(t,n.x,r)),e.format==="stencil8"&&(i=!1);let o=n?.r===!1?!1:n?.r===void 0||Jp(t,n.r,r),s=i&&e.render&&o&&Y4(t,e.format,r);return{format:e.format,create:i&&e.create,render:s,filter:i&&e.filter,blend:i&&e.blend,store:i&&e.store}}function Y4(t,e,r){let i=Dl[e],n=i?.gl;if(n===void 0||i?.x&&!wt(t,i.x,r))return!1;let o=t.getParameter(32873),s=t.getParameter(36006),a=t.createTexture(),c=t.createFramebuffer();if(!a||!c)return!1;let l=0,f=Number(t.getError());for(;f!==l;)f=t.getError();let u=!1;try{if(t.bindTexture(3553,a),t.texStorage2D(3553,1,n,1,1),Number(t.getError())!==l)return!1;t.bindFramebuffer(36160,c),t.framebufferTexture2D(36160,36064,3553,a,0),u=Number(t.checkFramebufferStatus(36160))===36053&&Number(t.getError())===l}finally{t.bindFramebuffer(36160,s),t.deleteFramebuffer(c),t.bindTexture(3553,o),t.deleteTexture(a)}return u}function Ll(t){let e=Dl[t],r=G4(t),i=Ue.getInfo(t);return i.compressed&&(e.dataFormat=r),{internalFormat:r,format:e?.dataFormat||X4(i.channels,i.integer,i.normalized,r),type:i.dataType?Il(i.dataType):e?.types?.[0]||5121,compressed:i.compressed||!1}}function M1(t){switch(Ue.getInfo(t).attachment){case"depth":return 36096;case"stencil":return 36128;case"depth-stencil":return 33306;default:throw new Error(`Not a depth stencil format: ${t}`)}}function X4(t,e,r,i){if(i===6408||i===6407)return i;switch(t){case"r":return e&&!r?36244:6403;case"rg":return e&&!r?33320:33319;case"rgb":return e&&!r?36248:6407;case"rgba":return e&&!r?36249:6408;case"bgra":throw new Error("bgra pixels not supported by WebGL");default:return 6408}}function G4(t){let r=Dl[t]?.gl;if(r===void 0)throw new Error(`Unsupported texture format ${t}`);return r}var Bs,ks,Dn,Ln,U4,z4,W4,V4,j4,$4,v1,E1,qp,Kp,Zp,Qp,Ol,H4,Nl,Dl,Fn=P(()=>{z();Fs();Gp();Bs="WEBGL_compressed_texture_s3tc",ks="WEBGL_compressed_texture_s3tc_srgb",Dn="EXT_texture_compression_rgtc",Ln="EXT_texture_compression_bptc",U4="WEBGL_compressed_texture_etc",z4="WEBGL_compressed_texture_astc",W4="WEBGL_compressed_texture_etc1",V4="WEBGL_compressed_texture_pvrtc",j4="WEBGL_compressed_texture_atc",$4="EXT_texture_norm16",v1="EXT_render_snorm",E1="EXT_color_buffer_float",qp="snorm8-renderable-webgl",Kp="norm16-renderable-webgl",Zp="snorm16-renderable-webgl",Qp="float16-renderable-webgl",Ol="float32-renderable-webgl",H4="rgb9e5ufloat-renderable-webgl",Nl={"float32-renderable-webgl":{extensions:[E1]},"float16-renderable-webgl":{extensions:["EXT_color_buffer_half_float"]},"rgb9e5ufloat-renderable-webgl":{extensions:["WEBGL_render_shared_exponent"]},"snorm8-renderable-webgl":{extensions:[v1]},"norm16-webgl":{extensions:[$4]},"norm16-renderable-webgl":{features:["norm16-webgl"]},"snorm16-renderable-webgl":{features:["norm16-webgl"],extensions:[v1]},"float32-filterable":{extensions:["OES_texture_float_linear"]},"float16-filterable-webgl":{extensions:["OES_texture_half_float_linear"]},"texture-filterable-anisotropic-webgl":{extensions:["EXT_texture_filter_anisotropic"]},"texture-blend-float-webgl":{extensions:["EXT_float_blend"]},"texture-compression-bc":{extensions:[Bs,ks,Dn,Ln]},"texture-compression-bc5-webgl":{extensions:[Dn]},"texture-compression-bc7-webgl":{extensions:[Ln]},"texture-compression-etc2":{extensions:[U4]},"texture-compression-astc":{extensions:[z4]},"texture-compression-etc1-webgl":{extensions:[W4]},"texture-compression-pvrtc-webgl":{extensions:[V4]},"texture-compression-atc-webgl":{extensions:[j4]}};Dl={r8unorm:{gl:33321,rb:!0},r8snorm:{gl:36756,r:qp},r8uint:{gl:33330,rb:!0},r8sint:{gl:33329,rb:!0},rg8unorm:{gl:33323,rb:!0},rg8snorm:{gl:36757,r:qp},rg8uint:{gl:33336,rb:!0},rg8sint:{gl:33335,rb:!0},r16uint:{gl:33332,rb:!0},r16sint:{gl:33331,rb:!0},r16float:{gl:33325,rb:!0,r:Qp},r16unorm:{gl:33322,rb:!0,r:Kp},r16snorm:{gl:36760,r:Zp},"rgba4unorm-webgl":{gl:32854,rb:!0},"rgb565unorm-webgl":{gl:36194,rb:!0},"rgb5a1unorm-webgl":{gl:32855,rb:!0},"rgb8unorm-webgl":{gl:32849},"rgb8snorm-webgl":{gl:36758},rgba8unorm:{gl:32856},"rgba8unorm-srgb":{gl:35907},rgba8snorm:{gl:36759,r:qp},rgba8uint:{gl:36220},rgba8sint:{gl:36238},bgra8unorm:{},"bgra8unorm-srgb":{},rg16uint:{gl:33338},rg16sint:{gl:33337},rg16float:{gl:33327,rb:!0,r:Qp},rg16unorm:{gl:33324,r:Kp},rg16snorm:{gl:36761,r:Zp},r32uint:{gl:33334,rb:!0},r32sint:{gl:33333,rb:!0},r32float:{gl:33326,r:Ol},rgb9e5ufloat:{gl:35901,r:H4},rg11b10ufloat:{gl:35898,rb:!0},rgb10a2unorm:{gl:32857,rb:!0},rgb10a2uint:{gl:36975,rb:!0},"rgb16unorm-webgl":{gl:32852,r:!1},"rgb16snorm-webgl":{gl:36762,r:!1},rg32uint:{gl:33340,rb:!0},rg32sint:{gl:33339,rb:!0},rg32float:{gl:33328,rb:!0,r:Ol},rgba16uint:{gl:36214,rb:!0},rgba16sint:{gl:36232,rb:!0},rgba16float:{gl:34842,r:Qp},rgba16unorm:{gl:32859,rb:!0,r:Kp},rgba16snorm:{gl:36763,r:Zp},"rgb32float-webgl":{gl:34837,x:E1,r:Ol,dataFormat:6407,types:[5126]},rgba32uint:{gl:36208,rb:!0},rgba32sint:{gl:36226,rb:!0},rgba32float:{gl:34836,rb:!0,r:Ol},stencil8:{gl:36168,rb:!0},depth16unorm:{gl:33189,dataFormat:6402,types:[5123],rb:!0},depth24plus:{gl:33190,dataFormat:6402,types:[5125]},depth32float:{gl:36012,dataFormat:6402,types:[5126],rb:!0},"depth24plus-stencil8":{gl:35056,rb:!0,depthTexture:!0,dataFormat:34041,types:[34042]},"depth32float-stencil8":{gl:36013,dataFormat:34041,types:[36269],rb:!0},"bc1-rgb-unorm-webgl":{gl:33776,x:Bs},"bc1-rgb-unorm-srgb-webgl":{gl:35916,x:ks},"bc1-rgba-unorm":{gl:33777,x:Bs},"bc1-rgba-unorm-srgb":{gl:35916,x:ks},"bc2-rgba-unorm":{gl:33778,x:Bs},"bc2-rgba-unorm-srgb":{gl:35918,x:ks},"bc3-rgba-unorm":{gl:33779,x:Bs},"bc3-rgba-unorm-srgb":{gl:35919,x:ks},"bc4-r-unorm":{gl:36283,x:Dn},"bc4-r-snorm":{gl:36284,x:Dn},"bc5-rg-unorm":{gl:36285,x:Dn},"bc5-rg-snorm":{gl:36286,x:Dn},"bc6h-rgb-ufloat":{gl:36495,x:Ln},"bc6h-rgb-float":{gl:36494,x:Ln},"bc7-rgba-unorm":{gl:36492,x:Ln},"bc7-rgba-unorm-srgb":{gl:36493,x:Ln},"etc2-rgb8unorm":{gl:37492},"etc2-rgb8unorm-srgb":{gl:37494},"etc2-rgb8a1unorm":{gl:37496},"etc2-rgb8a1unorm-srgb":{gl:37497},"etc2-rgba8unorm":{gl:37493},"etc2-rgba8unorm-srgb":{gl:37495},"eac-r11unorm":{gl:37488},"eac-r11snorm":{gl:37489},"eac-rg11unorm":{gl:37490},"eac-rg11snorm":{gl:37491},"astc-4x4-unorm":{gl:37808},"astc-4x4-unorm-srgb":{gl:37840},"astc-5x4-unorm":{gl:37809},"astc-5x4-unorm-srgb":{gl:37841},"astc-5x5-unorm":{gl:37810},"astc-5x5-unorm-srgb":{gl:37842},"astc-6x5-unorm":{gl:37811},"astc-6x5-unorm-srgb":{gl:37843},"astc-6x6-unorm":{gl:37812},"astc-6x6-unorm-srgb":{gl:37844},"astc-8x5-unorm":{gl:37813},"astc-8x5-unorm-srgb":{gl:37845},"astc-8x6-unorm":{gl:37814},"astc-8x6-unorm-srgb":{gl:37846},"astc-8x8-unorm":{gl:37815},"astc-8x8-unorm-srgb":{gl:37847},"astc-10x5-unorm":{gl:37816},"astc-10x5-unorm-srgb":{gl:37848},"astc-10x6-unorm":{gl:37817},"astc-10x6-unorm-srgb":{gl:37849},"astc-10x8-unorm":{gl:37818},"astc-10x8-unorm-srgb":{gl:37850},"astc-10x10-unorm":{gl:37819},"astc-10x10-unorm-srgb":{gl:37851},"astc-12x10-unorm":{gl:37820},"astc-12x10-unorm-srgb":{gl:37852},"astc-12x12-unorm":{gl:37821},"astc-12x12-unorm-srgb":{gl:37853},"pvrtc-rgb4unorm-webgl":{gl:35840},"pvrtc-rgba4unorm-webgl":{gl:35842},"pvrtc-rgb2unorm-webgl":{gl:35841},"pvrtc-rgba2unorm-webgl":{gl:35843},"etc1-rbg-unorm-webgl":{gl:36196},"atc-rgb-unorm-webgl":{gl:35986},"atc-rgba-unorm-webgl":{gl:35986},"atc-rgbai-unorm-webgl":{gl:34798}}});var I1,Fl,O1=P(()=>{z();Fs();Fn();I1={"depth-clip-control":"EXT_depth_clamp","timestamp-query":"EXT_disjoint_timer_query_webgl2","compilation-status-async-webgl":"KHR_parallel_shader_compile","polygon-mode-webgl":"WEBGL_polygon_mode","provoking-vertex-webgl":"WEBGL_provoking_vertex","shader-clip-cull-distance-webgl":"WEBGL_clip_cull_distance","shader-noperspective-interpolation-webgl":"NV_shader_noperspective_interpolation","shader-conservative-depth-webgl":"EXT_conservative_depth"},Fl=class extends Oo{gl;extensions;testedFeatures=new Set;constructor(e,r,i){super([],i),this.gl=e,this.extensions=r,wt(e,"EXT_color_buffer_float",r)}*[Symbol.iterator](){let e=this.getFeatures();for(let r of e)this.has(r)&&(yield r);return[]}has(e){return this.disabledFeatures?.[e]?!1:(this.testedFeatures.has(e)||(this.testedFeatures.add(e),R1(e)&&Jp(this.gl,e,this.extensions)&&this.features.add(e),this.getWebGLFeature(e)&&this.features.add(e)),this.features.has(e))}initializeFeatures(){let e=this.getFeatures().filter(r=>r!=="polygon-mode-webgl");for(let r of e)this.has(r)}getFeatures(){return[...Object.keys(I1),...Object.keys(Nl)]}getWebGLFeature(e){let r=I1[e];return typeof r=="string"?!!wt(this.gl,r,this.extensions):!!r}}});var Bl,N1=P(()=>{z();Bl=class extends Io{get maxTextureDimension1D(){return 0}get maxTextureDimension2D(){return this.getParameter(3379)}get maxTextureDimension3D(){return this.getParameter(32883)}get maxTextureArrayLayers(){return this.getParameter(35071)}get maxBindGroups(){return 0}get maxDynamicUniformBuffersPerPipelineLayout(){return 0}get maxDynamicStorageBuffersPerPipelineLayout(){return 0}get maxSampledTexturesPerShaderStage(){return this.getParameter(35660)}get maxSamplersPerShaderStage(){return this.getParameter(35661)}get maxStorageBuffersPerShaderStage(){return 0}get maxStorageTexturesPerShaderStage(){return 0}get maxUniformBuffersPerShaderStage(){return this.getParameter(35375)}get maxUniformBufferBindingSize(){return this.getParameter(35376)}get maxStorageBufferBindingSize(){return 0}get minUniformBufferOffsetAlignment(){return this.getParameter(35380)}get minStorageBufferOffsetAlignment(){return 0}get maxVertexBuffers(){return 16}get maxVertexAttributes(){return this.getParameter(34921)}get maxVertexBufferArrayStride(){return 2048}get maxInterStageShaderVariables(){return this.getParameter(35659)}get maxComputeWorkgroupStorageSize(){return 0}get maxComputeInvocationsPerWorkgroup(){return 0}get maxComputeWorkgroupSizeX(){return 0}get maxComputeWorkgroupSizeY(){return 0}get maxComputeWorkgroupSizeZ(){return 0}get maxComputeWorkgroupsPerDimension(){return 0}gl;limits={};constructor(e){super(),this.gl=e}getParameter(e){return this.limits[e]===void 0&&(this.limits[e]=this.gl.getParameter(e)),this.limits[e]||0}}});function q4(t){return t<34069?t+34069:t}function K4(t){switch(t){case 36053:return"success";case 36054:return"Mismatched attachments";case 36055:return"No attachments";case 36057:return"Height/width mismatch";case 36061:return"Unsupported or split attachments";case 36182:return"Samples mismatch";default:return`${t}`}}var jt,kl=P(()=>{z();Fn();jt=class extends mi{device;gl;handle;colorAttachments=[];depthStencilAttachment=null;constructor(e,r){super(e,r);let i=r.handle===null;this.device=e,this.gl=e.gl,this.handle=this.props.handle||i?this.props.handle:this.gl.createFramebuffer(),i||(e._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),r.handle||(this.autoCreateAttachmentTextures(),this.updateAttachments()))}destroy(){super.destroy(),!this.destroyed&&this.handle!==null&&!this.props.handle&&this.gl.deleteFramebuffer(this.handle)}updateAttachments(){let e=this.gl.bindFramebuffer(36160,this.handle);for(let r=0;r{z();kl();Ul=class extends Do{device;handle=null;_framebuffer=null;get[Symbol.toStringTag](){return"WebGLCanvasContext"}constructor(e,r){super(r),this.device=e,this._setAutoCreatedCanvasId(`${this.device.id}-canvas`),this._configureDevice()}_configureDevice(){(this.drawingBufferWidth!==this._framebuffer?.width||this.drawingBufferHeight!==this._framebuffer?.height)&&this._framebuffer?.resize([this.drawingBufferWidth,this.drawingBufferHeight])}_getCurrentFramebuffer(){return this._framebuffer||=new jt(this.device,{id:"canvas-context-framebuffer",handle:null,width:this.drawingBufferWidth,height:this.drawingBufferHeight}),this._framebuffer}}});var zl,L1=P(()=>{z();zl=class extends Lo{device;handle=null;context2d;get[Symbol.toStringTag](){return"WebGLPresentationContext"}constructor(e,r={}){super(r),this.device=e;let i=`${this[Symbol.toStringTag]}(${this.id})`;if(!this.device.getDefaultCanvasContext().offscreenCanvas)throw new Error(`${i}: WebGL PresentationContext requires the default CanvasContext canvas to be an OffscreenCanvas`);let o=this.canvas.getContext("2d");if(!o)throw new Error(`${i}: Failed to create 2d presentation context`);this.context2d=o,this._setAutoCreatedCanvasId(`${this.device.id}-presentation-canvas`),this._configureDevice(),this._startObservers()}present(){this._resizeDrawingBufferIfNeeded(),this.device.submit();let e=this.device.getDefaultCanvasContext(),[r,i]=e.getDrawingBufferSize();if(!(this.drawingBufferWidth===0||this.drawingBufferHeight===0||r===0||i===0||e.canvas.width===0||e.canvas.height===0)){if(r!==this.drawingBufferWidth||i!==this.drawingBufferHeight||e.canvas.width!==this.drawingBufferWidth||e.canvas.height!==this.drawingBufferHeight)throw new Error(`${this[Symbol.toStringTag]}(${this.id}): Default canvas context size ${r}x${i} does not match presentation size ${this.drawingBufferWidth}x${this.drawingBufferHeight}`);this.context2d.clearRect(0,0,this.drawingBufferWidth,this.drawingBufferHeight),this.context2d.drawImage(e.canvas,0,0)}}_configureDevice(){}_getCurrentFramebuffer(e){let r=this.device.getDefaultCanvasContext();return r.setDrawingBufferSize(this.drawingBufferWidth,this.drawingBufferHeight),r.getCurrentFramebuffer(e)}}});function F1(t="id"){eg[t]=eg[t]||1;let e=eg[t]++;return`${t}-${e}`}var eg,B1=P(()=>{eg={}});function Z4(t){return t&j.INDEX?34963:t&j.VERTEX?34962:t&j.UNIFORM?35345:34962}function Q4(t){return t&j.INDEX||t&j.VERTEX?35044:t&j.UNIFORM?35048:35044}var St,Wl=P(()=>{z();St=class extends j{device;gl;handle;glTarget;glUsage;glIndexType=5123;byteLength=0;bytesUsed=0;constructor(e,r={}){super(e,r),this.device=e,this.gl=this.device.gl;let i=typeof r=="object"?r.handle:void 0;this.handle=i||this.gl.createBuffer(),e._setWebGLDebugMetadata(this.handle,this,{spector:{...this.props,data:typeof this.props.data}}),this.glTarget=Z4(this.props.usage),this.glUsage=Q4(this.props.usage),this.glIndexType=this.props.indexType==="uint32"?5125:5123,r.data?this._initWithData(r.data,r.byteOffset,r.byteLength):this._initWithByteLength(r.byteLength||0)}destroy(){!this.destroyed&&this.handle&&(this.removeStats(),this.props.handle?this.trackDeallocatedReferencedMemory("Buffer"):(this.trackDeallocatedMemory(),this.gl.deleteBuffer(this.handle)),this.destroyed=!0,this.handle=null)}_initWithData(e,r=0,i=e.byteLength+r){let n=this.glTarget;this.gl.bindBuffer(n,this.handle),this.gl.bufferData(n,i,this.glUsage),this.gl.bufferSubData(n,r,e),this.gl.bindBuffer(n,null),this.bytesUsed=i,this.byteLength=i,this._setDebugData(e,r,i),this.props.handle?this.trackReferencedMemory(i,"Buffer"):this.trackAllocatedMemory(i)}_initWithByteLength(e){let r=e;e===0&&(r=new Float32Array(0));let i=this.glTarget;return this.gl.bindBuffer(i,this.handle),this.gl.bufferData(i,r,this.glUsage),this.gl.bindBuffer(i,null),this.bytesUsed=e,this.byteLength=e,this._setDebugData(null,0,e),this.props.handle?this.trackReferencedMemory(e,"Buffer"):this.trackAllocatedMemory(e),this}write(e,r=0){let i=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=0,o=void 0,s=36663;this.gl.bindBuffer(s,this.handle),n!==0||o!==void 0?this.gl.bufferSubData(s,r,i,n,o):this.gl.bufferSubData(s,r,i),this.gl.bindBuffer(s,null),this._setDebugData(e,r,e.byteLength)}async mapAndWriteAsync(e,r=0,i=this.byteLength-r){let n=new ArrayBuffer(i);await e(n,"copied"),this.write(n,r)}async readAsync(e=0,r){return this.readSyncWebGL(e,r)}async mapAndReadAsync(e,r=0,i){let n=await this.readAsync(r,i);return await e(n.buffer,"copied")}readSyncWebGL(e=0,r){r=r??this.byteLength-e;let i=new Uint8Array(r),n=0;return this.gl.bindBuffer(36662,this.handle),this.gl.getBufferSubData(36662,e,i,n,r),this.gl.bindBuffer(36662,null),this._setDebugData(i,e,r),i}}});function k1(t){let e=t.split(/\r?\n/),r=[];for(let i of e){if(i.length<=1)continue;let n=i.trim(),o=i.split(":"),s=o[0]?.trim();if(o.length===2){let[h,p]=o;if(!h||!p){r.push({message:n,type:Vl(s||"info"),lineNum:0,linePos:0});continue}r.push({message:p.trim(),type:Vl(h),lineNum:0,linePos:0});continue}let[a,c,l,...f]=o;if(!a||!c||!l){r.push({message:o.slice(1).join(":").trim()||n,type:Vl(s||"info"),lineNum:0,linePos:0});continue}let u=parseInt(l,10);Number.isNaN(u)&&(u=0);let d=parseInt(c,10);Number.isNaN(d)&&(d=0),r.push({message:f.join(":").trim(),type:Vl(a),lineNum:u,linePos:d})}return r}function Vl(t){let e=["warning","error","info"],r=t.toLowerCase();return e.includes(r)?r:"info"}var U1=P(()=>{});var jl,z1=P(()=>{z();U1();jl=class extends gi{device;handle;constructor(e,r){switch(super(e,r),this.device=e,this.props.stage){case"vertex":this.handle=this.props.handle||this.device.gl.createShader(35633);break;case"fragment":this.handle=this.props.handle||this.device.gl.createShader(35632);break;default:throw new Error(this.props.stage)}e._setWebGLDebugMetadata(this.handle,this,{spector:this.props});let i=this._compile(this.source);i&&typeof i.catch=="function"&&i.catch(()=>{this.compilationStatus="error"})}destroy(){this.handle&&(this.removeStats(),this.device.gl.deleteShader(this.handle),this.destroyed=!0,this.handle.destroyed=!0)}get asyncCompilationStatus(){return this._waitForCompilationComplete().then(()=>(this._getCompilationStatus(),this.compilationStatus))}async getCompilationInfo(){return await this._waitForCompilationComplete(),this.getCompilationInfoSync()}getCompilationInfoSync(){let e=this.device.gl.getShaderInfoLog(this.handle);return e?k1(e):[]}getTranslatedSource(){return this.device.getExtension("WEBGL_debug_shaders").WEBGL_debug_shaders?.getTranslatedShaderSource(this.handle)||null}_compile(e){e=e.startsWith("#version ")?e:`#version 300 es +${e}`;let{gl:r}=this.device;if(r.shaderSource(this.handle,e),r.compileShader(this.handle),!this.device.props.debug){this.compilationStatus="pending";return}if(!this.device.features.has("compilation-status-async-webgl")){if(this._getCompilationStatus(),this.debugShader(),this.compilationStatus==="error")throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`);return}return v.once(1,"Shader compilation is asynchronous")(),this._waitForCompilationComplete().then(()=>{v.info(2,`Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)(),this._getCompilationStatus(),this.debugShader()})}async _waitForCompilationComplete(){let e=async n=>await new Promise(o=>setTimeout(o,n));if(!this.device.features.has("compilation-status-async-webgl")){await e(10);return}let{gl:i}=this.device;for(;;){if(i.getShaderParameter(this.handle,37297))return;await e(10)}}_getCompilationStatus(){this.compilationStatus=this.device.gl.getShaderParameter(this.handle,35713)?"success":"error"}}});function V1(t,e,r,i){if(rN(e))return i(t);let n=t;n.pushState();try{return J4(t,e),bt(n.gl,r),i(t)}finally{n.popState()}}function J4(t,e){let r=t,{gl:i}=r;if(e.cullMode)switch(e.cullMode){case"none":i.disable(2884);break;case"front":i.enable(2884),i.cullFace(1028);break;case"back":i.enable(2884),i.cullFace(1029);break}if(e.frontFace&&i.frontFace(Oi("frontFace",e.frontFace,{ccw:2305,cw:2304})),e.unclippedDepth&&t.features.has("depth-clip-control")&&i.enable(34383),e.depthBias!==void 0&&(i.enable(32823),i.polygonOffset(e.depthBias,e.depthBiasSlopeScale||0)),e.provokingVertex&&t.features.has("provoking-vertex-webgl")){let o=r.getExtension("WEBGL_provoking_vertex").WEBGL_provoking_vertex,s=Oi("provokingVertex",e.provokingVertex,{first:36429,last:36430});o?.provokingVertexWEBGL(s)}if((e.polygonMode||e.polygonOffsetLine)&&t.features.has("polygon-mode-webgl")){if(e.polygonMode){let o=r.getExtension("WEBGL_polygon_mode").WEBGL_polygon_mode,s=Oi("polygonMode",e.polygonMode,{fill:6914,line:6913});o?.polygonModeWEBGL(1028,s),o?.polygonModeWEBGL(1029,s)}e.polygonOffsetLine&&i.enable(10754)}if(t.features.has("shader-clip-cull-distance-webgl")&&(e.clipDistance0&&i.enable(12288),e.clipDistance1&&i.enable(12289),e.clipDistance2&&i.enable(12290),e.clipDistance3&&i.enable(12291),e.clipDistance4&&i.enable(12292),e.clipDistance5&&i.enable(12293),e.clipDistance6&&i.enable(12294),e.clipDistance7&&i.enable(12295)),e.depthWriteEnabled!==void 0&&i.depthMask(tN("depthWriteEnabled",e.depthWriteEnabled)),e.depthCompare&&(e.depthCompare!=="always"?i.enable(2929):i.disable(2929),i.depthFunc(Hl("depthCompare",e.depthCompare))),e.clearDepth!==void 0&&i.clearDepth(e.clearDepth),e.stencilWriteMask){let n=e.stencilWriteMask;i.stencilMaskSeparate(1028,n),i.stencilMaskSeparate(1029,n)}if(e.stencilReadMask&&v.warn("stencilReadMask not supported under WebGL"),e.stencilCompare){let n=e.stencilReadMask||4294967295,o=Hl("depthCompare",e.stencilCompare);e.stencilCompare!=="always"?i.enable(2960):i.disable(2960),i.stencilFuncSeparate(1028,o,0,n),i.stencilFuncSeparate(1029,o,0,n)}if(e.stencilPassOperation&&e.stencilFailOperation&&e.stencilDepthFailOperation){let n=tg("stencilPassOperation",e.stencilPassOperation),o=tg("stencilFailOperation",e.stencilFailOperation),s=tg("stencilDepthFailOperation",e.stencilDepthFailOperation);i.stencilOpSeparate(1028,o,s,n),i.stencilOpSeparate(1029,o,s,n)}switch(e.blend){case!0:i.enable(3042);break;case!1:i.disable(3042);break;default:}if(e.blendColorOperation||e.blendAlphaOperation){let n=W1("blendColorOperation",e.blendColorOperation||"add"),o=W1("blendAlphaOperation",e.blendAlphaOperation||"add");i.blendEquationSeparate(n,o);let s=$l("blendColorSrcFactor",e.blendColorSrcFactor||"one"),a=$l("blendColorDstFactor",e.blendColorDstFactor||"zero"),c=$l("blendAlphaSrcFactor",e.blendAlphaSrcFactor||"one"),l=$l("blendAlphaDstFactor",e.blendAlphaDstFactor||"zero");i.blendFuncSeparate(s,a,c,l)}}function Hl(t,e){return Oi(t,e,{never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519})}function tg(t,e){return Oi(t,e,{keep:7680,zero:0,replace:7681,invert:5386,"increment-clamp":7682,"decrement-clamp":7683,"increment-wrap":34055,"decrement-wrap":34056})}function W1(t,e){return Oi(t,e,{add:32774,subtract:32778,"reverse-subtract":32779,min:32775,max:32776})}function $l(t,e,r="color"){return Oi(t,e,{one:1,zero:0,src:768,"one-minus-src":769,dst:774,"one-minus-dst":775,"src-alpha":770,"one-minus-src-alpha":771,"dst-alpha":772,"one-minus-dst-alpha":773,"src-alpha-saturated":776,constant:r==="color"?32769:32771,"one-minus-constant":r==="color"?32770:32772,src1:768,"one-minus-src1":769,"src1-alpha":770,"one-minus-src1-alpha":771})}function eN(t,e){return`Illegal parameter ${e} for ${t}`}function Oi(t,e,r){if(!(e in r))throw new Error(eN(t,e));return r[e]}function tN(t,e){return e}function rN(t){let e=!0;for(let r in t){e=!1;break}return e}var rg=P(()=>{z();Nn()});function Yl(t){let e={};return t.addressModeU&&(e[10242]=ig(t.addressModeU)),t.addressModeV&&(e[10243]=ig(t.addressModeV)),t.addressModeW&&(e[32882]=ig(t.addressModeW)),t.magFilter&&(e[10240]=ng(t.magFilter)),(t.minFilter||t.mipmapFilter)&&(e[10241]=iN(t.minFilter||"linear",t.mipmapFilter)),t.lodMinClamp!==void 0&&(e[33082]=t.lodMinClamp),t.lodMaxClamp!==void 0&&(e[33083]=t.lodMaxClamp),t.type==="comparison-sampler"&&(e[34892]=34894),t.compare&&(e[34893]=Hl("compare",t.compare)),t.maxAnisotropy&&(e[34046]=t.maxAnisotropy),e}function ig(t){switch(t){case"clamp-to-edge":return 33071;case"repeat":return 10497;case"mirror-repeat":return 33648}}function ng(t){switch(t){case"nearest":return 9728;case"linear":return 9729}}function iN(t,e="none"){if(!e)return ng(t);switch(e){case"none":return ng(t);case"nearest":switch(t){case"nearest":return 9984;case"linear":return 9985}break;case"linear":switch(t){case"nearest":return 9986;case"linear":return 9987}}}var og=P(()=>{rg()});var Xl,j1=P(()=>{z();og();Xl=class extends pt{device;handle;parameters;constructor(e,r){super(e,r),this.device=e,this.parameters=Yl(r),this.handle=r.handle||this.device.gl.createSampler(),this._setSamplerParameters(this.parameters)}destroy(){this.handle&&(this.device.gl.deleteSampler(this.handle),this.handle=void 0)}toString(){return`Sampler(${this.id},${JSON.stringify(this.props)})`}_setSamplerParameters(e){for(let[r,i]of Object.entries(e)){let n=Number(r);switch(n){case 33082:case 33083:this.device.gl.samplerParameterf(this.handle,n,i);break;default:this.device.gl.samplerParameteri(this.handle,n,i);break}}}}});function $t(t,e,r){if(nN(e))return r(t);let{nocatch:i=!0}=e,n=Tt.get(t);n.push(),bt(t,e);let o;if(i)o=r(t),n.pop();else try{o=r(t)}finally{n.pop()}return o}function nN(t){for(let e in t)return!1;return!0}var Gl=P(()=>{Nn();Xp()});var Ht,sg=P(()=>{z();Ht=class extends pi{device;gl;handle;texture;constructor(e,r){super(e,{...$.defaultProps,...r}),this.device=e,this.gl=this.device.gl,this.handle=null,this.texture=r.texture}}});function ql(t){return oN[t]}var oN,ag=P(()=>{oN={5124:"sint32",5125:"uint32",5122:"sint16",5123:"uint16",5120:"sint8",5121:"uint8",5126:"float32",5131:"float16",33635:"uint16",32819:"uint16",32820:"uint16",33640:"uint32",35899:"uint32",35902:"uint32",34042:"uint32",36269:"uint32"}});function sN(t,e=0){return e?new t.constructor(t.buffer,t.byteOffset+e,(t.byteLength-e)/t.BYTES_PER_ELEMENT):t}function aN(t,e){if(e%t.BYTES_PER_ELEMENT!==0)throw new Error(`Texture byteOffset ${e} must align to typed array element size ${t.BYTES_PER_ELEMENT}`);return e/t.BYTES_PER_ELEMENT}function cN(t){switch(t){case"1d":break;case"2d":return 3553;case"3d":return 32879;case"cube":return 34067;case"2d-array":return 35866;case"cube-array":break}throw new Error(t)}function Kl(t,e,r){return e==="cube"?34069+r:t}var Yt,Zl=P(()=>{z();Fn();og();Gl();sg();ag();Yt=class extends ${device;gl;handle;sampler=void 0;view;glTarget;glFormat;glType;glInternalFormat;compressed;_textureUnit=0;_framebuffer=null;_framebufferAttachmentKey=null;constructor(e,r){super(e,r,{byteAlignment:1}),this.device=e,this.gl=this.device.gl;let i=Ll(this.props.format);this.glTarget=cN(this.props.dimension),this.glInternalFormat=i.internalFormat,this.glFormat=i.format,this.glType=i.type,this.compressed=i.compressed,this.handle=this.props.handle||this.gl.createTexture(),this.device._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),this.gl.bindTexture(this.glTarget,this.handle);let{dimension:n,width:o,height:s,depth:a,mipLevels:c,glTarget:l,glInternalFormat:f}=this;if(!this.compressed)switch(n){case"2d":case"cube":this.gl.texStorage2D(l,c,f,o,s);break;case"2d-array":case"3d":this.gl.texStorage3D(l,c,f,o,s,a);break;default:throw new Error(n)}this.gl.bindTexture(this.glTarget,null),this._initializeData(r.data),this.props.handle?this.trackReferencedMemory(this.getAllocatedByteLength(),"Texture"):this.trackAllocatedMemory(this.getAllocatedByteLength(),"Texture"),this.setSampler(this.props.sampler),this.view=new Ht(this.device,{...this.props,texture:this}),Object.seal(this)}destroy(){this.handle&&(this._framebuffer?.destroy(),this._framebuffer=null,this._framebufferAttachmentKey=null,this.removeStats(),this.props.handle?this.trackDeallocatedReferencedMemory("Texture"):(this.gl.deleteTexture(this.handle),this.trackDeallocatedMemory("Texture")),this.destroyed=!0)}createView(e){return new Ht(this.device,{...e,texture:this})}setSampler(e={}){super.setSampler(e);let r=Yl(this.sampler.props);this._setSamplerParameters(r)}copyExternalImage(e){let r=this._normalizeCopyExternalImageOptions(e);if(r.sourceX||r.sourceY)throw new Error("WebGL does not support sourceX/sourceY)");let{glFormat:i,glType:n}=this,{image:o,depth:s,mipLevel:a,x:c,y:l,z:f,width:u,height:d}=r,h=Kl(this.glTarget,this.dimension,f),p=r.flipY?{37440:!0}:{};return this.gl.bindTexture(this.glTarget,this.handle),$t(this.gl,p,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(h,a,c,l,u,d,i,n,o);break;case"2d-array":case"3d":this.gl.texSubImage3D(h,a,c,l,f,u,d,s,i,n,o);break;default:}}),this.gl.bindTexture(this.glTarget,null),{width:r.width,height:r.height}}copyImageData(e){super.copyImageData(e)}readBuffer(e={},r){if(!r)throw new Error(`${this} readBuffer requires a destination buffer`);let i=this._getSupportedColorReadOptions(e),n=e.byteOffset??0,o=this.computeMemoryLayout(i);if(r.byteLength{this.gl.readPixels(i.x,i.y,i.width,i.height,this.glFormat,this.glType,n+a)})}finally{this.gl.bindBuffer(35051,null)}return r}async readDataAsync(e={}){throw new Error(`${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`)}writeBuffer(e,r={}){let i=this._normalizeTextureWriteOptions(r),{width:n,height:o,depthOrArrayLayers:s,mipLevel:a,byteOffset:c,x:l,y:f,z:u}=i,{glFormat:d,glType:h,compressed:p}=this,g=Kl(this.glTarget,this.dimension,u);if(p)throw new Error("writeBuffer for compressed textures is not implemented in WebGL");let{bytesPerPixel:m}=this.device.getTextureFormatInfo(this.format),_=m?i.bytesPerRow/m:void 0,T={3317:this.byteAlignment,..._!==void 0?{3314:_}:{},32878:i.rowsPerImage};this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,e.handle),$t(this.gl,T,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(g,a,l,f,n,o,d,h,c);break;case"2d-array":case"3d":this.gl.texSubImage3D(g,a,l,f,u,n,o,s,d,h,c);break;default:}}),this.gl.bindBuffer(35052,null),this.gl.bindTexture(this.glTarget,null)}writeData(e,r={}){let i=this._normalizeTextureWriteOptions(r),n=ArrayBuffer.isView(e)?e:new Uint8Array(e),{width:o,height:s,depthOrArrayLayers:a,mipLevel:c,x:l,y:f,z:u,byteOffset:d}=i,{glFormat:h,glType:p,compressed:g}=this,m=Kl(this.glTarget,this.dimension,u),_;if(!g){let{bytesPerPixel:E}=this.device.getTextureFormatInfo(this.format);E&&(_=i.bytesPerRow/E)}let T=this.compressed?{}:{3317:this.byteAlignment,..._!==void 0?{3314:_}:{},32878:i.rowsPerImage},y=aN(n,d),x=g?sN(n,d):n,w=this._getMipLevelSize(c),b=l===0&&f===0&&u===0&&o===w.width&&s===w.height&&a===w.depthOrArrayLayers;this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,null),$t(this.gl,T,()=>{switch(this.dimension){case"2d":case"cube":g?b?this.gl.compressedTexImage2D(m,c,h,o,s,0,x):this.gl.compressedTexSubImage2D(m,c,l,f,o,s,h,x):this.gl.texSubImage2D(m,c,l,f,o,s,h,p,n,y);break;case"2d-array":case"3d":g?b?this.gl.compressedTexImage3D(m,c,h,o,s,a,0,x):this.gl.compressedTexSubImage3D(m,c,l,f,u,o,s,a,h,x):this.gl.texSubImage3D(m,c,l,f,u,o,s,a,h,p,n,y);break;default:}}),this.gl.bindTexture(this.glTarget,null)}_getRowByteAlignment(e,r){return 1}_getFramebuffer(){return this._framebuffer||=this.device.createFramebuffer({id:`framebuffer-for-${this.id}`,width:this.width,height:this.height,colorAttachments:[this]}),this._framebuffer}readDataSyncWebGL(e={}){let r=this._getSupportedColorReadOptions(e),i=this.computeMemoryLayout(r),n=ql(this.glType),o=Go(n),s=new o(i.byteLength/o.BYTES_PER_ELEMENT);return this._readColorTextureLayers(r,i,a=>{let c=new o(s.buffer,s.byteOffset+a,i.bytesPerImage/o.BYTES_PER_ELEMENT);this.gl.readPixels(r.x,r.y,r.width,r.height,this.glFormat,this.glType,c)}),s.buffer}_readColorTextureLayers(e,r,i){let n=this._getFramebuffer(),o=r.bytesPerRow/r.bytesPerPixel,s={3333:this.byteAlignment,...o!==e.width?{3330:o}:{}},a=this.gl.getParameter(3074),c=this.gl.bindFramebuffer(36160,n.handle);try{this.gl.readBuffer(36064),$t(this.gl,s,()=>{for(let l=0;l{});function Y1(t){switch(t){case"point-list":return 0;case"line-list":return 1;case"line-strip":return 3;case"triangle-list":return 4;case"triangle-strip":return 5;default:throw new Error(t)}}function X1(t){switch(t){case"point-list":return 0;case"line-list":return 1;case"line-strip":return 1;case"triangle-list":return 4;case"triangle-strip":return 4;default:throw new Error(t)}}var cg=P(()=>{});function lN(t,e){let r={...t,attributes:t.attributes.map(i=>({...i})),bindings:t.bindings.map(i=>({...i}))};for(let i of e?.attributes||[]){let n=r.attributes.find(o=>o.name===i.name);n?(n.type=i.type||n.type,n.stepMode=i.stepMode||n.stepMode):v.warn(`shader layout attribute ${i.name} not present in shader`)}for(let i of e?.bindings||[]){let n=q1(r,i.name);if(!n){v.warn(`shader layout binding ${i.name} not present in shader`);continue}Object.assign(n,i)}return r}function q1(t,e){return t.bindings.find(r=>r.name===e||r.name===`${e}Uniforms`||`${r.name}Uniforms`===e)}function G1(t,e){return t[e]||t[`${e}Uniforms`]||t[e.replace(/Uniforms$/,"")]}var Ql,K1=P(()=>{z();rg();H1();Wl();kl();Zl();sg();cg();Ql=class extends st{device;handle;vs;fs;introspectedLayout;bindings={};uniforms={};varyings=null;_uniformCount=0;_uniformSetters={};get[Symbol.toStringTag](){return"WEBGLRenderPipeline"}constructor(e,r){super(e,r),this.device=e;let i=this.sharedRenderPipeline||this.device._createSharedRenderPipelineWebGL(r);this.sharedRenderPipeline=i,this.handle=i.handle,this.vs=i.vs,this.fs=i.fs,this.linkStatus=i.linkStatus,this.introspectedLayout=i.introspectedLayout,this.device._setWebGLDebugMetadata(this.handle,this,{spector:{id:this.props.id}}),this.shaderLayout=r.shaderLayout?lN(this.introspectedLayout,r.shaderLayout):this.introspectedLayout}destroy(){this.destroyed||(this.sharedRenderPipeline&&!this.props._sharedRenderPipeline&&this.sharedRenderPipeline.destroy(),this.destroyResource())}setBindings(e,r){let i=Uc(zo(this.shaderLayout,e));for(let[n,o]of Object.entries(i)){let s=q1(this.shaderLayout,n);if(s){switch(o||v.warn(`Unsetting binding "${n}" in render pipeline "${this.id}"`)(),s.type){case"uniform":if(!(o instanceof St)&&!(o.buffer instanceof St))throw new Error("buffer value");break;case"texture":if(!(o instanceof Ht||o instanceof Yt||o instanceof jt))throw new Error(`${this} Bad texture binding for ${n}`);break;case"sampler":v.warn(`Ignoring sampler ${n}`)();break;default:throw new Error(s.type)}this.bindings[n]=o}else{let a=this.shaderLayout.bindings.map(c=>`"${c.name}"`).join(", ");r?.disableWarnings||v.warn(`No binding "${n}" in render pipeline "${this.id}", expected one of ${a}`,o)()}}}draw(e){this._syncLinkStatus();let r=e.bindGroups?Uc(e.bindGroups):e.bindings||this.bindings,{renderPass:i,parameters:n=this.props.parameters,topology:o=this.props.topology,vertexArray:s,vertexCount:a,instanceCount:c,isInstanced:l=!1,firstVertex:f=0,transformFeedback:u,uniforms:d=this.uniforms}=e,h=Y1(o),p=!!s.indexBuffer,g=s.indexBuffer?.glIndexType;if(this.linkStatus!=="success")return v.info(2,`RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)(),!1;if(!this._areTexturesRenderable(r))return v.info(2,`RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)(),!1;this.device.gl.useProgram(this.handle),s.bindBeforeRender(i),u&&u.begin(this.props.topology),this._applyBindings(r,{disableWarnings:this.props.disableWarnings}),this._applyUniforms(d);let m=i;return V1(this.device,n,m.glParameters,()=>{p&&l?this.device.gl.drawElementsInstanced(h,a||0,g,f,c||0):p?this.device.gl.drawElements(h,a||0,g,f):l?this.device.gl.drawArraysInstanced(h,f,a||0,c||0):this.device.gl.drawArrays(h,f,a||0),u&&u.end()}),s.unbindAfterRender(i),!0}_areTexturesRenderable(e){let r=!0;for(let i of this.shaderLayout.bindings)G1(e,i.name)||(v.warn(`Binding ${i.name} not found in ${this.id}`)(),r=!1);return r}_applyBindings(e,r){if(this._syncLinkStatus(),this.linkStatus!=="success")return;let{gl:i}=this.device;i.useProgram(this.handle);let n=0,o=0;for(let s of this.shaderLayout.bindings){let a=G1(e,s.name);if(!a)throw new Error(`No value for binding ${s.name} in ${this.id}`);switch(s.type){case"uniform":let{name:c}=s,l=i.getUniformBlockIndex(this.handle,c);if(l===4294967295)throw new Error(`Invalid uniform block name ${c}`);if(i.uniformBlockBinding(this.handle,l,o),a instanceof St)i.bindBufferBase(35345,o,a.handle);else{let u=a;i.bindBufferRange(35345,o,u.buffer.handle,u.offset||0,u.size||u.buffer.byteLength-(u.offset||0))}o+=1;break;case"texture":if(!(a instanceof Ht||a instanceof Yt||a instanceof jt))throw new Error("texture");let f;if(a instanceof Ht)f=a.texture;else if(a instanceof Yt)f=a;else if(a instanceof jt&&a.colorAttachments[0]instanceof Ht)v.warn("Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead")(),f=a.colorAttachments[0].texture;else throw new Error("No texture");i.activeTexture(33984+n),i.bindTexture(f.glTarget,f.handle),n+=1;break;case"sampler":break;case"storage":case"read-only-storage":throw new Error(`binding type '${s.type}' not supported in WebGL`)}}}_applyUniforms(e){for(let r of this.shaderLayout.uniforms||[]){let{name:i,location:n,type:o,textureUnit:s}=r,a=e[i]??s;a!==void 0&&$1(this.device.gl,n,o,a)}}_syncLinkStatus(){this.linkStatus=this.sharedRenderPipeline.linkStatus}}});function Z1(t){return uN[t]}function Jl(t){return fN[t]}function ef(t){return!!J1[t]}function Q1(t){return J1[t]}var fN,J1,uN,tf=P(()=>{fN={5126:"f32",35664:"vec2",35665:"vec3",35666:"vec4",5124:"i32",35667:"vec2",35668:"vec3",35669:"vec4",5125:"u32",36294:"vec2",36295:"vec3",36296:"vec4",35670:"f32",35671:"vec2",35672:"vec3",35673:"vec4",35674:"mat2x2",35685:"mat2x3",35686:"mat2x4",35687:"mat3x2",35675:"mat3x3",35688:"mat3x4",35689:"mat4x2",35690:"mat4x3",35676:"mat4x4"},J1={35678:{viewDimension:"2d",sampleType:"float"},35680:{viewDimension:"cube",sampleType:"float"},35679:{viewDimension:"3d",sampleType:"float"},35682:{viewDimension:"3d",sampleType:"depth"},36289:{viewDimension:"2d-array",sampleType:"float"},36292:{viewDimension:"2d-array",sampleType:"depth"},36293:{viewDimension:"cube",sampleType:"float"},36298:{viewDimension:"2d",sampleType:"sint"},36299:{viewDimension:"3d",sampleType:"sint"},36300:{viewDimension:"cube",sampleType:"sint"},36303:{viewDimension:"2d-array",sampleType:"uint"},36306:{viewDimension:"2d",sampleType:"uint"},36307:{viewDimension:"3d",sampleType:"uint"},36308:{viewDimension:"cube",sampleType:"uint"},36311:{viewDimension:"2d-array",sampleType:"uint"}},uN={uint8:5121,sint8:5120,unorm8:5121,snorm8:5120,uint16:5123,sint16:5122,unorm16:5123,snorm16:5122,uint32:5125,sint32:5124,float16:5131,float32:5126}});function eT(t,e){let r={attributes:[],bindings:[]};r.attributes=dN(t,e);let i=gN(t,e);for(let a of i){let c=a.uniforms.map(l=>({name:l.name,format:l.format,byteOffset:l.byteOffset,byteStride:l.byteStride,arrayLength:l.arrayLength}));r.bindings.push({type:"uniform",name:a.name,group:0,location:a.location,visibility:(a.vertex?1:0)&(a.fragment?2:0),minBindingSize:a.byteLength,uniforms:c})}let n=pN(t,e),o=0;for(let a of n)if(ef(a.type)){let{viewDimension:c,sampleType:l}=Q1(a.type);r.bindings.push({type:"texture",name:a.name,group:0,location:o,viewDimension:c,sampleType:l}),a.textureUnit=o,o+=1}n.length&&(r.uniforms=n);let s=hN(t,e);return s?.length&&(r.varyings=s),r}function dN(t,e){let r=[],i=t.getProgramParameter(e,35721);for(let n=0;n=0){let l=Jl(a),f=/instance/i.test(s)?"instance":"vertex";r.push({name:s,location:c,stepMode:f,type:l})}}return r.sort((n,o)=>n.location-o.location),r}function hN(t,e){let r=[],i=t.getProgramParameter(e,35971);for(let n=0;nn.location-o.location),r}function pN(t,e){let r=[],i=t.getProgramParameter(e,35718);for(let n=0;n1)for(let h=0;ht.getActiveUniformBlockParameter(e,o,s),i=[],n=t.getProgramParameter(e,35382);for(let o=0;op.name.split(".")[0]).filter(p=>!!p)),h=s.name.replace(/Uniforms$/,"");if(d.size===1&&!d.has(s.name)&&!d.has(h)){let[p]=d;v.warn(`Uniform block "${s.name}" uses GLSL instance "${p}". luma.gl binds uniform buffers by block name ("${s.name}") and alias ("${h}"). Prefer matching the instance name to one of those to avoid confusing silent mismatches.`)()}i.push(s)}return i.sort((o,s)=>o.location-s.location),i}function mN(t){if(t[t.length-1]!=="]")return{name:t,length:1,isArray:!1};let r=/([^[]*)(\[[0-9]+\])?/.exec(t);return{name:hi(r?.[1],`Failed to parse GLSL uniform name ${t}`),length:r?.[2]?1:0,isArray:!!r?.[2]}}var tT=P(()=>{z();tf()});var rT,rf,iT=P(()=>{z();tT();tf();rT=4,rf=class extends Fo{device;handle;vs;fs;introspectedLayout={attributes:[],bindings:[],uniforms:[]};linkStatus="pending";constructor(e,r){super(e,r),this.device=e,this.handle=r.handle||this.device.gl.createProgram(),this.vs=r.vs,this.fs=r.fs,r.varyings&&r.varyings.length>0&&this.device.gl.transformFeedbackVaryings(this.handle,r.varyings,r.bufferMode||35981),this._linkShaders(),v.time(3,`RenderPipeline ${this.id} - shaderLayout introspection`)(),this.introspectedLayout=eT(this.device.gl,this.handle),v.timeEnd(3,`RenderPipeline ${this.id} - shaderLayout introspection`)()}destroy(){this.destroyed||(this.device.gl.useProgram(null),this.device.gl.deleteProgram(this.handle),this.handle.destroyed=!0,this.destroyResource())}async _linkShaders(){let{gl:e}=this.device;if(e.attachShader(this.handle,this.vs.handle),e.attachShader(this.handle,this.fs.handle),v.time(rT,`linkProgram for ${this.id}`)(),e.linkProgram(this.handle),v.timeEnd(rT,`linkProgram for ${this.id}`)(),!this.device.features.has("compilation-status-async-webgl")){let i=this._getLinkStatus();this._reportLinkStatus(i);return}v.once(1,"RenderPipeline linking is asynchronous")(),await this._waitForLinkComplete(),v.info(2,`RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();let r=this._getLinkStatus();this._reportLinkStatus(r)}async _reportLinkStatus(e){switch(e){case"success":return;default:let r=e==="link-error"?"Link error":"Validation error";switch(this.vs.compilationStatus){case"error":throw this.vs.debugShader(),new Error(`${this} ${r} during compilation of ${this.vs}`);case"pending":await this.vs.asyncCompilationStatus,this.vs.debugShader();break;case"success":break}switch(this.fs?.compilationStatus){case"error":throw this.fs.debugShader(),new Error(`${this} ${r} during compilation of ${this.fs}`);case"pending":await this.fs.asyncCompilationStatus,this.fs.debugShader();break;case"success":break}let i=this.device.gl.getProgramInfoLog(this.handle);this.device.reportError(new Error(`${r} during ${e}: ${i}`),this)(),this.device.debug()}}_getLinkStatus(){let{gl:e}=this.device;return e.getProgramParameter(this.handle,35714)?(this._initializeSamplerUniforms(),e.validateProgram(this.handle),e.getProgramParameter(this.handle,35715)?(this.linkStatus="success","success"):(this.linkStatus="error","validation-error")):(this.linkStatus="error","link-error")}_initializeSamplerUniforms(){let{gl:e}=this.device;e.useProgram(this.handle);let r=0,i=e.getProgramParameter(this.handle,35718);for(let n=0;n1){let s=Int32Array.from({length:r.size},(a,c)=>n+c);return o.uniform1iv(e,s),n+r.size}return o.uniform1i(e,n),n+1}async _waitForLinkComplete(){let e=async n=>await new Promise(o=>setTimeout(o,n));if(!this.device.features.has("compilation-status-async-webgl")){await e(10);return}let{gl:i}=this.device;for(;;){if(i.getProgramParameter(this.handle,37297))return;await e(10)}}}});function _N(t,e){let r=e.sourceBuffer,i=e.destinationBuffer;t.gl.bindBuffer(36662,r.handle),t.gl.bindBuffer(36663,i.handle),t.gl.copyBufferSubData(36662,36663,e.sourceOffset??0,e.destinationOffset??0,e.size),t.gl.bindBuffer(36662,null),t.gl.bindBuffer(36663,null)}function yN(t,e){throw new Error("copyBufferToTexture is not supported in WebGL")}function xN(t,e){let{sourceTexture:r,mipLevel:i=0,aspect:n="all",width:o=e.sourceTexture.width,height:s=e.sourceTexture.height,depthOrArrayLayers:a,origin:c=[0,0,0],destinationBuffer:l,byteOffset:f=0,bytesPerRow:u,rowsPerImage:d}=e;if(r instanceof $){r.readBuffer({x:c[0]??0,y:c[1]??0,z:c[2]??0,width:o,height:s,depthOrArrayLayers:a,mipLevel:i,aspect:n,byteOffset:f},l);return}if(n!=="all")throw new Error("aspect not supported in WebGL");if(i!==0||a!==void 0||u||d)throw new Error("not implemented");let{framebuffer:h,destroyFramebuffer:p}=nT(r),g;try{let m=l,_=o||h.width,T=s||h.height,y=hi(h.colorAttachments[0]),x=Ll(y.texture.props.format),w=x.format,b=x.type;t.gl.bindBuffer(35051,m.handle),g=t.gl.bindFramebuffer(36160,h.handle),t.gl.readPixels(c[0],c[1],_,T,w,b,f)}finally{t.gl.bindBuffer(35051,null),g!==void 0&&t.gl.bindFramebuffer(36160,g),p&&h.destroy()}}function bN(t,e){let{sourceTexture:r,destinationMipLevel:i=0,origin:n=[0,0],destinationOrigin:o=[0,0,0],destinationTexture:s}=e,{width:a=e.destinationTexture.width,height:c=e.destinationTexture.height}=e,{framebuffer:l,destroyFramebuffer:f}=nT(r),[u=0,d=0]=n,[h,p,g]=o,m=t.gl.bindFramebuffer(36160,l.handle),_,T;if(s instanceof Yt)_=s,a=Number.isFinite(a)?a:_.width,c=Number.isFinite(c)?c:_.height,_._bind(0),T=_.glTarget;else throw new Error("invalid destination");switch(T){case 3553:case 34067:t.gl.copyTexSubImage2D(T,i,h,p,u,d,a,c);break;case 35866:case 32879:t.gl.copyTexSubImage3D(T,i,h,p,g,u,d,a,c);break;default:}_&&_._unbind(),t.gl.bindFramebuffer(36160,m),f&&l.destroy()}function nT(t){if(t instanceof $){let{width:e,height:r,id:i}=t;return{framebuffer:t.device.createFramebuffer({id:`framebuffer-for-${i}`,width:e,height:r,colorAttachments:[t]}),destroyFramebuffer:!0}}return{framebuffer:t,destroyFramebuffer:!1}}var nf,oT=P(()=>{z();Fn();Zl();nf=class extends jo{device;handle=null;commands=[];constructor(e,r={}){super(e,r),this.device=e}_executeCommands(e=this.commands){for(let r of e)switch(r.name){case"copy-buffer-to-buffer":_N(this.device,r.options);break;case"copy-buffer-to-texture":yN(this.device,r.options);break;case"copy-texture-to-buffer":xN(this.device,r.options);break;case"copy-texture-to-texture":bN(this.device,r.options);break;default:throw new Error(r.name)}}}});var TN,of,sT=P(()=>{z();Gl();Nn();TN=[1,2,4,8],of=class extends Wo{device;handle=null;glParameters={};constructor(e,r){super(e,r),this.device=e;let i=this.props.framebuffer,n=!i||i.handle===null;n&&e.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded();let o;if(!r?.parameters?.viewport)if(!n&&i){let{width:s,height:a}=i;o=[0,0,s,a]}else{let[s,a]=e.getDefaultCanvasContext().getDrawingBufferSize();o=[0,0,s,a]}if(this.device.pushState(),this.setParameters({viewport:o,...this.props.parameters}),!n&&i?.colorAttachments.length){let s=i.colorAttachments.map((a,c)=>36064+c);this.device.gl.drawBuffers(s)}else n&&this.device.gl.drawBuffers([1029]);this.clear(),this.props.timestampQuerySet&&this.props.beginTimestampIndex!==void 0&&this.props.timestampQuerySet.writeTimestamp(this.props.beginTimestampIndex)}end(){this.destroyed||(this.props.timestampQuerySet&&this.props.endTimestampIndex!==void 0&&this.props.timestampQuerySet.writeTimestamp(this.props.endTimestampIndex),this.device.popState(),this.destroy())}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}setParameters(e={}){let r={...this.glParameters};r.framebuffer=this.props.framebuffer||null,this.props.depthReadOnly&&(r.depthMask=!this.props.depthReadOnly),r.stencilMask=this.props.stencilReadOnly?0:1,r[35977]=this.props.discard,e.viewport&&(e.viewport.length>=6?(r.viewport=e.viewport.slice(0,4),r.depthRange=[e.viewport[4],e.viewport[5]]):r.viewport=e.viewport),e.scissorRect&&(r.scissorTest=!0,r.scissor=e.scissorRect),e.blendConstant&&(r.blendColor=e.blendConstant),e.stencilReference!==void 0&&(r[2967]=e.stencilReference,r[36003]=e.stencilReference),"colorMask"in e&&(r.colorMask=TN.map(i=>!!(i&e.colorMask))),this.glParameters=r,bt(this.device.gl,r)}beginOcclusionQuery(e){this.props.occlusionQuerySet?.beginOcclusionQuery()}endOcclusionQuery(){this.props.occlusionQuerySet?.endOcclusionQuery()}clear(){let e={...this.glParameters},r=0;this.props.clearColors&&this.props.clearColors.forEach((i,n)=>{i&&this.clearColorBuffer(n,i)}),this.props.clearColor!==!1&&this.props.clearColors===void 0&&(r|=16384,e.clearColor=this.props.clearColor),this.props.clearDepth!==!1&&(r|=256,e.clearDepth=this.props.clearDepth),this.props.clearStencil!==!1&&(r|=1024,e.clearStencil=this.props.clearStencil),r!==0&&$t(this.device.gl,e,()=>{this.device.gl.clear(r)})}clearColorBuffer(e=0,r=[0,0,0,0]){$t(this.device.gl,{framebuffer:this.props.framebuffer},()=>{switch(r.constructor){case Int8Array:case Int16Array:case Int32Array:this.device.gl.clearBufferiv(6144,e,r);break;case Uint8Array:case Uint8ClampedArray:case Uint16Array:case Uint32Array:this.device.gl.clearBufferuiv(6144,e,r);break;case Float32Array:this.device.gl.clearBufferfv(6144,e,r);break;default:throw new Error("clearColorBuffer: color must be typed array")}})}}});var Us,aT=P(()=>{z();oT();sT();Us=class extends Vo{device;handle=null;commandBuffer;constructor(e,r){super(e,r),this.device=e,this.commandBuffer=new nf(e,{id:`${this.props.id}-command-buffer`})}destroy(){this.destroyResource()}finish(e){return e?.id&&this.commandBuffer.id!==e.id&&(this.commandBuffer.id=e.id,this.commandBuffer.props.id=e.id),this.destroy(),this.commandBuffer}beginRenderPass(e={}){return new of(this.device,this._applyTimeProfilingToPassProps(e))}beginComputePass(e={}){throw new Error("ComputePass not supported in WebGL")}copyBufferToBuffer(e){this.commandBuffer.commands.push({name:"copy-buffer-to-buffer",options:e})}copyBufferToTexture(e){this.commandBuffer.commands.push({name:"copy-buffer-to-texture",options:e})}copyTextureToBuffer(e){this.commandBuffer.commands.push({name:"copy-texture-to-buffer",options:e})}copyTextureToTexture(e){this.commandBuffer.commands.push({name:"copy-texture-to-texture",options:e})}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}resolveQuerySet(e,r,i){throw new Error("resolveQuerySet is not supported in WebGL")}writeTimestamp(e,r){e.writeTimestamp(r)}}});function cT(t){let{target:e,source:r,start:i=0,count:n=1}=t,o=r.length,s=n*o,a=0;for(let c=i;a{});function wN(t){return Array.isArray(t)?new Float32Array(t):t}function SN(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let r=0;r{z();Rr();Gp();lT();sf=class t extends $o{get[Symbol.toStringTag](){return"VertexArray"}device;handle;buffer=null;bufferValue=null;static isConstantAttributeZeroSupported(e){return Du()==="Chrome"}constructor(e,r){super(e,r),this.device=e,this.handle=this.device.gl.createVertexArray()}destroy(){super.destroy(),this.buffer&&this.buffer?.destroy(),this.handle&&(this.device.gl.deleteVertexArray(this.handle),this.handle=void 0)}setIndexBuffer(e){let r=e;if(r&&r.glTarget!==34963)throw new Error("Use .setBuffer()");this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34963,r?r.handle:null),this.indexBuffer=r,this.device.gl.bindVertexArray(null)}setBuffer(e,r){let i=r;if(i.glTarget===34963)throw new Error("Use .setIndexBuffer()");let{size:n,type:o,stride:s,offset:a,normalized:c,integer:l,divisor:f}=this._getAccessor(e);this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34962,i.handle),l?this.device.gl.vertexAttribIPointer(e,n,o,s,a):this.device.gl.vertexAttribPointer(e,n,o,c,s,a),this.device.gl.bindBuffer(34962,null),this.device.gl.enableVertexAttribArray(e),this.device.gl.vertexAttribDivisor(e,f||0),this.attributes[e]=i,this.device.gl.bindVertexArray(null)}setConstantWebGL(e,r){this._enable(e,!1),this.attributes[e]=r}bindBeforeRender(){this.device.gl.bindVertexArray(this.handle),this._applyConstantAttributes()}unbindAfterRender(){this.device.gl.bindVertexArray(null)}_applyConstantAttributes(){for(let e=0;e{z();cf();cg();af=class extends Ho{device;gl;handle;layout;buffers={};unusedBuffers={};bindOnUse=!0;_bound=!1;constructor(e,r){super(e,r),this.device=e,this.gl=e.gl,this.handle=this.props.handle||this.gl.createTransformFeedback(),this.layout=this.props.layout,r.buffers&&this.setBuffers(r.buffers),Object.seal(this)}destroy(){this.gl.deleteTransformFeedback(this.handle),super.destroy()}begin(e="point-list"){this.gl.bindTransformFeedback(36386,this.handle),this.bindOnUse&&this._bindBuffers(),this.gl.beginTransformFeedback(X1(e))}end(){this.gl.endTransformFeedback(),this.bindOnUse&&this._unbindBuffers(),this.gl.bindTransformFeedback(36386,null)}setBuffers(e){this.buffers={},this.unusedBuffers={},this.bind(()=>{for(let[r,i]of Object.entries(e))this.setBuffer(r,i)})}setBuffer(e,r){let i=this._getVaryingIndex(e),{buffer:n,byteLength:o,byteOffset:s}=this._getBufferRange(r);if(i<0){this.unusedBuffers[e]=n,v.warn(`${this.id} unusedBuffers varying buffer ${e}`)();return}this.buffers[i]={buffer:n,byteLength:o,byteOffset:s},this.bindOnUse||this._bindBuffer(i,n,s,o)}getBuffer(e){if(uT(e))return this.buffers[e]||null;let r=this._getVaryingIndex(e);return this.buffers[r]??null}bind(e=this.handle){if(typeof e!="function")return this.gl.bindTransformFeedback(36386,e),this;let r;return this._bound?r=e():(this.gl.bindTransformFeedback(36386,this.handle),this._bound=!0,r=e(),this._bound=!1,this.gl.bindTransformFeedback(36386,null)),r}unbind(){this.bind(null)}_getBufferRange(e){if(e instanceof St)return{buffer:e,byteOffset:0,byteLength:e.byteLength};let{buffer:r,byteOffset:i=0,byteLength:n=e.buffer.byteLength}=e;return{buffer:r,byteOffset:i,byteLength:n}}_getVaryingIndex(e){if(uT(e))return Number(e);for(let r of this.layout.varyings||[])if(e===r.name)return r.location;return-1}_bindBuffers(){for(let[e,r]of Object.entries(this.buffers)){let{buffer:i,byteLength:n,byteOffset:o}=this._getBufferRange(r);this._bindBuffer(Number(e),i,o,n)}}_unbindBuffers(){for(let e in this.buffers)this.gl.bindBufferBase(35982,Number(e),null)}_bindBuffer(e,r,i=0,n){let o=r&&r.handle;!o||n===void 0?this.gl.bindBufferBase(35982,e,o):this.gl.bindBufferRange(35982,e,o,i,n)}}});var lf,hT=P(()=>{z();lf=class extends Yo{device;handle;_timestampPairs=[];_pendingReads=new Set;_occlusionQuery=null;_occlusionActive=!1;get[Symbol.toStringTag](){return"QuerySet"}constructor(e,r){if(super(e,r),this.device=e,r.type==="timestamp"){if(r.count<2)throw new Error("Timestamp QuerySet requires at least two query slots");this._timestampPairs=new Array(Math.ceil(r.count/2)).fill(null).map(()=>({activeQuery:null,completedQueries:[]})),this.handle=null}else{if(r.count>1)throw new Error("WebGL occlusion QuerySet can only have one value");let i=this.device.gl.createQuery();if(!i)throw new Error("WebGL query not supported");this.handle=i}Object.seal(this)}destroy(){if(!this.destroyed){this.handle&&this.device.gl.deleteQuery(this.handle);for(let e of this._timestampPairs){e.activeQuery&&(this._cancelPendingQuery(e.activeQuery),this.device.gl.deleteQuery(e.activeQuery.handle));for(let r of e.completedQueries)this._cancelPendingQuery(r),this.device.gl.deleteQuery(r.handle)}this._occlusionQuery&&(this._cancelPendingQuery(this._occlusionQuery),this.device.gl.deleteQuery(this._occlusionQuery.handle));for(let e of Array.from(this._pendingReads))this._cancelPendingQuery(e);this.destroyResource()}}isResultAvailable(e){return this.props.type==="timestamp"?e===void 0?this._timestampPairs.some((r,i)=>this._isTimestampPairAvailable(i)):this._isTimestampPairAvailable(this._getTimestampPairIndex(e)):this._occlusionQuery?this._pollQueryAvailability(this._occlusionQuery):!1}async readResults(e){let r=e?.firstQuery||0,i=e?.queryCount||this.props.count-r;if(this._validateRange(r,i),this.props.type==="timestamp"){let n=new Array(i).fill(0n),o=Math.floor(r/2),s=Math.floor((r+i-1)/2);for(let a=o;a<=s;a++){let c=await this._consumeTimestampPairResult(a),l=a*2,f=l+1;l>=r&&l=r&&f=this.props.count||r<=e)throw new Error("Timestamp duration range is out of bounds");if(e%2!==0||r!==e+1)throw new Error("WebGL timestamp durations require adjacent even/odd query indices");let i=await this._consumeTimestampPairResult(this._getTimestampPairIndex(e));return Number(i)/1e6}beginOcclusionQuery(){if(this.props.type!=="occlusion")throw new Error("Occlusion queries require an occlusion QuerySet");if(!this.handle)throw new Error("WebGL occlusion query is not available");if(this._occlusionActive)throw new Error("Occlusion query is already active");this.device.gl.beginQuery(35887,this.handle),this._occlusionQuery={handle:this.handle,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null},this._occlusionActive=!0}endOcclusionQuery(){if(!this._occlusionActive)throw new Error("Occlusion query is not active");this.device.gl.endQuery(35887),this._occlusionActive=!1}writeTimestamp(e){if(this.props.type!=="timestamp")throw new Error("Timestamp writes require a timestamp QuerySet");let r=this._getTimestampPairIndex(e),i=this._timestampPairs[r];if(e%2===0){if(i.activeQuery)throw new Error("Timestamp query pair is already active");let n=this.device.gl.createQuery();if(!n)throw new Error("WebGL query not supported");let o={handle:n,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null};this.device.gl.beginQuery(35007,n),i.activeQuery=o;return}if(!i.activeQuery)throw new Error("Timestamp query pair was ended before it was started");this.device.gl.endQuery(35007),i.completedQueries.push(i.activeQuery),i.activeQuery=null}_validateRange(e,r){if(e<0||r<0||e+r>this.props.count)throw new Error("Query read range is out of bounds")}_getTimestampPairIndex(e){if(e<0||e>=this.props.count)throw new Error("Query index is out of bounds");return Math.floor(e/2)}_isTimestampPairAvailable(e){let r=this._timestampPairs[e];return!r||r.completedQueries.length===0?!1:this._pollQueryAvailability(r.completedQueries[0])}_pollQueryAvailability(e){if(e.cancelled||this.destroyed)return e.result=0n,!0;if(e.result!==null||e.disjoint)return!0;if(!this.device.gl.getQueryParameter(e.handle,34919))return!1;let i=!!this.device.gl.getParameter(36795);return e.disjoint=i,e.result=i?0n:BigInt(this.device.gl.getQueryParameter(e.handle,34918)),!0}async _consumeTimestampPairResult(e){let r=this._timestampPairs[e];if(!r||r.completedQueries.length===0)throw new Error("Timestamp query pair has no completed result");let i=r.completedQueries.shift();try{return await this._consumeQueryResult(i)}finally{this.device.gl.deleteQuery(i.handle)}}_consumeQueryResult(e){return e.promise||(this._pendingReads.add(e),e.promise=new Promise((r,i)=>{e.resolve=r,e.reject=i;let n=()=>{if(e.pollRequestId=null,e.cancelled||this.destroyed){this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,r(0n);return}if(!this._pollQueryAvailability(e)){e.pollRequestId=this._requestAnimationFrame(n);return}this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,e.disjoint?i(new Error("GPU timestamp query was invalidated by a disjoint event")):r(e.result||0n)};n()})),e.promise}_cancelPendingQuery(e){if(this._pendingReads.delete(e),e.cancelled=!0,e.pollRequestId!==null&&(this._cancelAnimationFrame(e.pollRequestId),e.pollRequestId=null),e.resolve){let r=e.resolve;e.promise=null,e.resolve=null,e.reject=null,r(0n)}}_requestAnimationFrame(e){return requestAnimationFrame(e)}_cancelAnimationFrame(e){cancelAnimationFrame(e)}}});var ff,pT=P(()=>{z();ff=class extends Xo{device;gl;handle;signaled;_signaled=!1;constructor(e,r={}){super(e,{}),this.device=e,this.gl=e.gl;let i=this.props.handle||this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE,0);if(!i)throw new Error("Failed to create WebGL fence");this.handle=i,this.signaled=new Promise(n=>{let o=()=>{let s=this.gl.clientWaitSync(this.handle,0,0);s===this.gl.ALREADY_SIGNALED||s===this.gl.CONDITION_SATISFIED?(this._signaled=!0,n()):setTimeout(o,1)};o()})}isSignaled(){if(this._signaled)return!0;let e=this.gl.getSyncParameter(this.handle,this.gl.SYNC_STATUS);return this._signaled=e===this.gl.SIGNALED,this._signaled}destroy(){this.destroyed||this.gl.deleteSync(this.handle)}}});function lg(t){switch(t){case 6406:case 33326:case 6403:case 36244:return 1;case 33339:case 33340:case 33328:case 33320:case 33319:return 2;case 6407:case 36248:case 34837:return 3;case 6408:case 36249:case 34836:return 4;default:return 0}}function gT(t){switch(t){case 5121:return 1;case 33635:case 32819:case 32820:return 2;case 5126:return 4;default:return 0}}var mT=P(()=>{});function _T(t,e){let{sourceX:r=0,sourceY:i=0,sourceAttachment:n=0}=e||{},{target:o=null,sourceWidth:s,sourceHeight:a,sourceDepth:c,sourceFormat:l,sourceType:f}=e||{},{framebuffer:u,deleteFramebuffer:d}=xT(t),{gl:h,handle:p}=u;s||=u.width,a||=u.height;let g=u.colorAttachments[n]?.texture;if(!g)throw new Error(`Invalid framebuffer attachment ${n}`);c=g?.depth||1,l||=g?.glFormat||6408,f||=g?.glType||5121,o=vN(o,f,l,s,a,c);let m=ke.getDataType(o);f=f||Z1(m);let _=h.bindFramebuffer(36160,p);return h.readBuffer(36064+n),h.readPixels(r,i,s,a,l,f,o),h.readBuffer(36064),h.bindFramebuffer(36160,_||null),d&&u.destroy(),o}function yT(t,e){let{target:r,sourceX:i=0,sourceY:n=0,sourceFormat:o=6408,targetByteOffset:s=0}=e||{},{sourceWidth:a,sourceHeight:c,sourceType:l}=e||{},{framebuffer:f,deleteFramebuffer:u}=xT(t);a=a||f.width,c=c||f.height;let d=f;l=l||5121;let h=r;if(!h){let g=lg(o),m=gT(l),_=s+a*c*g*m;h=d.device.createBuffer({byteLength:_})}let p=t.device.createCommandEncoder();return p.copyTextureToBuffer({sourceTexture:t,width:a,height:c,origin:[i,n],destinationBuffer:h,byteOffset:s}),p.destroy(),u&&f.destroy(),h}function xT(t){return t instanceof mi?{framebuffer:t,deleteFramebuffer:!1}:{framebuffer:AN(t),deleteFramebuffer:!0}}function AN(t,e){let{device:r,width:i,height:n,id:o}=t;return r.createFramebuffer({...e,id:`framebuffer-for-${o}`,width:i,height:n,colorAttachments:[t]})}function vN(t,e,r,i,n,o){if(t)return t;e||=5121;let s=ql(e),a=ke.getTypedArrayConstructor(s),c=lg(r);return new a(i*n*c)}var bT=P(()=>{z();tf();mT();ag()});var fg={};Zi(fg,{WebGLDevice:()=>jr});function EN(t,e,r){switch(r.length){case 1:t.gl.vertexAttrib1fv(e,r);break;case 2:t.gl.vertexAttrib2fv(e,r);break;case 3:t.gl.vertexAttrib3fv(e,r);break;case 4:t.gl.vertexAttrib4fv(e,r);break;default:}}function RN(t,e,r){t.gl.vertexAttribI4iv(e,r)}function CN(t,e,r){t.gl.vertexAttribI4uiv(e,r)}function PN(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let r=0;r{z();Xp();T1();Cl();A1();O1();N1();D1();L1();Wp();Vp();Fn();B1();Wl();z1();j1();Zl();kl();K1();iT();aT();fT();dT();hT();pT();bT();Nn();Gl();Fs();jr=class t extends ht{static getDeviceFromContext(e){return e?e.luma?.device??null:null}type="webgl";handle;features;limits;info;canvasContext;preferredColorFormat="rgba8unorm";preferredDepthFormat="depth24plus";commandEncoder;lost;_resolveContextLost;gl;_constants;extensions;_polyfilled=!1;spectorJS;get[Symbol.toStringTag](){return"WebGLDevice"}toString(){return`${this[Symbol.toStringTag]}(${this.id})`}isVertexFormatSupported(e){return e!=="unorm8x4-bgra"}constructor(e){super({...e,id:e.id||F1("webgl-device")});let r=ht._getCanvasContextProps(e);if(!r)throw new Error("WebGLDevice requires props.createCanvasContext to be set");let i=r.canvas?.gl??null,n=t.getDeviceFromContext(i);if(n)throw new Error(`WebGL context already attached to device ${n.id}`);this.canvasContext=new Ul(this,r),this.lost=new Promise(f=>{this._resolveContextLost=f});let o={...e.webgl};r.alphaMode==="premultiplied"&&(o.premultipliedAlpha=!0),e.powerPreference!==void 0&&(o.powerPreference=e.powerPreference),e.failIfMajorPerformanceCaveat!==void 0&&(o.failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat);let a=this.props._handle||b1(this.canvasContext.canvas,{onContextLost:f=>this._resolveContextLost?.({reason:"destroyed",message:"Entered sleep mode, or too many apps or browser tabs are using the GPU."}),onContextRestored:f=>console.log("WebGL context restored")},o);if(!a)throw new Error("WebGL context creation failed");if(n=t.getDeviceFromContext(a),n){if(e._reuseDevices)return v.log(1,`Not creating a new Device, instead returning a reference to Device ${n.id} already attached to WebGL context`,n)(),this.canvasContext.destroy(),n._reused=!0,n;throw new Error(`WebGL context already attached to device ${n.id}`)}this.handle=a,this.gl=a,this.spectorJS=o1({...this.props,gl:this.handle});let c=Ii(this.handle);c.device=this,c.extensions||(c.extensions={}),this.extensions=c.extensions,this.info=w1(this.gl,this.extensions),this.limits=new Bl(this.gl),this.features=new Fl(this.gl,this.extensions,this.props._disabledFeatures),this.props._initializeFeatures&&this.features.initializeFeatures(),new Tt(this.gl,{log:(...f)=>v.log(1,...f)()}).trackState(this.gl,{copyState:!1}),(e.debug||e.debugWebGL)&&(this.gl=l1(this.gl,{debugWebGL:!0,traceWebGL:e.debugWebGL}),v.warn("WebGL debug mode activated. Performance reduced.")()),e.debugWebGL&&(v.level=Math.max(v.level,1)),this.commandEncoder=new Us(this,{id:`${this}-command-encoder`}),this.canvasContext._startObservers()}destroy(){if(this.commandEncoder?.destroy(),!this.props._reuseDevices&&!this._reused){let e=Ii(this.handle);e.device=null}}get isLost(){return this.gl.isContextLost()}createCanvasContext(e){throw new Error("WebGL only supports a single canvas")}createPresentationContext(e){return new zl(this,e||{})}createBuffer(e){let r=this._normalizeBufferProps(e);return new St(this,r)}createTexture(e){return new Yt(this,e)}createExternalTexture(e){throw new Error("createExternalTexture() not implemented")}createSampler(e){return new Xl(this,e)}createShader(e){return new jl(this,e)}createFramebuffer(e){return new jt(this,e)}createVertexArray(e){return new sf(this,e)}createTransformFeedback(e){return new af(this,e)}createQuerySet(e){return new lf(this,e)}createFence(){return new ff(this)}createRenderPipeline(e){return new Ql(this,e)}_createSharedRenderPipelineWebGL(e){return new rf(this,e)}createComputePipeline(e){throw new Error("ComputePipeline not supported in WebGL")}createCommandEncoder(e={}){return new Us(this,e)}submit(e){let r=null;e||({submittedCommandEncoder:r,commandBuffer:e}=this._finalizeDefaultCommandEncoderForSubmit());try{e._executeCommands(),r&&r.resolveTimeProfilingQuerySet().then(()=>{this.commandEncoder._gpuTimeMs=r._gpuTimeMs}).catch(()=>{})}finally{e.destroy()}}_finalizeDefaultCommandEncoderForSubmit(){let e=this.commandEncoder,r=e.finish();return this.commandEncoder.destroy(),this.commandEncoder=this.createCommandEncoder({id:e.props.id,timeProfilingQuerySet:e.getTimeProfilingQuerySet()}),{submittedCommandEncoder:e,commandBuffer:r}}readPixelsToArrayWebGL(e,r){return _T(e,r)}readPixelsToBufferWebGL(e,r){return yT(e,r)}setParametersWebGL(e){bt(this.gl,e)}getParametersWebGL(e){return Ml(this.gl,e)}withParametersWebGL(e,r){return $t(this.gl,e,r)}resetWebGL(){v.warn("WebGLDevice.resetWebGL is deprecated, use only for debugging")(),g1(this.gl)}_getDeviceSpecificTextureFormatCapabilities(e){return P1(this.gl,e,this.extensions)}loseDevice(){let e=!1,i=this.getExtension("WEBGL_lose_context").WEBGL_lose_context;return i&&(e=!0,i.loseContext()),this._resolveContextLost?.({reason:"destroyed",message:"Application triggered context loss"}),e}pushState(){Tt.get(this.gl).push()}popState(){Tt.get(this.gl).pop()}getGLKey(e,r){let i=Number(e);for(let n in this.gl)if(this.gl[n]===i)return`GL.${n}`;return r?.emptyIfUnknown?"":String(e)}getGLKeys(e){let r={emptyIfUnknown:!0};return Object.entries(e).reduce((i,[n,o])=>(i[`${n}:${this.getGLKey(n,r)}`]=`${o}:${this.getGLKey(o,r)}`,i),{})}setConstantAttributeWebGL(e,r){let i=this.limits.maxVertexAttributes;this._constants=this._constants||new Array(i).fill(null);let n=this._constants[e];switch(n&&PN(n,r)&&v.info(1,`setConstantAttributeWebGL(${e}) could have been skipped, value unchanged`)(),this._constants[e]=r,r.constructor){case Float32Array:EN(this,e,r);break;case Int32Array:RN(this,e,r);break;case Uint32Array:CN(this,e,r);break;default:throw new Error("constant")}}getExtension(e){return wt(this.gl,e,this.extensions),this.extensions}_setWebGLDebugMetadata(e,r,i){e.luma=r;let n={props:i.spector,id:i.spector.id};e.__SPECTOR_Metadata=n}}});function MN(t){return typeof WebGL2RenderingContext<"u"&&t instanceof WebGL2RenderingContext?!0:!!(t&&typeof t.createVertexArray=="function")}var zs,ug,Ws,TT=P(()=>{z();r1();Wp();Vp();zs=1,ug=class extends No{type="webgl";constructor(){super(),ht.defaultProps={...ht.defaultProps,...Pl}}enforceWebGL2(e){t1(e)}isSupported(){return typeof WebGL2RenderingContext<"u"}isDeviceHandle(e){return typeof WebGL2RenderingContext<"u"&&e instanceof WebGL2RenderingContext?!0:(typeof WebGLRenderingContext<"u"&&e instanceof WebGLRenderingContext&&v.warn("WebGL1 is not supported",e)(),!1)}async attach(e,r={}){let{WebGLDevice:i}=await Promise.resolve().then(()=>(uf(),fg));if(e instanceof i)return e;let n=i.getDeviceFromContext(e);if(n)return n;if(!MN(e))throw new Error("Invalid WebGL2RenderingContext");let o=r.createCanvasContext===!0?{}:r.createCanvasContext;return new i({...r,_handle:e,createCanvasContext:{canvas:e.canvas,autoResize:!1,...o}})}async create(e={}){let{WebGLDevice:r}=await Promise.resolve().then(()=>(uf(),fg)),i=[];(e.debugWebGL||e.debug)&&i.push(c1()),e.debugSpectorJS&&i.push(n1(e));let n=await Promise.allSettled(i);for(let o of n)o.status==="rejected"&&v.error(`Failed to initialize debug libraries ${o.reason}`)();try{let o=new r(e);v.groupCollapsed(zs,`WebGLDevice ${o.id} created`)();let s=`${o._reused?"Reusing":"Created"} device with WebGL2 ${o.props.debug?"debug ":""}context: ${o.info.vendor}, ${o.info.renderer} for canvas: ${o.canvasContext.id}`;return v.probe(zs,s)(),v.table(zs,o.info)(),o}finally{v.groupEnd(zs)(),v.info(zs,"%cWebGL call tracing: luma.log.set('debug-webgl') ","color: white; background: blue; padding: 2px 6px; border-radius: 3px;")()}}};Ws=new ug});var cf=P(()=>{TT();uf();Wl()});var cv=er((av,Dm)=>{(function(t,e,r){function i(a){var c=this,l=s();c.next=function(){var f=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=f-(c.c=f|0)},c.c=1,c.s0=l(" "),c.s1=l(" "),c.s2=l(" "),c.s0-=l(a),c.s0<0&&(c.s0+=1),c.s1-=l(a),c.s1<0&&(c.s1+=1),c.s2-=l(a),c.s2<0&&(c.s2+=1),l=null}function n(a,c){return c.c=a.c,c.s0=a.s0,c.s1=a.s1,c.s2=a.s2,c}function o(a,c){var l=new i(a),f=c&&c.state,u=l.next;return u.int32=function(){return l.next()*4294967296|0},u.double=function(){return u()+(u()*2097152|0)*11102230246251565e-32},u.quick=u,f&&(typeof f=="object"&&n(f,l),u.state=function(){return n(l,{})}),u}function s(){var a=4022871197,c=function(l){l=String(l);for(var f=0;f>>0,u-=a,u*=a,a=u>>>0,u-=a,a+=u*4294967296}return(a>>>0)*23283064365386963e-26};return c}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(av,typeof Dm=="object"&&Dm,typeof define=="function"&&define)});var fv=er((lv,Lm)=>{(function(t,e,r){function i(s){var a=this,c="";a.x=0,a.y=0,a.z=0,a.w=0,a.next=function(){var f=a.x^a.x<<11;return a.x=a.y,a.y=a.z,a.z=a.w,a.w^=a.w>>>19^f^f>>>8},s===(s|0)?a.x=s:c+=s;for(var l=0;l>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(lv,typeof Lm=="object"&&Lm,typeof define=="function"&&define)});var dv=er((uv,Fm)=>{(function(t,e,r){function i(s){var a=this,c="";a.next=function(){var f=a.x^a.x>>>2;return a.x=a.y,a.y=a.z,a.z=a.w,a.w=a.v,(a.d=a.d+362437|0)+(a.v=a.v^a.v<<4^(f^f<<1))|0},a.x=0,a.y=0,a.z=0,a.w=0,a.v=0,s===(s|0)?a.x=s:c+=s;for(var l=0;l>>4),a.next()}function n(s,a){return a.x=s.x,a.y=s.y,a.z=s.z,a.w=s.w,a.v=s.v,a.d=s.d,a}function o(s,a){var c=new i(s),l=a&&a.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(uv,typeof Fm=="object"&&Fm,typeof define=="function"&&define)});var pv=er((hv,Bm)=>{(function(t,e,r){function i(s){var a=this;a.next=function(){var l=a.x,f=a.i,u,d,h;return u=l[f],u^=u>>>7,d=u^u<<24,u=l[f+1&7],d^=u^u>>>10,u=l[f+3&7],d^=u^u>>>3,u=l[f+4&7],d^=u^u<<7,u=l[f+7&7],u=u^u<<13,d^=u^u<<9,l[f]=d,a.i=f+1&7,d};function c(l,f){var u,d,h=[];if(f===(f|0))d=h[0]=f;else for(f=""+f,u=0;u0;--u)l.next()}c(a,s)}function n(s,a){return a.x=s.x.slice(),a.i=s.i,a}function o(s,a){s==null&&(s=+new Date);var c=new i(s),l=a&&a.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(l.x&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(hv,typeof Bm=="object"&&Bm,typeof define=="function"&&define)});var mv=er((gv,km)=>{(function(t,e,r){function i(s){var a=this;a.next=function(){var l=a.w,f=a.X,u=a.i,d,h;return a.w=l=l+1640531527|0,h=f[u+34&127],d=f[u=u+1&127],h^=h<<13,d^=d<<17,h^=h>>>15,d^=d>>>12,h=f[u]=h^d,a.i=u,h+(l^l>>>16)|0};function c(l,f){var u,d,h,p,g,m=[],_=128;for(f===(f|0)?(d=f,f=null):(f=f+"\0",d=0,_=Math.max(_,f.length)),h=0,p=-32;p<_;++p)f&&(d^=f.charCodeAt((p+32)%f.length)),p===0&&(g=d),d^=d<<10,d^=d>>>15,d^=d<<4,d^=d>>>13,p>=0&&(g=g+1640531527|0,u=m[p&127]^=d+g,h=u==0?h+1:0);for(h>=128&&(m[(f&&f.length||0)&127]=-1),h=127,p=512;p>0;--p)d=m[h+34&127],u=m[h=h+1&127],d^=d<<13,u^=u<<17,d^=d>>>15,u^=u>>>12,m[h]=d^u;l.w=g,l.X=m,l.i=h}c(a,s)}function n(s,a){return a.i=s.i,a.w=s.w,a.X=s.X.slice(),a}function o(s,a){s==null&&(s=+new Date);var c=new i(s),l=a&&a.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(l.X&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(gv,typeof km=="object"&&km,typeof define=="function"&&define)});var yv=er((_v,Um)=>{(function(t,e,r){function i(s){var a=this,c="";a.next=function(){var f=a.b,u=a.c,d=a.d,h=a.a;return f=f<<25^f>>>7^u,u=u-d|0,d=d<<24^d>>>8^h,h=h-f|0,a.b=f=f<<20^f>>>12^u,a.c=u=u-d|0,a.d=d<<16^u>>>16^h,a.a=h-f|0},a.a=0,a.b=0,a.c=-1640531527,a.d=1367130551,s===Math.floor(s)?(a.a=s/4294967296|0,a.b=s|0):c+=s;for(var l=0;l>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(_v,typeof Um=="object"&&Um,typeof define=="function"&&define)});var xv=er(()=>{});var Tv=er((bv,wu)=>{(function(t,e,r){var i=256,n=6,o=52,s="random",a=r.pow(i,n),c=r.pow(2,o),l=c*2,f=i-1,u;function d(y,x,w){var b=[];x=x==!0?{entropy:!0}:x||{};var E=m(g(x.entropy?[y,T(e)]:y??_(),3),b),S=new h(b),A=function(){for(var C=S.g(n),I=a,R=0;C=l;)C/=2,I/=2,R>>>=1;return(C+R)/I};return A.int32=function(){return S.g(4)|0},A.quick=function(){return S.g(4)/4294967296},A.double=A,m(T(S.S),e),(x.pass||w||function(C,I,R,N){return N&&(N.S&&p(N,S),C.state=function(){return p(S,{})}),R?(r[s]=C,I):C})(A,E,"global"in x?x.global:this==r,x.state)}function h(y){var x,w=y.length,b=this,E=0,S=b.i=b.j=0,A=b.S=[];for(w||(y=[w++]);E{var _B=cv(),yB=fv(),xB=dv(),bB=pv(),TB=mv(),wB=yv(),Xi=Tv();Xi.alea=_B;Xi.xor128=yB;Xi.xorwow=xB;Xi.xorshift7=bB;Xi.xor4096=TB;Xi.tychei=wB;wv.exports=Xi});function Er(t,e){if(!t)throw new Error(e||"loader assertion failed.")}var Ct={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},A2=Ct.self||Ct.window||Ct.global||{},v2=Ct.window||Ct.self||Ct.global||{},E2=Ct.global||Ct.self||Ct.window||{},R2=Ct.document||{};var ni=!!(typeof process!="object"||String(process)!=="[object process]"||process.browser);var Jm=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),C2=Jm&&parseFloat(Jm[1])||0;lo();var zu="4.4.2",F2=zu[0]>="0"&&zu[0]<="9"?`v${zu}`:"";function B2(){let t=new Le({id:"loaders.gl"});return globalThis.loaders||={},globalThis.loaders.log=t,globalThis.loaders.version=F2,globalThis.probe||={},globalThis.probe.loaders=t,t}var Wu=B2();var k2=t=>typeof t=="boolean",Pt=t=>typeof t=="function",Mt=t=>t!==null&&typeof t=="object",nc=t=>Mt(t)&&t.constructor==={}.constructor;var Vu=t=>typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer,tn=t=>Mt(t)&&typeof t.byteLength=="number"&&typeof t.slice=="function";var ju=t=>!!t&&Pt(t[Symbol.iterator]),$u=t=>!!t&&Pt(t[Symbol.asyncIterator]);var Ge=t=>typeof Response<"u"&&t instanceof Response||Mt(t)&&Pt(t.arrayBuffer)&&Pt(t.text)&&Pt(t.json);var qe=t=>typeof Blob<"u"&&t instanceof Blob;var m_=t=>typeof ReadableStream<"u"&&t instanceof ReadableStream||Mt(t)&&Pt(t.tee)&&Pt(t.cancel)&&Pt(t.getReader);var __=t=>Mt(t)&&Pt(t.read)&&Pt(t.pipe)&&k2(t.readable),fo=t=>m_(t)||__(t);function Hu(t,e){return y_(t||{},e)}function y_(t,e,r=0){if(r>3)return e;let i={...t};for(let[n,o]of Object.entries(e))o&&typeof o=="object"&&!Array.isArray(o)?i[n]=y_(i[n]||{},e[n],r+1):i[n]=e[n];return i}var x_="latest";function U2(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.4.2"),globalThis._loadersgl_.version}var b_=U2();function Fe(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}var It={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},Xk=It.self||It.window||It.global||{},Gk=It.window||It.self||It.global||{},qk=It.global||It.self||It.window||{},Kk=It.document||{};var rt=typeof process!="object"||String(process)!=="[object process]"||process.browser;var w_=typeof window<"u"&&typeof window.orientation<"u",T_=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),Zk=T_&&parseFloat(T_[1])||0;var uo=class{name;workerThread;isRunning=!0;result;_resolve=()=>{};_reject=()=>{};constructor(e,r){this.name=e,this.workerThread=r,this.result=new Promise((i,n)=>{this._resolve=i,this._reject=n})}postMessage(e,r){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:r})}done(e){Fe(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){Fe(this.isRunning),this.isRunning=!1,this._reject(e)}};var rn=class{terminate(){}};var Yu=new Map;function S_(t){Fe(t.source&&!t.url||!t.source&&t.url);let e=Yu.get(t.source||t.url);return e||(t.url&&(e=z2(t.url),Yu.set(t.url,e)),t.source&&(e=A_(t.source),Yu.set(t.source,e))),Fe(e),e}function z2(t){if(!t.startsWith("http"))return t;let e=W2(t);return A_(e)}function A_(t){let e=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(e)}function W2(t){return`try { + importScripts('${t}'); +} catch (error) { + console.error(error); + throw error; +}`}function Xu(t,e=!0,r){let i=r||new Set;if(t){if(v_(t))i.add(t);else if(v_(t.buffer))i.add(t.buffer);else if(!ArrayBuffer.isView(t)){if(e&&typeof t=="object")for(let n in t)Xu(t[n],e,i)}}return r===void 0?Array.from(i):[]}function v_(t){return t?t instanceof ArrayBuffer||typeof MessagePort<"u"&&t instanceof MessagePort||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas:!1}var Gu=()=>{},Cr=class{name;source;url;terminated=!1;worker;onMessage;onError;_loadableURL="";static isSupported(){return typeof Worker<"u"&&rt||typeof rn<"u"&&!rt}constructor(e){let{name:r,source:i,url:n}=e;Fe(i||n),this.name=r,this.source=i,this.url=n,this.onMessage=Gu,this.onError=o=>console.log(o),this.worker=rt?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=Gu,this.onError=Gu,this.worker.terminate(),this.terminated=!0}get isRunning(){return!!this.onMessage}postMessage(e,r){r=r||Xu(e),this.worker.postMessage(e,r)}_getErrorFromErrorEvent(e){let r="Failed to load ";return r+=`worker ${this.name} from ${this.url}. `,e.message&&(r+=`${e.message} in `),e.lineno&&(r+=`:${e.lineno}:${e.colno}`),new Error(r)}_createBrowserWorker(){this._loadableURL=S_({source:this.source,url:this.url});let e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=r=>{r.data?this.onMessage(r.data):this.onError(new Error("No data received"))},e.onerror=r=>{this.onError(this._getErrorFromErrorEvent(r)),this.terminated=!0},e.onmessageerror=r=>console.error(r),e}_createNodeWorker(){let e;if(this.url){let i=this.url.includes(":/")||this.url.startsWith("/")?this.url:`./${this.url}`,n=this.url.endsWith(".ts")||this.url.endsWith(".mjs")?"module":"commonjs";e=new rn(i,{eval:!1,type:n})}else if(this.source)e=new rn(this.source,{eval:!0});else throw new Error("no worker");return e.on("message",r=>{this.onMessage(r)}),e.on("error",r=>{this.onError(r)}),e.on("exit",r=>{}),e}};var ho=class{name="unnamed";source;url;maxConcurrency=1;maxMobileConcurrency=1;onDebug=()=>{};reuseWorkers=!0;props={};jobQueue=[];idleQueue=[];count=0;isDestroyed=!1;static isSupported(){return Cr.isSupported()}constructor(e){this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach(e=>e.destroy()),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},e.name!==void 0&&(this.name=e.name),e.maxConcurrency!==void 0&&(this.maxConcurrency=e.maxConcurrency),e.maxMobileConcurrency!==void 0&&(this.maxMobileConcurrency=e.maxMobileConcurrency),e.reuseWorkers!==void 0&&(this.reuseWorkers=e.reuseWorkers),e.onDebug!==void 0&&(this.onDebug=e.onDebug)}async startJob(e,r=(n,o,s)=>n.done(s),i=(n,o)=>n.error(o)){let n=new Promise(o=>(this.jobQueue.push({name:e,onMessage:r,onError:i,onStart:o}),this));return this._startQueuedJob(),await n}async _startQueuedJob(){if(!this.jobQueue.length)return;let e=this._getAvailableWorker();if(!e)return;let r=this.jobQueue.shift();if(r){this.onDebug({message:"Starting job",name:r.name,workerThread:e,backlog:this.jobQueue.length});let i=new uo(r.name,e);e.onMessage=n=>r.onMessage(i,n.type,n.payload),e.onError=n=>r.onError(i,n),r.onStart(i);try{await i.result}catch(n){console.error(`Worker exception: ${n}`)}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){!rt||this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}},si=class t{props;workerPools=new Map;static _workerFarm;static isSupported(){return Cr.isSupported()}static getWorkerFarm(e={}){return t._workerFarm=t._workerFarm||new t({}),t._workerFarm.setProps(e),t._workerFarm}constructor(e){this.props={...V2},this.setProps(e),this.workerPools=new Map}destroy(){for(let e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(let r of this.workerPools.values())r.setProps(this._getWorkerPoolProps())}getWorkerPool(e){let{name:r,source:i,url:n}=e,o=this.workerPools.get(r);return o||(o=new ho({name:r,source:i,url:n}),o.setProps(this._getWorkerPoolProps()),this.workerPools.set(r,o)),o}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}};function qu(t,e={}){let r=e[t.id]||{},i=rt?`${t.id}-worker.js`:`${t.id}-worker-node.js`,n=r.workerUrl;if(!n&&t.id==="compression"&&(n=e.workerUrl),(e._workerType||e?.core?._workerType)==="test"&&(rt?n=`modules/${t.module}/dist/${i}`:n=`modules/${t.module}/src/workers/${t.id}-worker-node.ts`),!n){let s=t.version;s==="latest"&&(s=x_);let a=s?`@${s}`:"";n=`https://unpkg.com/@loaders.gl/${t.module}${a}/dist/${i}`}return Fe(n),n}function Ku(t,e=b_){Fe(t,"no worker provided");let r=t.version;return!(!e||!r)}function Zu(t,e){if(!si.isSupported())return!1;let r=e?._nodeWorkers??e?.core?._nodeWorkers;if(!rt&&!r)return!1;let i=e?.worker??e?.core?.worker;return!!(t.worker&&i)}async function Qu(t,e,r,i,n){let o=t.id,s=qu(t,r),c=si.getWorkerFarm(r?.core).getWorkerPool({name:o,url:s});r=JSON.parse(JSON.stringify(r)),i=JSON.parse(JSON.stringify(i||{}));let l=await c.startJob("process-on-worker",j2.bind(null,n));return l.postMessage("process",{input:e,options:r,context:i}),await(await l.result).result}async function j2(t,e,r,i){switch(r){case"done":e.done(i);break;case"error":e.error(new Error(i.error));break;case"process":let{id:n,input:o,options:s}=i;try{let a=await t(o,s);e.postMessage("done",{id:n,result:a})}catch(a){let c=a instanceof Error?a.message:"unknown error";e.postMessage("error",{id:n,error:c})}break;default:console.warn(`parse-with-worker unknown message ${r}`)}}function Ju(t,e,r){if(r=r||t.byteLength,t.byteLengtho instanceof ArrayBuffer?new Uint8Array(o):o),r=e.reduce((o,s)=>o+s.byteLength,0),i=new Uint8Array(r),n=0;for(let o of e)i.set(o,n),n+=o.byteLength;return i.buffer}async function td(t){let e=[];for await(let r of t)e.push($2(r));return ed(...e)}function $2(t){if(t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t)){let{buffer:e,byteOffset:r,byteLength:i}=t;return R_(e,r,i)}return R_(t)}function R_(t,e=0,r=t.byteLength-e){let i=new Uint8Array(t,e,r),n=new Uint8Array(i.length);return n.set(i),n.buffer}var H2="",P_={};function nd(t){for(let e in P_)if(t.startsWith(e)){let r=P_[e];t=t.replace(e,r)}return!t.startsWith("http://")&&!t.startsWith("https://")&&(t=`${H2}${t}`),t}function sc(t){return t&&typeof t=="object"&&t.isBuffer}function nn(t){if(sc(t))return t;if(t instanceof ArrayBuffer)return t;if(Vu(t))return oc(t);if(ArrayBuffer.isView(t)){let e=t.buffer;return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?e:e.slice(t.byteOffset,t.byteOffset+t.byteLength)}if(typeof t=="string"){let e=t;return new TextEncoder().encode(e).buffer}if(t&&typeof t=="object"&&t._toArrayBuffer)return t._toArrayBuffer();throw new Error("toArrayBuffer")}function mo(t){if(t instanceof ArrayBuffer)return t;if(Vu(t))return oc(t);let{buffer:e,byteOffset:r,byteLength:i}=t;return e instanceof ArrayBuffer&&r===0&&i===e.byteLength?e:oc(e,r,i)}function oc(t,e=0,r=t.byteLength-e){let i=new Uint8Array(t,e,r),n=new Uint8Array(i.length);return n.set(i),n.buffer}function od(t){return ArrayBuffer.isView(t)?t:new Uint8Array(t)}var tr={};Zi(tr,{dirname:()=>X2,filename:()=>Y2,join:()=>G2,resolve:()=>q2});function M_(){if(typeof process<"u"&&typeof process.cwd<"u")return process.cwd();let t=window.location?.pathname;return t?.slice(0,t.lastIndexOf("/")+1)||""}function Y2(t){let e=t?t.lastIndexOf("/"):-1;return e>=0?t.substr(e+1):t}function X2(t){let e=t?t.lastIndexOf("/"):-1;return e>=0?t.substr(0,e):""}function G2(...t){return t=t.map((r,i)=>(i&&(r=r.replace(new RegExp("^/"),"")),i!==t.length-1&&(r=r.replace(new RegExp("/$"),"")),r)),t.join("/")}function q2(...t){let e=[];for(let o=0;o=-1&&!i;o--){let s;o>=0?s=e[o]:(n===void 0&&(n=M_()),s=n),s.length!==0&&(r=`${s}/${r}`,i=s.charCodeAt(0)===_o)}return r=K2(r,!i),i?`/${r}`:r.length>0?r:"."}var _o=47,sd=46;function K2(t,e){let r="",i=-1,n=0,o,s=!1;for(let a=0;a<=t.length;++a){if(a2){let c=r.length-1,l=c;for(;l>=0&&r.charCodeAt(l)!==_o;--l);if(l!==c){r=l===-1?"":r.slice(0,l),i=a,n=0,s=!1;continue}}else if(r.length===2||r.length===1){r="",i=a,n=0,s=!1;continue}}e&&(r.length>0?r+="/..":r="..",s=!0)}else{let c=t.slice(i+1,a);r.length>0?r+=`/${c}`:r=c,s=!1}i=a,n=0}else o===sd&&n!==-1?++n:n=-1}return r}var ac=class extends Error{constructor(e,r){super(e),this.reason=r.reason,this.url=r.url,this.response=r.response}reason;url;response};var J2=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,eE=/^([-\w.]+\/[-\w.+]+)/;function ad(t,e){return t.toLowerCase()===e.toLowerCase()}function I_(t){let e=eE.exec(t);return e?e[1]:t}function cd(t){let e=J2.exec(t);return e?e[1]:""}var O_=/\?.*/;function N_(t){let e=t.match(O_);return e&&e[0]}function Pr(t){return t.replace(O_,"")}function D_(t){if(t.length<50)return t;let e=t.slice(t.length-15);return`${t.substr(0,32)}...${e}`}function ci(t){return Ge(t)?t.url:qe(t)?("name"in t?t.name:"")||"":typeof t=="string"?t:""}function on(t){if(Ge(t)){let e=t.headers.get("content-type")||"",r=Pr(t.url);return I_(e)||cd(r)}return qe(t)?t.type||"":typeof t=="string"?cd(t):""}function L_(t){return Ge(t)?t.headers["content-length"]||-1:qe(t)?t.size:typeof t=="string"?t.length:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:-1}async function cc(t){if(Ge(t))return t;let e={},r=L_(t);r>=0&&(e["content-length"]=String(r));let i=ci(t),n=on(t);n&&(e["content-type"]=n);let o=await rE(t);o&&(e["x-first-bytes"]=o),typeof t=="string"&&(t=new TextEncoder().encode(t));let s=new Response(t,{headers:e});return Object.defineProperty(s,"url",{value:i}),s}async function F_(t){if(!t.ok)throw await tE(t)}async function tE(t){let e=D_(t.url),r=`Failed to fetch resource (${t.status}) ${t.statusText}: ${e}`;r=r.length>100?`${r.slice(0,100)}...`:r;let i={reason:t.statusText,url:t.url,response:t};try{let n=t.headers.get("Content-Type");i.reason=!t.bodyUsed&&n?.includes("application/json")?await t.json():await t.text()}catch{}return new ac(r,i)}async function rE(t){if(typeof t=="string")return`data:,${t.slice(0,5)}`;if(t instanceof Blob){let r=t.slice(0,5);return await new Promise(i=>{let n=new FileReader;n.onload=o=>i(o?.target?.result),n.readAsDataURL(r)})}if(t instanceof ArrayBuffer){let r=t.slice(0,5);return`data:base64,${iE(r)}`}return null}function iE(t){let e="",r=new Uint8Array(t);for(let i=0;i{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}},fc=class{console;constructor(){this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}};var uc={core:{baseUrl:void 0,fetch:null,mimeType:void 0,fallbackMimeType:void 0,ignoreRegisteredLoaders:void 0,nothrow:!1,log:new fc,useLocalLibraries:!1,CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:ni,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]}},B_={baseUri:"core.baseUrl",fetch:"core.fetch",mimeType:"core.mimeType",fallbackMimeType:"core.fallbackMimeType",ignoreRegisteredLoaders:"core.ignoreRegisteredLoaders",nothrow:"core.nothrow",log:"core.log",useLocalLibraries:"core.useLocalLibraries",CDN:"core.CDN",worker:"core.worker",maxConcurrency:"core.maxConcurrency",maxMobileConcurrency:"core.maxMobileConcurrency",reuseWorkers:"core.reuseWorkers",_nodeWorkers:"core.nodeWorkers",_workerType:"core._workerType",_worker:"core._workerType",limit:"core.limit",_limitMB:"core._limitMB",batchSize:"core.batchSize",batchDebounceMs:"core.batchDebounceMs",metadata:"core.metadata",transforms:"core.transforms",throws:"nothrow",dataType:"(no longer used)",uri:"core.baseUrl",method:"core.fetch.method",headers:"core.fetch.headers",body:"core.fetch.body",mode:"core.fetch.mode",credentials:"core.fetch.credentials",cache:"core.fetch.cache",redirect:"core.fetch.redirect",referrer:"core.fetch.referrer",referrerPolicy:"core.fetch.referrerPolicy",integrity:"core.fetch.integrity",keepalive:"core.fetch.keepalive",signal:"core.fetch.signal"};var fd=["baseUrl","fetch","mimeType","fallbackMimeType","ignoreRegisteredLoaders","nothrow","log","useLocalLibraries","CDN","worker","maxConcurrency","maxMobileConcurrency","reuseWorkers","_nodeWorkers","_workerType","limit","_limitMB","batchSize","batchDebounceMs","metadata","transforms"];function ud(){globalThis.loaders=globalThis.loaders||{};let{loaders:t}=globalThis;return t._state||(t._state={}),t._state}function dd(){let t=ud();return t.globalOptions=t.globalOptions||{...uc,core:{...uc.core}},rr(t.globalOptions)}function z_(t,e,r,i){return r=r||[],r=Array.isArray(r)?r:[r],aE(t,r),rr(lE(e,t,i))}function rr(t){let e=uE(t);W_(e);for(let r of fd)e.core&&e.core[r]!==void 0&&delete e[r];return e.core&&e.core._workerType!==void 0&&delete e._worker,e}function aE(t,e){k_(t,null,uc,B_,e);for(let r of e){let i=t&&t[r.id]||{},n=r.options&&r.options[r.id]||{},o=r.deprecatedOptions&&r.deprecatedOptions[r.id]||{};k_(i,r.id,n,o,e)}}function k_(t,e,r,i,n){let o=e||"Top level",s=e?`${e}.`:"";for(let a in t){let c=!e&&Mt(t[a]),l=a==="baseUri"&&!e,f=a==="workerUrl"&&e;if(!(a in r)&&!l&&!f){if(a in i)yo.level>0&&yo.warn(`${o} loader option '${s}${a}' no longer supported, use '${i[a]}'`)();else if(!c&&yo.level>0){let u=cE(a,n);yo.warn(`${o} loader option '${s}${a}' not recognized. ${u}`)()}}}}function cE(t,e){let r=t.toLowerCase(),i="";for(let n of e)for(let o in n.options){if(t===o)return`Did you mean '${n.id}.${o}'?`;let s=o.toLowerCase();(r.startsWith(s)||s.startsWith(r))&&(i=i||`Did you mean '${n.id}.${o}'?`)}return i}function lE(t,e,r){let i=t.options||{},n={...i};i.core&&(n.core={...i.core}),W_(n),n.core?.log===null&&(n.core={...n.core,log:new lc}),U_(n,rr(dd()));let o=rr(e);return U_(n,o),fE(n,r),dE(n),n}function U_(t,e){for(let r in e)if(r in e){let i=e[r];nc(i)&&nc(t[r])?t[r]={...t[r],...e[r]}:t[r]=e[r]}}function fE(t,e){if(!e)return;t.core?.baseUrl!==void 0||(t.core||={},t.core.baseUrl=tr.dirname(Pr(e)))}function uE(t){let e={...t};return t.core&&(e.core={...t.core}),e}function W_(t){t.baseUri!==void 0&&(t.core||={},t.core.baseUrl===void 0&&(t.core.baseUrl=t.baseUri));for(let r of fd)if(t[r]!==void 0){let n=t.core=t.core||{};n[r]===void 0&&(n[r]=t[r])}let e=t._worker;e!==void 0&&(t.core||={},t.core._workerType===void 0&&(t.core._workerType=e))}function dE(t){let e=t.core;if(e)for(let r of fd)e[r]!==void 0&&(t[r]=e[r])}function xo(t){return t?(Array.isArray(t)&&(t=t[0]),Array.isArray(t?.extensions)):!1}function bo(t){Er(t,"null loader"),Er(xo(t),"invalid loader");let e;return Array.isArray(t)&&(e=t[1],t=t[0],t={...t,options:{...t.options,...e}}),(t?.parseTextSync||t?.parseText)&&(t.text=!0),t.text||(t.binary=!0),t}var V_=()=>{let t=ud();return t.loaderRegistry=t.loaderRegistry||[],t.loaderRegistry};function hd(t){let e=V_();t=Array.isArray(t)?t:[t];for(let r of t){let i=bo(r);e.find(n=>i===n)||e.unshift(i)}}function j_(){return V_()}var hE=/\.([^.]+)$/;async function Y_(t,e=[],r,i){if(!X_(t))return null;let n=rr(r||{});if(n.core||={},t instanceof Response&&$_(t)){let s=await t.clone().text(),a=dc(s,e,{...n,core:{...n.core,nothrow:!0}},i);if(a)return a}let o=dc(t,e,{...n,core:{...n.core,nothrow:!0}},i);if(o)return o;if(qe(t)&&(t=await t.slice(0,10).arrayBuffer(),o=dc(t,e,n,i)),!o&&t instanceof Response&&$_(t)){let s=await t.clone().text();o=dc(s,e,n,i)}if(!o&&!n.core.nothrow)throw new Error(G_(t));return o}function $_(t){let e=on(t);return!!(e&&(e.startsWith("text/")||e==="application/json"||e.endsWith("+json")))}function dc(t,e=[],r,i){if(!X_(t))return null;let n=rr(r||{});if(n.core||={},e&&!Array.isArray(e))return bo(e);let o=[];e&&(o=o.concat(e)),n.core.ignoreRegisteredLoaders||o.push(...j_()),gE(o);let s=pE(t,o,n,i);if(!s&&!n.core.nothrow)throw new Error(G_(t));return s}function pE(t,e,r,i){let n=ci(t),o=on(t),s=Pr(n)||i?.url,a=null,c="";return r?.core?.mimeType&&(a=pd(e,r?.core?.mimeType),c=`match forced by supplied MIME type ${r?.core?.mimeType}`),a=a||mE(e,s),c=c||(a?`matched url ${s}`:""),a=a||pd(e,o),c=c||(a?`matched MIME type ${o}`:""),a=a||yE(e,t),c=c||(a?`matched initial data ${q_(t)}`:""),r?.core?.fallbackMimeType&&(a=a||pd(e,r?.core?.fallbackMimeType),c=c||(a?`matched fallback MIME type ${o}`:"")),c&&Wu.log(1,`selectLoader selected ${a?.name}: ${c}.`),a}function X_(t){return!(t instanceof Response&&t.status===204)}function G_(t){let e=ci(t),r=on(t),i="No valid loader found (";i+=e?`${tr.filename(e)}, `:"no url provided, ",i+=`MIME type: ${r?`"${r}"`:"not provided"}, `;let n=t?q_(t):"";return i+=n?` first bytes: "${n}"`:"first bytes: not available",i+=")",i}function gE(t){for(let e of t)bo(e)}function mE(t,e){let r=e&&hE.exec(e),i=r&&r[1];return i?_E(t,i):null}function _E(t,e){e=e.toLowerCase();for(let r of t)for(let i of r.extensions)if(i.toLowerCase()===e)return r;return null}function pd(t,e){for(let r of t)if(r.mimeTypes?.some(i=>ad(e,i))||ad(e,`application/x.${r.id}`))return r;return null}function yE(t,e){if(!e)return null;for(let r of t)if(typeof e=="string"){if(xE(e,r))return r}else if(ArrayBuffer.isView(e)){if(H_(e.buffer,e.byteOffset,r))return r}else if(e instanceof ArrayBuffer&&H_(e,0,r))return r;return null}function xE(t,e){return e.testText?e.testText(t):(Array.isArray(e.tests)?e.tests:[e.tests]).some(i=>t.startsWith(i))}function H_(t,e,r){return(Array.isArray(r.tests)?r.tests:[r.tests]).some(n=>bE(t,e,r,n))}function bE(t,e,r,i){if(tn(i))return Ju(i,t,i.byteLength);switch(typeof i){case"function":return i(mo(t));case"string":let n=gd(t,e,i.length);return i===n;default:return!1}}function q_(t,e=5){return typeof t=="string"?t.slice(0,e):ArrayBuffer.isView(t)?gd(t.buffer,t.byteOffset,e):t instanceof ArrayBuffer?gd(t,0,e):""}function gd(t,e,r){if(t.byteLengthld(o,n):e?.fetch?e?.fetch:ld}function r0(t,e,r){if(r)return r;let i={fetch:hc(e,t),...t};if(i.url){let n=Pr(i.url);i.baseUrl=n,i.queryString=N_(i.url),i.filename=tr.filename(n),i.baseUrl=tr.dirname(n)}return Array.isArray(i.loaders)||(i.loaders=null),i}function i0(t,e){if(t&&!Array.isArray(t))return t;let r;if(t&&(r=Array.isArray(t)?t:[t]),e&&e.loaders){let i=Array.isArray(e.loaders)?e.loaders:[e.loaders];r=r?[...r,...i]:i}return r&&r.length?r:void 0}async function To(t,e,r,i){e&&!Array.isArray(e)&&!xo(e)&&(i=void 0,r=e,e=void 0),t=await t,r=r||{};let n=ci(t),s=i0(e,i),a=await Y_(t,s,r);if(!a)return null;let c=z_(r,a,s,n);return i=r0({url:n,_parse:To,loaders:s},c,i||null),await vE(a,t,c,i)}async function vE(t,e,r,i){if(Ku(t),r=Hu(t.options,r),Ge(e)){let{ok:o,redirected:s,status:a,statusText:c,type:l,url:f}=e,u=Object.fromEntries(e.headers.entries());i.response={headers:u,ok:o,redirected:s,status:a,statusText:c,type:l,url:f}}e=await t0(e,t,r);let n=t;if(n.parseTextSync&&typeof e=="string")return n.parseTextSync(e,r,i);if(Zu(t,r))return await Qu(t,e,r,i,To);if(n.parseText&&typeof e=="string")return await n.parseText(e,r,i);if(n.parse)return await n.parse(e,r,i);throw Fe(!n.parseSync),new Error(`${t.id} loader - no parser found and worker is disabled`)}function n0(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function o0(t){return Array.isArray(t)?t.length===0||typeof t[0]=="number":!1}function _d(t){return n0(t)||o0(t)}async function Mr(t,e,r,i){let n,o;!Array.isArray(e)&&!xo(e)?(n=[],o=e,i=void 0):(n=e,o=r);let s=hc(o),a=t;return typeof t=="string"&&(a=await s(t)),qe(t)&&(a=await s(t)),typeof t=="string"&&(rr(o||{}).core?.baseUrl||(o={...o,core:{...o?.core,baseUrl:t}})),Array.isArray(n)?await To(a,n,o):await To(a,n,o)}var s0="4.4.2";var EE=globalThis.loaders?.parseImageNode,yd=typeof Image<"u",xd=typeof ImageBitmap<"u",RE=!!EE,bd=ni?!0:RE;function a0(t){switch(t){case"auto":return xd||yd||bd;case"imagebitmap":return xd;case"image":return yd;case"data":return bd;default:throw new Error(`@loaders.gl/images: image ${t} not supported in this environment`)}}function c0(){if(xd)return"imagebitmap";if(yd)return"image";if(bd)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}function CE(t){let e=PE(t);if(!e)throw new Error("Not an image");return e}function l0(t){switch(CE(t)){case"data":return t;case"image":case"imagebitmap":let e=document.createElement("canvas"),r=e.getContext("2d");if(!r)throw new Error("getImageData");return e.width=t.width,e.height=t.height,r.drawImage(t,0,0),r.getImageData(0,0,t.width,t.height);default:throw new Error("getImageData")}}function PE(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap?"imagebitmap":typeof Image<"u"&&t instanceof Image?"image":t&&typeof t=="object"&&t.data&&t.width&&t.height?"data":null}var ME=/^data:image\/svg\+xml/,IE=/\.svg((\?|#).*)?$/;function pc(t){return t&&(ME.test(t)||IE.test(t))}function f0(t,e){if(pc(e)){let i=new TextDecoder().decode(t);try{typeof unescape=="function"&&typeof encodeURIComponent=="function"&&(i=unescape(encodeURIComponent(i)))}catch(o){throw new Error(o.message)}return`data:image/svg+xml;base64,${btoa(i)}`}return Td(t,e)}function Td(t,e){if(pc(e))throw new Error("SVG cannot be parsed directly to imagebitmap");return new Blob([new Uint8Array(t)])}async function gc(t,e,r){let i=f0(t,r),n=self.URL||self.webkitURL,o=typeof i!="string"&&n.createObjectURL(i);try{return await OE(o||i,e)}finally{o&&n.revokeObjectURL(o)}}async function OE(t,e){let r=new Image;return r.src=t,e.image&&e.image.decode&&r.decode?(await r.decode(),r):await new Promise((i,n)=>{try{r.onload=()=>i(r),r.onerror=o=>{let s=o instanceof Error?o.message:"error";n(new Error(s))}}catch(o){n(o)}})}var u0=!0;async function d0(t,e,r){let i;pc(r)?i=await gc(t,e,r):i=Td(t,r);let n=e&&e.imagebitmap;return await NE(i,n)}async function NE(t,e=null){if((DE(e)||!u0)&&(e=null),e)try{return await createImageBitmap(t,e)}catch(r){console.warn(r),u0=!1}return await createImageBitmap(t)}function DE(t){if(!t)return!0;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function h0(t){return!kE(t,"ftyp",4)||(t[8]&96)===0?null:LE(t)}function LE(t){switch(FE(t,8,12).replace("\0"," ").trim()){case"avif":case"avis":return{extension:"avif",mimeType:"image/avif"};default:return null}}function FE(t,e,r){return String.fromCharCode(...t.slice(e,r))}function BE(t){return[...t].map(e=>e.charCodeAt(0))}function kE(t,e,r=0){let i=BE(e);for(let n=0;n=24&&e.getUint32(0,Ot)===2303741511?{mimeType:"image/png",width:e.getUint32(16,Ot),height:e.getUint32(20,Ot)}:null}function WE(t){let e=So(t);return e.byteLength>=10&&e.getUint32(0,Ot)===1195984440?{mimeType:"image/gif",width:e.getUint16(6,wo),height:e.getUint16(8,wo)}:null}function VE(t){let e=So(t);return e.byteLength>=14&&e.getUint16(0,Ot)===16973&&e.getUint32(2,wo)===e.byteLength?{mimeType:"image/bmp",width:e.getUint32(18,wo),height:e.getUint32(22,wo)}:null}function jE(t){let e=So(t);if(!(e.byteLength>=3&&e.getUint16(0,Ot)===65496&&e.getUint8(2)===255))return null;let{tableMarkers:i,sofMarkers:n}=$E(),o=2;for(;o+9!!mc(new DataView(t))],options:GE};lo();var qE=new Le({id:"deck"}),F=qE;var Sd={};function m0(t){Sd=t}function ae(t,e,r,i){F.level>0&&Sd[t]&&Sd[t].call(null,e,r,i)}function KE(t){let e=t[0],r=t[t.length-1];return e==="{"&&r==="}"||e==="["&&r==="]"}var _0={dataType:null,batchType:null,id:"JSON",name:"JSON",module:"",version:"",options:{},extensions:["json","geojson"],mimeTypes:["application/json","application/geo+json"],testText:KE,parseTextSync:JSON.parse};function ZE(){let t="9.3.2",e=globalThis.deck&&globalThis.deck.VERSION;if(e&&e!==t)throw new Error(`deck.gl - multiple versions detected: ${e} vs ${t}`);return e||(F.log(1,`deck.gl ${t}`)(),globalThis.deck={...globalThis.deck,VERSION:t,version:t,log:F,_registerLoggers:m0},hd([_0,[wd,{imagebitmap:{premultiplyAlpha:"none"}}]])),t}var y0=ZE();function li(t,e){if(!t){let r=new Error(e||"shadertools: assertion failed.");throw Error.captureStackTrace?.(r,li),r}}var Ad={number:{type:"number",validate(t,e){return Number.isFinite(t)&&typeof e=="object"&&(e.max===void 0||t<=e.max)&&(e.min===void 0||t>=e.min)}},array:{type:"array",validate(t,e){return Array.isArray(t)||ArrayBuffer.isView(t)}}};function b0(t){let e={};for(let[r,i]of Object.entries(t))e[r]=QE(i);return e}function QE(t){let e=x0(t);if(e!=="object")return{value:t,...Ad[e],type:e};if(typeof t=="object")return t?t.type!==void 0?{...t,...Ad[t.type],type:t.type}:t.value===void 0?{type:"object",value:t}:(e=x0(t.value),{...t,...Ad[e],type:e}):{type:"object",value:null};throw new Error("props")}function x0(t){return Array.isArray(t)||ArrayBuffer.isView(t)?"array":typeof t}var T0=`#ifdef MODULE_LOGDEPTH + logdepth_adjustPosition(gl_Position); +#endif +`,w0=`#ifdef MODULE_MATERIAL + fragColor = material_filterColor(fragColor); +#endif + +#ifdef MODULE_LIGHTING + fragColor = lighting_filterColor(fragColor); +#endif + +#ifdef MODULE_FOG + fragColor = fog_filterColor(fragColor); +#endif + +#ifdef MODULE_PICKING + fragColor = picking_filterHighlightColor(fragColor); + fragColor = picking_filterPickingColor(fragColor); +#endif + +#ifdef MODULE_LOGDEPTH + logdepth_setFragDepth(); +#endif +`;var JE={vertex:T0,fragment:w0},S0=/void\s+main\s*\([^)]*\)\s*\{\n?/,A0=/}\n?[^{}]*$/,vd=[],Ao="__LUMA_INJECT_DECLARATIONS__";function v0(t){let e={vertex:{},fragment:{}};for(let r in t){let i=t[r],n=e3(r);typeof i=="string"&&(i={order:0,injection:i}),e[n][r]=i}return e}function e3(t){let e=t.slice(0,2);switch(e){case"vs":return"vertex";case"fs":return"fragment";default:throw new Error(e)}}function vo(t,e,r,i=!1){let n=e==="vertex";for(let o in r){let s=r[o];s.sort((c,l)=>c.order-l.order),vd.length=s.length;for(let c=0,l=s.length;cc+a));break;case"vs:#main-end":n&&(t=t.replace(A0,c=>a+c));break;case"fs:#decl":n||(t=t.replace(Ao,a));break;case"fs:#main-start":n||(t=t.replace(S0,c=>c+a));break;case"fs:#main-end":n||(t=t.replace(A0,c=>a+c));break;default:t=t.replace(o,c=>c+a)}}return t=t.replace(Ao,""),i&&(t=t.replace(/\}\s*$/,o=>o+JE[e])),t}function sn(t){t.map(e=>t3(e))}function t3(t){if(t.instance)return;sn(t.dependencies||[]);let{propTypes:e={},deprecations:r=[],inject:i={}}=t,n={normalizedInjections:v0(i),parsedDeprecations:r3(r)};e&&(n.propValidators=b0(e)),t.instance=n;let o={};e&&(o=Object.entries(e).reduce((s,[a,c])=>{let l=c?.value;return l&&(s[a]=l),s},{})),t.defaultUniforms={...t.defaultUniforms,...o}}function Ed(t,e,r){t.deprecations?.forEach(i=>{i.regex?.test(e)&&(i.deprecated?r.deprecated(i.old,i.new)():r.removed(i.old,i.new)())})}function r3(t){return t.forEach(e=>{e.type==="function"?e.regex=new RegExp(`\\b${e.old}\\(`):e.regex=new RegExp(`${e.type} ${e.old};`)}),t}function an(t){sn(t);let e={},r={};E0({modules:t,level:0,moduleMap:e,moduleDepth:r});let i=Object.keys(r).sort((n,o)=>r[o]-r[n]).map(n=>e[n]);return sn(i),i}function E0(t){let{modules:e,level:r,moduleMap:i,moduleDepth:n}=t;if(r>=5)throw new Error("Possible loop in shader dependency graph");for(let o of e)i[o.name]=o,(n[o.name]===void 0||n[o.name]]+>)?\s+([A-Za-z0-9_]+)(?:\s*\[[^\]]+\])?\s*;/,n3=/((?:layout\s*\([^)]*\)\s*)*)uniform\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([\s\S]*?)\}\s*([A-Za-z_][A-Za-z0-9_]*)?\s*;/g;function C0(t){return`${t.name}Uniforms`}function o3(t,e){let r=e==="wgsl"?t.source:e==="vertex"?t.vs:t.fs;if(!r)return null;let i=C0(t);return a3(r,e==="wgsl"?"wgsl":"glsl",i)}function s3(t,e){let r=Object.keys(t.uniformTypes||{});if(!r.length)return null;let i=o3(t,e);return i?{moduleName:t.name,uniformBlockName:C0(t),stage:e,expectedUniformNames:r,actualUniformNames:i,matches:f3(r,i)}:null}function P0(t,e,r={}){let i=s3(t,e);if(!i||i.matches)return i;let n=u3(i);return r.log?.error?.(n,i)(),r.throwOnError!==!1&&li(!1,n),i}function M0(t){let e=[],r=d3(t);for(let i of r.matchAll(n3)){let n=i[1]?.trim()||null;e.push({blockName:i[2],body:i[3],instanceName:i[4]||null,layoutQualifier:n,hasLayoutQualifier:!!n,isStd140:!!(n&&/\blayout\s*\([^)]*\bstd140\b[^)]*\)/.exec(n))})}return e}function I0(t,e,r,i){let n=M0(t).filter(s=>!s.isStd140),o=new Set;for(let s of n){if(o.has(s.blockName))continue;o.add(s.blockName);let a=i?.label?`${i.label} `:"",c=s.hasLayoutQualifier?`declares ${h3(s.layoutQualifier)} instead of layout(std140)`:"does not declare layout(std140)",l=`${a}${e} shader uniform block ${s.blockName} ${c}. luma.gl host-side shader block packing assumes explicit layout(std140) for GLSL uniform blocks. Add \`layout(std140)\` to the block declaration.`;r?.warn?.(l,s)()}return n}function a3(t,e,r){let i=e==="wgsl"?c3(t,r):l3(t,r);if(!i)return null;let n=[];for(let o of i.split(` +`)){let s=o.replace(/\/\/.*$/,"").trim();if(!s||s.startsWith("#"))continue;let a=e==="wgsl"?s.match(/^([A-Za-z0-9_]+)\s*:/):s.match(i3);a&&n.push(a[1])}return n}function c3(t,e){let r=new RegExp(`\\bstruct\\s+${e}\\b`,"m").exec(t);if(!r)return null;let i=t.indexOf("{",r.index);if(i<0)return null;let n=0;for(let o=i;oi.blockName===e)?.body||null}function f3(t,e){if(t.length!==e.length)return!1;for(let r=0;r!r.includes(a)),n=r.filter(a=>!e.includes(a)),o=[`Expected ${e.length} fields, found ${r.length}.`],s=p3(e,r);return s&&o.push(s),i.length&&o.push(`Missing from shader block (${i.length}): ${R0(i)}.`),n.length&&o.push(`Unexpected in shader block (${n.length}): ${R0(n)}.`),e.length<=12&&r.length<=12&&(i.length||n.length)&&(o.push(`Expected: ${e.join(", ")}.`),o.push(`Actual: ${r.join(", ")}.`)),`${t.moduleName}: ${t.stage} shader uniform block ${t.uniformBlockName} does not match module.uniformTypes. ${o.join(" ")}`}function d3(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function h3(t){return t.replace(/\s+/g," ").trim()}function p3(t,e){let r=Math.min(t.length,e.length);for(let i=0;ie.length?`Shader block ends after field ${e.length}; expected next field ${t[e.length]}.`:e.length>t.length?`Shader block has extra field ${e.length}: ${e[t.length]}.`:null}function R0(t,e=8){if(t.length<=e)return t.join(", ");let r=t.length-e;return`${t.slice(0,e).join(", ")}, ... (${r} more)`}function O0(t){switch(t?.gpu.toLowerCase()){case"apple":return`#define APPLE_GPU +// Apple optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +`;case"nvidia":return`#define NVIDIA_GPU +// Nvidia optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +`;case"intel":return`#define INTEL_GPU +// Intel optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +// Intel's built-in 'tan' function doesn't have acceptable precision +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +`;case"amd":return`#define AMD_GPU +`;default:return`#define DEFAULT_GPU +// Prevent driver from optimizing away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +// Headless Chrome's software shader 'tan' function doesn't have acceptable precision +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// If the GPU doesn't have full 32 bits precision, will causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +`}}function D0(t,e){if(Number(t.match(/^#version[ \t]+(\d+)/m)?.[1]||100)!==300)throw new Error("luma.gl v9 only supports GLSL 3.00 shader sources");switch(e){case"vertex":return t=N0(t,g3),t;case"fragment":return t=N0(t,m3),t;default:throw new Error(e)}}var L0=[[/^(#version[ \t]+(100|300[ \t]+es))?[ \t]*\n/,`#version 300 es +`],[/\btexture(2D|2DProj|Cube)Lod(EXT)?\(/g,"textureLod("],[/\btexture(2D|2DProj|Cube)(EXT)?\(/g,"texture("]],g3=[...L0,[Rd("attribute"),"in $1"],[Rd("varying"),"out $1"]],m3=[...L0,[Rd("varying"),"in $1"]];function N0(t,e){for(let[r,i]of e)t=t.replace(r,i);return t}function Rd(t){return new RegExp(`\\b${t}[ \\t]+(\\w+[ \\t]+\\w+(\\[\\w+\\])?;)`,"g")}function Cd(t,e){let r="";for(let i in t){let n=t[i];if(r+=`void ${n.signature} { +`,n.header&&(r+=` ${n.header}`),e[i]){let o=e[i];o.sort((s,a)=>s.order-a.order);for(let s of o)r+=` ${s.injection} +`}n.footer&&(r+=` ${n.footer}`),r+=`} +`}return r}function Pd(t){let e={vertex:{},fragment:{}};for(let r of t){let i,n;typeof r!="string"?(i=r,n=i.hook):(i={},n=r),n=n.trim();let[o,s]=n.split(":"),a=n.replace(/\(.+/,""),c=Object.assign(i,{signature:s});switch(o){case"vs":e.vertex[a]=c;break;case"fs":e.fragment[a]=c;break;default:throw new Error(o)}}return e}function F0(t,e){return{name:_3(t,e),language:"glsl",version:y3(t)}}function _3(t,e="unnamed"){let i=/#define[^\S\r\n]*SHADER_NAME[^\S\r\n]*([A-Za-z0-9_-]+)\s*/.exec(t);return i?i[1]:e}function y3(t){let e=100,r=t.match(/[^\s]+/g);if(r&&r.length>=2&&r[0]==="#version"){let i=parseInt(r[1],10);Number.isFinite(i)&&(e=i)}if(e!==100&&e!==300)throw new Error(`Invalid GLSL version ${e}`);return e}var Ke="(?:var<\\s*(uniform|storage(?:\\s*,\\s*[A-Za-z_][A-Za-z0-9_]*)?)\\s*>|var)\\s+([A-Za-z_][A-Za-z0-9_]*)";var cn=[new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*${Ke}`,"g")],_c=[new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*${Ke}`,"g")],B0=[new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g")],x3=[new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${Ke}`,"g")];function yc(t){let e=t.split(""),r=0,i=0,n=!1,o=!1,s=!1;for(;r0){if(a==="/"&&c==="*"){e[r]=" ",e[r+1]=" ",i++,r+=2;continue}if(a==="*"&&c==="/"){e[r]=" ",e[r+1]=" ",i--,r+=2;continue}a!==` +`&&a!=="\r"&&(e[r]=" "),r++;continue}if(a==='"'){o=!0,r++;continue}if(a==="/"&&c==="/"){e[r]=" ",e[r+1]=" ",n=!0,r+=2;continue}if(a==="/"&&c==="*"){e[r]=" ",e[r+1]=" ",i=1,r+=2;continue}r++}return e.join("")}function fi(t,e){let r=yc(t),i=[];for(let n of e){n.lastIndex=0;let o;for(o=n.exec(r);o;){let s=n===e[0],a=o.index,c=o[0].length;i.push({match:t.slice(a,a+c),index:a,length:c,bindingToken:o[s?1:2],groupToken:o[s?2:1],accessDeclaration:o[3]?.trim(),name:o[4]}),o=n.exec(r)}}return i.sort((n,o)=>n.index-o.index)}function Md(t,e,r){let i=fi(t,e);if(!i.length)return t;let n="",o=0;for(let s of i)n+=t.slice(o,s.index),n+=r(s),o=s.index+s.length;return n+=t.slice(o),n}function Id(t){return/@binding\(\s*auto\s*\)/.test(yc(t))}function k0(t,e){return fi(t,e===cn||e===_c?x3:e).find(i=>i.bindingToken==="auto")}var U0=[new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}\\s*:\\s*([^;]+);`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(\\d+)\\s*\\)\\s*${Ke}\\s*:\\s*([^;]+);`,"g")];function xc(t,e=[]){let r=yc(t),i=new Map;for(let o of e)i.set(z0(o.name,o.group,o.location),o.moduleName);let n=[];for(let o of U0){o.lastIndex=0;let s;for(s=o.exec(r);s;){let a=o===U0[0],c=Number(s[a?1:2]),l=Number(s[a?2:1]),f=s[3]?.trim(),u=s[4],d=s[5].trim(),h=i.get(z0(u,l,c));n.push(b3({name:u,group:l,binding:c,owner:h?"module":"application",moduleName:h,accessDeclaration:f,resourceType:d})),s=o.exec(r)}}return n.sort((o,s)=>o.group!==s.group?o.group-s.group:o.binding!==s.binding?o.binding-s.binding:o.name.localeCompare(s.name))}function b3(t){let e={name:t.name,group:t.group,binding:t.binding,owner:t.owner,kind:"unknown",moduleName:t.moduleName,resourceType:t.resourceType};if(t.accessDeclaration){let r=t.accessDeclaration.split(",").map(i=>i.trim());if(r[0]==="uniform")return{...e,kind:"uniform",access:"uniform"};if(r[0]==="storage"){let i=r[1]||"read_write";return{...e,kind:i==="read"?"read-only-storage":"storage",access:i}}}return t.resourceType==="sampler"||t.resourceType==="sampler_comparison"?{...e,kind:"sampler",samplerKind:t.resourceType==="sampler_comparison"?"comparison":"filtering"}:t.resourceType.startsWith("texture_storage_")?{...e,kind:"storage-texture",access:w3(t.resourceType),viewDimension:W0(t.resourceType)}:t.resourceType.startsWith("texture_")?{...e,kind:"texture",viewDimension:W0(t.resourceType),sampleType:T3(t.resourceType),multisampled:t.resourceType.startsWith("texture_multisampled_")}:e}function z0(t,e,r){return`${e}:${r}:${t}`}function W0(t){if(t.includes("cube_array"))return"cube-array";if(t.includes("2d_array"))return"2d-array";if(t.includes("cube"))return"cube";if(t.includes("3d"))return"3d";if(t.includes("2d"))return"2d";if(t.includes("1d"))return"1d"}function T3(t){if(t.startsWith("texture_depth_"))return"depth";if(t.includes(""))return"sint";if(t.includes(""))return"uint";if(t.includes(""))return"float"}function w3(t){return/,\s*([A-Za-z_][A-Za-z0-9_]*)\s*>$/.exec(t)?.[1]}var Od=` + +${Ao} +`,Eo=100,S3=`precision highp float; +`;function H0(t){let e=an(t.modules||[]),{source:r,bindingAssignments:i}=A3(t.platformInfo,{...t,source:t.source,stage:"vertex",modules:e});return{source:r,getUniforms:X0(e),bindingAssignments:i,bindingTable:xc(r,i)}}function Y0(t){let{vs:e,fs:r}=t,i=an(t.modules||[]);return{vs:V0(t.platformInfo,{...t,source:e,stage:"vertex",modules:i}),fs:V0(t.platformInfo,{...t,source:r,stage:"fragment",modules:i}),getUniforms:X0(i)}}function A3(t,e){let{source:r,stage:i,modules:n,hookFunctions:o=[],inject:s={},log:a}=e;li(typeof r=="string","shader source must be a string");let c=r,l="",f=Pd(o),u={},d={},h={};for(let y in s){let x=typeof s[y]=="string"?{injection:s[y],order:0}:s[y],w=/^(v|f)s:(#)?([\w-]+)$/.exec(y);if(w){let b=w[2],E=w[3];b?E==="decl"?d[y]=[x]:h[y]=[x]:u[y]=[x]}else h[y]=[x]}let p=n,g=R3(c),m=E3(g.source),_=I3(p,e._bindingRegistry,m),T=[];for(let y of p){a&&Ed(y,c,a);let x=C3(G0(y,"wgsl",a),y,{usedBindingsByGroup:m,bindingRegistry:e._bindingRegistry,reservedBindingKeysByGroup:_});T.push(...x.bindingAssignments);let w=x.source;l+=w;let b=y.injections?.[i]||{};for(let E in b){let S=/^(v|f)s:#([\w-]+)$/.exec(E);if(S){let C=S[2]==="decl"?d:h;C[E]=C[E]||[],C[E].push(b[E])}else u[E]=u[E]||[],u[E].push(b[E])}}return l+=Od,l=vo(l,i,d),l+=Cd(f[i],u),l+=F3(T),l+=g.source,l=vo(l,i,h),L3(l),{source:l,bindingAssignments:T}}function V0(t,e){let{source:r,stage:i,language:n="glsl",modules:o,defines:s={},hookFunctions:a=[],inject:c={},prologue:l=!0,log:f}=e;li(typeof r=="string","shader source must be a string");let u=n==="glsl"?F0(r).version:-1,d=t.shaderLanguageVersion,h=u===100?"#version 100":"#version 300 es",g=r.split(` +`).slice(1).join(` +`),m={};o.forEach(b=>{Object.assign(m,b.defines)}),Object.assign(m,s);let _="";switch(n){case"wgsl":break;case"glsl":_=l?`${h} + +// ----- PROLOGUE ------------------------- +${`#define SHADER_TYPE_${i.toUpperCase()}`} + +${O0(t)} +${i==="fragment"?S3:""} + +// ----- APPLICATION DEFINES ------------------------- + +${v3(m)} + +`:`${h} +`;break}let T=Pd(a),y={},x={},w={};for(let b in c){let E=typeof c[b]=="string"?{injection:c[b],order:0}:c[b],S=/^(v|f)s:(#)?([\w-]+)$/.exec(b);if(S){let A=S[2],C=S[3];A?C==="decl"?x[b]=[E]:w[b]=[E]:y[b]=[E]}else w[b]=[E]}for(let b of o){f&&Ed(b,g,f);let E=G0(b,i,f);_+=E;let S=b.instance?.normalizedInjections[i]||{};for(let A in S){let C=/^(v|f)s:#([\w-]+)$/.exec(A);if(C){let R=C[2]==="decl"?x:w;R[A]=R[A]||[],R[A].push(S[A])}else y[A]=y[A]||[],y[A].push(S[A])}}return _+="// ----- MAIN SHADER SOURCE -------------------------",_+=Od,_=vo(_,i,x),_+=Cd(T[i],y),_+=g,_=vo(_,i,w),n==="glsl"&&u!==d&&(_=D0(_,i)),n==="glsl"&&I0(_,i,f),_.trim()}function X0(t){return function(r){let i={};for(let n of t){let o=n.getUniforms?.(r,i);Object.assign(i,o)}return i}}function v3(t={}){let e="";for(let r in t){let i=t[r];(i||Number.isFinite(i))&&(e+=`#define ${r.toUpperCase()} ${t[r]} +`)}return e}function G0(t,e,r){let i;switch(e){case"vertex":i=t.vs||"";break;case"fragment":i=t.fs||"";break;case"wgsl":i=t.source||"";break;default:li(!1)}if(!t.name)throw new Error("Shader module must have a name");P0(t,e,{log:r});let n=t.name.toUpperCase().replace(/[^0-9a-z]/gi,"_"),o=`// ----- MODULE ${t.name} --------------- + +`;return e!=="wgsl"&&(o+=`#define MODULE_${n} +`),o+=`${i} +`,o}function E3(t){let e=new Map;for(let r of fi(t,B0)){let i=Number(r.bindingToken),n=Number(r.groupToken);Nd(n,i,r.name),ln(e,n,i,`application binding "${r.name}"`)}return e}function R3(t){let e=fi(t,_c),r=new Map;for(let o of e){if(o.bindingToken==="auto")continue;let s=Number(o.bindingToken),a=Number(o.groupToken);Nd(a,s,o.name),ln(r,a,s,`application binding "${o.name}"`)}let i={sawSupportedBindingDeclaration:e.length>0},n=Md(t,_c,o=>M3(o,r,i));if(Id(t)&&!i.sawSupportedBindingDeclaration)throw new Error('Unsupported @binding(auto) declaration form in application WGSL. Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.');return{source:n}}function C3(t,e,r){let i=[],o={sawSupportedBindingDeclaration:fi(t,cn).length>0,nextHintedBindingLocation:typeof e.firstBindingSlot=="number"?e.firstBindingSlot:null},s=Md(t,cn,a=>P3(a,{module:e,context:r,bindingAssignments:i,relocationState:o}));if(Id(t)&&!o.sawSupportedBindingDeclaration)throw new Error(`Unsupported @binding(auto) declaration form in module "${e.name}". Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.`);return{source:s,bindingAssignments:i}}function P3(t,e){let{module:r,context:i,bindingAssignments:n,relocationState:o}=e,{match:s,bindingToken:a,groupToken:c,name:l}=t,f=Number(c);if(a==="auto"){let d=q0(f,r.name,l),h=i.bindingRegistry?.get(d),p=h!==void 0?h:o.nextHintedBindingLocation===null?$0(f,i.usedBindingsByGroup):$0(f,i.usedBindingsByGroup,o.nextHintedBindingLocation);return j0(r.name,f,p,l),h!==void 0&&O3(i.reservedBindingKeysByGroup,f,p,d)?(n.push({moduleName:r.name,name:l,group:f,location:p}),s.replace(/@binding\(\s*auto\s*\)/,`@binding(${p})`)):(ln(i.usedBindingsByGroup,f,p,`module "${r.name}" binding "${l}"`),i.bindingRegistry?.set(d,p),n.push({moduleName:r.name,name:l,group:f,location:p}),o.nextHintedBindingLocation!==null&&h===void 0&&(o.nextHintedBindingLocation=p+1),s.replace(/@binding\(\s*auto\s*\)/,`@binding(${p})`))}let u=Number(a);return j0(r.name,f,u,l),ln(i.usedBindingsByGroup,f,u,`module "${r.name}" binding "${l}"`),n.push({moduleName:r.name,name:l,group:f,location:u}),s}function M3(t,e,r){let{match:i,bindingToken:n,groupToken:o,name:s}=t,a=Number(o);if(n==="auto"){let c=D3(a,e);return Nd(a,c,s),ln(e,a,c,`application binding "${s}"`),i.replace(/@binding\(\s*auto\s*\)/,`@binding(${c})`)}return r.sawSupportedBindingDeclaration=!0,i}function I3(t,e,r){let i=new Map;if(!e)return i;for(let n of t)for(let o of N3(n)){let s=q0(o.group,n.name,o.name),a=e.get(s);if(a!==void 0){let c=i.get(o.group)||new Map,l=c.get(a);if(l&&l!==s)throw new Error(`Duplicate WGSL binding reservation for modules "${l}" and "${s}": group ${o.group}, binding ${a}.`);ln(r,o.group,a,`registered module binding "${s}"`),c.set(a,s),i.set(o.group,c)}}return i}function O3(t,e,r,i){let n=t.get(e);if(!n)return!1;let o=n.get(r);if(!o)return!1;if(o!==i)throw new Error(`Registered module binding "${i}" collided with "${o}": group ${e}, binding ${r}.`);return!0}function N3(t){let e=[],r=t.source||"";for(let i of fi(r,cn))e.push({name:i.name,group:Number(i.groupToken)});return e}function Nd(t,e,r){if(t===0&&e>=Eo)throw new Error(`Application binding "${r}" in group 0 uses reserved binding ${e}. Application-owned explicit group-0 bindings must stay below ${Eo}.`)}function j0(t,e,r,i){if(e===0&&r0?Math.max(...i)+1:0);for(;i.has(n);)n++;return n}function D3(t,e){let r=e.get(t)||new Set,i=0;for(;r.has(i);)i++;return i}function L3(t){let e=k0(t,cn);if(!e)return;let r=B3(t,e.index);throw r?new Error(`Unresolved @binding(auto) for module "${r}" binding "${e.name}" remained in assembled WGSL source.`):k3(t,e.index)?new Error(`Unresolved @binding(auto) for application binding "${e.name}" remained in assembled WGSL source.`):new Error(`Unresolved @binding(auto) remained in assembled WGSL source near "${U3(e.match)}".`)}function F3(t){if(t.length===0)return"";let e=`// ----- MODULE WGSL BINDING ASSIGNMENTS --------------- +`;for(let r of t)e+=`// ${r.moduleName}.${r.name} -> @group(${r.group}) @binding(${r.location}) +`;return e+=` +`,e}function q0(t,e,r){return`${t}:${e}:${r}`}function B3(t,e){let r=/^\/\/ ----- MODULE ([^\n]+) ---------------$/gm,i,n;for(n=r.exec(t);n&&n.index<=e;)i=n[1],n=r.exec(t);return i}function k3(t,e){let r=t.indexOf(Od);return r>=0?e>r:!0}function U3(t){return t.replace(/\s+/g," ").trim()}var Dd="([a-zA-Z_][a-zA-Z0-9_]*)",z3=new RegExp(`^\\s*\\#\\s*ifdef\\s*${Dd}\\s*$`),W3=new RegExp(`^\\s*\\#\\s*ifndef\\s*${Dd}\\s*(?:\\/\\/.*)?$`),V3=/^\s*\#\s*else\s*(?:\/\/.*)?$/,j3=/^\s*\#\s*endif\s*$/,$3=new RegExp(`^\\s*\\#\\s*ifdef\\s*${Dd}\\s*(?:\\/\\/.*)?$`),H3=/^\s*\#\s*endif\s*(?:\/\/.*)?$/;function K0(t,e){let r=t.split(` +`),i=[],n=[],o=!0;for(let s of r){let a=s.match($3)||s.match(z3),c=s.match(W3),l=s.match(V3),f=s.match(H3)||s.match(j3);if(a||c){let u=(a||c)?.[1],d=!!e?.defines?.[u],h=a?d:!d,p=o&&h;n.push({parentActive:o,branchTaken:h,active:p}),o=p}else if(l){let u=n[n.length-1];if(!u)throw new Error("Encountered #else without matching #ifdef or #ifndef");u.active=u.parentActive&&!u.branchTaken,u.branchTaken=!0,o=u.active}else f?(n.pop(),o=n.length?n[n.length-1].active:!0):o&&i.push(s)}if(n.length>0)throw new Error("Unterminated conditional block in shader source");return i.join(` +`)}var ui=class t{static defaultShaderAssembler;_hookFunctions=[];_defaultModules=[];_wgslBindingRegistry=new Map;static getDefaultShaderAssembler(){return t.defaultShaderAssembler=t.defaultShaderAssembler||new t,t.defaultShaderAssembler}addDefaultModule(e){this._defaultModules.find(r=>r.name===(typeof e=="string"?e:e.name))||this._defaultModules.push(e)}removeDefaultModule(e){let r=typeof e=="string"?e:e.name;this._defaultModules=this._defaultModules.filter(i=>i.name!==r)}addShaderHook(e,r){r&&(e=Object.assign(r,{hook:e})),this._hookFunctions.push(e)}assembleWGSLShader(e){let r=this._getModuleList(e.modules),i=this._hookFunctions,{source:n,getUniforms:o,bindingAssignments:s}=H0({...e,source:e.source,_bindingRegistry:this._wgslBindingRegistry,modules:r,hookFunctions:i}),a={...r.reduce((l,f)=>(Object.assign(l,f.defines),l),{}),...e.defines},c=e.platformInfo.shaderLanguage==="wgsl"?K0(n,{defines:a}):n;return{source:c,getUniforms:o,modules:r,bindingAssignments:s,bindingTable:xc(c,s)}}assembleGLSLShaderPair(e){let r=this._getModuleList(e.modules),i=this._hookFunctions;return{...Y0({...e,vs:e.vs,fs:e.fs,modules:r,hookFunctions:i}),modules:r}}_getModuleList(e=[]){let r=new Array(this._defaultModules.length+e.length),i={},n=0;for(let o=0,s=this._defaultModules.length;oMath.max(e,Math.min(r,i)))}function di(t,e,r){return ir(t)?t.map((i,n)=>di(i,e[n],r)):r*e+(1-r)*t}function nr(t,e,r){let i=ye.EPSILON;r&&(ye.EPSILON=r);try{if(t===e)return!0;if(ir(t)&&ir(e)){if(t.length!==e.length)return!1;for(let n=0;n0?", ":"")+Fd(this[i],e);return`${e.printTypes?this.constructor.name:""}[${r}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let r=0;r=0&&e=0&&enR,angle:()=>SR,ceil:()=>oR,clone:()=>eR,copy:()=>rR,create:()=>Q0,cross:()=>mR,dist:()=>OR,distance:()=>ry,div:()=>IR,divide:()=>ty,dot:()=>gR,equals:()=>RR,exactEquals:()=>ER,floor:()=>sR,forEach:()=>LR,fromValues:()=>tR,inverse:()=>hR,len:()=>CR,length:()=>ny,lerp:()=>_R,max:()=>cR,min:()=>aR,mul:()=>MR,multiply:()=>ey,negate:()=>dR,normalize:()=>pR,random:()=>yR,rotate:()=>wR,round:()=>lR,scale:()=>fR,scaleAndAdd:()=>uR,set:()=>iR,sqrDist:()=>NR,sqrLen:()=>DR,squaredDistance:()=>iy,squaredLength:()=>oy,str:()=>vR,sub:()=>PR,subtract:()=>J0,transformMat2:()=>xR,transformMat2d:()=>bR,transformMat3:()=>TR,transformMat4:()=>kd,zero:()=>AR});var le=typeof Float32Array<"u"?Float32Array:Array,Nt=Math.random;function nt(t){return t>=0?Math.round(t):t%.5===0?Math.floor(t):Math.round(t)}var L9=Math.PI/180;function Q0(){let t=new le(2);return le!=Float32Array&&(t[0]=0,t[1]=0),t}function eR(t){let e=new le(2);return e[0]=t[0],e[1]=t[1],e}function tR(t,e){let r=new le(2);return r[0]=t,r[1]=e,r}function rR(t,e){return t[0]=e[0],t[1]=e[1],t}function iR(t,e,r){return t[0]=e,t[1]=r,t}function nR(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t}function J0(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t}function ey(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t}function ty(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t}function oR(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t}function sR(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t}function aR(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t}function cR(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t}function lR(t,e){return t[0]=nt(e[0]),t[1]=nt(e[1]),t}function fR(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t}function uR(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t}function ry(t,e){let r=e[0]-t[0],i=e[1]-t[1];return Math.sqrt(r*r+i*i)}function iy(t,e){let r=e[0]-t[0],i=e[1]-t[1];return r*r+i*i}function ny(t){let e=t[0],r=t[1];return Math.sqrt(e*e+r*r)}function oy(t){let e=t[0],r=t[1];return e*e+r*r}function dR(t,e){return t[0]=-e[0],t[1]=-e[1],t}function hR(t,e){return t[0]=1/e[0],t[1]=1/e[1],t}function pR(t,e){let r=e[0],i=e[1],n=r*r+i*i;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t}function gR(t,e){return t[0]*e[0]+t[1]*e[1]}function mR(t,e,r){let i=e[0]*r[1]-e[1]*r[0];return t[0]=t[1]=0,t[2]=i,t}function _R(t,e,r,i){let n=e[0],o=e[1];return t[0]=n+i*(r[0]-n),t[1]=o+i*(r[1]-o),t}function yR(t,e){e=e===void 0?1:e;let r=Nt()*2*Math.PI;return t[0]=Math.cos(r)*e,t[1]=Math.sin(r)*e,t}function xR(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[2]*n,t[1]=r[1]*i+r[3]*n,t}function bR(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[2]*n+r[4],t[1]=r[1]*i+r[3]*n+r[5],t}function TR(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[3]*n+r[6],t[1]=r[1]*i+r[4]*n+r[7],t}function kd(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[4]*n+r[12],t[1]=r[1]*i+r[5]*n+r[13],t}function wR(t,e,r,i){let n=e[0]-r[0],o=e[1]-r[1],s=Math.sin(i),a=Math.cos(i);return t[0]=n*a-o*s+r[0],t[1]=n*s+o*a+r[1],t}function SR(t,e){let r=t[0],i=t[1],n=e[0],o=e[1],s=Math.sqrt((r*r+i*i)*(n*n+o*o)),a=s&&(r*n+i*o)/s;return Math.acos(Math.min(Math.max(a,-1),1))}function AR(t){return t[0]=0,t[1]=0,t}function vR(t){return`vec2(${t[0]}, ${t[1]})`}function ER(t,e){return t[0]===e[0]&&t[1]===e[1]}function RR(t,e){let r=t[0],i=t[1],n=e[0],o=e[1];return Math.abs(r-n)<=1e-6*Math.max(1,Math.abs(r),Math.abs(n))&&Math.abs(i-o)<=1e-6*Math.max(1,Math.abs(i),Math.abs(o))}var CR=ny,PR=J0,MR=ey,IR=ty,OR=ry,NR=iy,DR=oy,LR=(function(){let t=Q0();return function(e,r,i,n,o,s){let a,c;for(r||(r=2),i||(i=0),n?c=Math.min(n*r+i,e.length):c=e.length,a=i;azR,angle:()=>Yd,bezier:()=>eC,ceil:()=>WR,clone:()=>FR,copy:()=>kR,create:()=>cy,cross:()=>zd,dist:()=>lC,distance:()=>hy,div:()=>cC,divide:()=>dy,dot:()=>Ud,equals:()=>oC,exactEquals:()=>nC,floor:()=>VR,forEach:()=>hC,fromValues:()=>BR,hermite:()=>JR,inverse:()=>qR,len:()=>uC,length:()=>ly,lerp:()=>ZR,max:()=>$R,min:()=>jR,mul:()=>aC,multiply:()=>uy,negate:()=>GR,normalize:()=>KR,random:()=>tC,rotateX:()=>jd,rotateY:()=>$d,rotateZ:()=>Hd,round:()=>HR,scale:()=>YR,scaleAndAdd:()=>XR,set:()=>UR,slerp:()=>QR,sqrDist:()=>fC,sqrLen:()=>dC,squaredDistance:()=>py,squaredLength:()=>gy,str:()=>iC,sub:()=>sC,subtract:()=>fy,transformMat3:()=>Wd,transformMat4:()=>Ro,transformQuat:()=>Vd,zero:()=>rC});function cy(){let t=new le(3);return le!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function FR(t){let e=new le(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function ly(t){let e=t[0],r=t[1],i=t[2];return Math.sqrt(e*e+r*r+i*i)}function BR(t,e,r){let i=new le(3);return i[0]=t,i[1]=e,i[2]=r,i}function kR(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function UR(t,e,r,i){return t[0]=e,t[1]=r,t[2]=i,t}function zR(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}function fy(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function uy(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function dy(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function WR(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t}function VR(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t}function jR(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}function $R(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}function HR(t,e){return t[0]=nt(e[0]),t[1]=nt(e[1]),t[2]=nt(e[2]),t}function YR(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}function XR(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t[2]=e[2]+r[2]*i,t}function hy(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2];return Math.sqrt(r*r+i*i+n*n)}function py(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2];return r*r+i*i+n*n}function gy(t){let e=t[0],r=t[1],i=t[2];return e*e+r*r+i*i}function GR(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}function qR(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}function KR(t,e){let r=e[0],i=e[1],n=e[2],o=r*r+i*i+n*n;return o>0&&(o=1/Math.sqrt(o)),t[0]=e[0]*o,t[1]=e[1]*o,t[2]=e[2]*o,t}function Ud(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function zd(t,e,r){let i=e[0],n=e[1],o=e[2],s=r[0],a=r[1],c=r[2];return t[0]=n*c-o*a,t[1]=o*s-i*c,t[2]=i*a-n*s,t}function ZR(t,e,r,i){let n=e[0],o=e[1],s=e[2];return t[0]=n+i*(r[0]-n),t[1]=o+i*(r[1]-o),t[2]=s+i*(r[2]-s),t}function QR(t,e,r,i){let n=Math.acos(Math.min(Math.max(Ud(e,r),-1),1)),o=Math.sin(n),s=Math.sin((1-i)*n)/o,a=Math.sin(i*n)/o;return t[0]=s*e[0]+a*r[0],t[1]=s*e[1]+a*r[1],t[2]=s*e[2]+a*r[2],t}function JR(t,e,r,i,n,o){let s=o*o,a=s*(2*o-3)+1,c=s*(o-2)+o,l=s*(o-1),f=s*(3-2*o);return t[0]=e[0]*a+r[0]*c+i[0]*l+n[0]*f,t[1]=e[1]*a+r[1]*c+i[1]*l+n[1]*f,t[2]=e[2]*a+r[2]*c+i[2]*l+n[2]*f,t}function eC(t,e,r,i,n,o){let s=1-o,a=s*s,c=o*o,l=a*s,f=3*o*a,u=3*c*s,d=c*o;return t[0]=e[0]*l+r[0]*f+i[0]*u+n[0]*d,t[1]=e[1]*l+r[1]*f+i[1]*u+n[1]*d,t[2]=e[2]*l+r[2]*f+i[2]*u+n[2]*d,t}function tC(t,e){e=e===void 0?1:e;let r=Nt()*2*Math.PI,i=Nt()*2-1,n=Math.sqrt(1-i*i)*e;return t[0]=Math.cos(r)*n,t[1]=Math.sin(r)*n,t[2]=i*e,t}function Ro(t,e,r){let i=e[0],n=e[1],o=e[2],s=r[3]*i+r[7]*n+r[11]*o+r[15];return s=s||1,t[0]=(r[0]*i+r[4]*n+r[8]*o+r[12])/s,t[1]=(r[1]*i+r[5]*n+r[9]*o+r[13])/s,t[2]=(r[2]*i+r[6]*n+r[10]*o+r[14])/s,t}function Wd(t,e,r){let i=e[0],n=e[1],o=e[2];return t[0]=i*r[0]+n*r[3]+o*r[6],t[1]=i*r[1]+n*r[4]+o*r[7],t[2]=i*r[2]+n*r[5]+o*r[8],t}function Vd(t,e,r){let i=r[0],n=r[1],o=r[2],s=r[3],a=e[0],c=e[1],l=e[2],f=n*l-o*c,u=o*a-i*l,d=i*c-n*a,h=n*d-o*u,p=o*f-i*d,g=i*u-n*f,m=s*2;return f*=m,u*=m,d*=m,h*=2,p*=2,g*=2,t[0]=a+f+h,t[1]=c+u+p,t[2]=l+d+g,t}function jd(t,e,r,i){let n=[],o=[];return n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],o[0]=n[0],o[1]=n[1]*Math.cos(i)-n[2]*Math.sin(i),o[2]=n[1]*Math.sin(i)+n[2]*Math.cos(i),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function $d(t,e,r,i){let n=[],o=[];return n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],o[0]=n[2]*Math.sin(i)+n[0]*Math.cos(i),o[1]=n[1],o[2]=n[2]*Math.cos(i)-n[0]*Math.sin(i),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function Hd(t,e,r,i){let n=[],o=[];return n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],o[0]=n[0]*Math.cos(i)-n[1]*Math.sin(i),o[1]=n[0]*Math.sin(i)+n[1]*Math.cos(i),o[2]=n[2],t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function Yd(t,e){let r=t[0],i=t[1],n=t[2],o=e[0],s=e[1],a=e[2],c=Math.sqrt((r*r+i*i+n*n)*(o*o+s*s+a*a)),l=c&&Ud(t,e)/c;return Math.acos(Math.min(Math.max(l,-1),1))}function rC(t){return t[0]=0,t[1]=0,t[2]=0,t}function iC(t){return`vec3(${t[0]}, ${t[1]}, ${t[2]})`}function nC(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}function oC(t,e){let r=t[0],i=t[1],n=t[2],o=e[0],s=e[1],a=e[2];return Math.abs(r-o)<=1e-6*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(i-s)<=1e-6*Math.max(1,Math.abs(i),Math.abs(s))&&Math.abs(n-a)<=1e-6*Math.max(1,Math.abs(n),Math.abs(a))}var sC=fy,aC=uy,cC=dy,lC=hy,fC=py,uC=ly,dC=gy,hC=(function(){let t=cy();return function(e,r,i,n,o,s){let a,c;for(r||(r=3),i||(i=0),n?c=Math.min(n*r+i,e.length):c=e.length,a=i;akC,adjoint:()=>xC,clone:()=>gC,copy:()=>mC,create:()=>pC,decompose:()=>PC,determinant:()=>Kd,equals:()=>VC,exactEquals:()=>WC,frob:()=>BC,fromQuat:()=>ih,fromQuat2:()=>EC,fromRotation:()=>wC,fromRotationTranslation:()=>_y,fromRotationTranslationScale:()=>MC,fromRotationTranslationScaleOrigin:()=>IC,fromScaling:()=>TC,fromTranslation:()=>bC,fromValues:()=>_C,fromXRotation:()=>SC,fromYRotation:()=>AC,fromZRotation:()=>vC,frustum:()=>nh,getRotation:()=>CC,getScaling:()=>yy,getTranslation:()=>RC,identity:()=>my,invert:()=>qd,lookAt:()=>ah,mul:()=>jC,multiply:()=>Co,multiplyScalar:()=>UC,multiplyScalarAndAdd:()=>zC,ortho:()=>sh,orthoNO:()=>by,orthoZO:()=>DC,perspective:()=>oh,perspectiveFromFieldOfView:()=>NC,perspectiveNO:()=>xy,perspectiveZO:()=>OC,rotate:()=>Jd,rotateX:()=>eh,rotateY:()=>th,rotateZ:()=>rh,scale:()=>Qd,set:()=>yC,str:()=>FC,sub:()=>$C,subtract:()=>Ty,targetTo:()=>LC,translate:()=>Zd,transpose:()=>Gd});function pC(){let t=new le(16);return le!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function gC(t){let e=new le(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function mC(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function _C(t,e,r,i,n,o,s,a,c,l,f,u,d,h,p,g){let m=new le(16);return m[0]=t,m[1]=e,m[2]=r,m[3]=i,m[4]=n,m[5]=o,m[6]=s,m[7]=a,m[8]=c,m[9]=l,m[10]=f,m[11]=u,m[12]=d,m[13]=h,m[14]=p,m[15]=g,m}function yC(t,e,r,i,n,o,s,a,c,l,f,u,d,h,p,g,m){return t[0]=e,t[1]=r,t[2]=i,t[3]=n,t[4]=o,t[5]=s,t[6]=a,t[7]=c,t[8]=l,t[9]=f,t[10]=u,t[11]=d,t[12]=h,t[13]=p,t[14]=g,t[15]=m,t}function my(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Gd(t,e){if(t===e){let r=e[1],i=e[2],n=e[3],o=e[6],s=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=i,t[9]=o,t[11]=e[14],t[12]=n,t[13]=s,t[14]=a}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function qd(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=e[4],a=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],p=e[12],g=e[13],m=e[14],_=e[15],T=r*a-i*s,y=r*c-n*s,x=r*l-o*s,w=i*c-n*a,b=i*l-o*a,E=n*l-o*c,S=f*g-u*p,A=f*m-d*p,C=f*_-h*p,I=u*m-d*g,R=u*_-h*g,N=d*_-h*m,O=T*N-y*R+x*I+w*C-b*A+E*S;return O?(O=1/O,t[0]=(a*N-c*R+l*I)*O,t[1]=(n*R-i*N-o*I)*O,t[2]=(g*E-m*b+_*w)*O,t[3]=(d*b-u*E-h*w)*O,t[4]=(c*C-s*N-l*A)*O,t[5]=(r*N-n*C+o*A)*O,t[6]=(m*x-p*E-_*y)*O,t[7]=(f*E-d*x+h*y)*O,t[8]=(s*R-a*C+l*S)*O,t[9]=(i*C-r*R-o*S)*O,t[10]=(p*b-g*x+_*T)*O,t[11]=(u*x-f*b-h*T)*O,t[12]=(a*A-s*I-c*S)*O,t[13]=(r*I-i*A+n*S)*O,t[14]=(g*y-p*w-m*T)*O,t[15]=(f*w-u*y+d*T)*O,t):null}function xC(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=e[4],a=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],p=e[12],g=e[13],m=e[14],_=e[15],T=r*a-i*s,y=r*c-n*s,x=r*l-o*s,w=i*c-n*a,b=i*l-o*a,E=n*l-o*c,S=f*g-u*p,A=f*m-d*p,C=f*_-h*p,I=u*m-d*g,R=u*_-h*g,N=d*_-h*m;return t[0]=a*N-c*R+l*I,t[1]=n*R-i*N-o*I,t[2]=g*E-m*b+_*w,t[3]=d*b-u*E-h*w,t[4]=c*C-s*N-l*A,t[5]=r*N-n*C+o*A,t[6]=m*x-p*E-_*y,t[7]=f*E-d*x+h*y,t[8]=s*R-a*C+l*S,t[9]=i*C-r*R-o*S,t[10]=p*b-g*x+_*T,t[11]=u*x-f*b-h*T,t[12]=a*A-s*I-c*S,t[13]=r*I-i*A+n*S,t[14]=g*y-p*w-m*T,t[15]=f*w-u*y+d*T,t}function Kd(t){let e=t[0],r=t[1],i=t[2],n=t[3],o=t[4],s=t[5],a=t[6],c=t[7],l=t[8],f=t[9],u=t[10],d=t[11],h=t[12],p=t[13],g=t[14],m=t[15],_=e*s-r*o,T=e*a-i*o,y=r*a-i*s,x=l*p-f*h,w=l*g-u*h,b=f*g-u*p,E=e*b-r*w+i*x,S=o*b-s*w+a*x,A=l*y-f*T+u*_,C=h*y-p*T+g*_;return c*E-n*S+m*A-d*C}function Co(t,e,r){let i=e[0],n=e[1],o=e[2],s=e[3],a=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=e[9],h=e[10],p=e[11],g=e[12],m=e[13],_=e[14],T=e[15],y=r[0],x=r[1],w=r[2],b=r[3];return t[0]=y*i+x*a+w*u+b*g,t[1]=y*n+x*c+w*d+b*m,t[2]=y*o+x*l+w*h+b*_,t[3]=y*s+x*f+w*p+b*T,y=r[4],x=r[5],w=r[6],b=r[7],t[4]=y*i+x*a+w*u+b*g,t[5]=y*n+x*c+w*d+b*m,t[6]=y*o+x*l+w*h+b*_,t[7]=y*s+x*f+w*p+b*T,y=r[8],x=r[9],w=r[10],b=r[11],t[8]=y*i+x*a+w*u+b*g,t[9]=y*n+x*c+w*d+b*m,t[10]=y*o+x*l+w*h+b*_,t[11]=y*s+x*f+w*p+b*T,y=r[12],x=r[13],w=r[14],b=r[15],t[12]=y*i+x*a+w*u+b*g,t[13]=y*n+x*c+w*d+b*m,t[14]=y*o+x*l+w*h+b*_,t[15]=y*s+x*f+w*p+b*T,t}function Zd(t,e,r){let i=r[0],n=r[1],o=r[2],s,a,c,l,f,u,d,h,p,g,m,_;return e===t?(t[12]=e[0]*i+e[4]*n+e[8]*o+e[12],t[13]=e[1]*i+e[5]*n+e[9]*o+e[13],t[14]=e[2]*i+e[6]*n+e[10]*o+e[14],t[15]=e[3]*i+e[7]*n+e[11]*o+e[15]):(s=e[0],a=e[1],c=e[2],l=e[3],f=e[4],u=e[5],d=e[6],h=e[7],p=e[8],g=e[9],m=e[10],_=e[11],t[0]=s,t[1]=a,t[2]=c,t[3]=l,t[4]=f,t[5]=u,t[6]=d,t[7]=h,t[8]=p,t[9]=g,t[10]=m,t[11]=_,t[12]=s*i+f*n+p*o+e[12],t[13]=a*i+u*n+g*o+e[13],t[14]=c*i+d*n+m*o+e[14],t[15]=l*i+h*n+_*o+e[15]),t}function Qd(t,e,r){let i=r[0],n=r[1],o=r[2];return t[0]=e[0]*i,t[1]=e[1]*i,t[2]=e[2]*i,t[3]=e[3]*i,t[4]=e[4]*n,t[5]=e[5]*n,t[6]=e[6]*n,t[7]=e[7]*n,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function Jd(t,e,r,i){let n=i[0],o=i[1],s=i[2],a=Math.sqrt(n*n+o*o+s*s),c,l,f,u,d,h,p,g,m,_,T,y,x,w,b,E,S,A,C,I,R,N,O,W;return a<1e-6?null:(a=1/a,n*=a,o*=a,s*=a,l=Math.sin(r),c=Math.cos(r),f=1-c,u=e[0],d=e[1],h=e[2],p=e[3],g=e[4],m=e[5],_=e[6],T=e[7],y=e[8],x=e[9],w=e[10],b=e[11],E=n*n*f+c,S=o*n*f+s*l,A=s*n*f-o*l,C=n*o*f-s*l,I=o*o*f+c,R=s*o*f+n*l,N=n*s*f+o*l,O=o*s*f-n*l,W=s*s*f+c,t[0]=u*E+g*S+y*A,t[1]=d*E+m*S+x*A,t[2]=h*E+_*S+w*A,t[3]=p*E+T*S+b*A,t[4]=u*C+g*I+y*R,t[5]=d*C+m*I+x*R,t[6]=h*C+_*I+w*R,t[7]=p*C+T*I+b*R,t[8]=u*N+g*O+y*W,t[9]=d*N+m*O+x*W,t[10]=h*N+_*O+w*W,t[11]=p*N+T*O+b*W,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}function eh(t,e,r){let i=Math.sin(r),n=Math.cos(r),o=e[4],s=e[5],a=e[6],c=e[7],l=e[8],f=e[9],u=e[10],d=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=o*n+l*i,t[5]=s*n+f*i,t[6]=a*n+u*i,t[7]=c*n+d*i,t[8]=l*n-o*i,t[9]=f*n-s*i,t[10]=u*n-a*i,t[11]=d*n-c*i,t}function th(t,e,r){let i=Math.sin(r),n=Math.cos(r),o=e[0],s=e[1],a=e[2],c=e[3],l=e[8],f=e[9],u=e[10],d=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*n-l*i,t[1]=s*n-f*i,t[2]=a*n-u*i,t[3]=c*n-d*i,t[8]=o*i+l*n,t[9]=s*i+f*n,t[10]=a*i+u*n,t[11]=c*i+d*n,t}function rh(t,e,r){let i=Math.sin(r),n=Math.cos(r),o=e[0],s=e[1],a=e[2],c=e[3],l=e[4],f=e[5],u=e[6],d=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*n+l*i,t[1]=s*n+f*i,t[2]=a*n+u*i,t[3]=c*n+d*i,t[4]=l*n-o*i,t[5]=f*n-s*i,t[6]=u*n-a*i,t[7]=d*n-c*i,t}function bC(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e[0],t[13]=e[1],t[14]=e[2],t[15]=1,t}function TC(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function wC(t,e,r){let i=r[0],n=r[1],o=r[2],s=Math.sqrt(i*i+n*n+o*o),a,c,l;return s<1e-6?null:(s=1/s,i*=s,n*=s,o*=s,c=Math.sin(e),a=Math.cos(e),l=1-a,t[0]=i*i*l+a,t[1]=n*i*l+o*c,t[2]=o*i*l-n*c,t[3]=0,t[4]=i*n*l-o*c,t[5]=n*n*l+a,t[6]=o*n*l+i*c,t[7]=0,t[8]=i*o*l+n*c,t[9]=n*o*l-i*c,t[10]=o*o*l+a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}function SC(t,e){let r=Math.sin(e),i=Math.cos(e);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=i,t[6]=r,t[7]=0,t[8]=0,t[9]=-r,t[10]=i,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function AC(t,e){let r=Math.sin(e),i=Math.cos(e);return t[0]=i,t[1]=0,t[2]=-r,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=r,t[9]=0,t[10]=i,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function vC(t,e){let r=Math.sin(e),i=Math.cos(e);return t[0]=i,t[1]=r,t[2]=0,t[3]=0,t[4]=-r,t[5]=i,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function _y(t,e,r){let i=e[0],n=e[1],o=e[2],s=e[3],a=i+i,c=n+n,l=o+o,f=i*a,u=i*c,d=i*l,h=n*c,p=n*l,g=o*l,m=s*a,_=s*c,T=s*l;return t[0]=1-(h+g),t[1]=u+T,t[2]=d-_,t[3]=0,t[4]=u-T,t[5]=1-(f+g),t[6]=p+m,t[7]=0,t[8]=d+_,t[9]=p-m,t[10]=1-(f+h),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function EC(t,e){let r=new le(3),i=-e[0],n=-e[1],o=-e[2],s=e[3],a=e[4],c=e[5],l=e[6],f=e[7],u=i*i+n*n+o*o+s*s;return u>0?(r[0]=(a*s+f*i+c*o-l*n)*2/u,r[1]=(c*s+f*n+l*i-a*o)*2/u,r[2]=(l*s+f*o+a*n-c*i)*2/u):(r[0]=(a*s+f*i+c*o-l*n)*2,r[1]=(c*s+f*n+l*i-a*o)*2,r[2]=(l*s+f*o+a*n-c*i)*2),_y(t,e,r),t}function RC(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function yy(t,e){let r=e[0],i=e[1],n=e[2],o=e[4],s=e[5],a=e[6],c=e[8],l=e[9],f=e[10];return t[0]=Math.sqrt(r*r+i*i+n*n),t[1]=Math.sqrt(o*o+s*s+a*a),t[2]=Math.sqrt(c*c+l*l+f*f),t}function CC(t,e){let r=new le(3);yy(r,e);let i=1/r[0],n=1/r[1],o=1/r[2],s=e[0]*i,a=e[1]*n,c=e[2]*o,l=e[4]*i,f=e[5]*n,u=e[6]*o,d=e[8]*i,h=e[9]*n,p=e[10]*o,g=s+f+p,m=0;return g>0?(m=Math.sqrt(g+1)*2,t[3]=.25*m,t[0]=(u-h)/m,t[1]=(d-c)/m,t[2]=(a-l)/m):s>f&&s>p?(m=Math.sqrt(1+s-f-p)*2,t[3]=(u-h)/m,t[0]=.25*m,t[1]=(a+l)/m,t[2]=(d+c)/m):f>p?(m=Math.sqrt(1+f-s-p)*2,t[3]=(d-c)/m,t[0]=(a+l)/m,t[1]=.25*m,t[2]=(u+h)/m):(m=Math.sqrt(1+p-s-f)*2,t[3]=(a-l)/m,t[0]=(d+c)/m,t[1]=(u+h)/m,t[2]=.25*m),t}function PC(t,e,r,i){e[0]=i[12],e[1]=i[13],e[2]=i[14];let n=i[0],o=i[1],s=i[2],a=i[4],c=i[5],l=i[6],f=i[8],u=i[9],d=i[10];r[0]=Math.sqrt(n*n+o*o+s*s),r[1]=Math.sqrt(a*a+c*c+l*l),r[2]=Math.sqrt(f*f+u*u+d*d);let h=1/r[0],p=1/r[1],g=1/r[2],m=n*h,_=o*p,T=s*g,y=a*h,x=c*p,w=l*g,b=f*h,E=u*p,S=d*g,A=m+x+S,C=0;return A>0?(C=Math.sqrt(A+1)*2,t[3]=.25*C,t[0]=(w-E)/C,t[1]=(b-T)/C,t[2]=(_-y)/C):m>x&&m>S?(C=Math.sqrt(1+m-x-S)*2,t[3]=(w-E)/C,t[0]=.25*C,t[1]=(_+y)/C,t[2]=(b+T)/C):x>S?(C=Math.sqrt(1+x-m-S)*2,t[3]=(b-T)/C,t[0]=(_+y)/C,t[1]=.25*C,t[2]=(w+E)/C):(C=Math.sqrt(1+S-m-x)*2,t[3]=(_-y)/C,t[0]=(b+T)/C,t[1]=(w+E)/C,t[2]=.25*C),t}function MC(t,e,r,i){let n=e[0],o=e[1],s=e[2],a=e[3],c=n+n,l=o+o,f=s+s,u=n*c,d=n*l,h=n*f,p=o*l,g=o*f,m=s*f,_=a*c,T=a*l,y=a*f,x=i[0],w=i[1],b=i[2];return t[0]=(1-(p+m))*x,t[1]=(d+y)*x,t[2]=(h-T)*x,t[3]=0,t[4]=(d-y)*w,t[5]=(1-(u+m))*w,t[6]=(g+_)*w,t[7]=0,t[8]=(h+T)*b,t[9]=(g-_)*b,t[10]=(1-(u+p))*b,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function IC(t,e,r,i,n){let o=e[0],s=e[1],a=e[2],c=e[3],l=o+o,f=s+s,u=a+a,d=o*l,h=o*f,p=o*u,g=s*f,m=s*u,_=a*u,T=c*l,y=c*f,x=c*u,w=i[0],b=i[1],E=i[2],S=n[0],A=n[1],C=n[2],I=(1-(g+_))*w,R=(h+x)*w,N=(p-y)*w,O=(h-x)*b,W=(1-(d+_))*b,G=(m+T)*b,L=(p+y)*E,H=(m-T)*E,Re=(1-(d+g))*E;return t[0]=I,t[1]=R,t[2]=N,t[3]=0,t[4]=O,t[5]=W,t[6]=G,t[7]=0,t[8]=L,t[9]=H,t[10]=Re,t[11]=0,t[12]=r[0]+S-(I*S+O*A+L*C),t[13]=r[1]+A-(R*S+W*A+H*C),t[14]=r[2]+C-(N*S+G*A+Re*C),t[15]=1,t}function ih(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=r+r,a=i+i,c=n+n,l=r*s,f=i*s,u=i*a,d=n*s,h=n*a,p=n*c,g=o*s,m=o*a,_=o*c;return t[0]=1-u-p,t[1]=f+_,t[2]=d-m,t[3]=0,t[4]=f-_,t[5]=1-l-p,t[6]=h+g,t[7]=0,t[8]=d+m,t[9]=h-g,t[10]=1-l-u,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function nh(t,e,r,i,n,o,s){let a=1/(r-e),c=1/(n-i),l=1/(o-s);return t[0]=o*2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o*2*c,t[6]=0,t[7]=0,t[8]=(r+e)*a,t[9]=(n+i)*c,t[10]=(s+o)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=s*o*2*l,t[15]=0,t}function xy(t,e,r,i,n){let o=1/Math.tan(e/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,n!=null&&n!==1/0){let s=1/(i-n);t[10]=(n+i)*s,t[14]=2*n*i*s}else t[10]=-1,t[14]=-2*i;return t}var oh=xy;function OC(t,e,r,i,n){let o=1/Math.tan(e/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,n!=null&&n!==1/0){let s=1/(i-n);t[10]=n*s,t[14]=n*i*s}else t[10]=-1,t[14]=-i;return t}function NC(t,e,r,i){let n=Math.tan(e.upDegrees*Math.PI/180),o=Math.tan(e.downDegrees*Math.PI/180),s=Math.tan(e.leftDegrees*Math.PI/180),a=Math.tan(e.rightDegrees*Math.PI/180),c=2/(s+a),l=2/(n+o);return t[0]=c,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=l,t[6]=0,t[7]=0,t[8]=-((s-a)*c*.5),t[9]=(n-o)*l*.5,t[10]=i/(r-i),t[11]=-1,t[12]=0,t[13]=0,t[14]=i*r/(r-i),t[15]=0,t}function by(t,e,r,i,n,o,s){let a=1/(e-r),c=1/(i-n),l=1/(o-s);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*a,t[13]=(n+i)*c,t[14]=(s+o)*l,t[15]=1,t}var sh=by;function DC(t,e,r,i,n,o,s){let a=1/(e-r),c=1/(i-n),l=1/(o-s);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=l,t[11]=0,t[12]=(e+r)*a,t[13]=(n+i)*c,t[14]=o*l,t[15]=1,t}function ah(t,e,r,i){let n,o,s,a,c,l,f,u,d,h,p=e[0],g=e[1],m=e[2],_=i[0],T=i[1],y=i[2],x=r[0],w=r[1],b=r[2];return Math.abs(p-x)<1e-6&&Math.abs(g-w)<1e-6&&Math.abs(m-b)<1e-6?my(t):(u=p-x,d=g-w,h=m-b,n=1/Math.sqrt(u*u+d*d+h*h),u*=n,d*=n,h*=n,o=T*h-y*d,s=y*u-_*h,a=_*d-T*u,n=Math.sqrt(o*o+s*s+a*a),n?(n=1/n,o*=n,s*=n,a*=n):(o=0,s=0,a=0),c=d*a-h*s,l=h*o-u*a,f=u*s-d*o,n=Math.sqrt(c*c+l*l+f*f),n?(n=1/n,c*=n,l*=n,f*=n):(c=0,l=0,f=0),t[0]=o,t[1]=c,t[2]=u,t[3]=0,t[4]=s,t[5]=l,t[6]=d,t[7]=0,t[8]=a,t[9]=f,t[10]=h,t[11]=0,t[12]=-(o*p+s*g+a*m),t[13]=-(c*p+l*g+f*m),t[14]=-(u*p+d*g+h*m),t[15]=1,t)}function LC(t,e,r,i){let n=e[0],o=e[1],s=e[2],a=i[0],c=i[1],l=i[2],f=n-r[0],u=o-r[1],d=s-r[2],h=f*f+u*u+d*d;h>0&&(h=1/Math.sqrt(h),f*=h,u*=h,d*=h);let p=c*d-l*u,g=l*f-a*d,m=a*u-c*f;return h=p*p+g*g+m*m,h>0&&(h=1/Math.sqrt(h),p*=h,g*=h,m*=h),t[0]=p,t[1]=g,t[2]=m,t[3]=0,t[4]=u*m-d*g,t[5]=d*p-f*m,t[6]=f*g-u*p,t[7]=0,t[8]=f,t[9]=u,t[10]=d,t[11]=0,t[12]=n,t[13]=o,t[14]=s,t[15]=1,t}function FC(t){return`mat4(${t[0]}, ${t[1]}, ${t[2]}, ${t[3]}, ${t[4]}, ${t[5]}, ${t[6]}, ${t[7]}, ${t[8]}, ${t[9]}, ${t[10]}, ${t[11]}, ${t[12]}, ${t[13]}, ${t[14]}, ${t[15]})`}function BC(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function kC(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t}function Ty(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}function UC(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t}function zC(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t[2]=e[2]+r[2]*i,t[3]=e[3]+r[3]*i,t[4]=e[4]+r[4]*i,t[5]=e[5]+r[5]*i,t[6]=e[6]+r[6]*i,t[7]=e[7]+r[7]*i,t[8]=e[8]+r[8]*i,t[9]=e[9]+r[9]*i,t[10]=e[10]+r[10]*i,t[11]=e[11]+r[11]*i,t[12]=e[12]+r[12]*i,t[13]=e[13]+r[13]*i,t[14]=e[14]+r[14]*i,t[15]=e[15]+r[15]*i,t}function WC(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]}function VC(t,e){let r=t[0],i=t[1],n=t[2],o=t[3],s=t[4],a=t[5],c=t[6],l=t[7],f=t[8],u=t[9],d=t[10],h=t[11],p=t[12],g=t[13],m=t[14],_=t[15],T=e[0],y=e[1],x=e[2],w=e[3],b=e[4],E=e[5],S=e[6],A=e[7],C=e[8],I=e[9],R=e[10],N=e[11],O=e[12],W=e[13],G=e[14],L=e[15];return Math.abs(r-T)<=1e-6*Math.max(1,Math.abs(r),Math.abs(T))&&Math.abs(i-y)<=1e-6*Math.max(1,Math.abs(i),Math.abs(y))&&Math.abs(n-x)<=1e-6*Math.max(1,Math.abs(n),Math.abs(x))&&Math.abs(o-w)<=1e-6*Math.max(1,Math.abs(o),Math.abs(w))&&Math.abs(s-b)<=1e-6*Math.max(1,Math.abs(s),Math.abs(b))&&Math.abs(a-E)<=1e-6*Math.max(1,Math.abs(a),Math.abs(E))&&Math.abs(c-S)<=1e-6*Math.max(1,Math.abs(c),Math.abs(S))&&Math.abs(l-A)<=1e-6*Math.max(1,Math.abs(l),Math.abs(A))&&Math.abs(f-C)<=1e-6*Math.max(1,Math.abs(f),Math.abs(C))&&Math.abs(u-I)<=1e-6*Math.max(1,Math.abs(u),Math.abs(I))&&Math.abs(d-R)<=1e-6*Math.max(1,Math.abs(d),Math.abs(R))&&Math.abs(h-N)<=1e-6*Math.max(1,Math.abs(h),Math.abs(N))&&Math.abs(p-O)<=1e-6*Math.max(1,Math.abs(p),Math.abs(O))&&Math.abs(g-W)<=1e-6*Math.max(1,Math.abs(g),Math.abs(W))&&Math.abs(m-G)<=1e-6*Math.max(1,Math.abs(m),Math.abs(G))&&Math.abs(_-L)<=1e-6*Math.max(1,Math.abs(_),Math.abs(L))}var jC=Co,$C=Ty;var Ze={};Zi(Ze,{add:()=>qC,ceil:()=>KC,clone:()=>HC,copy:()=>XC,create:()=>wy,cross:()=>aP,dist:()=>yP,distance:()=>Ey,div:()=>_P,divide:()=>vy,dot:()=>sP,equals:()=>pP,exactEquals:()=>hP,floor:()=>ZC,forEach:()=>wP,fromValues:()=>YC,inverse:()=>nP,len:()=>bP,length:()=>Cy,lerp:()=>cP,max:()=>JC,min:()=>QC,mul:()=>mP,multiply:()=>Ay,negate:()=>iP,normalize:()=>oP,random:()=>lP,round:()=>eP,scale:()=>tP,scaleAndAdd:()=>rP,set:()=>GC,sqrDist:()=>xP,sqrLen:()=>TP,squaredDistance:()=>Ry,squaredLength:()=>Py,str:()=>dP,sub:()=>gP,subtract:()=>Sy,transformMat4:()=>ch,transformQuat:()=>fP,zero:()=>uP});function wy(){let t=new le(4);return le!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function HC(t){let e=new le(4);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function YC(t,e,r,i){let n=new le(4);return n[0]=t,n[1]=e,n[2]=r,n[3]=i,n}function XC(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}function GC(t,e,r,i,n){return t[0]=e,t[1]=r,t[2]=i,t[3]=n,t}function qC(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t}function Sy(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}function Ay(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t}function vy(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t[3]=e[3]/r[3],t}function KC(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t[3]=Math.ceil(e[3]),t}function ZC(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t[3]=Math.floor(e[3]),t}function QC(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t[3]=Math.min(e[3],r[3]),t}function JC(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t[3]=Math.max(e[3],r[3]),t}function eP(t,e){return t[0]=nt(e[0]),t[1]=nt(e[1]),t[2]=nt(e[2]),t[3]=nt(e[3]),t}function tP(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t}function rP(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t[2]=e[2]+r[2]*i,t[3]=e[3]+r[3]*i,t}function Ey(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2],o=e[3]-t[3];return Math.sqrt(r*r+i*i+n*n+o*o)}function Ry(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2],o=e[3]-t[3];return r*r+i*i+n*n+o*o}function Cy(t){let e=t[0],r=t[1],i=t[2],n=t[3];return Math.sqrt(e*e+r*r+i*i+n*n)}function Py(t){let e=t[0],r=t[1],i=t[2],n=t[3];return e*e+r*r+i*i+n*n}function iP(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t}function nP(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t[3]=1/e[3],t}function oP(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=r*r+i*i+n*n+o*o;return s>0&&(s=1/Math.sqrt(s)),t[0]=r*s,t[1]=i*s,t[2]=n*s,t[3]=o*s,t}function sP(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function aP(t,e,r,i){let n=r[0]*i[1]-r[1]*i[0],o=r[0]*i[2]-r[2]*i[0],s=r[0]*i[3]-r[3]*i[0],a=r[1]*i[2]-r[2]*i[1],c=r[1]*i[3]-r[3]*i[1],l=r[2]*i[3]-r[3]*i[2],f=e[0],u=e[1],d=e[2],h=e[3];return t[0]=u*l-d*c+h*a,t[1]=-(f*l)+d*s-h*o,t[2]=f*c-u*s+h*n,t[3]=-(f*a)+u*o-d*n,t}function cP(t,e,r,i){let n=e[0],o=e[1],s=e[2],a=e[3];return t[0]=n+i*(r[0]-n),t[1]=o+i*(r[1]-o),t[2]=s+i*(r[2]-s),t[3]=a+i*(r[3]-a),t}function lP(t,e){e=e===void 0?1:e;let r,i,n,o,s,a;do r=Nt()*2-1,i=Nt()*2-1,s=r*r+i*i;while(s>=1);do n=Nt()*2-1,o=Nt()*2-1,a=n*n+o*o;while(a>=1);let c=Math.sqrt((1-s)/a);return t[0]=e*r,t[1]=e*i,t[2]=e*n*c,t[3]=e*o*c,t}function ch(t,e,r){let i=e[0],n=e[1],o=e[2],s=e[3];return t[0]=r[0]*i+r[4]*n+r[8]*o+r[12]*s,t[1]=r[1]*i+r[5]*n+r[9]*o+r[13]*s,t[2]=r[2]*i+r[6]*n+r[10]*o+r[14]*s,t[3]=r[3]*i+r[7]*n+r[11]*o+r[15]*s,t}function fP(t,e,r){let i=e[0],n=e[1],o=e[2],s=r[0],a=r[1],c=r[2],l=r[3],f=l*i+a*o-c*n,u=l*n+c*i-s*o,d=l*o+s*n-a*i,h=-s*i-a*n-c*o;return t[0]=f*l+h*-s+u*-c-d*-a,t[1]=u*l+h*-a+d*-s-f*-c,t[2]=d*l+h*-c+f*-a-u*-s,t[3]=e[3],t}function uP(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}function dP(t){return`vec4(${t[0]}, ${t[1]}, ${t[2]}, ${t[3]})`}function hP(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]}function pP(t,e){let r=t[0],i=t[1],n=t[2],o=t[3],s=e[0],a=e[1],c=e[2],l=e[3];return Math.abs(r-s)<=1e-6*Math.max(1,Math.abs(r),Math.abs(s))&&Math.abs(i-a)<=1e-6*Math.max(1,Math.abs(i),Math.abs(a))&&Math.abs(n-c)<=1e-6*Math.max(1,Math.abs(n),Math.abs(c))&&Math.abs(o-l)<=1e-6*Math.max(1,Math.abs(o),Math.abs(l))}var gP=Sy,mP=Ay,_P=vy,yP=Ey,xP=Ry,bP=Cy,TP=Py,wP=(function(){let t=wy();return function(e,r,i,n,o,s){let a,c;for(r||(r=4),i||(i=0),n?c=Math.min(n*r+i,e.length):c=e.length,a=i;aMath.PI*2)throw Error("expected radians")}function CP(t,e,r,i,n,o){let s=2*o/(r-e),a=2*o/(n-i),c=(r+e)/(r-e),l=(n+i)/(n-i),f=-1,u=-1,d=-2*o;return t[0]=s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=c,t[9]=l,t[10]=f,t[11]=u,t[12]=0,t[13]=0,t[14]=d,t[15]=0,t}function dh(t,e=[],r=0){let i=Math.fround(t),n=t-i;return e[r]=i,e[r+1]=n,e}function Iy(t){return t-Math.fround(t)}function Oy(t){let e=new Float32Array(32);for(let r=0;r<4;++r)for(let i=0;i<4;++i){let n=r*4+i;dh(t[i*4+r],e,n*2)}return e}function Ny(t,e=!0){return t??e}function PP(t=[0,0,0],e=!0){return e?t.map(r=>r/255):[...t]}function Dy(t,e=!0){let r=PP(t.slice(0,3),e),i=Number.isFinite(t[3]),n=i?t[3]:1;return[r[0],r[1],r[2],e&&i?n/255:n]}var MP=`#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND + +// All these functions are for substituting tan() function from Intel GPU only +const float TWO_PI = 6.2831854820251465; +const float PI_2 = 1.5707963705062866; +const float PI_16 = 0.1963495463132858; + +const float SIN_TABLE_0 = 0.19509032368659973; +const float SIN_TABLE_1 = 0.3826834261417389; +const float SIN_TABLE_2 = 0.5555702447891235; +const float SIN_TABLE_3 = 0.7071067690849304; + +const float COS_TABLE_0 = 0.9807852506637573; +const float COS_TABLE_1 = 0.9238795042037964; +const float COS_TABLE_2 = 0.8314695954322815; +const float COS_TABLE_3 = 0.7071067690849304; + +const float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3! +const float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5! +const float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7! +const float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9! + +float sin_taylor_fp32(float a) { + float r, s, t, x; + + if (a == 0.0) { + return 0.0; + } + + x = -a * a; + s = a; + r = a; + + r = r * x; + t = r * INVERSE_FACTORIAL_3; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_5; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_7; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_9; + s = s + t; + + return s; +} + +void sincos_taylor_fp32(float a, out float sin_t, out float cos_t) { + if (a == 0.0) { + sin_t = 0.0; + cos_t = 1.0; + } + sin_t = sin_taylor_fp32(a); + cos_t = sqrt(1.0 - sin_t * sin_t); +} + +float tan_taylor_fp32(float a) { + float sin_a; + float cos_a; + + if (a == 0.0) { + return 0.0; + } + + // 2pi range reduction + float z = floor(a / TWO_PI); + float r = a - TWO_PI * z; + + float t; + float q = floor(r / PI_2 + 0.5); + int j = int(q); + + if (j < -2 || j > 2) { + return 1.0 / 0.0; + } + + t = r - PI_2 * q; + + q = floor(t / PI_16 + 0.5); + int k = int(q); + int abs_k = int(abs(float(k))); + + if (abs_k > 4) { + return 1.0 / 0.0; + } else { + t = t - PI_16 * q; + } + + float u = 0.0; + float v = 0.0; + + float sin_t, cos_t; + float s, c; + sincos_taylor_fp32(t, sin_t, cos_t); + + if (k == 0) { + s = sin_t; + c = cos_t; + } else { + if (abs(float(abs_k) - 1.0) < 0.5) { + u = COS_TABLE_0; + v = SIN_TABLE_0; + } else if (abs(float(abs_k) - 2.0) < 0.5) { + u = COS_TABLE_1; + v = SIN_TABLE_1; + } else if (abs(float(abs_k) - 3.0) < 0.5) { + u = COS_TABLE_2; + v = SIN_TABLE_2; + } else if (abs(float(abs_k) - 4.0) < 0.5) { + u = COS_TABLE_3; + v = SIN_TABLE_3; + } + if (k > 0) { + s = u * sin_t + v * cos_t; + c = u * cos_t - v * sin_t; + } else { + s = u * sin_t - v * cos_t; + c = u * cos_t + v * sin_t; + } + } + + if (j == 0) { + sin_a = s; + cos_a = c; + } else if (j == 1) { + sin_a = c; + cos_a = -s; + } else if (j == -1) { + sin_a = -c; + cos_a = s; + } else { + sin_a = -s; + cos_a = -c; + } + return sin_a / cos_a; +} +#endif + +float tan_fp32(float a) { +#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND + return tan_taylor_fp32(a); +#else + return tan(a); +#endif +} +`,hh={name:"fp32",vs:MP};var ph=` +layout(std140) uniform fp64arithmeticUniforms { + uniform float ONE; + uniform float SPLIT; +} fp64; + +/* +About LUMA_FP64_CODE_ELIMINATION_WORKAROUND + +The purpose of this workaround is to prevent shader compilers from +optimizing away necessary arithmetic operations by swapping their sequences +or transform the equation to some 'equivalent' form. + +These helpers implement Dekker/Veltkamp-style error tracking. If the compiler +folds constants or reassociates the arithmetic, the high/low split can stop +tracking the rounding error correctly. That failure mode tends to look fine in +simple coordinate setup, but then breaks down inside iterative arithmetic such +as fp64 Mandelbrot loops. + +The method is to multiply an artifical variable, ONE, which will be known to +the compiler to be 1 only at runtime. The whole expression is then represented +as a polynomial with respective to ONE. In the coefficients of all terms, only one a +and one b should appear + +err = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE +*/ + +float prevent_fp64_optimization(float value) { +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + return value + fp64.ONE * 0.0; +#else + return value; +#endif +} + +// Divide float number to high and low floats to extend fraction bits +vec2 split(float a) { + // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker + // split into a constant expression and reassociate the recovery steps. + float split = prevent_fp64_optimization(fp64.SPLIT); + float t = prevent_fp64_optimization(a * split); + float temp = t - a; + float a_hi = t - temp; + float a_lo = a - a_hi; + return vec2(a_hi, a_lo); +} + +// Divide float number again when high float uses too many fraction bits +vec2 split2(vec2 a) { + vec2 b = split(a.x); + b.y += a.y; + return b; +} + +// Special sum operation when a > b +vec2 quickTwoSum(float a, float b) { +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float sum = (a + b) * fp64.ONE; + float err = b - (sum - a) * fp64.ONE; +#else + float sum = a + b; + float err = b - (sum - a); +#endif + return vec2(sum, err); +} + +// General sum operation +vec2 twoSum(float a, float b) { + float s = (a + b); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float v = (s * fp64.ONE - a) * fp64.ONE; + float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v); +#else + float v = s - a; + float err = (a - (s - v)) + (b - v); +#endif + return vec2(s, err); +} + +vec2 twoSub(float a, float b) { + float s = (a - b); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float v = (s * fp64.ONE - a) * fp64.ONE; + float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v); +#else + float v = s - a; + float err = (a - (s - v)) - (b + v); +#endif + return vec2(s, err); +} + +vec2 twoSqr(float a) { + float prod = a * a; + vec2 a_fp64 = split(a); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x * + a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE; +#else + float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y; +#endif + return vec2(prod, err); +} + +vec2 twoProd(float a, float b) { + float prod = a * b; + vec2 a_fp64 = split(a); + vec2 b_fp64 = split(b); + // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend + // on the split terms and cross terms staying in the original evaluation + // order. If the compiler folds or reassociates them, the low part tends to + // collapse to zero or NaN on some drivers. + float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x); + float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y); + float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x); + float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float err1 = (highProduct - prod) * fp64.ONE; + float err2 = crossProduct1 * fp64.ONE * fp64.ONE; + float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE; + float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE; +#else + float err1 = highProduct - prod; + float err2 = crossProduct1; + float err3 = crossProduct2; + float err4 = lowProduct; +#endif + float err = ((err1 + err2) + err3) + err4; + return vec2(prod, err); +} + +vec2 sum_fp64(vec2 a, vec2 b) { + vec2 s, t; + s = twoSum(a.x, b.x); + t = twoSum(a.y, b.y); + s.y += t.x; + s = quickTwoSum(s.x, s.y); + s.y += t.y; + s = quickTwoSum(s.x, s.y); + return s; +} + +vec2 sub_fp64(vec2 a, vec2 b) { + vec2 s, t; + s = twoSub(a.x, b.x); + t = twoSub(a.y, b.y); + s.y += t.x; + s = quickTwoSum(s.x, s.y); + s.y += t.y; + s = quickTwoSum(s.x, s.y); + return s; +} + +vec2 mul_fp64(vec2 a, vec2 b) { + vec2 prod = twoProd(a.x, b.x); + // y component is for the error + prod.y += a.x * b.y; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + prod.y += a.y * b.x; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + return prod; +} + +vec2 div_fp64(vec2 a, vec2 b) { + float xn = 1.0 / b.x; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + vec2 yn = mul_fp64(a, vec2(xn, 0)); +#else + vec2 yn = a * xn; +#endif + float diff = (sub_fp64(a, mul_fp64(b, yn))).x; + vec2 prod = twoProd(xn, diff); + return sum_fp64(yn, prod); +} + +vec2 sqrt_fp64(vec2 a) { + if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0); + if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0); + + float x = 1.0 / sqrt(a.x); + float yn = a.x * x; +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + vec2 yn_sqr = twoSqr(yn) * fp64.ONE; +#else + vec2 yn_sqr = twoSqr(yn); +#endif + float diff = sub_fp64(a, yn_sqr).x; + vec2 prod = twoProd(x * 0.5, diff); +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + return sum_fp64(split(yn), prod); +#else + return sum_fp64(vec2(yn, 0.0), prod); +#endif +} +`;var Ly=`struct Fp64ArithmeticUniforms { + ONE: f32, + SPLIT: f32, +}; + +@group(0) @binding(auto) var fp64arithmetic : Fp64ArithmeticUniforms; + +fn fp64_nan(seed: f32) -> f32 { + let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0); + return bitcast(nanBits); +} + +fn fp64_runtime_zero() -> f32 { + return fp64arithmetic.ONE * 0.0; +} + +fn prevent_fp64_optimization(value: f32) -> f32 { +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + return value + fp64_runtime_zero(); +#else + return value; +#endif +} + +fn split(a: f32) -> vec2f { + let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero()); + let t = prevent_fp64_optimization(a * splitValue); + let temp = prevent_fp64_optimization(t - a); + let aHi = prevent_fp64_optimization(t - temp); + let aLo = prevent_fp64_optimization(a - aHi); + return vec2f(aHi, aLo); +} + +fn split2(a: vec2f) -> vec2f { + var b = split(a.x); + b.y = b.y + a.y; + return b; +} + +fn quickTwoSum(a: f32, b: f32) -> vec2f { +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE); + let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE); +#else + let sum = prevent_fp64_optimization(a + b); + let err = prevent_fp64_optimization(b - (sum - a)); +#endif + return vec2f(sum, err); +} + +fn twoSum(a: f32, b: f32) -> vec2f { + let s = prevent_fp64_optimization(a + b); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); + let err = + prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE) + + prevent_fp64_optimization(b - v); +#else + let v = prevent_fp64_optimization(s - a); + let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v); +#endif + return vec2f(s, err); +} + +fn twoSub(a: f32, b: f32) -> vec2f { + let s = prevent_fp64_optimization(a - b); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); + let err = + prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE) - + prevent_fp64_optimization(b + v); +#else + let v = prevent_fp64_optimization(s - a); + let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v); +#endif + return vec2f(s, err); +} + +fn twoSqr(a: f32) -> vec2f { + let prod = prevent_fp64_optimization(a * a); + let aFp64 = split(a); + let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x); + let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y); + let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let err = + (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE + + crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) + + lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; +#else + let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct); +#endif + return vec2f(prod, err); +} + +fn twoProd(a: f32, b: f32) -> vec2f { + let prod = prevent_fp64_optimization(a * b); + let aFp64 = split(a); + let bFp64 = split(b); + let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x); + let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y); + let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x); + let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let err1 = (highProduct - prod) * fp64arithmetic.ONE; + let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE; + let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; + let err4 = + lowProduct * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE; +#else + let err1 = highProduct - prod; + let err2 = crossProduct1; + let err3 = crossProduct2; + let err4 = lowProduct; +#endif + let err12InputA = prevent_fp64_optimization(err1); + let err12InputB = prevent_fp64_optimization(err2); + let err12 = prevent_fp64_optimization(err12InputA + err12InputB); + let err123InputA = prevent_fp64_optimization(err12); + let err123InputB = prevent_fp64_optimization(err3); + let err123 = prevent_fp64_optimization(err123InputA + err123InputB); + let err1234InputA = prevent_fp64_optimization(err123); + let err1234InputB = prevent_fp64_optimization(err4); + let err = prevent_fp64_optimization(err1234InputA + err1234InputB); + return vec2f(prod, err); +} + +fn sum_fp64(a: vec2f, b: vec2f) -> vec2f { + var s = twoSum(a.x, b.x); + let t = twoSum(a.y, b.y); + s.y = prevent_fp64_optimization(s.y + t.x); + s = quickTwoSum(s.x, s.y); + s.y = prevent_fp64_optimization(s.y + t.y); + s = quickTwoSum(s.x, s.y); + return s; +} + +fn sub_fp64(a: vec2f, b: vec2f) -> vec2f { + var s = twoSub(a.x, b.x); + let t = twoSub(a.y, b.y); + s.y = prevent_fp64_optimization(s.y + t.x); + s = quickTwoSum(s.x, s.y); + s.y = prevent_fp64_optimization(s.y + t.y); + s = quickTwoSum(s.x, s.y); + return s; +} + +fn mul_fp64(a: vec2f, b: vec2f) -> vec2f { + var prod = twoProd(a.x, b.x); + let crossProduct1 = prevent_fp64_optimization(a.x * b.y); + prod.y = prevent_fp64_optimization(prod.y + crossProduct1); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + let crossProduct2 = prevent_fp64_optimization(a.y * b.x); + prod.y = prevent_fp64_optimization(prod.y + crossProduct2); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + return prod; +} + +fn div_fp64(a: vec2f, b: vec2f) -> vec2f { + let xn = prevent_fp64_optimization(1.0 / b.x); + let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero())); + let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x); + let prod = twoProd(xn, diff); + return sum_fp64(yn, prod); +} + +fn sqrt_fp64(a: vec2f) -> vec2f { + if (a.x == 0.0 && a.y == 0.0) { + return vec2f(0.0, 0.0); + } + if (a.x < 0.0) { + let nanValue = fp64_nan(a.x); + return vec2f(nanValue, nanValue); + } + + let x = prevent_fp64_optimization(1.0 / sqrt(a.x)); + let yn = prevent_fp64_optimization(a.x * x); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let ynSqr = twoSqr(yn) * fp64arithmetic.ONE; +#else + let ynSqr = twoSqr(yn); +#endif + let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x); + let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + return sum_fp64(split(yn), prod); +#else + return sum_fp64(vec2f(yn, 0.0), prod); +#endif +} +`;var IP={ONE:1,SPLIT:4097},gh={name:"fp64arithmetic",source:Ly,fs:ph,vs:ph,defaultUniforms:IP,uniformTypes:{ONE:"f32",SPLIT:"f32"},fp64ify:dh,fp64LowPart:Iy,fp64ifyMatrix4:Oy};var OP=[0,1,1,1],NP=`layout(std140) uniform pickingUniforms { + float isActive; + float isAttribute; + float isHighlightActive; + float useByteColors; + vec3 highlightedObjectColor; + vec4 highlightColor; +} picking; + +out vec4 picking_vRGBcolor_Avalid; + +// Normalize unsigned byte color to 0-1 range +vec3 picking_normalizeColor(vec3 color) { + return picking.useByteColors > 0.5 ? color / 255.0 : color; +} + +// Normalize unsigned byte color to 0-1 range +vec4 picking_normalizeColor(vec4 color) { + return picking.useByteColors > 0.5 ? color / 255.0 : color; +} + +bool picking_isColorZero(vec3 color) { + return dot(color, vec3(1.0)) < 0.00001; +} + +bool picking_isColorValid(vec3 color) { + return dot(color, vec3(1.0)) > 0.00001; +} + +// Check if this vertex is highlighted +bool isVertexHighlighted(vec3 vertexColor) { + vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + return + bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor)); +} + +// Set the current picking color +void picking_setPickingColor(vec3 pickingColor) { + pickingColor = picking_normalizeColor(pickingColor); + + if (bool(picking.isActive)) { + // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable + picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor)); + + if (!bool(picking.isAttribute)) { + // Stores the picking color so that the fragment shader can render it during picking + picking_vRGBcolor_Avalid.rgb = pickingColor; + } + } else { + // Do the comparison with selected item color in vertex shader as it should mean fewer compares + picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor)); + } +} + +void picking_setPickingAttribute(float value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.r = value; + } +} + +void picking_setPickingAttribute(vec2 value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.rg = value; + } +} + +void picking_setPickingAttribute(vec3 value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.rgb = value; + } +} +`,DP=`layout(std140) uniform pickingUniforms { + float isActive; + float isAttribute; + float isHighlightActive; + float useByteColors; + vec3 highlightedObjectColor; + vec4 highlightColor; +} picking; + +in vec4 picking_vRGBcolor_Avalid; + +/* + * Returns highlight color if this item is selected. + */ +vec4 picking_filterHighlightColor(vec4 color) { + // If we are still picking, we don't highlight + if (picking.isActive > 0.5) { + return color; + } + + bool selected = bool(picking_vRGBcolor_Avalid.a); + + if (selected) { + // Blend in highlight color based on its alpha value + float highLightAlpha = picking.highlightColor.a; + float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha); + float highLightRatio = highLightAlpha / blendedAlpha; + + vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio); + return vec4(blendedRGB, blendedAlpha); + } else { + return color; + } +} + +/* + * Returns picking color if picking enabled else unmodified argument. + */ +vec4 picking_filterPickingColor(vec4 color) { + if (bool(picking.isActive)) { + if (picking_vRGBcolor_Avalid.a == 0.0) { + discard; + } + return picking_vRGBcolor_Avalid; + } + return color; +} + +/* + * Returns picking color if picking is enabled if not + * highlight color if this item is selected, otherwise unmodified argument. + */ +vec4 picking_filterColor(vec4 color) { + vec4 highlightColor = picking_filterHighlightColor(color); + return picking_filterPickingColor(highlightColor); +} +`,Cc={props:{},uniforms:{},name:"picking",uniformTypes:{isActive:"f32",isAttribute:"f32",isHighlightActive:"f32",useByteColors:"f32",highlightedObjectColor:"vec3",highlightColor:"vec4"},defaultUniforms:{isActive:!1,isAttribute:!1,isHighlightActive:!1,useByteColors:!0,highlightedObjectColor:[0,0,0],highlightColor:OP},vs:NP,fs:DP,getUniforms:LP};function LP(t={},e){let r={},i=Ny(t.useByteColors,!0);if(t.highlightedObjectColor!==void 0)if(t.highlightedObjectColor===null)r.isHighlightActive=!1;else{r.isHighlightActive=!0;let n=t.highlightedObjectColor.slice(0,3);r.highlightedObjectColor=n}return t.highlightColor&&(r.highlightColor=Dy(t.highlightColor,i)),t.isActive!==void 0&&(r.isActive=!!t.isActive,r.isAttribute=!!t.isAttribute),t.useByteColors!==void 0&&(r.useByteColors=!!t.useByteColors),r}var ZM=`struct LayerUniforms { + opacity: f32, +}; + +@group(0) @binding(auto) +var layer: LayerUniforms; +`,Bx=`layout(std140) uniform layerUniforms { + uniform float opacity; +} layer; +`,Jh={name:"layer",source:ZM,vs:Bx,fs:Bx,getUniforms:t=>({opacity:Math.pow(t.opacity,.45454545454545453)}),uniformTypes:{opacity:"f32"}};var QM=` + +@must_use +fn deckgl_premultiplied_alpha(fragColor: vec4) -> vec4 { + return vec4(fragColor.rgb * fragColor.a, fragColor.a); +}; +`,mn={name:"color",dependencies:[],source:QM,getUniforms:t=>({})};var JM=`const SMOOTH_EDGE_RADIUS: f32 = 0.5; + +struct VertexGeometry { + position: vec4, + worldPosition: vec3, + worldPositionAlt: vec3, + normal: vec3, + uv: vec2, + pickingColor: vec3, +}; + +var geometry_: VertexGeometry = VertexGeometry( + vec4(0.0, 0.0, 1.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec2(0.0, 0.0), + vec3(0.0, 0.0, 0.0) +); + +struct FragmentGeometry { + uv: vec2, +}; + +var fragmentGeometry: FragmentGeometry; + +fn smoothedge(edge: f32, x: f32) -> f32 { + return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); +} +`,kx="#define SMOOTH_EDGE_RADIUS 0.5",eI=`${kx} + +struct VertexGeometry { + vec4 position; + vec3 worldPosition; + vec3 worldPositionAlt; + vec3 normal; + vec2 uv; + vec3 pickingColor; +} geometry = VertexGeometry( + vec4(0.0, 0.0, 1.0, 0.0), + vec3(0.0), + vec3(0.0), + vec3(0.0), + vec2(0.0), + vec3(0.0) +); +`,tI=`${kx} + +struct FragmentGeometry { + vec2 uv; +} geometry; + +float smoothedge(float edge, float x) { + return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); +} +`,Yc={name:"geometry",source:JM,vs:eI,fs:tI};var Q;(function(t){t[t.Start=1]="Start",t[t.Move=2]="Move",t[t.End=4]="End",t[t.Cancel=8]="Cancel"})(Q||(Q={}));var ie;(function(t){t[t.None=0]="None",t[t.Left=1]="Left",t[t.Right=2]="Right",t[t.Up=4]="Up",t[t.Down=8]="Down",t[t.Horizontal=3]="Horizontal",t[t.Vertical=12]="Vertical",t[t.All=15]="All"})(ie||(ie={}));var B;(function(t){t[t.Possible=1]="Possible",t[t.Began=2]="Began",t[t.Changed=4]="Changed",t[t.Ended=8]="Ended",t[t.Recognized=8]="Recognized",t[t.Cancelled=16]="Cancelled",t[t.Failed=32]="Failed"})(B||(B={}));var Ux="compute",ep="auto",Zo="manipulation",_i="none",Qo="pan-x",Jo="pan-y";function tp(t){if(t.includes(_i))return _i;let e=t.includes(Qo),r=t.includes(Jo);return e&&r?_i:e||r?e?Qo:Jo:t.includes(Zo)?Zo:ep}var es=class{constructor(e,r){this.actions="",this.manager=e,this.set(r)}set(e){e===Ux&&(e=this.compute()),this.manager.element&&(this.manager.element.style.touchAction=e,this.actions=e)}update(){this.set(this.manager.options.touchAction)}compute(){let e=[];for(let r of this.manager.recognizers)r.options.enable&&(e=e.concat(r.getTouchAction()));return tp(e.join(" "))}};function _n(t){return t.trim().split(/\s+/g)}function Xc(t,e,r){if(t)for(let i of _n(e))t.addEventListener(i,r,!1)}function Gc(t,e,r){if(t)for(let i of _n(e))t.removeEventListener(i,r,!1)}function rp(t){return(t.ownerDocument||t).defaultView}function ip(t,e){let r=t;for(;r;){if(r===e)return!0;r=r.parentNode}return!1}function qc(t){let e=t.length;if(e===1)return{x:Math.round(t[0].clientX),y:Math.round(t[0].clientY)};let r=0,i=0,n=0;for(;n=Math.abs(e)?t<0?ie.Left:ie.Right:e<0?ie.Up:ie.Down}function Wx(t,e){let r=e.center,i=t.offsetDelta,n=t.prevDelta,o=t.prevInput;return(e.eventType===Q.Start||o?.eventType===Q.End)&&(n=t.prevDelta={x:o?.deltaX||0,y:o?.deltaY||0},i=t.offsetDelta={x:r.x,y:r.y}),{deltaX:n.x+(r.x-i.x),deltaY:n.y+(r.y-i.y)}}function Qc(t,e,r){return{x:e/t||0,y:r/t||0}}function Vx(t,e){return op(e[0],e[1])/op(t[0],t[1])}function jx(t,e){return sp(e[1],e[0])-sp(t[1],t[0])}function $x(t,e){let r=t.lastInterval||e,i=e.timeStamp-r.timeStamp,n,o,s,a;if(e.eventType!==Q.Cancel&&(i>25||r.velocity===void 0)){let c=e.deltaX-r.deltaX,l=e.deltaY-r.deltaY,f=Qc(i,c,l);o=f.x,s=f.y,n=Math.abs(f.x)>Math.abs(f.y)?f.x:f.y,a=Zc(c,l),t.lastInterval=e}else n=r.velocity,o=r.velocityX,s=r.velocityY,a=r.direction;e.velocity=n,e.velocityX=o,e.velocityY=s,e.direction=a}function Hx(t,e){let{session:r}=t,{pointers:i}=e,{length:n}=i;r.firstInput||(r.firstInput=np(e)),n>1&&!r.firstMultiple?r.firstMultiple=np(e):n===1&&(r.firstMultiple=!1);let{firstInput:o,firstMultiple:s}=r,a=s?s.center:o.center,c=e.center=qc(i);e.timeStamp=Date.now(),e.deltaTime=e.timeStamp-o.timeStamp,e.angle=zx(a,c),e.distance=Kc(a,c);let{deltaX:l,deltaY:f}=Wx(r,e);e.deltaX=l,e.deltaY=f,e.offsetDirection=Zc(e.deltaX,e.deltaY);let u=Qc(e.deltaTime,e.deltaX,e.deltaY);e.overallVelocityX=u.x,e.overallVelocityY=u.y,e.overallVelocity=Math.abs(u.x)>Math.abs(u.y)?u.x:u.y,e.scale=s?Vx(s.pointers,i):1,e.rotation=s?jx(s.pointers,i):0,e.maxPointers=r.prevInput?e.pointers.length>r.prevInput.maxPointers?e.pointers.length:r.prevInput.maxPointers:e.pointers.length;let d=t.element;return ip(e.srcEvent.target,d)&&(d=e.srcEvent.target),e.target=d,$x(r,e),e}function Yx(t,e,r){let i=r.pointers.length,n=r.changedPointers.length,o=e&Q.Start&&i-n===0,s=e&(Q.End|Q.Cancel)&&i-n===0;r.isFirst=!!o,r.isFinal=!!s,o&&(t.session={}),r.eventType=e;let a=Hx(t,r);t.emit("hammer.input",a),t.recognize(a),t.session.prevInput=a}var ts=class{constructor(e){this.evEl="",this.evWin="",this.evTarget="",this.domHandler=r=>{this.manager.options.enable&&this.handler(r)},this.manager=e,this.element=e.element,this.target=e.options.inputTarget||e.element}callback(e,r){Yx(this.manager,e,r)}init(){Xc(this.element,this.evEl,this.domHandler),Xc(this.target,this.evTarget,this.domHandler),Xc(rp(this.element),this.evWin,this.domHandler)}destroy(){Gc(this.element,this.evEl,this.domHandler),Gc(this.target,this.evTarget,this.domHandler),Gc(rp(this.element),this.evWin,this.domHandler)}};var iI={pointerdown:Q.Start,pointermove:Q.Move,pointerup:Q.End,pointercancel:Q.Cancel,pointerout:Q.Cancel},nI="pointerdown",oI="pointermove pointerup pointercancel",rs=class extends ts{constructor(e){super(e),this.evEl=nI,this.evWin=oI,this.store=this.manager.session.pointerEvents=[],this.init()}handler(e){let{store:r}=this,i=!1,n=iI[e.type],o=e.pointerType,s=o==="touch",a=r.findIndex(c=>c.pointerId===e.pointerId);n&Q.Start&&(e.buttons||s)?a<0&&(r.push(e),a=r.length-1):n&(Q.End|Q.Cancel)&&(i=!0),!(a<0)&&(r[a]=e,this.callback(n,{pointers:r,changedPointers:[e],eventType:n,pointerType:o,srcEvent:e}),i&&r.splice(a,1))}};var sI=["","webkit","Moz","MS","ms","o"];function Xx(t,e){let r=e[0].toUpperCase()+e.slice(1);for(let i of sI){let n=i?i+r:e;if(n in t)return n}}var aI=1,Gx=2,qx={touchAction:"compute",enable:!0,inputTarget:null,cssProps:{userSelect:"none",userDrag:"none",touchCallout:"none",tapHighlightColor:"rgba(0,0,0,0)"}},is=class{constructor(e,r){this.options={...qx,...r,cssProps:{...qx.cssProps,...r.cssProps},inputTarget:r.inputTarget||e},this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=e,this.input=new rs(this),this.touchAction=new es(this,this.options.touchAction),this.toggleCssProps(!0)}set(e){return Object.assign(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this}stop(e){this.session.stopped=e?Gx:aI}recognize(e){let{session:r}=this;if(r.stopped)return;this.session.prevented&&e.srcEvent.preventDefault();let i,{recognizers:n}=this,{curRecognizer:o}=r;(!o||o&&o.state&B.Recognized)&&(o=r.curRecognizer=null);let s=0;for(;s-1&&this.requireFail.splice(i,1)}return this}hasRequireFailures(){return!!this.requireFail.find(e=>e.options.enable)}canRecognizeWith(e){return!!this.simultaneous[e.id]}emit(e){if(!e)return;let{state:r}=this;r=B.Ended&&this.manager.emit(this.options.event+ap(r),e)}tryEmit(e){this.canEmit()?this.emit(e):this.state=B.Failed}canEmit(){let e=0;for(;e{this.state=B.Recognized,this.tryEmit(this._input)},r.interval),B.Began):B.Recognized}return B.Failed}failTimeout(){return this._timer=setTimeout(()=>{this.state=B.Failed},this.options.interval),B.Failed}reset(){clearTimeout(this._timer)}emit(e){this.state===B.Recognized&&(e.tapCount=this.count,this.manager.emit(this.options.event,e))}};var lI=["","start","move","end","cancel","up","down","left","right"],Lr=class extends ar{constructor(e={}){super({enable:!0,pointers:1,event:"pan",threshold:10,direction:ie.All,...e}),this.pX=null,this.pY=null}getTouchAction(){let{options:{direction:e}}=this,r=[];return e&ie.Horizontal&&r.push(Jo),e&ie.Vertical&&r.push(Qo),r}getEventNames(){return lI.map(e=>this.options.event+e)}directionTest(e){let{options:r}=this,i=!0,{distance:n}=e,{direction:o}=e,s=e.deltaX,a=e.deltaY;return o&r.direction||(r.direction&ie.Horizontal?(o=s===0?ie.None:s<0?ie.Left:ie.Right,i=s!==this.pX,n=Math.abs(e.deltaX)):(o=a===0?ie.None:a<0?ie.Up:ie.Down,i=a!==this.pY,n=Math.abs(e.deltaY))),e.direction=o,i&&n>r.threshold&&!!(o&r.direction)}attrTest(e){return super.attrTest(e)&&(!!(this.state&B.Began)||!(this.state&B.Began)&&this.directionTest(e))}emit(e){this.pX=e.deltaX,this.pY=e.deltaY;let r=ie[e.direction].toLowerCase();r&&(e.additionalEvent=this.options.event+r),super.emit(e)}};var fI=["","start","move","end","cancel","in","out"],yn=class extends ar{constructor(e={}){super({enable:!0,event:"pinch",threshold:0,pointers:2,...e})}getTouchAction(){return[_i]}getEventNames(){return fI.map(e=>this.options.event+e)}attrTest(e){return super.attrTest(e)&&(Math.abs(e.scale-1)>this.options.threshold||!!(this.state&B.Began))}emit(e){if(e.scale!==1){let r=e.scale<1?"in":"out";e.additionalEvent=this.options.event+r}super.emit(e)}};var Bt=class{constructor(e,r,i){this.element=e,this.callback=r,this.options=i}};var Zx=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",GH=typeof window<"u"?window:global;var pI=Zx.indexOf("firefox")!==-1,Qx=4.000244140625,gI=40,mI=.25,Jc=class extends Bt{constructor(e,r,i){super(e,r,{enable:!0,...i}),this.handleEvent=n=>{if(!this.options.enable)return;let o=n.deltaY;globalThis.WheelEvent&&(pI&&n.deltaMode===globalThis.WheelEvent.DOM_DELTA_PIXEL&&(o/=globalThis.devicePixelRatio),n.deltaMode===globalThis.WheelEvent.DOM_DELTA_LINE&&(o*=gI)),o!==0&&o%Qx===0&&(o=Math.floor(o/Qx)),n.shiftKey&&o&&(o=o*mI),this.callback({type:"wheel",center:{x:n.clientX,y:n.clientY},delta:-o,srcEvent:n,pointerType:"mouse",target:n.target})},e.addEventListener("wheel",this.handleEvent,{passive:!1})}destroy(){this.element.removeEventListener("wheel",this.handleEvent)}enableEventType(e,r){e==="wheel"&&(this.options.enable=r)}};var Jx=["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"],el=class extends Bt{constructor(e,r,i){super(e,r,{enable:!0,...i}),this.handleEvent=o=>{this.handleOverEvent(o),this.handleOutEvent(o),this.handleEnterEvent(o),this.handleLeaveEvent(o),this.handleMoveEvent(o)},this.pressed=!1;let{enable:n}=this.options;this.enableMoveEvent=n,this.enableLeaveEvent=n,this.enableEnterEvent=n,this.enableOutEvent=n,this.enableOverEvent=n,Jx.forEach(o=>e.addEventListener(o,this.handleEvent))}destroy(){Jx.forEach(e=>this.element.removeEventListener(e,this.handleEvent))}enableEventType(e,r){switch(e){case"pointermove":this.enableMoveEvent=r;break;case"pointerover":this.enableOverEvent=r;break;case"pointerout":this.enableOutEvent=r;break;case"pointerenter":this.enableEnterEvent=r;break;case"pointerleave":this.enableLeaveEvent=r;break;default:}}handleOverEvent(e){this.enableOverEvent&&e.type==="mouseover"&&this._emit("pointerover",e)}handleOutEvent(e){this.enableOutEvent&&e.type==="mouseout"&&this._emit("pointerout",e)}handleEnterEvent(e){this.enableEnterEvent&&e.type==="mouseenter"&&this._emit("pointerenter",e)}handleLeaveEvent(e){this.enableLeaveEvent&&e.type==="mouseleave"&&this._emit("pointerleave",e)}handleMoveEvent(e){if(this.enableMoveEvent)switch(e.type){case"mousedown":e.button>=0&&(this.pressed=!0);break;case"mousemove":e.buttons===0&&(this.pressed=!1),this.pressed||this._emit("pointermove",e);break;case"mouseup":this.pressed=!1;break;default:}}_emit(e,r){this.callback({type:e,center:{x:r.clientX,y:r.clientY},srcEvent:r,pointerType:"mouse",target:r.target})}};var eb=["keydown","keyup"],tl=class extends Bt{constructor(e,r,i){super(e,r,{enable:!0,tabIndex:0,...i}),this.handleEvent=n=>{let o=n.target||n.srcElement;o.tagName==="INPUT"&&o.type==="text"||o.tagName==="TEXTAREA"||(this.enableDownEvent&&n.type==="keydown"&&this.callback({type:"keydown",srcEvent:n,key:n.key,target:n.target}),this.enableUpEvent&&n.type==="keyup"&&this.callback({type:"keyup",srcEvent:n,key:n.key,target:n.target}))},this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,e.tabIndex=this.options.tabIndex,e.style.outline="none",eb.forEach(n=>e.addEventListener(n,this.handleEvent))}destroy(){eb.forEach(e=>this.element.removeEventListener(e,this.handleEvent))}enableEventType(e,r){e==="keydown"&&(this.enableDownEvent=r),e==="keyup"&&(this.enableUpEvent=r)}};var rl=class extends Bt{constructor(e,r,i){super(e,r,i),this.handleEvent=n=>{this.options.enable&&this.callback({type:"contextmenu",center:{x:n.clientX,y:n.clientY},srcEvent:n,pointerType:"mouse",target:n.target})},e.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(e,r){e==="contextmenu"&&(this.options.enable=r)}};var _I={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4},yI=0,xI=1,bI=2,TI=1,wI=2,SI=4;function tb(t){let e=_I[t.srcEvent.type];if(!e)return null;let{buttons:r,button:i}=t.srcEvent,n=!1,o=!1,s=!1;return e===2?(n=!!(r&TI),o=!!(r&SI),s=!!(r&wI)):(n=i===yI,o=i===xI,s=i===bI),{leftButton:n,middleButton:o,rightButton:s}}function rb(t,e){let r=t.center;if(!r)return null;let i=e.getBoundingClientRect(),n=i.width/e.offsetWidth||1,o=i.height/e.offsetHeight||1,s={x:(r.x-i.left-e.clientLeft)/n,y:(r.y-i.top-e.clientTop)/o};return{center:r,offsetCenter:s}}var AI={srcElement:"root",priority:0},il=class{constructor(e,r){this.handleEvent=i=>{if(this.isEmpty())return;let n=this._normalizeEvent(i),o=i.srcEvent.target;for(;o&&o!==n.rootElement;){if(this._emit(n,o),n.handled)return;o=o.parentNode}this._emit(n,"root")},this.eventManager=e,this.recognizerName=r,this.handlers=[],this.handlersByElement=new Map,this._active=!1}isEmpty(){return!this._active}add(e,r,i,n=!1,o=!1){let{handlers:s,handlersByElement:a}=this,c={...AI,...i},l=a.get(c.srcElement);l||(l=[],a.set(c.srcElement,l));let f={type:e,handler:r,srcElement:c.srcElement,priority:c.priority};n&&(f.once=!0),o&&(f.passive=!0),s.push(f),this._active=this._active||!f.passive;let u=l.length-1;for(;u>=0&&!(l[u].priority>=f.priority);)u--;l.splice(u+1,0,f)}remove(e,r){let{handlers:i,handlersByElement:n}=this;for(let o=i.length-1;o>=0;o--){let s=i[o];if(s.type===e&&s.handler===r){i.splice(o,1);let a=n.get(s.srcElement);a.splice(a.indexOf(s),1),a.length===0&&n.delete(s.srcElement)}}this._active=i.some(o=>!o.passive)}_emit(e,r){let i=this.handlersByElement.get(r);if(i){let n=!1,o=()=>{e.handled=!0},s=()=>{e.handled=!0,n=!0},a=[];for(let c=0;c{e.srcEvent.preventDefault()},stopImmediatePropagation:null,stopPropagation:null,handled:!1,rootElement:r}}};function vI(t){if("recognizer"in t)return t;let e,r=Array.isArray(t)?[...t]:[t];if(typeof r[0]=="function"){let i=r.shift(),n=r.shift()||{};e=new i(n)}else e=r.shift();return{recognizer:e,recognizeWith:typeof r[0]=="string"?[r[0]]:r[0],requireFailure:typeof r[1]=="string"?[r[1]]:r[1]}}var ns=class{constructor(e=null,r={}){if(this._onBasicInput=i=>{this.manager.emit(i.srcEvent.type,i)},this._onOtherEvent=i=>{this.manager.emit(i.type,i)},this.options={recognizers:[],events:{},touchAction:"compute",tabIndex:0,cssProps:{},...r},this.events=new Map,this.element=e,!!e){this.manager=new is(e,this.options);for(let i of this.options.recognizers){let{recognizer:n,recognizeWith:o,requireFailure:s}=vI(i);this.manager.add(n),o&&n.recognizeWith(o),s&&n.requireFailure(s)}this.manager.on("hammer.input",this._onBasicInput),this.wheelInput=new Jc(e,this._onOtherEvent,{enable:!1}),this.moveInput=new el(e,this._onOtherEvent,{enable:!1}),this.keyInput=new tl(e,this._onOtherEvent,{enable:!1,tabIndex:r.tabIndex}),this.contextmenuInput=new rl(e,this._onOtherEvent,{enable:!1}),this.on(this.options.events)}}getElement(){return this.element}destroy(){this.element&&(this.wheelInput.destroy(),this.moveInput.destroy(),this.keyInput.destroy(),this.contextmenuInput.destroy(),this.manager.destroy())}on(e,r,i){this._addEventHandler(e,r,i,!1)}once(e,r,i){this._addEventHandler(e,r,i,!0)}watch(e,r,i){this._addEventHandler(e,r,i,!1,!0)}off(e,r){this._removeEventHandler(e,r)}_toggleRecognizer(e,r){let{manager:i}=this;if(!i)return;let n=i.get(e);n&&(n.set({enable:r}),i.touchAction.update()),this.wheelInput?.enableEventType(e,r),this.moveInput?.enableEventType(e,r),this.keyInput?.enableEventType(e,r),this.contextmenuInput?.enableEventType(e,r)}_addEventHandler(e,r,i,n,o){if(typeof e!="string"){i=r;for(let[l,f]of Object.entries(e))this._addEventHandler(l,f,i,n,o);return}let{manager:s,events:a}=this;if(!s)return;let c=a.get(e);if(!c){let l=this._getRecognizerName(e)||e;c=new il(this,l),a.set(e,c),s&&s.on(e,c.handleEvent)}c.add(e,r,i,n,o),c.isEmpty()||this._toggleRecognizer(c.recognizerName,!0)}_removeEventHandler(e,r){if(typeof e!="string"){for(let[o,s]of Object.entries(e))this._removeEventHandler(o,s);return}let{events:i}=this,n=i.get(e);if(n&&(n.remove(e,r),n.isEmpty())){let{recognizerName:o}=n,s=!1;for(let a of i.values())if(a.recognizerName===o&&!a.isEmpty()){s=!0;break}s||this._toggleRecognizer(o,!1)}}_getRecognizerName(e){return this.manager.recognizers.find(r=>r.getEventNames().includes(e))?.options.event}};var cp={DEFAULT:"default",LNGLAT:"lnglat",METER_OFFSETS:"meter-offsets",LNGLAT_OFFSETS:"lnglat-offsets",CARTESIAN:"cartesian"};Object.defineProperty(cp,"IDENTITY",{get:()=>(F.deprecated("COORDINATE_SYSTEM.IDENTITY","COORDINATE_SYSTEM.CARTESIAN")(),cp.CARTESIAN)});var _e={WEB_MERCATOR:1,GLOBE:2,WEB_MERCATOR_AUTO_OFFSET:4,IDENTITY:0},je={common:0,meters:1,pixels:2},xn={click:"onClick",dblclick:"onClick",panstart:"onDragStart",panmove:"onDrag",panend:"onDragEnd"},lp={multipan:[Lr,{threshold:10,direction:ie.Vertical,pointers:2}],pinch:[yn,{},null,["multipan"]],pan:[Lr,{threshold:1},["pinch"],["multipan"]],dblclick:[yi,{event:"dblclick",taps:2}],click:[yi,{event:"click"},null,["dblclick"]]};function EI(t,e){if(t===e)return!0;if(Array.isArray(t)){let r=t.length;if(!e||e.length!==r)return!1;for(let i=0;i{for(let n in i)if(!EI(i[n],e[n])){r=t(i),e=i;break}return r}}var ib=[0,0,0,0],RI=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0],nb=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],CI=[0,0,0],ob=[0,0,0],PI={default:-1,cartesian:0,lnglat:1,"meter-offsets":2,"lnglat-offsets":3};function xi(t){let e=PI[t];if(e===void 0)throw new Error(`Invalid coordinateSystem: ${t}`);return e}var MI=kt(OI);function fp(t,e,r=ob){r.length<3&&(r=[r[0],r[1],0]);let i=r,n,o=!0;switch(e==="lnglat-offsets"||e==="meter-offsets"?n=r:n=t.isGeospatial?[Math.fround(t.longitude),Math.fround(t.latitude),0]:null,t.projectionMode){case _e.WEB_MERCATOR:(e==="lnglat"||e==="cartesian")&&(n=[0,0,0],o=!1);break;case _e.WEB_MERCATOR_AUTO_OFFSET:e==="lnglat"?i=n:e==="cartesian"&&(i=[Math.fround(t.center[0]),Math.fround(t.center[1]),0],n=t.unprojectPosition(i),i[0]-=r[0],i[1]-=r[1],i[2]-=r[2]);break;case _e.IDENTITY:i=t.position.map(Math.fround),i[2]=i[2]||0;break;case _e.GLOBE:o=!1,n=null;break;default:o=!1}return{geospatialOrigin:n,shaderCoordinateOrigin:i,offsetMode:o}}function II(t,e,r){let{viewMatrixUncentered:i,projectionMatrix:n}=t,{viewMatrix:o,viewProjectionMatrix:s}=t,a=ib,c=ib,l=t.cameraPosition,{geospatialOrigin:f,shaderCoordinateOrigin:u,offsetMode:d}=fp(t,e,r);return d&&(c=t.projectPosition(f||u),l=[l[0]-c[0],l[1]-c[1],l[2]-c[2]],c[3]=1,a=Ze.transformMat4([],c,s),o=i||o,s=ee.multiply([],n,o),s=ee.multiply([],s,RI)),{viewMatrix:o,viewProjectionMatrix:s,projectionCenter:a,originCommon:c,cameraPosCommon:l,shaderCoordinateOrigin:u,geospatialOrigin:f}}function sb({viewport:t,devicePixelRatio:e=1,modelMatrix:r=null,coordinateSystem:i="default",coordinateOrigin:n=ob,autoWrapLongitude:o=!1}){i==="default"&&(i=t.isGeospatial?"lnglat":"cartesian");let s=MI({viewport:t,devicePixelRatio:e,coordinateSystem:i,coordinateOrigin:n});return s.wrapLongitude=o,s.modelMatrix=r||nb,s}function OI({viewport:t,devicePixelRatio:e,coordinateSystem:r,coordinateOrigin:i}){let{projectionCenter:n,viewProjectionMatrix:o,originCommon:s,cameraPosCommon:a,shaderCoordinateOrigin:c,geospatialOrigin:l}=II(t,r,i),f=t.getDistanceScales(),u=[t.width*e,t.height*e],d=Ze.transformMat4([],[0,0,-t.focalDistance,1],t.projectionMatrix)[3]||1,h={coordinateSystem:xi(r),projectionMode:t.projectionMode,coordinateOrigin:c,commonOrigin:s.slice(0,3),center:n,pseudoMeters:!!t._pseudoMeters,viewportSize:u,devicePixelRatio:e,focalDistance:d,commonUnitsPerMeter:f.unitsPerMeter,commonUnitsPerWorldUnit:f.unitsPerMeter,commonUnitsPerWorldUnit2:CI,scale:t.scale,wrapLongitude:!1,viewProjectionMatrix:o,modelMatrix:nb,cameraPosition:a};if(l){let p=t.getDistanceScales(l);switch(r){case"meter-offsets":h.commonUnitsPerWorldUnit=p.unitsPerMeter,h.commonUnitsPerWorldUnit2=p.unitsPerMeter2;break;case"lnglat":case"lnglat-offsets":t._pseudoMeters||(h.commonUnitsPerMeter=p.unitsPerMeter),h.commonUnitsPerWorldUnit=p.unitsPerDegree,h.commonUnitsPerWorldUnit2=p.unitsPerDegree2;break;case"cartesian":h.commonUnitsPerWorldUnit=[1,1,p.unitsPerMeter[2]],h.commonUnitsPerWorldUnit2=[0,0,p.unitsPerMeter2[2]];break;default:break}}return h}var NI=["default","lnglat","meter-offsets","lnglat-offsets","cartesian"],DI=NI.map(t=>`const COORDINATE_SYSTEM_${t.toUpperCase().replaceAll("-","_")}: i32 = ${xi(t)};`).join(""),LI=Object.keys(_e).map(t=>`const PROJECTION_MODE_${t}: i32 = ${_e[t]};`).join(""),FI=Object.keys(je).map(t=>`const UNIT_${t.toUpperCase()}: i32 = ${je[t]};`).join(""),BI=`${DI} +${LI} +${FI} + +const TILE_SIZE: f32 = 512.0; +const PI: f32 = 3.1415926536; +const WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0); +const ZERO_64_LOW: vec3 = vec3(0.0, 0.0, 0.0); +const EARTH_RADIUS: f32 = 6370972.0; // meters +const GLOBE_RADIUS: f32 = 256.0; + +// ----------------------------------------------------------------------------- +// Uniform block (converted from GLSL uniform block) +// ----------------------------------------------------------------------------- +struct ProjectUniforms { + wrapLongitude: i32, + coordinateSystem: i32, + commonUnitsPerMeter: vec3, + projectionMode: i32, + scale: f32, + commonUnitsPerWorldUnit: vec3, + commonUnitsPerWorldUnit2: vec3, + center: vec4, + modelMatrix: mat4x4, + viewProjectionMatrix: mat4x4, + viewportSize: vec2, + devicePixelRatio: f32, + focalDistance: f32, + cameraPosition: vec3, + coordinateOrigin: vec3, + commonOrigin: vec3, + pseudoMeters: i32, +}; + +@group(0) @binding(auto) +var project: ProjectUniforms; + +// ----------------------------------------------------------------------------- +// Geometry data shared across the project helpers. +// The active layer shader is responsible for populating this private module +// state before calling the project functions below. +// ----------------------------------------------------------------------------- + +// Structure to carry additional geometry data used by deck.gl filters. +struct Geometry { + worldPosition: vec3, + worldPositionAlt: vec3, + position: vec4, + normal: vec3, + uv: vec2, + pickingColor: vec3, +}; + +var geometry: Geometry; +`,ab=`${BI} + +// ----------------------------------------------------------------------------- +// Functions +// ----------------------------------------------------------------------------- + +// Returns an adjustment factor for commonUnitsPerMeter +fn _project_size_at_latitude(lat: f32) -> f32 { + let y = clamp(lat, -89.9, 89.9); + return 1.0 / cos(radians(y)); +} + +// Overloaded version: scales a value in meters at a given latitude. +fn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 { + return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat); +} + +// Computes a non-linear scale factor based on geometry. +// (Note: This function relies on "geometry" being provided.) +fn project_size() -> f32 { + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && + project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && + project.pseudoMeters == 0) { + if (geometry.position.w == 0.0) { + return _project_size_at_latitude(geometry.worldPosition.y); + } + let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0; + let y2 = y * y; + let y4 = y2 * y2; + let y6 = y4 * y2; + return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; + } + return 1.0; +} + +// Overloads to scale offsets (meters to world units) +fn project_size_float(meters: f32) -> f32 { + return meters * project.commonUnitsPerMeter.z * project_size(); +} + +fn project_size_vec2(meters: vec2) -> vec2 { + return meters * project.commonUnitsPerMeter.xy * project_size(); +} + +fn project_size_vec3(meters: vec3) -> vec3 { + return meters * project.commonUnitsPerMeter * project_size(); +} + +fn project_size_vec4(meters: vec4) -> vec4 { + return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); +} + +// Returns a rotation matrix aligning the z\u2011axis with the given up vector. +fn project_get_orientation_matrix(up: vec3) -> mat3x3 { + let uz = normalize(up); + let ux = select( + vec3(1.0, 0.0, 0.0), + normalize(vec3(uz.y, -uz.x, 0.0)), + abs(uz.z) == 1.0 + ); + let uy = cross(uz, ux); + return mat3x3(ux, uy, uz); +} + +// Since WGSL does not support "out" parameters, we return a struct. +struct RotationResult { + needsRotation: bool, + transform: mat3x3, +}; + +fn project_needs_rotation(commonPosition: vec3) -> RotationResult { + if (project.projectionMode == PROJECTION_MODE_GLOBE) { + return RotationResult(true, project_get_orientation_matrix(commonPosition)); + } else { + return RotationResult(false, mat3x3()); // identity alternative if needed + }; +} + +// Projects a normal vector from the current coordinate system to world space. +fn project_normal(vector: vec3) -> vec3 { + let normal_modelspace = project.modelMatrix * vec4(vector, 0.0); + var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); + let rotResult = project_needs_rotation(geometry.position.xyz); + if (rotResult.needsRotation) { + n = rotResult.transform * n; + } + return n; +} + +// Applies a scale offset based on y-offset (dy) +fn project_offset_(offset: vec4) -> vec4 { + let dy: f32 = offset.y; + let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; + return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); +} + +// Projects lng/lat coordinates to a unit tile [0,1] +fn project_mercator_(lnglat: vec2) -> vec2 { + var x = lnglat.x; + if (project.wrapLongitude != 0) { + x = ((x + 180.0) % 360.0) - 180.0; + } + let y = clamp(lnglat.y, -89.9, 89.9); + return vec2( + radians(x) + PI, + PI + log(tan(PI * 0.25 + radians(y) * 0.5)) + ) * WORLD_SCALE; +} + +// Projects lng/lat/z coordinates for a globe projection. +fn project_globe_(lnglatz: vec3) -> vec3 { + let lambda = radians(lnglatz.x); + let phi = radians(lnglatz.y); + let cosPhi = cos(phi); + let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; + return vec3( + sin(lambda) * cosPhi, + -cos(lambda) * cosPhi, + sin(phi) + ) * D; +} + +// Projects positions (with an optional 64-bit low part) from the input +// coordinate system to the common space. +fn project_position_vec4_f64(position: vec4, position64Low: vec3) -> vec4 { + var position_world = project.modelMatrix * position; + + // Work around for a Mac+NVIDIA bug: + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + return vec4( + project_mercator_(position_world.xy), + _project_size_at_latitude_m(position_world.z, position_world.y), + position_world.w + ); + } + if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { + position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w); + } + } + if (project.projectionMode == PROJECTION_MODE_GLOBE) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + return vec4( + project_globe_(position_world.xyz), + position_world.w + ); + } + } + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { + return vec4( + project_mercator_(position_world.xy) - project.commonOrigin.xy, + project_size_float(position_world.z), + position_world.w + ); + } + } + } + if (project.projectionMode == PROJECTION_MODE_IDENTITY || + (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && + (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || + project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { + position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w); + } + + return project_offset_(position_world) + + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); +} + +// Overloaded versions for different input types. +fn project_position_vec4_f32(position: vec4) -> vec4 { + return project_position_vec4_f64(position, ZERO_64_LOW); +} + +fn project_position_vec3_f64(position: vec3, position64Low: vec3) -> vec3 { + let projected_position = project_position_vec4_f64(vec4(position, 1.0), position64Low); + return projected_position.xyz; +} + +fn project_position_vec3_f32(position: vec3) -> vec3 { + let projected_position = project_position_vec4_f64(vec4(position, 1.0), ZERO_64_LOW); + return projected_position.xyz; +} + +fn project_position_vec2_f32(position: vec2) -> vec2 { + let projected_position = project_position_vec4_f64(vec4(position, 0.0, 1.0), ZERO_64_LOW); + return projected_position.xy; +} + +// Transforms a common space position to clip space. +fn project_common_position_to_clipspace_with_projection(position: vec4, viewProjectionMatrix: mat4x4, center: vec4) -> vec4 { + return viewProjectionMatrix * position + center; +} + +// Uses the project viewProjectionMatrix and center. +fn project_common_position_to_clipspace(position: vec4) -> vec4 { + return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center); +} + +// Returns a clip space offset corresponding to a given number of screen pixels. +fn project_pixel_size_to_clipspace(pixels: vec2) -> vec2 { + let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; + return offset * project.focalDistance; +} + +fn project_meter_size_to_pixel(meters: f32) -> f32 { + return project_size_float(meters) * project.scale; +} + +fn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 { + if (unit == UNIT_METERS) { + return project_meter_size_to_pixel(size); + } else if (unit == UNIT_COMMON) { + return size * project.scale; + } + // UNIT_PIXELS: no scaling applied. + return size; +} + +fn project_pixel_size_float(pixels: f32) -> f32 { + return pixels / project.scale; +} + +fn project_pixel_size_vec2(pixels: vec2) -> vec2 { + return pixels / project.scale; +} +`;var kI=["default","lnglat","meter-offsets","lnglat-offsets","cartesian"],UI=kI.map(t=>`const int COORDINATE_SYSTEM_${t.toUpperCase().replaceAll("-","_")} = ${xi(t)};`).join(""),zI=Object.keys(_e).map(t=>`const int PROJECTION_MODE_${t} = ${_e[t]};`).join(""),WI=Object.keys(je).map(t=>`const int UNIT_${t.toUpperCase()} = ${je[t]};`).join(""),cb=`${UI} +${zI} +${WI} +layout(std140) uniform projectUniforms { +bool wrapLongitude; +int coordinateSystem; +vec3 commonUnitsPerMeter; +int projectionMode; +float scale; +vec3 commonUnitsPerWorldUnit; +vec3 commonUnitsPerWorldUnit2; +vec4 center; +mat4 modelMatrix; +mat4 viewProjectionMatrix; +vec2 viewportSize; +float devicePixelRatio; +float focalDistance; +vec3 cameraPosition; +vec3 coordinateOrigin; +vec3 commonOrigin; +bool pseudoMeters; +} project; +const float TILE_SIZE = 512.0; +const float PI = 3.1415926536; +const float WORLD_SCALE = TILE_SIZE / (PI * 2.0); +const vec3 ZERO_64_LOW = vec3(0.0); +const float EARTH_RADIUS = 6370972.0; +const float GLOBE_RADIUS = 256.0; +float project_size_at_latitude(float lat) { +float y = clamp(lat, -89.9, 89.9); +return 1.0 / cos(radians(y)); +} +float project_size() { +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && +project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && +project.pseudoMeters == false) { +if (geometry.position.w == 0.0) { +return project_size_at_latitude(geometry.worldPosition.y); +} +float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0; +float y2 = y * y; +float y4 = y2 * y2; +float y6 = y4 * y2; +return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; +} +return 1.0; +} +float project_size_at_latitude(float meters, float lat) { +return meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat); +} +float project_size(float meters) { +return meters * project.commonUnitsPerMeter.z * project_size(); +} +vec2 project_size(vec2 meters) { +return meters * project.commonUnitsPerMeter.xy * project_size(); +} +vec3 project_size(vec3 meters) { +return meters * project.commonUnitsPerMeter * project_size(); +} +vec4 project_size(vec4 meters) { +return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); +} +mat3 project_get_orientation_matrix(vec3 up) { +vec3 uz = normalize(up); +vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0)); +vec3 uy = cross(uz, ux); +return mat3(ux, uy, uz); +} +bool project_needs_rotation(vec3 commonPosition, out mat3 transform) { +if (project.projectionMode == PROJECTION_MODE_GLOBE) { +transform = project_get_orientation_matrix(commonPosition); +return true; +} +return false; +} +vec3 project_normal(vec3 vector) { +vec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0); +vec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); +mat3 rotation; +if (project_needs_rotation(geometry.position.xyz, rotation)) { +n = rotation * n; +} +return n; +} +vec4 project_offset_(vec4 offset) { +float dy = offset.y; +vec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; +return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); +} +vec2 project_mercator_(vec2 lnglat) { +float x = lnglat.x; +if (project.wrapLongitude) { +x = mod(x + 180., 360.0) - 180.; +} +float y = clamp(lnglat.y, -89.9, 89.9); +return vec2( +radians(x) + PI, +PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5)) +) * WORLD_SCALE; +} +vec3 project_globe_(vec3 lnglatz) { +float lambda = radians(lnglatz.x); +float phi = radians(lnglatz.y); +float cosPhi = cos(phi); +float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; +return vec3( +sin(lambda) * cosPhi, +-cos(lambda) * cosPhi, +sin(phi) +) * D; +} +vec4 project_position(vec4 position, vec3 position64Low) { +vec4 position_world = project.modelMatrix * position; +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +return vec4( +project_mercator_(position_world.xy), +project_size_at_latitude(position_world.z, position_world.y), +position_world.w +); +} +if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { +position_world.xyz += project.coordinateOrigin; +} +} +if (project.projectionMode == PROJECTION_MODE_GLOBE) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +return vec4( +project_globe_(position_world.xyz), +position_world.w +); +} +} +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { +return vec4( +project_mercator_(position_world.xy) - project.commonOrigin.xy, +project_size(position_world.z), +position_world.w +); +} +} +} +if (project.projectionMode == PROJECTION_MODE_IDENTITY || +(project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && +(project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || +project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { +position_world.xyz -= project.coordinateOrigin; +} +return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); +} +vec4 project_position(vec4 position) { +return project_position(position, ZERO_64_LOW); +} +vec3 project_position(vec3 position, vec3 position64Low) { +vec4 projected_position = project_position(vec4(position, 1.0), position64Low); +return projected_position.xyz; +} +vec3 project_position(vec3 position) { +vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW); +return projected_position.xyz; +} +vec2 project_position(vec2 position) { +vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW); +return projected_position.xy; +} +vec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) { +return viewProjectionMatrix * position + center; +} +vec4 project_common_position_to_clipspace(vec4 position) { +return project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center); +} +vec2 project_pixel_size_to_clipspace(vec2 pixels) { +vec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; +return offset * project.focalDistance; +} +float project_size_to_pixel(float meters) { +return project_size(meters) * project.scale; +} +vec2 project_size_to_pixel(vec2 meters) { +return project_size(meters) * project.scale; +} +float project_size_to_pixel(float size, int unit) { +if (unit == UNIT_METERS) return project_size_to_pixel(size); +if (unit == UNIT_COMMON) return size * project.scale; +return size; +} +float project_pixel_size(float pixels) { +return pixels / project.scale; +} +vec2 project_pixel_size(vec2 pixels) { +return pixels / project.scale; +} +`;var VI={};function jI(t=VI){return"viewport"in t?sb(t):{}}var bn={name:"project",dependencies:[hh,Yc],source:ab,vs:cb,getUniforms:jI,uniformTypes:{wrapLongitude:"f32",coordinateSystem:"i32",commonUnitsPerMeter:"vec3",projectionMode:"i32",scale:"f32",commonUnitsPerWorldUnit:"vec3",commonUnitsPerWorldUnit2:"vec3",center:"vec4",modelMatrix:"mat4x4",viewProjectionMatrix:"mat4x4",viewportSize:"vec2",devicePixelRatio:"f32",focalDistance:"f32",cameraPosition:"vec3",coordinateOrigin:"vec3",commonOrigin:"vec3",pseudoMeters:"f32"}};var $I=`// Define a structure to hold both the clip-space position and the common position. +struct ProjectResult { + clipPosition: vec4, + commonPosition: vec4, +}; + +// This function mimics the GLSL version with the 'out' parameter by returning both values. +fn project_position_to_clipspace_and_commonspace( + position: vec3, + position64Low: vec3, + offset: vec3 +) -> ProjectResult { + // Compute the projected position. + let projectedPosition: vec3 = project_position_vec3_f64(position, position64Low); + + // Start with the provided offset. + var finalOffset: vec3 = offset; + + // Get whether a rotation is needed and the rotation matrix. + let rotationResult = project_needs_rotation(projectedPosition); + + // If rotation is needed, update the offset. + if (rotationResult.needsRotation) { + finalOffset = rotationResult.transform * offset; + } + + // Compute the common position. + let commonPosition: vec4 = vec4(projectedPosition + finalOffset, 1.0); + + // Convert to clip-space. + let clipPosition: vec4 = project_common_position_to_clipspace(commonPosition); + + return ProjectResult(clipPosition, commonPosition); +} + +// A convenience overload that returns only the clip-space position. +fn project_position_to_clipspace( + position: vec3, + position64Low: vec3, + offset: vec3 +) -> vec4 { + return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition; +} +`,HI=`vec4 project_position_to_clipspace( + vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition +) { + vec3 projectedPosition = project_position(position, position64Low); + mat3 rotation; + if (project_needs_rotation(projectedPosition, rotation)) { + // offset is specified as ENU + // when in globe projection, rotate offset so that the ground alighs with the surface of the globe + offset = rotation * offset; + } + commonPosition = vec4(projectedPosition + offset, 1.0); + return project_common_position_to_clipspace(commonPosition); +} + +vec4 project_position_to_clipspace( + vec3 position, vec3 position64Low, vec3 offset +) { + vec4 commonPosition; + return project_position_to_clipspace(position, position64Low, offset, commonPosition); +} +`,Oe={name:"project32",dependencies:[bn],source:$I,vs:HI};function Tn(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Fr(t,e){let r=Ze.transformMat4([],e,t);return Ze.scale(r,r,1/r[3]),r}function os(t,e,r){return tr?r:t}function YI(t){return Math.log(t)*Math.LOG2E}var ss=Math.log2||YI;function gt(t,e){if(!t)throw new Error(e||"@math.gl/web-mercator: assertion failed.")}var mt=Math.PI,lb=mt/4,at=mt/180,up=180/mt,wn=512,nl=4003e4,ze=85.051129,dp=1.5;function ol(t){return Math.pow(2,t)}function hp(t){return ss(t)}function xe(t){let[e,r]=t;gt(Number.isFinite(e)),gt(Number.isFinite(r)&&r>=-90&&r<=90,"invalid latitude");let i=e*at,n=r*at,o=wn*(i+mt)/(2*mt),s=wn*(mt+Math.log(Math.tan(lb+n*.5)))/(2*mt);return[o,s]}function Se(t){let[e,r]=t,i=e/wn*(2*mt)-mt,n=2*(Math.atan(Math.exp(r/wn*(2*mt)-mt))-lb);return[i*up,n*up]}function pp(t){let{latitude:e}=t;gt(Number.isFinite(e));let r=Math.cos(e*at);return hp(nl*r)-9}function bi(t){let e=Math.cos(t*at);return wn/nl/e}function Ti(t){let{latitude:e,longitude:r,highPrecision:i=!1}=t;gt(Number.isFinite(e)&&Number.isFinite(r));let n=wn,o=Math.cos(e*at),s=n/360,a=s/o,c=n/nl/o,l={unitsPerMeter:[c,c,c],metersPerUnit:[1/c,1/c,1/c],unitsPerDegree:[s,a,c],degreesPerUnit:[1/s,1/a,1/c]};if(i){let f=at*Math.tan(e*at)/o,u=s*f/2,d=n/nl*f,h=d/a*c;l.unitsPerDegree2=[0,u,d],l.unitsPerMeter2=[h,0,h]}return l}function as(t,e){let[r,i,n]=t,[o,s,a]=e,{unitsPerMeter:c,unitsPerMeter2:l}=Ti({longitude:r,latitude:i,highPrecision:!0}),f=xe(t);f[0]+=o*(c[0]+l[0]*s),f[1]+=s*(c[1]+l[1]*s);let u=Se(f),d=(n||0)+(a||0);return Number.isFinite(n)||Number.isFinite(a)?[u[0],u[1],d]:u}function cs(t){let{height:e,pitch:r,bearing:i,altitude:n,scale:o,center:s}=t,a=Tn();ee.translate(a,a,[0,0,-n]),ee.rotateX(a,a,-r*at),ee.rotateZ(a,a,i*at);let c=o/e;return ee.scale(a,a,[c,c,c]),s&&ee.translate(a,a,Pe.negate([],s)),a}function sl(t){let{width:e,height:r,altitude:i,pitch:n=0,offset:o,center:s,scale:a,nearZMultiplier:c=1,farZMultiplier:l=1}=t,{fovy:f=_t(dp)}=t;i!==void 0&&(f=_t(i));let u=f*at,d=n*at,h=Br(f),p=h;s&&(p+=s[2]*a/Math.cos(d)/r);let g=u*(.5+(o?o[1]:0)/r),m=Math.sin(g)*p/Math.sin(os(Math.PI/2-d-g,.01,Math.PI-.01)),_=Math.sin(d)*m+p,T=p*10,y=Math.min(_*l,T);return{fov:u,aspect:e/r,focalDistance:h,near:c,far:y}}function gp(t){let{fov:e,aspect:r,near:i,far:n}=sl(t);return ee.perspective([],e,r,i,n)}function _t(t){return 2*Math.atan(.5/t)*up}function Br(t){return .5/Math.tan(.5*t*at)}function wi(t,e){let[r,i,n=0]=t;return gt(Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)),Fr(e,[r,i,n,1])}function Ut(t,e,r=0){let[i,n,o]=t;if(gt(Number.isFinite(i)&&Number.isFinite(n),"invalid pixel coordinate"),Number.isFinite(o))return Fr(e,[i,n,o,1]);let s=Fr(e,[i,n,0,1]),a=Fr(e,[i,n,1,1]),c=s[2],l=a[2],f=c===l?0:((r||0)-c)/(l-c);return Be.lerp([],s,a,f)}function Si(t){let{width:e,height:r,bounds:i,minExtent:n=0,maxZoom:o=24,offset:s=[0,0]}=t,[[a,c],[l,f]]=i,u=XI(t.padding),d=xe([a,os(f,-ze,ze)]),h=xe([l,os(c,-ze,ze)]),p=[Math.max(Math.abs(h[0]-d[0]),n),Math.max(Math.abs(h[1]-d[1]),n)],g=[e-u.left-u.right-Math.abs(s[0])*2,r-u.top-u.bottom-Math.abs(s[1])*2];gt(g[0]>0&&g[1]>0);let m=g[0]/p[0],_=g[1]/p[1],T=(u.right-u.left)/2/m,y=(u.top-u.bottom)/2/_,x=[(h[0]+d[0])/2+T,(h[1]+d[1])/2+y],w=Se(x),b=Math.min(o,ss(Math.abs(Math.min(m,_))));return gt(Number.isFinite(b)),{longitude:w[0],latitude:w[1],zoom:b}}function XI(t=0){return typeof t=="number"?{top:t,bottom:t,left:t,right:t}:(gt(Number.isFinite(t.top)&&Number.isFinite(t.bottom)&&Number.isFinite(t.left)&&Number.isFinite(t.right)),t)}var fb=Math.PI/180;function ls(t,e=0){let{width:r,height:i,unproject:n}=t,o={targetZ:e},s=n([0,i],o),a=n([r,i],o),c,l,f=t.fovy?.5*t.fovy*fb:Math.atan(.5/t.altitude),u=(90-t.pitch)*fb;return f>u-.01?(c=ub(t,0,e),l=ub(t,r,e)):(c=n([0,0],o),l=n([r,0],o)),[s,a,l,c]}function ub(t,e,r){let{pixelUnprojectionMatrix:i}=t,n=Fr(i,[e,0,1,1]),o=Fr(i,[e,t.height,1,1]),a=(r*t.distanceScales.unitsPerMeter[2]-n[2])/(o[2]-n[2]),c=Be.lerp([],n,o,a),l=Se(c);return l.push(r),l}var Sn=class t{constructor(e={width:1,height:1}){this.equals=_=>_ instanceof t?_.width===this.width&&_.height===this.height&&ee.equals(_.projectionMatrix,this.projectionMatrix)&&ee.equals(_.viewMatrix,this.viewMatrix):!1,this.project=(_,T={})=>{let{topLeft:y=!0}=T,x=this.projectPosition(_),w=wi(x,this.pixelProjectionMatrix),[b,E]=w,S=y?E:this.height-E;return _.length===2?[b,S]:[b,S,w[2]]},this.unproject=(_,T={})=>{let{topLeft:y=!0,targetZ:x=void 0}=T,[w,b,E]=_,S=y?b:this.height-b,A=x&&x*this.distanceScales.unitsPerMeter[2],C=Ut([w,S,E],this.pixelUnprojectionMatrix,A),[I,R,N]=this.unprojectPosition(C);return Number.isFinite(E)?[I,R,N]:Number.isFinite(x)?[I,R,x]:[I,R]},this.projectPosition=_=>{let[T,y]=xe(_),x=(_[2]||0)*this.distanceScales.unitsPerMeter[2];return[T,y,x]},this.unprojectPosition=_=>{let[T,y]=Se(_),x=(_[2]||0)*this.distanceScales.metersPerUnit[2];return[T,y,x]};let{width:r,height:i,altitude:n=null,fovy:o=null}=e,{latitude:s=0,longitude:a=0,zoom:c=0,pitch:l=0,bearing:f=0,position:u=null,nearZMultiplier:d=.02,farZMultiplier:h=1.01}=e;r=r||1,i=i||1,o===null&&n===null?(n=dp,o=_t(n)):o===null?o=_t(n):n===null&&(n=Br(o));let p=ol(c);n=Math.max(.75,n);let g=Ti({longitude:a,latitude:s}),m=xe([a,s]);m.push(0),u&&Pe.add(m,m,Pe.mul([],u,g.unitsPerMeter)),this.projectionMatrix=gp({width:r,height:i,scale:p,center:m,pitch:l,fovy:o,nearZMultiplier:d,farZMultiplier:h}),this.viewMatrix=cs({height:i,scale:p,center:m,pitch:l,bearing:f,altitude:n}),this.width=r,this.height=i,this.scale=p,this.latitude=s,this.longitude=a,this.zoom=c,this.pitch=l,this.bearing=f,this.altitude=n,this.fovy=o,this.center=m,this.meterOffset=u||[0,0,0],this.distanceScales=g,this._initMatrices(),Object.freeze(this)}_initMatrices(){let{width:e,height:r,projectionMatrix:i,viewMatrix:n}=this,o=Tn();ee.multiply(o,o,i),ee.multiply(o,o,n),this.viewProjectionMatrix=o;let s=Tn();ee.scale(s,s,[e/2,-r/2,1]),ee.translate(s,s,[1,-1,0]),ee.multiply(s,s,o);let a=ee.invert(Tn(),s);if(!a)throw new Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=s,this.pixelUnprojectionMatrix=a}projectFlat(e){return xe(e)}unprojectFlat(e){return Se(e)}getMapCenterByLngLatPosition({lngLat:e,pos:r}){let i=Ut(r,this.pixelUnprojectionMatrix),n=xe(e),o=Be.add([],n,Be.negate([],i)),s=Be.add([],this.center,o);return Se(s)}fitBounds(e,r={}){let{width:i,height:n}=this,{longitude:o,latitude:s,zoom:a}=Si(Object.assign({width:i,height:n,bounds:e},r));return new t({width:i,height:n,longitude:o,latitude:s,zoom:a})}getBounds(e){let r=this.getBoundingRegion(e),i=Math.min(...r.map(a=>a[0])),n=Math.max(...r.map(a=>a[0])),o=Math.min(...r.map(a=>a[1])),s=Math.max(...r.map(a=>a[1]));return[[i,o],[n,s]]}getBoundingRegion(e={}){return ls(this,e.z||0)}getLocationAtPoint({lngLat:e,pos:r}){return this.getMapCenterByLngLatPosition({lngLat:e,pos:r})}};var db=` +layout(std140) uniform shadowUniforms { + bool drawShadowMap; + bool useShadowMap; + vec4 color; + highp int lightId; + float lightCount; + mat4 viewProjectionMatrix0; + mat4 viewProjectionMatrix1; + vec4 projectCenter0; + vec4 projectCenter1; +} shadow; +`,GI=` +const int max_lights = 2; + +out vec3 shadow_vPosition[max_lights]; + +vec4 shadow_setVertexPosition(vec4 position_commonspace) { + mat4 viewProjectionMatrices[max_lights]; + viewProjectionMatrices[0] = shadow.viewProjectionMatrix0; + viewProjectionMatrices[1] = shadow.viewProjectionMatrix1; + vec4 projectCenters[max_lights]; + projectCenters[0] = shadow.projectCenter0; + projectCenters[1] = shadow.projectCenter1; + + if (shadow.drawShadowMap) { + return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]); + } + if (shadow.useShadowMap) { + for (int i = 0; i < max_lights; i++) { + if(i < int(shadow.lightCount)) { + vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]); + shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0; + } + } + } + return gl_Position; +} +`,qI=` +${db} +${GI} +`,KI=` +const int max_lights = 2; +uniform sampler2D shadow_uShadowMap0; +uniform sampler2D shadow_uShadowMap1; + +in vec3 shadow_vPosition[max_lights]; + +const vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0); +const vec4 bitUnpackShift = 1.0 / bitPackShift; +const vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); + +float shadow_getShadowWeight(vec3 position, sampler2D shadowMap) { + vec4 rgbaDepth = texture(shadowMap, position.xy); + + float z = dot(rgbaDepth, bitUnpackShift); + return smoothstep(0.001, 0.01, position.z - z); +} + +vec4 shadow_filterShadowColor(vec4 color) { + if (shadow.drawShadowMap) { + vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift); + rgbaDepth -= rgbaDepth.gbaa * bitMask; + return rgbaDepth; + } + if (shadow.useShadowMap) { + float shadowAlpha = 0.0; + shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0); + if(shadow.lightCount > 1.0) { + shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1); + } + shadowAlpha *= shadow.color.a / shadow.lightCount; + float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha); + + return vec4( + mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha), + blendedAlpha + ); + } + return color; +} +`,ZI=` +${db} +${KI} +`,QI=kt(iO),JI=kt(nO),eO=[0,0,0,1],tO=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0];function rO(t,e){let[r,i,n]=t,o=Ut([r,i,n],e);return Number.isFinite(n)?o:[o[0],o[1],0]}function iO({viewport:t,center:e}){return new me(t.viewProjectionMatrix).invert().transform(e)}function nO({viewport:t,shadowMatrices:e}){let r=[],i=t.pixelUnprojectionMatrix,n=t.isGeospatial?void 0:1,o=[[0,0,n],[t.width,0,n],[0,t.height,n],[t.width,t.height,n],[0,0,-1],[t.width,0,-1],[0,t.height,-1],[t.width,t.height,-1]].map(s=>rO(s,i));for(let s of e){let a=s.clone().translate(new Me(t.center).negate()),c=o.map(f=>a.transform(f)),l=new me().ortho({left:Math.min(...c.map(f=>f[0])),right:Math.max(...c.map(f=>f[0])),bottom:Math.min(...c.map(f=>f[1])),top:Math.max(...c.map(f=>f[1])),near:Math.min(...c.map(f=>-f[2])),far:Math.max(...c.map(f=>-f[2]))});r.push(l.multiplyRight(s))}return r}function oO(t){let{shadowEnabled:e=!0,project:r}=t;if(!e||!r||!t.shadowMatrices||!t.shadowMatrices.length)return{drawShadowMap:!1,useShadowMap:!1,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};let i=bn.getUniforms(r),n=QI({viewport:r.viewport,center:i.center}),o=[],s=JI({shadowMatrices:t.shadowMatrices,viewport:r.viewport}).slice();for(let c=0;c0:!1,color:t.shadowColor||eO,lightId:t.shadowLightId||0,lightCount:t.shadowMatrices.length,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};for(let c=0;c",lightId:"i32",lightCount:"f32",viewProjectionMatrix0:"mat4x4",viewProjectionMatrix1:"mat4x4",projectCenter0:"vec4",projectCenter1:"vec4"}};var sO=`struct pickingUniforms { + isActive: f32, + isAttribute: f32, + isHighlightActive: f32, + useByteColors: f32, + highlightedObjectColor: vec3, + highlightColor: vec4, +}; + +@group(0) @binding(auto) var picking: pickingUniforms; + +fn picking_normalizeColor(color: vec3) -> vec3 { + return select(color, color / 255.0, picking.useByteColors > 0.5); +} + +fn picking_normalizeColor4(color: vec4) -> vec4 { + return select(color, color / 255.0, picking.useByteColors > 0.5); +} + +fn picking_isColorZero(color: vec3) -> bool { + return dot(color, vec3(1.0)) < 0.00001; +} + +fn picking_isColorValid(color: vec3) -> bool { + return dot(color, vec3(1.0)) > 0.00001; +} +`,Ne={...Cc,source:sO,defaultUniforms:{...Cc.defaultUniforms,useByteColors:!0},inject:{"vs:DECKGL_FILTER_GL_POSITION":` + // for picking depth values + picking_setPickingAttribute(position.z / position.w); + `,"vs:DECKGL_FILTER_COLOR":` + picking_setPickingColor(geometry.pickingColor); + `,"fs:DECKGL_FILTER_COLOR":{order:99,injection:` + // use highlight color if this fragment belongs to the selected object. + color = picking_filterHighlightColor(color); + + // use picking color if rendering to picking FBO. + color = picking_filterPickingColor(color); + `}}};var lO=[Yc],fO=["vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)","vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)","vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)","fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)"],uO=[];function hb(t){let e=ui.getDefaultShaderAssembler();for(let i of lO)e.addDefaultModule(i);e._hookFunctions.length=0;let r=t==="glsl"?fO:uO;for(let i of r)e.addShaderHook(i);return e}var dO=[255,255,255],hO=1,pO=0,cl=class{constructor(e={}){this.type="ambient";let{color:r=dO}=e,{intensity:i=hO}=e;this.id=e.id||`ambient-${pO++}`,this.color=r,this.intensity=i}};var gO=[255,255,255],mO=1,_O=[0,0,-1],yO=0,fs=class{constructor(e={}){this.type="directional";let{color:r=gO}=e,{intensity:i=mO}=e,{direction:n=_O}=e,{_shadow:o=!1}=e;this.id=e.id||`directional-${yO++}`,this.color=r,this.intensity=i,this.type="directional",this.direction=new Me(n).normalize().toArray(),this.shadow=o}getProjectedLight(e){return this}};var us=class{constructor(e,r={id:"pass"}){let{id:i}=r;this.id=i,this.device=e,this.props={...r}}setProps(e){Object.assign(this.props,e)}render(e){}cleanup(){}};var xO={depthWriteEnabled:!0,depthCompare:"less-equal",blendColorOperation:"add",blendColorSrcFactor:"src-alpha",blendColorDstFactor:"one",blendAlphaOperation:"add",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"},cr=class extends us{constructor(){super(...arguments),this._lastRenderIndex=-1}render(e){this._render(e)}_render(e){let r=this.device.canvasContext,i=e.target??r.getCurrentFramebuffer(),[n,o]=r.getDrawingBufferSize(),s=e.clearCanvas??!0,a=e.clearColor??(s?[0,0,0,0]:!1),c=s?1:!1,l=s?0:!1,f=e.colorMask??15,u={viewport:[0,0,n,o]};e.colorMask&&(u.colorMask=f),e.scissorRect&&(u.scissorRect=e.scissorRect);let d=this.device.beginRenderPass({framebuffer:i,parameters:u,clearColor:a,clearDepth:c,clearStencil:l});try{return this._drawLayers(d,e)}finally{d.end(),this.device.submit()}}_drawLayers(e,r){let{target:i,shaderModuleProps:n,viewports:o,views:s,onViewportActive:a,clearStack:c=!0}=r;r.pass=r.pass||"unknown",c&&(this._lastRenderIndex=-1);let l=[];for(let f of o){let u=s&&s[f.id];a?.(f);let d=this._getDrawLayerParams(f,r),h=f.subViewports||[f];for(let p of h){let g=this._drawLayersInViewport(e,{target:i,shaderModuleProps:n,viewport:p,view:u,pass:r.pass,layers:r.layers},d);l.push(g)}}return l}_getDrawLayerParams(e,{layers:r,pass:i,isPicking:n=!1,layerFilter:o,cullRect:s,effects:a,shaderModuleProps:c},l=!1){let f=[],u=gb(this._lastRenderIndex+1),d={layer:r[0],viewport:e,isPicking:n,renderPass:i,cullRect:s},h={};for(let p=0;py/255):d===!1&&(g=!1),h!==void 0&&(m=h),p!==void 0&&(_=p),this.device.beginRenderPass({framebuffer:o,parameters:{viewport:l,scissorRect:l},clearColor:g,clearDepth:m,clearStencil:_}).end()}}let f={totalCount:r.length,visibleCount:0,compositeCount:0,pickableCount:0};e.setParameters({viewport:l});for(let u=0;u{let s=n.props._offset,a=n.id,c=n.parent&&n.parent.id,l;if(c&&!(c in e)&&i(n.parent,!1),c in r){let f=r[c]=r[c]||gb(e[c],e);l=f(n,o),r[a]=f}else Number.isFinite(s)?(l=s+(e[c]||0),r[a]=null):l=t;return o&&l>=t&&(t=l+1),e[a]=l,l};return i}function bO(t,{shaderModuleProps:e,target:r,viewport:i}){let n=e?.project?.devicePixelRatio??t.canvasContext.cssToDeviceRatio(),[,o]=t.canvasContext.getDrawingBufferSize(),s=r?r.height:o,a=i;return[a.x*n,s-(a.y+a.height)*n,a.width*n,a.height*n]}function pb(t,...e){for(let r of e)if(r)for(let i in r)t[i]?Object.assign(t[i],r[i]):t[i]=r[i];return t}var ds=class extends cr{constructor(e,r){super(e,r);let i=e.createTexture({format:"rgba8unorm",width:1,height:1,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}}),n=e.createTexture({format:"depth16unorm",width:1,height:1});this.fbo=e.createFramebuffer({id:"shadowmap",width:1,height:1,colorAttachments:[i],depthStencilAttachment:n})}delete(){this.fbo&&(this.fbo.destroy(),this.fbo=null)}getShadowMap(){return this.fbo.colorAttachments[0].texture}render(e){let r=this.fbo,i=this.device.canvasContext.cssToDeviceRatio(),n=e.viewports[0],o=n.width*i,s=n.height*i,a=[1,1,1,1];(o!==r.width||s!==r.height)&&r.resize({width:o,height:s}),super.render({...e,clearColor:a,target:r,pass:"shadow"})}getLayerParameters(e,r,i){return{...e.props.parameters,blend:!1,depthWriteEnabled:!0,depthCompare:"less-equal"}}shouldDrawLayer(e){return e.props.shadowEnabled!==!1}getShaderModuleProps(e,r,i){return{shadow:{project:i.project,drawToShadowMap:!0}}}};var TO={color:[255,255,255],intensity:1},mb=[{color:[255,255,255],intensity:1,direction:[-1,3,-1]},{color:[255,255,255],intensity:.9,direction:[1,-8,-2.5]}],wO=[0,0,0,200/255],An=class{constructor(e={}){this.id="lighting-effect",this.shadowColor=wO,this.shadow=!1,this.directionalLights=[],this.pointLights=[],this.shadowPasses=[],this.dummyShadowMap=null,this.setProps(e)}setup(e){this.context=e;let{device:r,deck:i}=e;this.shadow&&!this.dummyShadowMap&&(this._createShadowPasses(r),i._addDefaultShaderModule(al),this.dummyShadowMap=r.createTexture({width:1,height:1}))}setProps(e){this.ambientLight=void 0,this.directionalLights=[],this.pointLights=[];for(let r in e){let i=e[r];switch(i.type){case"ambient":this.ambientLight=i;break;case"directional":this.directionalLights.push(i);break;case"point":this.pointLights.push(i);break;default:}}this._applyDefaultLights(),this.shadow=this.directionalLights.some(r=>r.shadow),this.context&&this.setup(this.context),this.props=e}preRender({layers:e,layerFilter:r,viewports:i,onViewportActive:n,views:o}){if(this.shadow){this.shadowMatrices=this._calculateMatrices();for(let s=0;ss.getShadowMap()),dummyShadowMap:this.dummyShadowMap,shadowColor:this.shadowColor,shadowMatrices:this.shadowMatrices}:{},n={enabled:!0,lights:this._getLights(e)},o=e.props.material;return{shadow:i,lighting:n,phongMaterial:o,gouraudMaterial:o}}cleanup(e){for(let r of this.shadowPasses)r.delete();this.shadowPasses.length=0,this.dummyShadowMap&&(this.dummyShadowMap.destroy(),this.dummyShadowMap=null,e.deck._removeDefaultShaderModule(al))}_calculateMatrices(){let e=[];for(let r of this.directionalLights){let i=new me().lookAt({eye:new Me(r.direction).negate()});e.push(i)}return e}_createShadowPasses(e){for(let r=0;rn&&(o=n);let s=this._pool,a=e.BYTES_PER_ELEMENT*o,c=s.findIndex(l=>l.byteLength>=a);if(c>=0){let l=new e(s.splice(c,1)[0],0,o);return i&&l.fill(0),l}return new e(o)}_release(e){if(!ArrayBuffer.isView(e))return;let r=this._pool,{buffer:i}=e,{byteLength:n}=i,o=r.findIndex(s=>s.byteLength>=n);o<0?r.push(i):(o>0||r.lengththis.opts.poolSize&&r.shift()}},lr=new mp;function En(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function ps(t,e){let r=t%e;return r<0?e+r:r}function yb(t){return[t[12],t[13],t[14]]}function xb(t){return{left:vn(t[3]+t[0],t[7]+t[4],t[11]+t[8],t[15]+t[12]),right:vn(t[3]-t[0],t[7]-t[4],t[11]-t[8],t[15]-t[12]),bottom:vn(t[3]+t[1],t[7]+t[5],t[11]+t[9],t[15]+t[13]),top:vn(t[3]-t[1],t[7]-t[5],t[11]-t[9],t[15]-t[13]),near:vn(t[3]+t[2],t[7]+t[6],t[11]+t[10],t[15]+t[14]),far:vn(t[3]-t[2],t[7]-t[6],t[11]-t[10],t[15]-t[14])}}var _b=new Me;function vn(t,e,r,i){_b.set(t,e,r);let n=_b.len();return{distance:i/n,normal:new Me(-t/n,-e/n,-r/n)}}function SO(t){return t-Math.fround(t)}var hs;function ll(t,e){let{size:r=1,startIndex:i=0}=e,n=e.endIndex!==void 0?e.endIndex:t.length,o=(n-i)/r;hs=lr.allocate(hs,o,{type:Float32Array,size:r*2});let s=i,a=0;for(;s=r.delay+r.duration*r.repeat}getTime(e){if(e===void 0)return this.time;let r=this.channels.get(e);return r===void 0?-1:r.time}setTime(e){this.time=Math.max(0,e);let r=this.channels.values();for(let n of r)this._setChannelTime(n,this.time);let i=this.animations.values();for(let n of i){let{animation:o,channel:s}=n;o.setTime(this.getTime(s))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,r){let i=MO++;return this.animations.set(i,{animation:e,channel:r}),e.setTime(this.getTime(r)),i}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,r){let i=r-e.delay,n=e.duration*e.repeat;i>=n?e.time=e.duration*e.rate:(e.time=Math.max(0,i)%e.duration,e.time*=e.rate)}};z();function Ab(t){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,t):setTimeout(()=>t(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function vb(t){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,t);return}clearTimeout(t)}go();var IO=0,OO="Animation Loop",gs=class t{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>console.error(e),stats:void 0,autoResizeViewport:!1};device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...t.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new it({id:`animation-loop-${IO++}`}),this.sharedStats=hn.stats.get(OO),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this.props.onError(e),this._error=e}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){return"autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){let r=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(r),r}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0),this}redraw(e){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=Ab(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(vb(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e){this._running&&(this.redraw(e),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}this.props.onRender(this._getAnimationProps()),this.device?.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let r=e?.canvas,i=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:r,useDevicePixels:i,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:r,aspect:i}=this._getSizeAndAspect();(e!==this.animationProps.width||r!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),i!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=r,this.animationProps.aspect=i,this.animationProps.needsRedraw=this._needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let r=document.createElement("div");r.style.position="absolute",r.style.left="10px",r.style.bottom="10px",r.style.width="300px",r.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(r);let i=this.props.onAddHTML(r);i&&(r.innerHTML=i)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,r]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),i=e>0&&r>0?e/r:1;return{width:e,height:r,aspect:i}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){let r=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let i=r-this._lastFrameTime;i>0&&this.frameRate.addTime(i)}this._lastFrameTime=r,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let r=this.sharedStats.get(e.name,e.type);r.sampleSize=e.sampleSize,r.time=e.time,r.count=e.count,r.samples=e.samples,r.lastTiming=e.lastTiming,r.lastSampleTime=e.lastSampleTime,r.lastSampleCount=e.lastSampleCount,r._count=e._count,r._time=e._time,r._samples=e._samples,r._startTime=e._startTime,r._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}};z();z();var yp={};function kr(t="id"){yp[t]=yp[t]||1;let e=yp[t]++;return`${t}-${e}`}var hl=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||kr("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&j.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function Eb(t,e){if(e instanceof hl)return e;let r=NO(t,e),{attributes:i,bufferLayout:n}=DO(t,e);return new hl({topology:e.topology||"triangle-list",bufferLayout:n,vertexCount:e.vertexCount,indices:r,attributes:i})}function NO(t,e){if(!e.indices)return;let r=e.indices.value;return t.createBuffer({usage:j.INDEX,data:r})}function DO(t,e){let r=[],i={};for(let[o,s]of Object.entries(e.attributes)){let a=o;switch(o){case"POSITION":a="positions";break;case"NORMAL":a="normals";break;case"TEXCOORD_0":a="texCoords";break;case"TEXCOORD_1":a="texCoords1";break;case"COLOR_0":a="colors";break}if(s){i[a]=t.createBuffer({data:s.value,id:`${o}-buffer`});let{value:c,size:l,normalized:f}=s;if(l===void 0)throw new Error(`Attribute ${o} is missing a size`);r.push({name:a,format:or.getVertexFormatFromAttribute(c,l,f)})}}let n=e._calculateVertexCount(e.attributes,e.indices);return{attributes:i,bufferLayout:r,vertexCount:n}}function Rb(t,e){let r={},i="Values";if(t.attributes.length===0&&!t.varyings?.length)return{"No attributes or varyings":{[i]:"N/A"}};for(let n of t.attributes)if(n){let o=`${n.location} ${n.name}: ${n.type}`;r[`in ${o}`]={[i]:n.stepMode||"vertex"}}for(let n of t.varyings||[]){let o=`${n.location} ${n.name}`;r[`out ${o}`]={[i]:JSON.stringify(n)}}return r}var Cb="__debugFramebufferState";function Mb(t,e,r){if(t.device.type!=="webgl")return;let i=BO(t.device);if(!i.flushing){if(UO(t)){LO(t,r,i);return}e&&kO(e)&&e.handle!==null&&(i.queuedFramebuffers.includes(e)||i.queuedFramebuffers.push(e))}}function LO(t,e,r){if(r.queuedFramebuffers.length===0)return;let i=t.device,{gl:n}=i,o=n.getParameter(36010),s=n.getParameter(36006),[a,c]=t.device.getDefaultCanvasContext().getDrawingBufferSize(),l=Pb(e.top,8),f=Pb(e.left,8);r.flushing=!0;try{for(let u of r.queuedFramebuffers){let[d,h,p,g,m]=FO({framebuffer:u,targetWidth:a,targetHeight:c,topPx:l,leftPx:f,minimap:e.minimap});n.bindFramebuffer(36008,u.handle),n.bindFramebuffer(36009,null),n.blitFramebuffer(0,0,u.width,u.height,d,h,p,g,16384,9728),l+=m+8}}finally{n.bindFramebuffer(36008,o),n.bindFramebuffer(36009,s),r.flushing=!1}}function FO(t){let{framebuffer:e,targetWidth:r,targetHeight:i,topPx:n,leftPx:o,minimap:s}=t,a=s?Math.max(Math.floor(r/4),1):r,c=s?Math.max(Math.floor(i/4),1):i,l=Math.min(a/e.width,c/e.height),f=Math.max(Math.floor(e.width*l),1),u=Math.max(Math.floor(e.height*l),1),d=o,h=Math.max(i-n-u,0),p=d+f,g=h+u;return[d,h,p,g,u]}function BO(t){return t.userData[Cb]||={flushing:!1,queuedFramebuffers:[]},t.userData[Cb]}function kO(t){return"colorAttachments"in t}function UO(t){let e=t.props.framebuffer;return!e||e.handle===null}function Pb(t,e){if(!t)return e;let r=Number.parseInt(t,10);return Number.isFinite(r)?r:e}function pl(t,e,r){if(t===e)return!0;if(!r||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;ir.name===e)||null}getAttributeNamesForBuffer(e){return e.attributes?e.attributes?.map(r=>r.attribute):[e.name]}mergeBufferLayouts(e,r){let i=[...e];for(let n of r){let o=i.findIndex(s=>s.name===n.name);o<0?i.push(n):i[o]=n}return i}getBufferIndex(e){let r=this.bufferLayouts.findIndex(i=>i.name===e);return r===-1&&v.warn(`BufferLayout: Missing buffer for "${e}".`)(),r}};function Ib(t,e){let r=1/0;for(let i of t){let n=e[i];n!==void 0&&(r=Math.min(r,n))}return r}function Ob(t,e){let r=Object.fromEntries(t.attributes.map(n=>[n.name,n.location])),i=e.slice();return i.sort((n,o)=>{let s=n.attributes?n.attributes.map(f=>f.attribute):[n.name],a=o.attributes?o.attributes.map(f=>f.attribute):[o.name],c=Ib(s,r),l=Ib(a,r);return c-l}),i}function xp(t,e){if(!t||!e.some(i=>i.bindingLayout?.length))return t;let r={...t,bindings:t.bindings.map(i=>({...i}))};"attributes"in(t||{})&&(r.attributes=t?.attributes||[]);for(let i of e)for(let n of i.bindingLayout||[])for(let o of zO(n.name)){let s=r.bindings.find(a=>a.name===o);s?.group===0&&(s.group=n.group)}return r}function Nb(t){return!!(t.uniformTypes&&!WO(t.uniformTypes))}function zO(t){let e=new Set([t,`${t}Uniforms`]);return t.endsWith("Uniforms")||e.add(`${t}Sampler`),[...e]}function WO(t){for(let e in t)return!1;return!0}z();function VO(t){return _d(t)||typeof t=="number"||typeof t=="boolean"}function Db(t,e={}){let r={bindings:{},uniforms:{}};return Object.keys(t).forEach(i=>{let n=t[i];Object.prototype.hasOwnProperty.call(e,i)||VO(n)?r.uniforms[i]=n:r.bindings[i]=n}),r}var gl=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(e,r){Object.assign(this.options,r);let i=an(Object.values(e).filter(jO));for(let n of i)e[n.name]=n;v.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[n,o]of Object.entries(e))o&&(this._addModule(o),o.name&&n!==o.name&&!this.options.disableWarnings&&v.warn(`Module name: ${n} vs ${o.name}`)())}destroy(){}setProps(e){for(let r of Object.keys(e)){let i=r,n=e[i]||{},o=this.modules[i];if(!o)this.options.disableWarnings||v.warn(`Module ${r} not found`)();else{let s=this.moduleUniforms[i],a=this.moduleBindings[i],c=o.getUniforms?.(n,s)||n,{uniforms:l,bindings:f}=Db(c,o.uniformTypes);this.moduleUniforms[i]=Lb(s,l,o.uniformTypes),this.moduleBindings[i]={...a,...f}}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let r of Object.values(this.moduleBindings))Object.assign(e,r);return e}getDebugTable(){let e={};for(let[r,i]of Object.entries(this.moduleUniforms))for(let[n,o]of Object.entries(i))e[`${r}.${n}`]={type:this.modules[r].uniformTypes?.[n],value:String(o)};return e}_addModule(e){let r=e.name;this.moduleUniforms[r]=Lb({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[r]={}}};function Lb(t={},e={},r={}){let i={...t};for(let[n,o]of Object.entries(e))o!==void 0&&(i[n]=bp(t[n],o,r[n]));return i}function bp(t,e,r){if(!r||typeof r=="string")return ms(e);if(Array.isArray(r)){if(Tp(e)||!Array.isArray(e))return ms(e);let s=Array.isArray(t)&&!Tp(t)?[...t]:[],a=s.slice();for(let c=0;cr===void 0?void 0:ms(r)):wp(t)?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r===void 0?void 0:ms(r)])):t}function Tp(t){return ArrayBuffer.isView(t)||Array.isArray(t)&&(t.length===0||typeof t[0]=="number")}function wp(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&!ArrayBuffer.isView(t)}function jO(t){return!!t?.dependencies}z();z();var Sp={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function _s(t){return t?Array.isArray(t)?t[0]??null:t:null}function Fb(t){let{dimension:e,data:r}=t;if(!r)return null;switch(e){case"1d":{let i=_s(r);if(!i)return null;let{width:n}=ys(i);return{width:n,height:1}}case"2d":{let i=_s(r);return i?ys(i):null}case"3d":case"2d-array":{if(!Array.isArray(r)||r.length===0)return null;let i=_s(r[0]);return i?ys(i):null}case"cube":{let i=Object.keys(r)[0]??null;if(!i)return null;let n=r[i],o=_s(n);return o?ys(o):null}case"cube-array":{if(!Array.isArray(r)||r.length===0)return null;let i=r[0],n=Object.keys(i)[0]??null;if(!n)return null;let o=_s(i[n]);return o?ys(o):null}default:return null}}function ys(t){if(dn(t))return Mo(t);if(typeof t=="object"&&"width"in t&&"height"in t)return{width:t.width,height:t.height};throw new Error("Unsupported mip-level data")}function $O(t){return typeof t=="object"&&t!==null&&"data"in t&&"width"in t&&"height"in t}function HO(t){return ArrayBuffer.isView(t)}function Ap(t){let{textureFormat:e,format:r}=t;if(e&&r&&e!==r)throw new Error(`Conflicting texture formats "${e}" and "${r}" provided for the same mip level`);return e??r}function Bb(t){let e=Sp[t];if(e===void 0)throw new Error(`Invalid cube face: ${t}`);return e}function YO(t,e){return 6*t+Bb(e)}function vp(t){throw new Error("setTexture1DData not supported in WebGL.")}function XO(t){return Array.isArray(t)?t:[t]}function vi(t,e,r,i){let n=XO(e),o=t,s=[];for(let a=0;a>a),height:Math.max(1,r.height>>a),...i?{format:i}:{}},textureFormat:i,z:o,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return s}function Ep(t){let e=[];for(let r=0;r{for(let[n,o]of Object.entries(r)){let s=YO(i,n);e.push(...vi(s,o))}}),e}var Ei=class t{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",r=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${r}px:(${this.isReady?"ready":"loading..."})`}constructor(e,r){this.device=e;let i=kr("dynamic-texture"),n=r;this.props={...t.defaultProps,id:i,...r,data:null},this.id=this.props.id,this.ready=new Promise((o,s)=>{this.resolveReady=o,this.rejectReady=s}),this.initAsync(n)}async initAsync(e){try{let r=await this._loadAllData(e);this._checkNotDestroyed();let i=r.data?GO({...r,width:e.width,height:e.height,format:e.format}):[],n="format"in e&&e.format!==void 0,o="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let g=Fb(r);return g||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=qO(this.device,i,a,{format:n?e.format:void 0}),l=c.format??this.props.format,f={...this.props,...a,format:l,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(l)&&!o&&(f.usage=$.SAMPLE|$.COPY_DST);let u=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(l);if(this.device.type==="webgpu"&&u){let g=this.props.dimension==="3d"?$.SAMPLE|$.STORAGE|$.COPY_DST|$.COPY_SRC:$.SAMPLE|$.RENDER|$.COPY_DST|$.COPY_SRC;f.usage|=g}let d=this.device.getMipLevelCount(f.width,f.height),h=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?d:Math.max(1,Math.min(d,this.props.mipLevels??1)),p={...f,mipLevels:h};this._texture=this.device.createTexture(p),this._sampler=this.texture.sampler,this._view=this.texture.view,c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!u&&v.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),u&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),v.info(0,`${this} created`)()}catch(r){let i=r instanceof Error?r:new Error(String(r));this.rejectReady(i)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?this.texture.generateMipmapsWebGL():this.device.type==="webgpu"?this.device.generateMipmapsWebGPU(this.texture):v.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let r=e instanceof pt?e:this.device.createSampler(e);this.texture.setSampler(r),this._sampler=r}async readBuffer(e={}){this.isReady||await this.ready;let r=e.width??this.texture.width,i=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,o=this.texture.computeMemoryLayout({width:r,height:i,depthOrArrayLayers:n}),s=this.device.createBuffer({byteLength:o.byteLength,usage:j.COPY_DST|j.MAP_READ});this.texture.readBuffer({...e,width:r,height:i,depthOrArrayLayers:n},s);let a=this.device.createFence();return await a.signaled,a.destroy(),s}async readAsync(e={}){this.isReady||await this.ready;let r=e.width??this.texture.width,i=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,o=this.texture.computeMemoryLayout({width:r,height:i,depthOrArrayLayers:n}),s=await this.readBuffer(e),a=await s.readAsync(0,o.byteLength);return s.destroy(),a.buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let r=this.texture;return this._texture=r.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,r.destroy(),v.info(`${this} resized`),!0}getCubeFaceIndex(e){let r=Sp[e];if(r===void 0)throw new Error(`Invalid cube face: ${e}`);return r}getCubeArrayFaceIndex(e,r){return 6*e+this.getCubeFaceIndex(r)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let r=vp(e);this._setTextureSubresources(r)}setTexture2DData(e,r=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let i=vi(r,e);this._setTextureSubresources(i)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let r=Ep(e);this._setTextureSubresources(r)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let r=Rp(e);this._setTextureSubresources(r)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let r=Cp(e);this._setTextureSubresources(r)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let r=Pp(e);this._setTextureSubresources(r)}_setTextureSubresources(e){for(let r of e){let{z:i,mipLevel:n}=r;switch(r.type){case"external-image":let{image:o,flipY:s}=r;this.texture.copyExternalImage({image:o,z:i,mipLevel:n,flipY:s});break;case"texture-data":let{data:a,textureFormat:c}=r;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${n} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:i,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:n});break;default:throw new Error("Unsupported 2D mip-level payload")}}}async _loadAllData(e){let r=await Mp(e.data);return{dimension:e.dimension??"2d",data:r??null}}_checkNotDestroyed(){this.destroyed&&v.warn(`${this} already destroyed`)}_checkReady(){this.isReady||v.warn(`${this} Cannot perform this operation before ready`)}static defaultProps={...$.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function GO(t){if(!t.data)return[];let e=t.width&&t.height?{width:t.width,height:t.height}:void 0,r="format"in t?t.format:void 0;switch(t.dimension){case"1d":return vp(t.data);case"2d":return vi(0,t.data,e,r);case"3d":return Ep(t.data);case"2d-array":return Rp(t.data);case"cube":return Cp(t.data);case"cube-array":return Pp(t.data);default:throw new Error(`Unhandled dimension ${t.dimension}`)}}function qO(t,e,r,i){if(e.length===0)return{subresources:e,mipLevels:1,format:i.format,hasExplicitMipChain:!1};let n=new Map;for(let f of e){let u=n.get(f.z)??[];u.push(f),n.set(f.z,u)}let o=e.some(f=>f.mipLevel>0),s=i.format,a=Number.POSITIVE_INFINITY,c=[];for(let[f,u]of n){let d=[...u].sort((T,y)=>T.mipLevel-y.mipLevel),h=d[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${f} is missing mip level 0`);let p=Ub(t,h);if(p.width!==r.width||p.height!==r.height)throw new Error(`DynamicTexture: slice ${f} base level dimensions ${p.width}x${p.height} do not match expected ${r.width}x${r.height}`);let g=kb(h);if(g){if(s&&s!==g)throw new Error(`DynamicTexture: slice ${f} base level format "${g}" does not match texture format "${s}"`);s=g}let m=s&&t.isTextureFormatCompressed(s)?KO(t,p.width,p.height,s):t.getMipLevelCount(p.width,p.height),_=0;for(let T=0;T=m)break;let x=Ub(t,y),w=Math.max(1,p.width>>T),b=Math.max(1,p.height>>T);if(x.width!==w||x.height!==b)break;let E=kb(y);if(E&&(s||(s=E),E!==s))break;_++,c.push(y)}a=Math.min(a,_)}let l=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(f=>f.mipLevel>a),l=Math.max(1,r>>a);if(c[c.name,c])||[]),n=r.shaderInputs||new gl(i,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(n);let o=QO(e),s=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.props.shaderLayout=xp(this.props.shaderLayout,s)||null,this.device.type==="webgpu"&&this.props.source){let{source:c,getUniforms:l,bindingTable:f}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:o,...this.props,modules:s});this.source=c,this._getModuleUniforms=l,this._bindingTable=f;let u=e.getShaderLayout?.(this.source);this.props.shaderLayout=xp(this.props.shaderLayout||u||null,s)||null}else{let{vs:c,fs:l,getUniforms:f}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:o,...this.props,modules:s});this.vs=c,this.fs=l,this._getModuleUniforms=f,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,r.geometry&&this.setGeometry(r.geometry),this.pipelineFactory=r.pipelineFactory||ko.getDefaultPipelineFactory(this.device),this.shaderFactory=r.shaderFactory||Uo.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=e.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in r&&(this.isInstanced=r.isInstanced),r.instanceCount&&this.setInstanceCount(r.instanceCount),r.vertexCount&&this.setVertexCount(r.vertexCount),r.indexBuffer&&this.setIndexBuffer(r.indexBuffer),r.attributes&&this.setAttributes(r.attributes),r.constantAttributes&&this.setConstantAttributes(r.constantAttributes),r.bindings&&this.setBindings(r.bindings),r.transformFeedback&&(this.transformFeedback=r.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(e){let r=this._areBindingsLoading();if(r)return v.info(Ur,`>>> DRAWING ABORTED ${this.id}: ${r} not loaded`)(),!1;try{e.pushDebugGroup(`${this}.predraw(${e})`),this.predraw()}finally{e.popDebugGroup()}let i,n=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),n=this.pipeline.isErrored,n)v.info(Ur,`>>> DRAWING ABORTED ${this.id}: ${zb}`)(),i=!1;else{let o=this._getBindings(),s=this._getBindGroups(),{indexBuffer:a}=this.vertexArray,c=a?a.byteLength/(a.indexType==="uint32"?4:2):void 0;i=this.pipeline.draw({renderPass:e,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:c,transformFeedback:this.transformFeedback||void 0,bindings:o,bindGroups:s,_bindGroupCacheKeys:this._getBindGroupCacheKeys(),uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),i?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):n?this._needsRedraw=zb:this._needsRedraw="waiting for resource initialization",i}setGeometry(e){this._gpuGeometry?.destroy();let r=e&&Eb(this.device,e);if(r){this.setTopology(r.topology||"triangle-list");let i=new Pn(this.bufferLayout);this.bufferLayout=i.mergeBufferLayouts(r.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(r)}this._gpuGeometry=r}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let r=new Pn(this.bufferLayout);this.bufferLayout=this._gpuGeometry?r.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(e){pl(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this.setNeedsRedraw("vertexCount")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new Ko(this.device,this.shaderInputs.modules);for(let[r,i]of Object.entries(this.shaderInputs.modules))if(Nb(i)&&!this.material?.ownsModule(r)){let n=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=n}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){this.vertexArray.setIndexBuffer(e),this.setNeedsRedraw("indexBuffer")}setAttributes(e,r){let i=r?.disableWarnings??this.props.disableWarnings;e.indices&&v.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Ob(this.pipeline.shaderLayout,this.bufferLayout);let n=new Pn(this.bufferLayout);for(let[o,s]of Object.entries(e)){let a=n.getBufferLayout(o);if(!a){i||v.warn(`Model(${this.id}): Missing layout for buffer "${o}".`)();continue}let c=n.getAttributeNamesForBuffer(a),l=!1;for(let f of c){let u=this._attributeInfos[f];if(u){let d=this.device.type==="webgpu"?n.getBufferIndex(u.bufferName):u.location;this.vertexArray.setBuffer(d,s),l=!0}}!l&&!i&&v.warn(`Model(${this.id}): Ignoring buffer "${s.id}" for unknown attribute "${o}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,r){for(let[i,n]of Object.entries(e)){let o=this._attributeInfos[i];o?this.vertexArray.setConstantWebGL(o.location,n):(r?.disableWarnings??this.props.disableWarnings)||v.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${i}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(e instanceof Ei&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(e instanceof Ei&&!e.isReady)return e.id;return!1}_getBindings(){let e={};for(let[r,i]of Object.entries(this.bindings))i instanceof Ei?i.isReady&&(e[r]=i.texture):e[r]=i;return e}_getBindGroups(){let e=this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]},r=e.bindings.length?zo(e,this._getBindings()):{0:this._getBindings()};if(!this.material)return r;for(let[i,n]of Object.entries(this.material.getBindingsByGroup())){let o=Number(i);r[o]={...r[o]||{},...n}}return r}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;for(let r of Object.values(this.bindings))r instanceof pi?e=Math.max(e,r.texture.updateTimestamp):r instanceof j||r instanceof $?e=Math.max(e,r.updateTimestamp):r instanceof Ei?e=r.texture?Math.max(e,r.texture.updateTimestamp):1/0:r instanceof pt||(e=Math.max(e,r.buffer.updateTimestamp));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let r={...e.attributes};for(let[i]of Object.entries(r))!this.pipeline.shaderLayout.attributes.find(n=>n.name===i)&&i!=="positions"&&delete r[i];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(r,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,r=null;this.pipeline&&(v.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,r=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let i=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),n=null;this.source?n=i:this.fs&&(n=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindGroups:this._getBindGroups(),vs:i,fs:n}),this._attributeInfos=Vc(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),r&&r!==e&&this.shaderFactory.release(r)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=v.level>3?0:ZO;v.level<2||Date.now()-this._lastLogTime>> DRAWING MODEL ${this.id}`,{collapsed:v.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=Rb(this.pipeline.shaderLayout,this.id);v.table(Ur,e)();let r=this.shaderInputs.getDebugTable();v.table(Ur,r)();let i=this._getAttributeDebugTable();v.table(Ur,this._attributeInfos)(),v.table(Ur,i)(),v.groupEnd(Ur)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let r=this.device.props.debugFramebuffers;if(this._drawCount++,!r)return;let i=e.props.framebuffer;Mb(e,i,{id:i?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[r,i]of Object.entries(this._attributeInfos)){let n=this.vertexArray.attributes[i.location];e[i.location]={name:r,type:i.shaderType,values:n?this._getBufferOrConstantValues(n,i.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:r}=this.vertexArray,i=r.indexType==="uint32"?new Uint32Array(r.debugData):new Uint16Array(r.debugData);e.indices={name:"indices",type:r.indexType,values:i.toString()}}return e}_getBufferOrConstantValues(e,r){let i=ke.getTypedArrayConstructor(r);return(e instanceof j?new i(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let r={};for(let[i,n]of Object.entries(e))this.material.ownsBinding(i)||(r[i]=n);return r}};function QO(t){return{type:t.type,shaderLanguage:t.info.shadingLanguage,shaderLanguageVersion:t.info.shadingLanguageVersion,gpu:t.info.gpu,features:t.features}}z();var zr=class t{device;model;transformFeedback;static defaultProps={...he.defaultProps,outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,r=t.defaultProps){if(!t.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new he(this.device,{id:r.id||"buffer-transform-model",fs:r.fs||Ld(),topology:r.topology||"point-list",varyings:r.outputs||r.varyings,...r}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:r.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);let r=this.device.beginRenderPass(e);this.model.draw(r),r.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let r=this.getBuffer(e);if(!r)throw new Error("BufferTransform#getBuffer");if(r instanceof j)return r.readAsync();let{buffer:i,byteOffset:n=0,byteLength:o=i.byteLength}=r;return i.readAsync(n,o)}};var Ae=class{id;topology;vertexCount;indices;attributes;userData={};constructor(e){let{attributes:r={},indices:i=null,vertexCount:n=null}=e;this.id=e.id||kr("geometry"),this.topology=e.topology,i&&(this.indices=ArrayBuffer.isView(i)?{value:i,size:1}:i),this.attributes={};for(let[o,s]of Object.entries(r)){let a=ArrayBuffer.isView(s)?{value:s}:s;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(o)}: must be typed array or object with value as typed array`);if((o==="POSITION"||o==="positions")&&!a.size&&(a.size=3),o==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else this.attributes[o]=a}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=n||this._calculateVertexCount(this.attributes,this.indices)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,r){return this}_calculateVertexCount(e,r){if(r)return r.value.length;let i=1/0;for(let n of Object.values(e)){let{value:o,size:s,constant:a}=n;!a&&o&&s!==void 0&&s>=1&&(i=Math.min(i,o.length/s))}return i}};var JO={blendColorOperation:"add",blendColorSrcFactor:"one",blendColorDstFactor:"zero",blendAlphaOperation:"add",blendAlphaSrcFactor:"constant",blendAlphaDstFactor:"zero"},Ri=class extends cr{constructor(){super(...arguments),this._colorEncoderState=null}render(e){return"pickingFBO"in e?this._drawPickingBuffer(e):{decodePickingColor:null,stats:super._render(e)}}_drawPickingBuffer({layers:e,layerFilter:r,views:i,viewports:n,onViewportActive:o,pickingFBO:s,deviceRect:{x:a,y:c,width:l,height:f},cullRect:u,effects:d,pass:h="picking",pickZ:p,shaderModuleProps:g,clearColor:m}){this.pickZ=p;let _=this._resetColorEncoder(p),T=[a,c,l,f],y=super._render({target:s,layers:e,layerFilter:r,views:i,viewports:n,onViewportActive:o,cullRect:u,effects:d?.filter(w=>w.useInPicking),pass:h,isPicking:!0,shaderModuleProps:g,clearColor:m??[0,0,0,0],colorMask:15,scissorRect:T});return this._colorEncoderState=null,{decodePickingColor:_&&e4.bind(null,_),stats:y}}shouldDrawLayer(e){let{pickable:r,operation:i}=e.props;return r&&i.includes("draw")||i.includes("terrain")||i.includes("mask")}getShaderModuleProps(e,r,i){return{picking:{isActive:1,isAttribute:this.pickZ},lighting:{enabled:!1}}}getLayerParameters(e,r,i){let n={...e.props.parameters},{pickable:o,operation:s}=e.props;return this._colorEncoderState?o&&s.includes("draw")?(Object.assign(n,JO),n.blend=!0,this.device.type==="webgpu"?n.blendConstant=Wb(this._colorEncoderState,e,i):n.blendColor=Wb(this._colorEncoderState,e,i),s.includes("terrain")&&e.state?._hasPickingCover&&(n.blendAlphaSrcFactor="one")):s.includes("terrain")&&(n.blend=!1):n.blend=!1,n}_resetColorEncoder(e){return this._colorEncoderState=e?null:{byLayer:new Map,byAlpha:[]},this._colorEncoderState}};function Wb(t,e,r){let{byLayer:i,byAlpha:n}=t,o,s=i.get(e);return s?(s.viewports.push(r),o=s.a):(o=i.size+1,o<=255?(s={a:o,layer:e,viewports:[r]},i.set(e,s),n[o]=s):(F.warn("Too many pickable layers, only picking the first 255")(),o=0)),[0,0,0,o/255]}function e4(t,e){let r=t.byAlpha[e[3]];return r&&{pickedLayer:r.layer,pickedViewports:r.viewports,pickedObjectIndex:r.layer.decodePickingColor(e)}}var Wr={NO_STATE:"Awaiting state",MATCHED:"Matched. State transferred from previous layer",INITIALIZED:"Initialized",AWAITING_GC:"Discarded. Awaiting garbage collection",AWAITING_FINALIZATION:"No longer matched. Awaiting garbage collection",FINALIZED:"Finalized! Awaiting garbage collection"},Mn=Symbol.for("component"),ct=Symbol.for("propTypes"),ml=Symbol.for("deprecatedProps"),fr=Symbol.for("asyncPropDefaults"),zt=Symbol.for("asyncPropOriginal"),yt=Symbol.for("asyncPropResolved");function lt(t,e=()=>!0){return Array.isArray(t)?Vb(t,e,[]):e(t)?[t]:[]}function Vb(t,e,r){let i=-1;for(;++i0}delete(){}getData(){return this.isLoaded?this._error?Promise.reject(this._error):this._content:this._loader.then(()=>this.getData())}setData(e,r){if(e===this._data&&!r)return;this._data=e;let i=++this._loadCount,n=e;typeof e=="string"&&(n=Mr(e)),n instanceof Promise?(this.isLoaded=!1,this._loader=n.then(o=>{this._loadCount===i&&(this.isLoaded=!0,this._error=void 0,this._content=o)}).catch(o=>{this._loadCount===i&&(this.isLoaded=!0,this._error=o||!0)})):(this.isLoaded=!0,this._error=void 0,this._content=e);for(let o of this._subscribers)o.onChange(this.getData())}};var bs=class{constructor(e){this.protocol=e.protocol||"resource://",this._context={device:e.device,gl:e.device?.gl,resourceManager:this},this._resources={},this._consumers={},this._pruneRequest=null}contains(e){return e.startsWith(this.protocol)?!0:e in this._resources}add({resourceId:e,data:r,forceUpdate:i=!1,persistent:n=!0}){let o=this._resources[e];o?o.setData(r,i):(o=new xs(e,r,this._context),this._resources[e]=o),o.persistent=n}remove(e){let r=this._resources[e];r&&(r.delete(),delete this._resources[e])}unsubscribe({consumerId:e}){let r=this._consumers[e];if(r){for(let i in r){let n=r[i],o=this._resources[n.resourceId];o&&o.unsubscribe(n)}delete this._consumers[e],this.prune()}}subscribe({resourceId:e,onChange:r,consumerId:i,requestId:n="default"}){let{_resources:o,protocol:s}=this;e.startsWith(s)&&(e=e.replace(s,""),o[e]||this.add({resourceId:e,data:null,persistent:!1}));let a=o[e];if(this._track(i,n,a,r),a)return a.getData()}prune(){this._pruneRequest||(this._pruneRequest=setTimeout(()=>this._prune(),0))}finalize(){for(let e in this._resources)this._resources[e].delete()}_track(e,r,i,n){let o=this._consumers,s=o[e]=o[e]||{},a=s[r],c=a&&a.resourceId&&this._resources[a.resourceId];c&&(c.unsubscribe(a),this.prune()),i&&(a?(a.onChange=n,a.resourceId=i.id):a={onChange:n,resourceId:i.id},s[r]=a,i.subscribe(a))}_prune(){this._pruneRequest=null;for(let e of Object.keys(this._resources)){let r=this._resources[e];!r.persistent&&!r.inUse()&&(r.delete(),delete this._resources[e])}}};var t4="layerManager.setLayers",r4="layerManager.activateViewport",Ts=class{constructor(e,r){this._lastRenderedLayers=[],this._needsRedraw=!1,this._needsUpdate=!1,this._nextLayers=null,this._debug=!1,this._defaultShaderModulesChanged=!1,this.activateViewport=a=>{ae(r4,this,a),a&&(this.context.viewport=a)};let{deck:i,stats:n,viewport:o,timeline:s}=r||{};this.layers=[],this.resourceManager=new bs({device:e,protocol:"deck://"}),this.context={mousePosition:null,userData:{},layerManager:this,device:e,gl:e?.gl,deck:i,shaderAssembler:hb(e?.info?.shadingLanguage||"glsl"),defaultShaderModules:[Jh],renderPass:void 0,stats:n||new it({id:"deck.gl"}),viewport:o||new Rn({id:"DEFAULT-INITIAL-VIEWPORT"}),timeline:s||new Ai,resourceManager:this.resourceManager,onError:void 0},Object.seal(this)}finalize(){this.resourceManager.finalize();for(let e of this.layers)this._finalizeLayer(e)}needsRedraw(e={clearRedrawFlags:!1}){let r=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);for(let i of this.layers){let n=i.getNeedsRedraw(e);r=r||n}return r}needsUpdate(){return this._nextLayers&&this._nextLayers!==this._lastRenderedLayers?"layers changed":this._defaultShaderModulesChanged?"shader modules changed":this._needsUpdate}setNeedsRedraw(e){this._needsRedraw=this._needsRedraw||e}setNeedsUpdate(e){this._needsUpdate=this._needsUpdate||e}getLayers({layerIds:e}={}){return e?this.layers.filter(r=>e.find(i=>r.id.indexOf(i)===0)):this.layers}setProps(e){"debug"in e&&(this._debug=e.debug),"userData"in e&&(this.context.userData=e.userData),"layers"in e&&(this._nextLayers=e.layers),"onError"in e&&(this.context.onError=e.onError)}setLayers(e,r){ae(t4,this,r,e),this._lastRenderedLayers=e;let i=lt(e,Boolean);for(let n of i)n.context=this.context;this._updateLayers(this.layers,i)}updateLayers(){let e=this.needsUpdate();e&&(this.setNeedsRedraw(`updating layers: ${e}`),this.setLayers(this._nextLayers||this._lastRenderedLayers,e)),this._nextLayers=null}addDefaultShaderModule(e){let{defaultShaderModules:r}=this.context;r.find(i=>i.name===e.name)||(r.push(e),this._defaultShaderModulesChanged=!0)}removeDefaultShaderModule(e){let{defaultShaderModules:r}=this.context,i=r.findIndex(n=>n.name===e.name);i>=0&&(r.splice(i,1),this._defaultShaderModulesChanged=!0)}_handleError(e,r,i){i.raiseError(r,`${e} of ${i}`)}_updateLayers(e,r){let i={};for(let s of e)i[s.id]?F.warn(`Multiple old layers with same id ${s.id}`)():i[s.id]=s;if(this._defaultShaderModulesChanged){for(let s of e)s.setNeedsUpdate(),s.setChangeFlags({extensionsChanged:!0});this._defaultShaderModulesChanged=!1}let n=[];this._updateSublayersRecursively(r,i,n),this._finalizeOldLayers(i);let o=!1;for(let s of n)if(s.hasUniformTransition()){o=`Uniform transition in ${s}`;break}this._needsUpdate=o,this.layers=n}_updateSublayersRecursively(e,r,i){for(let n of e){n.context=this.context;let o=r[n.id];o===null&&F.warn(`Multiple new layers with same id ${n.id}`)(),r[n.id]=null;let s=null;try{this._debug&&o!==n&&n.validateProps(),o?(this._transferLayerState(o,n),this._updateLayer(n)):this._initializeLayer(n),i.push(n),s=n.isComposite?n.getSubLayers():null}catch(a){this._handleError("matching",a,n)}s&&this._updateSublayersRecursively(s,r,i)}}_finalizeOldLayers(e){for(let r in e){let i=e[r];i&&this._finalizeLayer(i)}}_initializeLayer(e){try{e._initialize(),e.lifecycle=Wr.INITIALIZED}catch(r){this._handleError("initialization",r,e)}}_transferLayerState(e,r){r._transferState(e),r.lifecycle=Wr.MATCHED,r!==e&&(e.lifecycle=Wr.AWAITING_GC)}_updateLayer(e){try{e._update()}catch(r){this._handleError("update",r,e)}}_finalizeLayer(e){this._needsRedraw=this._needsRedraw||`finalized ${e}`,e.lifecycle=Wr.AWAITING_FINALIZATION;try{e._finalize(),e.lifecycle=Wr.FINALIZED}catch(r){this._handleError("finalization",r,e)}}};function de(t,e,r){if(t===e)return!0;if(!r||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;ir.containsPixel(e)):this._viewports}getViews(){let e={};return this.views.forEach(r=>{e[r.id]=r}),e}getView(e){return this.views.find(r=>r.id===e)}getViewState(e){let r=typeof e=="string"?this.getView(e):e,i=r&&this.viewState[r.getViewStateId()]||this.viewState;return r?r.filterViewState(i):i}getViewport(e){return this._viewportMap[e]}unproject(e,r){let i=this.getViewports(),n={x:e[0],y:e[1]};for(let o=i.length-1;o>=0;--o){let s=i[o];if(s.containsPixel(n)){let a=e.slice();return a[0]-=s.x,a[1]-=s.y,s.unproject(a,r)}}return null}setProps(e){e.views&&this._setViews(e.views),e.viewState&&this._setViewState(e.viewState),("width"in e||"height"in e)&&this._setSize(e.width,e.height),"pickPosition"in e&&(this._pickPosition=e.pickPosition),this._isUpdating||this._update()}_update(){this._isUpdating=!0,this._needsUpdate&&(this._needsUpdate=!1,this._rebuildViewports()),this._needsUpdate&&(this._needsUpdate=!1,this._rebuildViewports()),this._isUpdating=!1}_setSize(e,r){(e!==this.width||r!==this.height)&&(this.width=e,this.height=r,this.setNeedsUpdate("Size changed"))}_setViews(e){e=lt(e,Boolean),this._diffViews(e,this.views)&&this.setNeedsUpdate("views changed"),this.views=e}_setViewState(e){e?(!de(e,this.viewState,3)&&this.setNeedsUpdate("viewState changed"),this.viewState=e):F.warn("missing `viewState` or `initialViewState`")()}_createController(e,r){let i=r.type;return new i({timeline:this.timeline,eventManager:this._eventManager,onViewStateChange:this._eventCallbacks.onViewStateChange,onStateChange:this._eventCallbacks.onInteractionStateChange,makeViewport:o=>this.getView(e.id)?.makeViewport({viewState:o,width:this.width,height:this.height}),pickPosition:this._pickPosition})}_updateController(e,r,i,n){let o=e.controller;if(o&&i){let s={...r,...o,id:e.id,x:i.x,y:i.y,width:i.width,height:i.height};return(!n||n.constructor!==o.type)&&(n=this._createController(e,s)),n&&n.setProps(s),n}return null}_rebuildViewports(){let{views:e}=this,r=this.controllers;this._viewports=[],this.controllers={};let i=!1;for(let n=e.length;n--;){let o=e[n],s=this.getViewState(o),a=o.makeViewport({viewState:s,width:this.width,height:this.height}),c=r[o.id],l=!!o.controller;l&&!c&&(i=!0),(i||!l)&&c&&(c.finalize(),c=null),this.controllers[o.id]=this._updateController(o,s,a,c),a&&this._viewports.unshift(a)}for(let n in r){let o=r[n];o&&!this.controllers[n]&&o.finalize()}this._buildViewportMap()}_buildViewportMap(){this._viewportMap={},this._viewports.forEach(e=>{e.id&&(this._viewportMap[e.id]=this._viewportMap[e.id]||e)})}_diffViews(e,r){return e.length!==r.length?!0:e.some((i,n)=>!e[n].equals(r[n]))}};var i4=/^(?:\d+\.?\d*|\.\d+)$/;function ur(t){switch(typeof t){case"number":if(!Number.isFinite(t))throw new Error(`Could not parse position string ${t}`);return{type:"literal",value:t};case"string":try{let e=n4(t);return new Np(e).parseExpression()}catch(e){let r=e instanceof Error?e.message:String(e);throw new Error(`Could not parse position string ${t}: ${r}`)}default:throw new Error(`Could not parse position string ${t}`)}}function Op(t,e){switch(t.type){case"literal":return t.value;case"percentage":return Math.round(t.value*e);case"binary":let r=Op(t.left,e),i=Op(t.right,e);return t.operator==="+"?r+i:r-i;default:throw new Error("Unknown layout expression type")}}function dr(t,e){return Op(t,e)}function n4(t){let e=[],r=0;for(;r="0"&&t<="9"}function $b(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}function o4(t){return!!(t&&t.type==="symbol"&&(t.value==="+"||t.value==="-"))}function Hb(t,e){let r={...t};for(let i in e)i!=="id"&&(Array.isArray(r[i])&&Array.isArray(e[i])?r[i]=s4(r[i],e[i]):r[i]=e[i]);return r}function s4(t,e){t=t.slice();for(let r=0;r{},Dp={BREAK:1,SNAP_TO_END:2,IGNORE:3},a4=t=>t,c4=Dp.BREAK,Ss=class{constructor(e){this._onTransitionUpdate=r=>{let{time:i,settings:{interpolator:n,startProps:o,endProps:s,duration:a,easing:c}}=r,l=c(i/a),f=n.interpolateProps(o,s,l);this.propsInTransition=this.getControllerState({...this.props,...f}).getViewportProps(),this.onViewStateChange({viewState:this.propsInTransition,oldViewState:this.props})},this.getControllerState=e.getControllerState,this.propsInTransition=null,this.transition=new xt(e.timeline),this.onViewStateChange=e.onViewStateChange||Yb,this.onStateChange=e.onStateChange||Yb}finalize(){this.transition.cancel()}getViewportInTransition(){return this.propsInTransition}processViewStateChange(e){let r=!1,i=this.props;if(this.props=e,!i||this._shouldIgnoreViewportChange(i,e))return!1;if(this._isTransitionEnabled(e)){let n=i;if(this.transition.inProgress){let{interruption:o,endProps:s}=this.transition.settings;n={...i,...o===Dp.SNAP_TO_END?s:this.propsInTransition||i}}this._triggerTransition(n,e),r=!0}else this.transition.cancel();return r}updateTransition(){this.transition.update()}_isTransitionEnabled(e){let{transitionDuration:r,transitionInterpolator:i}=e;return(r>0||r==="auto")&&!!i}_isUpdateDueToCurrentTransition(e){return this.transition.inProgress&&this.propsInTransition?this.transition.settings.interpolator.arePropsEqual(e,this.propsInTransition):!1}_shouldIgnoreViewportChange(e,r){return this.transition.inProgress?this.transition.settings.interruption===Dp.IGNORE||this._isUpdateDueToCurrentTransition(r):this._isTransitionEnabled(r)?r.transitionInterpolator.arePropsEqual(e,r):!0}_triggerTransition(e,r){let i=this.getControllerState(e),n=this.getControllerState(r).shortestPathFrom(i),o=r.transitionInterpolator,s=o.getDuration?o.getDuration(e,r):r.transitionDuration;if(s===0)return;let a=o.initializeProps(e,n);this.propsInTransition={};let c={duration:s,easing:r.transitionEasing||a4,interpolator:o,interruption:r.transitionInterruption||c4,startProps:a.start,endProps:a.end,onStart:r.onTransitionStart,onUpdate:this._onTransitionUpdate,onInterrupt:this._onTransitionEnd(r.onTransitionInterrupt),onEnd:this._onTransitionEnd(r.onTransitionEnd)};this.transition.start(c),this.onStateChange({inTransition:!0}),this.updateTransition()}_onTransitionEnd(e){return r=>{this.propsInTransition=null,this.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1}),e?.(r)}}};function J(t,e){if(!t)throw new Error(e||"deck.gl: assertion failed.")}var As=class{constructor(e){let{compare:r,extract:i,required:n}=e;this._propsToCompare=r,this._propsToExtract=i||r,this._requiredProps=n}arePropsEqual(e,r){for(let i of this._propsToCompare)if(!(i in e)||!(i in r)||!nr(e[i],r[i]))return!1;return!0}initializeProps(e,r){let i={},n={};for(let o of this._propsToExtract)(o in e||o in r)&&(i[o]=e[o],n[o]=r[o]);return this._checkRequiredProps(i),this._checkRequiredProps(n),{start:i,end:n}}getDuration(e,r){return r.transitionDuration}_checkRequiredProps(e){this._requiredProps&&this._requiredProps.forEach(r=>{let i=e[r];J(Number.isFinite(i)||Array.isArray(i),`${r} is required for transition`)})}};var _l=Math.PI/180,Xb=180/Math.PI,yl=6370972,hr=256;function l4(){let t=hr/yl,e=Math.PI/180*hr;return{unitsPerMeter:[t,t,t],unitsPerMeter2:[0,0,0],metersPerUnit:[1/t,1/t,1/t],unitsPerDegree:[e,e,t],unitsPerDegree2:[0,0,0],degreesPerUnit:[1/e,1/e,1/t]}}var xl=class extends Rn{constructor(e={}){let{longitude:r=0,zoom:i=0,nearZMultiplier:n=.5,farZMultiplier:o=1,resolution:s=10}=e,{latitude:a=0,height:c,altitude:l=1.5,fovy:f}=e;a=Math.max(Math.min(a,ze),-ze),c=c||1,f?l=Br(f):f=_t(l);let u=Math.pow(2,i-Wt(a)),d=e.nearZ??n,h=e.farZ??(l+hr*2*u/c)*o,p=new me().lookAt({eye:[0,-l,0],up:[0,0,1]});p.rotateX(a*_l),p.rotateZ(-r*_l),p.scale(u/c),super({...e,height:c,viewMatrix:p,longitude:r,latitude:a,zoom:i,distanceScales:l4(),fovy:f,focalDistance:l,near:d,far:h}),this.scale=u,this.latitude=a,this.longitude=r,this.fovy=f,this.resolution=s}get projectionMode(){return _e.GLOBE}getDistanceScales(){return this.distanceScales}getBounds(e={}){let r={targetZ:e.z||0},i=this.unproject([0,this.height/2],r),n=this.unproject([this.width/2,0],r),o=this.unproject([this.width,this.height/2],r),s=this.unproject([this.width/2,this.height],r);return o[0]this.longitude&&(i[0]-=360),[Math.min(i[0],o[0],n[0],s[0]),Math.min(i[1],o[1],n[1],s[1]),Math.max(i[0],o[0],n[0],s[0]),Math.max(i[1],o[1],n[1],s[1])]}unproject(e,{topLeft:r=!0,targetZ:i}={}){let[n,o,s]=e,a=r?o:this.height-o,{pixelUnprojectionMatrix:c}=this,l;if(Number.isFinite(s))l=Lp(c,[n,a,s,1]);else{let h=Lp(c,[n,a,-1,1]),p=Lp(c,[n,a,1,1]),g=((i||0)/yl+1)*hr,m=Pe.sqrLen(Pe.sub([],h,p)),_=Pe.sqrLen(h),T=Pe.sqrLen(p),x=4*((4*_*T-(m-_-T)**2)/16)/m,w=Math.sqrt(_-x),b=Math.sqrt(Math.max(0,g*g-x)),E=(w-b)/Math.sqrt(m);l=Pe.lerp([],h,p,E)}let[f,u,d]=this.unprojectPosition(l);return Number.isFinite(s)?[f,u,d]:Number.isFinite(i)?[f,u,i]:[f,u]}projectPosition(e){let[r,i,n=0]=e,o=r*_l,s=i*_l,a=Math.cos(s),c=(n/yl+1)*hr;return[Math.sin(o)*a*c,-Math.cos(o)*a*c,Math.sin(s)*c]}unprojectPosition(e){let[r,i,n]=e,o=Pe.len(e),s=Math.asin(n/o),c=Math.atan2(r,-i)*Xb,l=s*Xb,f=(o/hr-1)*yl;return[c,l,f]}projectFlat(e){return e}unprojectFlat(e){return e}panByPosition([e,r,i],n,o){let a=.25/Math.pow(2,this.zoom-Wt(this.latitude)),c=e+a*(o[0]-n[0]),l=r-a*(o[1]-n[1]);l=Math.max(Math.min(l,ze),-ze);let f={longitude:c,latitude:l,zoom:i-Wt(r)};return f.zoom+=Wt(f.latitude),f}};xl.displayName="GlobeViewport";var bl=xl;function Wt(t){let e=Math.PI*Math.cos(t*Math.PI/180);return Math.log2(e)}function Lp(t,e){let r=Ze.transformMat4([],e,t);return Ze.scale(r,r,1/r[3]),r}var f4=["longitude","latitude","zoom","bearing","pitch"],u4=["longitude","latitude","zoom"],pr=class extends As{constructor(e={}){let r=Array.isArray(e)?e:e.transitionProps,i=Array.isArray(e)?{}:e;i.transitionProps=Array.isArray(r)?{compare:r,required:r}:r||{compare:f4,required:u4},super(i.transitionProps),this.opts=i}initializeProps(e,r){let i=super.initializeProps(e,r),{makeViewport:n,around:o}=this.opts;if(n&&o)if(n(e)instanceof bl)F.warn("around not supported in GlobeView")();else{let a=n(e),c=n(r),l=a.unproject(o);i.start.around=o,Object.assign(i.end,{around:c.project(l),aroundPosition:l,width:r.width,height:r.height})}return i}interpolateProps(e,r,i){let n={};for(let o of this._propsToExtract)n[o]=di(e[o]||0,r[o]||0,i);if(r.aroundPosition&&this.opts.makeViewport){let o=this.opts.makeViewport({...r,...n});Object.assign(n,o.panByPosition(r.aroundPosition,di(e.around,r.around,i)))}return n}};var gr={transitionDuration:0},d4=300,Tl=t=>1-(1-t)*(1-t),In={WHEEL:["wheel"],PAN:["panstart","panmove","panend"],PINCH:["pinchstart","pinchmove","pinchend"],MULTI_PAN:["multipanstart","multipanmove","multipanend"],DOUBLE_CLICK:["dblclick"],KEYBOARD:["keydown"]},Pi={},Mi=class{constructor(e){this.state={},this._events={},this._interactionState={isDragging:!1},this._customEvents=[],this._eventStartBlocked=null,this._panMove=!1,this.invertPan=!1,this.dragMode="rotate",this.inertia=0,this.scrollZoom=!0,this.dragPan=!0,this.dragRotate=!0,this.doubleClickZoom=!0,this.touchZoom=!0,this.touchRotate=!1,this.keyboard=!0,this.transitionManager=new Ss({...e,getControllerState:r=>new this.ControllerState(r),onViewStateChange:this._onTransition.bind(this),onStateChange:this._setInteractionState.bind(this)}),this.handleEvent=this.handleEvent.bind(this),this.eventManager=e.eventManager,this.onViewStateChange=e.onViewStateChange||(()=>{}),this.onStateChange=e.onStateChange||(()=>{}),this.makeViewport=e.makeViewport,this.pickPosition=e.pickPosition}set events(e){this.toggleEvents(this._customEvents,!1),this.toggleEvents(e,!0),this._customEvents=e,this.props&&this.setProps(this.props)}finalize(){for(let e in this._events)this._events[e]&&this.eventManager?.off(e,this.handleEvent);this.transitionManager.finalize()}handleEvent(e){this._controllerState=void 0;let r=this._eventStartBlocked;switch(e.type){case"panstart":return r?!1:this._onPanStart(e);case"panmove":return this._onPan(e);case"panend":return this._onPanEnd(e);case"pinchstart":return r?!1:this._onPinchStart(e);case"pinchmove":return this._onPinch(e);case"pinchend":return this._onPinchEnd(e);case"multipanstart":return r?!1:this._onMultiPanStart(e);case"multipanmove":return this._onMultiPan(e);case"multipanend":return this._onMultiPanEnd(e);case"dblclick":return this._onDoubleClick(e);case"wheel":return this._onWheel(e);case"keydown":return this._onKeyDown(e);default:return!1}}get controllerState(){return this._controllerState=this._controllerState||new this.ControllerState({makeViewport:this.makeViewport,...this.props,...this.state}),this._controllerState}getCenter(e){let{x:r,y:i}=this.props,{offsetCenter:n}=e;return[n.x-r,n.y-i]}isPointInBounds(e,r){let{width:i,height:n}=this.props;if(r&&r.handled)return!1;let o=e[0]>=0&&e[0]<=i&&e[1]>=0&&e[1]<=n;return o&&r&&r.stopPropagation(),o}isFunctionKeyPressed(e){let{srcEvent:r}=e;return!!(r.metaKey||r.altKey||r.ctrlKey||r.shiftKey)}isDragging(){return this._interactionState.isDragging||!1}blockEvents(e){let r=setTimeout(()=>{this._eventStartBlocked===r&&(this._eventStartBlocked=null)},e);this._eventStartBlocked=r}setProps(e){e.dragMode&&(this.dragMode=e.dragMode);let r=this.props;this.props=e,"transitionInterpolator"in e||(e.transitionInterpolator=this._getTransitionProps().transitionInterpolator),this.transitionManager.processViewStateChange(e);let{inertia:i}=e;this.inertia=Number.isFinite(i)?i:i===!0?d4:0;let{scrollZoom:n=!0,dragPan:o=!0,dragRotate:s=!0,doubleClickZoom:a=!0,touchZoom:c=!0,touchRotate:l=!1,keyboard:f=!0}=e,u=!!this.onViewStateChange;if(this.toggleEvents(In.WHEEL,u&&n),this.toggleEvents(In.PAN,u),this.toggleEvents(In.PINCH,u&&(c||l)),this.toggleEvents(In.MULTI_PAN,u&&l),this.toggleEvents(In.DOUBLE_CLICK,u&&a),this.toggleEvents(In.KEYBOARD,u&&f),this.scrollZoom=n,this.dragPan=o,this.dragRotate=s,this.doubleClickZoom=a,this.touchZoom=c,this.touchRotate=l,this.keyboard=f,(!r||r.height!==e.height||r.width!==e.width||r.maxBounds!==e.maxBounds)&&e.maxBounds){let h=new this.ControllerState({...e,makeViewport:this.makeViewport}),p=h.getViewportProps();Object.keys(p).some(m=>!de(p[m],e[m],1))&&this.updateViewport(h)}}updateTransition(){this.transitionManager.updateTransition()}toggleEvents(e,r){this.eventManager&&e.forEach(i=>{this._events[i]!==r&&(this._events[i]=r,r?this.eventManager.on(i,this.handleEvent):this.eventManager.off(i,this.handleEvent))})}updateViewport(e,r=null,i={}){let n={...e.getViewportProps(),...r},o=this.controllerState!==e;if(this.state=e.getState(),this._setInteractionState(i),o){let s=this.controllerState&&this.controllerState.getViewportProps();this.onViewStateChange&&this.onViewStateChange({viewState:n,interactionState:this._interactionState,oldViewState:s,viewId:this.props.id})}}_onTransition(e){this.onViewStateChange({...e,interactionState:this._interactionState,viewId:this.props.id})}_setInteractionState(e){Object.assign(this._interactionState,e),this.onStateChange(this._interactionState)}_onPanStart(e){let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.isFunctionKeyPressed(e)||e.rightButton||!1;(this.invertPan||this.dragMode==="pan")&&(i=!i);let n=this.controllerState[i?"panStart":"rotateStart"]({pos:r});return this._panMove=i,this.updateViewport(n,gr,{isDragging:!0}),!0}_onPan(e){return this.isDragging()?this._panMove?this._onPanMove(e):this._onPanRotate(e):!1}_onPanEnd(e){return this.isDragging()?this._panMove?this._onPanMoveEnd(e):this._onPanRotateEnd(e):!1}_onPanMove(e){if(!this.dragPan)return!1;let r=this.getCenter(e),i=this.controllerState.pan({pos:r});return this.updateViewport(i,gr,{isDragging:!0,isPanning:!0}),!0}_onPanMoveEnd(e){let{inertia:r}=this;if(this.dragPan&&r&&e.velocity){let i=this.getCenter(e),n=[i[0]+e.velocityX*r/2,i[1]+e.velocityY*r/2],o=this.controllerState.pan({pos:n}).panEnd();this.updateViewport(o,{...this._getTransitionProps(),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isPanning:!0})}else{let i=this.controllerState.panEnd();this.updateViewport(i,null,{isDragging:!1,isPanning:!1})}return!0}_onPanRotate(e){if(!this.dragRotate)return!1;let r=this.getCenter(e),i=this.controllerState.rotate({pos:r});return this.updateViewport(i,gr,{isDragging:!0,isRotating:!0}),!0}_onPanRotateEnd(e){let{inertia:r}=this;if(this.dragRotate&&r&&e.velocity){let i=this.getCenter(e),n=[i[0]+e.velocityX*r/2,i[1]+e.velocityY*r/2],o=this.controllerState.rotate({pos:n}).rotateEnd();this.updateViewport(o,{...this._getTransitionProps(),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isRotating:!0})}else{let i=this.controllerState.rotateEnd();this.updateViewport(i,null,{isDragging:!1,isRotating:!1})}return!0}_onWheel(e){if(!this.scrollZoom)return!1;let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;e.srcEvent.preventDefault();let{speed:i=.01,smooth:n=!1}=this.scrollZoom===!0?{}:this.scrollZoom,{delta:o}=e,s=2/(1+Math.exp(-Math.abs(o*i)));o<0&&s!==0&&(s=1/s);let a=n?{...this._getTransitionProps({around:r}),transitionDuration:250}:gr,c=this.controllerState.zoom({pos:r,scale:s});return this.updateViewport(c,a,{isZooming:!0,isPanning:!0}),n||this._setInteractionState({isZooming:!1,isPanning:!1}),!0}_onMultiPanStart(e){let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.controllerState.rotateStart({pos:r});return this.updateViewport(i,gr,{isDragging:!0}),!0}_onMultiPan(e){if(!this.touchRotate||!this.isDragging())return!1;let r=this.getCenter(e);r[0]-=e.deltaX;let i=this.controllerState.rotate({pos:r});return this.updateViewport(i,gr,{isDragging:!0,isRotating:!0}),!0}_onMultiPanEnd(e){if(!this.isDragging())return!1;let{inertia:r}=this;if(this.touchRotate&&r&&e.velocityY){let i=this.getCenter(e),n=[i[0],i[1]+=e.velocityY*r/2],o=this.controllerState.rotate({pos:n});this.updateViewport(o,{...this._getTransitionProps(),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isRotating:!0}),this.blockEvents(r)}else{let i=this.controllerState.rotateEnd();this.updateViewport(i,null,{isDragging:!1,isRotating:!1})}return!0}_onPinchStart(e){let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.controllerState.zoomStart({pos:r}).rotateStart({pos:r});return Pi._startPinchRotation=e.rotation,Pi._lastPinchEvent=e,this.updateViewport(i,gr,{isDragging:!0}),!0}_onPinch(e){if(!this.touchZoom&&!this.touchRotate||!this.isDragging())return!1;let r=this.controllerState;if(this.touchZoom){let{scale:i}=e,n=this.getCenter(e);r=r.zoom({pos:n,scale:i})}if(this.touchRotate){let{rotation:i}=e;r=r.rotate({deltaAngleX:Pi._startPinchRotation-i})}return this.updateViewport(r,gr,{isDragging:!0,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:this.touchRotate}),Pi._lastPinchEvent=e,!0}_onPinchEnd(e){if(!this.isDragging())return!1;let{inertia:r}=this,{_lastPinchEvent:i}=Pi;if(this.touchZoom&&r&&i&&e.scale!==i.scale){let n=this.getCenter(e),o=this.controllerState.rotateEnd(),s=Math.log2(e.scale),a=(s-Math.log2(i.scale))/(e.deltaTime-i.deltaTime),c=Math.pow(2,s+a*r/2);o=o.zoom({pos:n,scale:c}).zoomEnd(),this.updateViewport(o,{...this._getTransitionProps({around:n}),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:!1}),this.blockEvents(r)}else{let n=this.controllerState.zoomEnd().rotateEnd();this.updateViewport(n,null,{isDragging:!1,isPanning:!1,isZooming:!1,isRotating:!1})}return Pi._startPinchRotation=null,Pi._lastPinchEvent=null,!0}_onDoubleClick(e){if(!this.doubleClickZoom)return!1;let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.isFunctionKeyPressed(e),n=this.controllerState.zoom({pos:r,scale:i?.5:2});return this.updateViewport(n,this._getTransitionProps({around:r}),{isZooming:!0,isPanning:!0}),this.blockEvents(100),!0}_onKeyDown(e){if(!this.keyboard)return!1;let r=this.isFunctionKeyPressed(e),{zoomSpeed:i,moveSpeed:n,rotateSpeedX:o,rotateSpeedY:s}=this.keyboard===!0?{}:this.keyboard,{controllerState:a}=this,c,l={};switch(e.srcEvent.code){case"Minus":c=r?a.zoomOut(i).zoomOut(i):a.zoomOut(i),l.isZooming=!0;break;case"Equal":c=r?a.zoomIn(i).zoomIn(i):a.zoomIn(i),l.isZooming=!0;break;case"ArrowLeft":r?(c=a.rotateLeft(o),l.isRotating=!0):(c=a.moveLeft(n),l.isPanning=!0);break;case"ArrowRight":r?(c=a.rotateRight(o),l.isRotating=!0):(c=a.moveRight(n),l.isPanning=!0);break;case"ArrowUp":r?(c=a.rotateUp(s),l.isRotating=!0):(c=a.moveUp(n),l.isPanning=!0);break;case"ArrowDown":r?(c=a.rotateDown(s),l.isRotating=!0):(c=a.moveDown(n),l.isPanning=!0);break;default:return!1}return this.updateViewport(c,this._getTransitionProps(),l),!0}_getTransitionProps(e){let{transition:r}=this;return!r||!r.transitionInterpolator?gr:e?{...r,transitionInterpolator:new pr({...e,...r.transitionInterpolator.opts,makeViewport:this.controllerState.makeViewport})}:r}};var vs=class{constructor(e,r,i){this.makeViewport=i,this._viewportProps=this.applyConstraints(e),this._state=r}getViewportProps(){return this._viewportProps}getState(){return this._state}};var Gb=5,h4=1.2,qb=512,Kb=[[-1/0,-90],[1/0,90]];function wl([t,e]){if(Math.abs(e)>90&&(e=Math.sign(e)*90),Number.isFinite(t)){let[i,n]=xe([t,e]);return[i,ce(n,0,qb)]}let[,r]=xe([0,e]);return[t,ce(r,0,qb)]}var Es=class extends vs{constructor(e){let{width:r,height:i,latitude:n,longitude:o,zoom:s,bearing:a=0,pitch:c=0,altitude:l=1.5,position:f=[0,0,0],maxZoom:u=20,minZoom:d=0,maxPitch:h=60,minPitch:p=0,startPanLngLat:g,startZoomLngLat:m,startRotatePos:_,startRotateLngLat:T,startBearing:y,startPitch:x,startZoom:w,normalize:b=!0}=e;J(Number.isFinite(o)),J(Number.isFinite(n)),J(Number.isFinite(s));let E=e.maxBounds||(b?Kb:null);super({width:r,height:i,latitude:n,longitude:o,zoom:s,bearing:a,pitch:c,altitude:l,maxZoom:u,minZoom:d,maxPitch:h,minPitch:p,normalize:b,position:f,maxBounds:E},{startPanLngLat:g,startZoomLngLat:m,startRotatePos:_,startRotateLngLat:T,startBearing:y,startPitch:x,startZoom:w},e.makeViewport),this.getAltitude=e.getAltitude}panStart({pos:e}){return this._getUpdatedState({startPanLngLat:this._unproject(e)})}pan({pos:e,startPos:r}){let i=this.getState().startPanLngLat||this._unproject(r);if(!i)return this;let o=this.makeViewport(this.getViewportProps()).panByPosition(i,e);return this._getUpdatedState(o)}panEnd(){return this._getUpdatedState({startPanLngLat:null})}rotateStart({pos:e}){let r=this.getAltitude?.(e);return this._getUpdatedState({startRotatePos:e,startRotateLngLat:r!==void 0?this._unproject3D(e,r):void 0,startBearing:this.getViewportProps().bearing,startPitch:this.getViewportProps().pitch})}rotate({pos:e,deltaAngleX:r=0,deltaAngleY:i=0}){let{startRotatePos:n,startRotateLngLat:o,startBearing:s,startPitch:a}=this.getState();if(!n||s===void 0||a===void 0)return this;let c;if(e?c=this._getNewRotation(e,n,a,s):c={bearing:s+r,pitch:a+i},o){let l=this.makeViewport({...this.getViewportProps(),...c}),f="panByPosition3D"in l?"panByPosition3D":"panByPosition";return this._getUpdatedState({...c,...l[f](o,n)})}return this._getUpdatedState(c)}rotateEnd(){return this._getUpdatedState({startRotatePos:null,startRotateLngLat:null,startBearing:null,startPitch:null})}zoomStart({pos:e}){return this._getUpdatedState({startZoomLngLat:this._unproject(e),startZoom:this.getViewportProps().zoom})}zoom({pos:e,startPos:r,scale:i}){let{startZoom:n,startZoomLngLat:o}=this.getState();if(o||(n=this.getViewportProps().zoom,o=this._unproject(r)||this._unproject(e)),!o)return this;let s=this._constrainZoom(n+Math.log2(i)),a=this.makeViewport({...this.getViewportProps(),zoom:s});return this._getUpdatedState({zoom:s,...a.panByPosition(o,e)})}zoomEnd(){return this._getUpdatedState({startZoomLngLat:null,startZoom:null})}zoomIn(e=2){return this._zoomFromCenter(e)}zoomOut(e=2){return this._zoomFromCenter(1/e)}moveLeft(e=100){return this._panFromCenter([e,0])}moveRight(e=100){return this._panFromCenter([-e,0])}moveUp(e=100){return this._panFromCenter([0,e])}moveDown(e=100){return this._panFromCenter([0,-e])}rotateLeft(e=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing-e})}rotateRight(e=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing+e})}rotateUp(e=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch+e})}rotateDown(e=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch-e})}shortestPathFrom(e){let r=e.getViewportProps(),i={...this.getViewportProps()},{bearing:n,longitude:o}=i;return Math.abs(n-r.bearing)>180&&(i.bearing=n<0?n+360:n-360),Math.abs(o-r.longitude)>180&&(i.longitude=o<0?o+360:o-360),i}applyConstraints(e){let{maxPitch:r,minPitch:i,pitch:n,longitude:o,bearing:s,normalize:a,maxBounds:c}=e;if(a&&((o<-180||o>180)&&(e.longitude=ps(o+180,360)-180),(s<-180||s>180)&&(e.bearing=ps(s+180,360)-180)),e.pitch=ce(n,i,r),e.zoom=this._constrainZoom(e.zoom,e),c){let l=wl(c[0]),f=wl(c[1]),u=2**e.zoom,d=e.width/2/u,h=e.height/2/u,[p,g]=Se([l[0]+d,l[1]+h]),[m,_]=Se([f[0]-d,f[1]-h]);e.longitude=ce(e.longitude,p,m),e.latitude=ce(e.latitude,g,_)}return e}_constrainZoom(e,r){r||(r=this.getViewportProps());let{maxZoom:i,maxBounds:n}=r,o=n!==null&&r.width>0&&r.height>0,{minZoom:s}=r;if(o){let a=wl(n[0]),c=wl(n[1]),l=c[0]-a[0],f=c[1]-a[1];Number.isFinite(l)&&l>0&&(s=Math.max(s,Math.log2(r.width/l))),Number.isFinite(f)&&f>0&&(s=Math.max(s,Math.log2(r.height/f))),s>i&&(s=i)}return ce(e,s,i)}_zoomFromCenter(e){let{width:r,height:i}=this.getViewportProps();return this.zoom({pos:[r/2,i/2],scale:e})}_panFromCenter(e){let{width:r,height:i}=this.getViewportProps();return this.pan({startPos:[r/2,i/2],pos:[r/2+e[0],i/2+e[1]]})}_getUpdatedState(e){return new this.constructor({makeViewport:this.makeViewport,...this.getViewportProps(),...this.getState(),...e})}_unproject(e){let r=this.makeViewport(this.getViewportProps());return e&&r.unproject(e)}_unproject3D(e,r){return this.makeViewport(this.getViewportProps()).unproject(e,{targetZ:r})}_getNewRotation(e,r,i,n){let o=e[0]-r[0],s=e[1]-r[1],a=e[1],c=r[1],{width:l,height:f}=this.getViewportProps(),u=o/l,d=0;s>0?Math.abs(f-c)>Gb&&(d=s/(c-f)*h4):s<0&&c>Gb&&(d=1-a/c),d=ce(d,-1,1);let{minPitch:h,maxPitch:p}=this.getViewportProps(),g=n+180*u,m=i;return d>0?m=i+d*(p-i):d<0&&(m=i-d*(h-i)),{pitch:m,bearing:g}}},Rs=class extends Mi{constructor(){super(...arguments),this.ControllerState=Es,this.transition={transitionDuration:300,transitionInterpolator:new pr({transitionProps:{compare:["longitude","latitude","zoom","bearing","pitch","position"],required:["longitude","latitude","zoom"]}})},this.dragMode="pan",this.rotationPivot="center",this._getAltitude=e=>{if(this.rotationPivot==="2d")return 0;if(this.rotationPivot==="3d"&&this.pickPosition){let{x:r,y:i}=this.props,n=this.pickPosition(r+e[0],i+e[1]);if(n&&n.coordinate&&n.coordinate.length>=3)return n.coordinate[2]}}}setProps(e){"rotationPivot"in e&&(this.rotationPivot=e.rotationPivot||"center"),e.getAltitude=this._getAltitude,e.position=e.position||[0,0,0],e.maxBounds=e.maxBounds||(e.normalize===!1?null:Kb),super.setProps(e)}updateViewport(e,r=null,i={}){let n=e.getState();i.isDragging&&n.startRotateLngLat?i={...i,rotationPivotPosition:n.startRotateLngLat}:i.isDragging===!1&&(i={...i,rotationPivotPosition:void 0}),super.updateViewport(e,r,i)}};var Sl=class extends Ci{constructor(e={}){super(e)}getViewportType(){return Cn}get ControllerType(){return Rs}};Sl.displayName="MapView";var Cs=Sl;var p4=new An;function g4(t,e){let r=t.order??1/0,i=e.order??1/0;return r-i}var Ps=class{constructor(e){this._resolvedEffects=[],this._defaultEffects=[],this.effects=[],this._context=e,this._needsRedraw="Initial render",this._setEffects([])}addDefaultEffect(e){let r=this._defaultEffects;if(!r.find(i=>i.id===e.id)){let i=r.findIndex(n=>g4(n,e)>0);i<0?r.push(e):r.splice(i,0,e),e.setup(this._context),this._setEffects(this.effects)}}setProps(e){"effects"in e&&(de(e.effects,this.effects,1)||this._setEffects(e.effects))}needsRedraw(e={clearRedrawFlags:!1}){let r=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),r}getEffects(){return this._resolvedEffects}_setEffects(e){let r={};for(let n of this.effects)r[n.id]=n;let i=[];for(let n of e){let o=r[n.id],s=n;o&&o!==n?o.setProps?(o.setProps(n.props),s=o):o.cleanup(this._context):o||n.setup(this._context),i.push(s),delete r[n.id]}for(let n in r)r[n].cleanup(this._context);this.effects=i,this._resolvedEffects=i.concat(this._defaultEffects),e.some(n=>n instanceof An)||this._resolvedEffects.push(p4),this._needsRedraw="effects changed"}finalize(){for(let e of this._resolvedEffects)e.cleanup(this._context);this.effects.length=0,this._resolvedEffects.length=0,this._defaultEffects.length=0}};var Ms=class extends cr{shouldDrawLayer(e){let{operation:r}=e.props;return r.includes("draw")||r.includes("terrain")}render(e){return this._render(e)}};var m4="deckRenderer.renderLayers",Is=class{constructor(e,r={}){this.device=e,this.stats=r.stats,this.layerFilter=null,this.drawPickingColors=!1,this.drawLayersPass=new Ms(e),this.pickLayersPass=new Ri(e),this.renderCount=0,this._needsRedraw="Initial render",this.renderBuffers=[],this.lastPostProcessEffect=null}setProps(e){this.layerFilter!==e.layerFilter&&(this.layerFilter=e.layerFilter,this._needsRedraw="layerFilter changed"),this.drawPickingColors!==e.drawPickingColors&&(this.drawPickingColors=e.drawPickingColors,this._needsRedraw="drawPickingColors changed")}renderLayers(e){if(!e.viewports.length)return;let r=this.drawPickingColors?this.pickLayersPass:this.drawLayersPass,i={layerFilter:this.layerFilter,isPicking:this.drawPickingColors,...e};i.effects&&this._preRender(i.effects,i);let n=this.lastPostProcessEffect?this.renderBuffers[0]:i.target;this.lastPostProcessEffect&&(i.clearColor=[0,0,0,0],i.clearCanvas=!0);let o=r.render({...i,target:n}),s="stats"in o?o.stats:o;i.effects&&(this.lastPostProcessEffect&&(i.clearCanvas=e.clearCanvas===void 0?!0:e.clearCanvas),this._postRender(i.effects,i)),this.renderCount++,ae(m4,this,s,e),this._updateStats(s)}needsRedraw(e={clearRedrawFlags:!1}){let r=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),r}finalize(){let{renderBuffers:e}=this;for(let r of e)r.delete();e.length=0}_updateStats(e){if(!this.stats)return;let r=0;for(let{visibleCount:i}of e)r+=i;this.stats.get("Layers rendered").addCount(r)}_preRender(e,r){this.lastPostProcessEffect=null,r.preRenderStats=r.preRenderStats||{};for(let i of e)r.preRenderStats[i.id]=i.preRender(r),i.postRender&&(this.lastPostProcessEffect=i.id);this.lastPostProcessEffect&&this._resizeRenderBuffers()}_resizeRenderBuffers(){let{renderBuffers:e}=this,r=this.device.canvasContext.getDrawingBufferSize(),[i,n]=r;e.length===0&&[0,1].map(o=>{let s=this.device.createTexture({sampler:{minFilter:"linear",magFilter:"linear"},width:i,height:n});e.push(this.device.createFramebuffer({id:`deck-renderbuffer-${o}`,colorAttachments:[s]}))});for(let o of e)o.resize(r)}_postRender(e,r){let{renderBuffers:i}=this,n={...r,inputBuffer:i[0],swapBuffer:i[1]};for(let o of e)if(o.postRender){n.target=o.id===this.lastPostProcessEffect?r.target:void 0;let s=o.postRender(n);n.inputBuffer=s,n.swapBuffer=s===i[0]?i[1]:i[0]}}};z();var _4={pickedColor:null,pickedObjectIndex:-1};function Fp({pickedColors:t,decodePickingColor:e,deviceX:r,deviceY:i,deviceRadius:n,deviceRect:o}){let{x:s,y:a,width:c,height:l}=o,f=n*n,u=-1,d=0;for(let h=0;hf)d+=4*c;else for(let m=0;m=0){let T=m+s-r,y=T*T+g;y<=f&&(f=y,u=d)}d+=4}}if(u>=0){let h=t.slice(u,u+4),p=e(h);if(p){let g=Math.floor(u/4/c),m=u/4-g*c;return{...p,pickedColor:h,pickedX:s+m,pickedY:a+g}}F.error("Picked non-existent layer. Is picking buffer corrupt?")()}return _4}function Bp({pickedColors:t,decodePickingColor:e}){let r=new Map;if(t){for(let i=0;i=0){let o=t.slice(i,i+4),s=o.join(",");if(!r.has(s)){let a=e(o);a?r.set(s,{...a,color:o}):F.error("Picked non-existent layer. Is picking buffer corrupt?")()}}}return Array.from(r.values())}function Al({pickInfo:t,viewports:e,pixelRatio:r,x:i,y:n,z:o}){let s=e[0];e.length>1&&(s=y4(t?.pickedViewports||e,{x:i,y:n}));let a;if(s){let c=[i-s.x,n-s.y];o!==void 0&&(c[2]=o),a=s.unproject(c)}return{color:null,layer:null,viewport:s,index:-1,picked:!1,x:i,y:n,pixel:[i,n],coordinate:a,devicePixel:t&&"pickedX"in t?[t.pickedX,t.pickedY]:void 0,pixelRatio:r}}function kp(t){let{pickInfo:e,lastPickedInfo:r,mode:i,layers:n}=t,{pickedColor:o,pickedLayer:s,pickedObjectIndex:a}=e,c=s?[s]:[];if(i==="hover"){let u=r.index,d=r.layerId,h=s?s.props.id:null;if(h!==d||a!==u){if(h!==d){let p=n.find(g=>g.props.id===d);p&&c.unshift(p)}r.layerId=h,r.index=a,r.info=null}}let l=Al(t),f=new Map;return f.set(null,l),c.forEach(u=>{let d={...l};u===s&&(d.color=o,d.index=a,d.picked=!0),d=vl({layer:u,info:d,mode:i});let h=d.layer;u===s&&i==="hover"&&(r.info=d),f.set(h.id,d),i==="hover"&&h.updateAutoHighlight(d)}),f}function vl({layer:t,info:e,mode:r}){for(;t&&e;){let i=e.layer||null;e.sourceLayer=i,e.layer=t,e=t.getPickingInfo({info:e,mode:r,sourceLayer:i}),t=t.parent}return e}function y4(t,e){for(let r=t.length-1;r>=0;r--){let i=t[r];if(i.containsPixel(e))return i}return t[0]}var Os=class{constructor(e,r={}){this._pickable=!0,this.device=e,this.stats=r.stats,this.pickLayersPass=new Ri(e),this.lastPickedInfo={index:-1,layerId:null,info:null}}setProps(e){"layerFilter"in e&&(this.layerFilter=e.layerFilter),"_pickable"in e&&(this._pickable=e._pickable)}finalize(){this.pickingFBO&&this.pickingFBO.destroy(),this.depthFBO&&this.depthFBO.destroy()}pickObjectAsync(e){return this._pickClosestObjectAsync(e)}pickObjectsAsync(e){return this._pickVisibleObjectsAsync(e)}pickObject(e){return this._pickClosestObject(e)}pickObjects(e){return this._pickVisibleObjects(e)}getLastPickedObject({x:e,y:r,layers:i,viewports:n},o=this.lastPickedInfo.info){let s=o&&o.layer&&o.layer.id,a=o&&o.viewport&&o.viewport.id,c=s?i.find(d=>d.id===s):null,l=a&&n.find(d=>d.id===a)||n[0],f=l&&l.unproject([e-l.x,r-l.y]);return{...o,...{x:e,y:r,viewport:l,coordinate:f,layer:c}}}_resizeBuffer(){if(!this.pickingFBO){let r=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:$.RENDER_ATTACHMENT|$.COPY_SRC});if(this.pickingFBO=this.device.createFramebuffer({colorAttachments:[r],depthStencilAttachment:"depth16unorm"}),this.device.isTextureFormatRenderable("rgba32float")){let i=this.device.createTexture({format:"rgba32float",width:1,height:1,usage:$.RENDER_ATTACHMENT|$.COPY_SRC}),n=this.device.createFramebuffer({colorAttachments:[i],depthStencilAttachment:"depth16unorm"});this.depthFBO=n}}let{canvas:e}=this.device.getDefaultCanvasContext();this.pickingFBO?.resize({width:e.width,height:e.height}),this.depthFBO?.resize({width:e.width,height:e.height})}_getPickable(e){if(this._pickable===!1)return null;let r=e.filter(i=>this.pickLayersPass.shouldDrawLayer(i)&&!i.isComposite);return r.length?r:null}async _pickClosestObjectAsync({layers:e,views:r,viewports:i,x:n,y:o,radius:s=0,depth:a=1,mode:c="query",unproject3D:l,onViewportActive:f,effects:u}){let d=this.device.canvasContext.cssToDeviceRatio(),h=this._getPickable(e);if(!h||i.length===0)return{result:[],emptyInfo:Al({viewports:i,x:n,y:o,pixelRatio:d})};this._resizeBuffer();let p=this.device.canvasContext.cssToDevicePixels([n,o],!0),g=[p.x+Math.floor(p.width/2),p.y+Math.floor(p.height/2)],m=Math.round(s*d),{width:_,height:T}=this.pickingFBO,y=this._getPickingRect({deviceX:g[0],deviceY:g[1],deviceRadius:m,deviceWidth:_,deviceHeight:T}),x={x:n-s,y:o-s,width:s*2+1,height:s*2+1},w,b=[],E=new Set;for(let S=0;S0){let{pickedColors:R}=await this._drawAndSampleAsync({layers:I,views:r,viewports:i,onViewportActive:f,deviceRect:{x:A.pickedX??g[0],y:A.pickedY??g[1],width:1,height:1},cullRect:x,effects:u,pass:`picking:${c}:z`},!0);R[3]&&(C=R[0])}A.pickedLayer&&S+10){let{pickedColors:R}=this._drawAndSample({layers:I,views:r,viewports:i,onViewportActive:f,deviceRect:{x:A.pickedX??g[0],y:A.pickedY??g[1],width:1,height:1},cullRect:x,effects:u,pass:`picking:${c}:z`},!0);R[3]&&(C=R[0])}A.pickedLayer&&S+1=l);C++){let I=b[C],R={color:I.pickedColor,layer:null,index:I.pickedObjectIndex,picked:!0,x:n,y:o,pixelRatio:h};R=vl({layer:I.pickedLayer,info:R,mode:c});let N=R.layer.id;E.has(N)||E.set(N,new Set);let O=E.get(N),W=R.object??R.index;O.has(W)||(O.add(W),S.push(R))}return S}_pickVisibleObjects({layers:e,views:r,viewports:i,x:n,y:o,width:s=1,height:a=1,mode:c="query",maxObjects:l=null,onViewportActive:f,effects:u}){let d=this._getPickable(e);if(!d||i.length===0)return[];this._resizeBuffer();let h=this.device.canvasContext.cssToDeviceRatio(),p=this.device.canvasContext.cssToDevicePixels([n,o],!0),g=p.x,m=p.y+p.height,_=this.device.canvasContext.cssToDevicePixels([n+s,o+a],!0),T=_.x+_.width,y=_.y,x={x:g,y,width:T-g,height:m-y},w=this._drawAndSample({layers:d,views:r,viewports:i,onViewportActive:f,deviceRect:x,cullRect:{x:n,y:o,width:s,height:a},effects:u,pass:`picking:${c}`}),b=Bp(w),E=new Map,S=[],A=Number.isFinite(l);for(let C=0;C=l);C++){let I=b[C],R={color:I.pickedColor,layer:null,index:I.pickedObjectIndex,picked:!0,x:n,y:o,pixelRatio:h};R=vl({layer:I.pickedLayer,info:R,mode:c});let N=R.layer.id;E.has(N)||E.set(N,new Set);let O=E.get(N),W=R.object??R.index;O.has(W)||(O.add(W),S.push(R))}return S}async _drawAndSampleAsync({layers:e,views:r,viewports:i,onViewportActive:n,deviceRect:o,cullRect:s,effects:a,pass:c},l=!1){let f=l?this.depthFBO:this.pickingFBO,u={layers:e,layerFilter:this.layerFilter,views:r,viewports:i,onViewportActive:n,pickingFBO:f,deviceRect:o,cullRect:s,effects:a,pass:c,pickZ:l,preRenderStats:{},isPicking:!0};for(let x of a)x.useInPicking&&(u.preRenderStats[x.id]=x.preRender(u));let{decodePickingColor:d,stats:h}=this.pickLayersPass.render(u);this._updateStats(h);let{x:p,y:g,width:m,height:_}=o,T=f.colorAttachments[0]?.texture;if(!T)throw new Error("Picking framebuffer color attachment is missing");let y=await this._readTextureDataAsync(T,{x:p,y:g,width:m,height:_},l?Float32Array:Uint8Array);if(!l){let x=!1;for(let w=3;w0&&F.warn("Async pick readback returned only zero alpha values",{deviceRect:o,bytes:Array.from(y.subarray(0,Math.min(y.length,16)))})()}return{pickedColors:y,decodePickingColor:d}}async _readTextureDataAsync(e,r,i){let{width:n,height:o}=r,s=e.computeMemoryLayout(r),a=this.device.createBuffer({byteLength:s.byteLength,usage:j.COPY_DST|j.MAP_READ});try{e.readBuffer(r,a);let c=await a.readAsync(0,s.byteLength),l=i.BYTES_PER_ELEMENT;if(s.bytesPerRow%l!==0)throw new Error(`Texture readback row stride ${s.bytesPerRow} is not aligned to ${l}-byte elements.`);let f=new i(c.buffer,c.byteOffset,s.byteLength/l),u=n*4,d=s.bytesPerRow/l;if(ds.props.operation.includes("terrain"))}_getPickingRect({deviceX:e,deviceY:r,deviceRadius:i,deviceWidth:n,deviceHeight:o}){let s=Math.max(0,e-i),a=Math.max(0,r-i),c=Math.min(n,e+i+1)-s,l=Math.min(o,r+i+1)-a;return c<=0||l<=0?null:{x:s,y:a,width:c,height:l}}};var x4={"top-left":{top:0,left:0},"top-right":{top:0,right:0},"bottom-left":{bottom:0,left:0},"bottom-right":{bottom:0,right:0},fill:{top:0,left:0,bottom:0,right:0}},b4="top-left",Zb="root",El=class{constructor({deck:e,parentElement:r}){this.defaultWidgets=[],this.widgets=[],this.resolvedWidgets=[],this.containers={},this.lastViewports={},this.deck=e,r?.classList.add("deck-widget-container"),this.parentElement=r}getWidgets(){return this.resolvedWidgets}setProps(e){if(e.widgets&&!de(e.widgets,this.widgets,1)){let r=e.widgets.filter(Boolean);this._setWidgets(r)}}finalize(){for(let e of this.getWidgets())this._removeWidget(e);this.defaultWidgets.length=0,this.resolvedWidgets.length=0;for(let e in this.containers)this.containers[e].remove()}addDefault(e){this.defaultWidgets.find(r=>r.id===e.id)||(this._addWidget(e),this.defaultWidgets.push(e),this._setWidgets(this.widgets))}onRedraw({viewports:e,layers:r}){let i=e.reduce((n,o)=>(n[o.id]=o,n),{});for(let n of this.getWidgets()){let{viewId:o}=n;if(o){let s=i[o];s&&(n.onViewportChange&&n.onViewportChange(s),n.onRedraw?.({viewports:[s],layers:r}))}else{if(n.onViewportChange)for(let s of e)n.onViewportChange(s);n.onRedraw?.({viewports:e,layers:r})}}this.lastViewports=i,this._updateContainers()}onHover(e,r){for(let i of this.getWidgets()){let{viewId:n}=i;(!n||n===e.viewport?.id)&&i.onHover?.(e,r)}}onEvent(e,r){let i=xn[r.type];if(i)for(let n of this.getWidgets()){let{viewId:o}=n;(!o||o===e.viewport?.id)&&n[i]?.(e,r)}}_setWidgets(e){let r={};for(let i of this.resolvedWidgets)r[i.id]=i;this.resolvedWidgets.length=0;for(let i of this.defaultWidgets)r[i.id]=null,this.resolvedWidgets.push(i);for(let i of e){let n=r[i.id];n?n.viewId!==i.viewId||n.placement!==i.placement?(this._removeWidget(n),this._addWidget(i)):i!==n&&(n.setProps(i.props),i=n):this._addWidget(i),r[i.id]=null,this.resolvedWidgets.push(i)}for(let i in r){let n=r[i];n&&this._removeWidget(n)}this.widgets=e}_addWidget(e){let{viewId:r=null,placement:i=b4}=e,n=e.props._container??r;e.widgetManager=this,e.deck=this.deck,e.rootElement=e._onAdd({deck:this.deck,viewId:r}),e.rootElement&&this._getContainer(n,i).append(e.rootElement),e.updateHTML()}_removeWidget(e){e.onRemove?.(),e.rootElement&&e.rootElement.remove(),e.rootElement=void 0,e.deck=void 0,e.widgetManager=void 0}_getContainer(e,r){if(e&&typeof e!="string")return e;let i=e||Zb,n=this.containers[i];n||(n=document.createElement("div"),n.style.pointerEvents="none",n.style.position="absolute",n.style.overflow="hidden",this.parentElement?.append(n),this.containers[i]=n);let o=n.querySelector(`.${r}`);return o||(o=globalThis.document.createElement("div"),o.className=r,o.style.position="absolute",o.style.zIndex="2",Object.assign(o.style,x4[r]),n.append(o)),o}_updateContainers(){let e=this.deck.width,r=this.deck.height;for(let i in this.containers){let n=this.lastViewports[i]||null,o=i===Zb||n,s=this.containers[i];o?(s.style.display="block",s.style.left=`${n?n.x:0}px`,s.style.top=`${n?n.y:0}px`,s.style.width=`${n?n.width:e}px`,s.style.height=`${n?n.height:r}px`):s.style.display="none"}}};function Up(t,e){e&&Object.entries(e).map(([r,i])=>{r.startsWith("--")?t.style.setProperty(r,i):t.style[r]=i})}function Qb(t,e){e&&Object.keys(e).map(r=>{r.startsWith("--")?t.style.removeProperty(r):t.style[r]=""})}var On=class{constructor(e){this.viewId=null,this.props={...this.constructor.defaultProps,...e},this.id=this.props.id}setProps(e){let r=this.props,i=this.rootElement;i&&r.className!==e.className&&(r.className&&i.classList.remove(r.className),e.className&&i.classList.add(e.className)),i&&!de(r.style,e.style,1)&&(Qb(i,r.style),Up(i,e.style)),Object.assign(this.props,e),this.updateHTML()}updateHTML(){this.rootElement&&this.onRenderHTML(this.rootElement)}get viewIds(){return this.viewId?[this.viewId]:this.deck?.getViews().map(e=>e.id)??[]}getViewState(e){return this.deck?.viewManager?.getViewState(e)||{}}setViewState(e,r){this.deck?._onViewStateChange({viewId:e,viewState:r,interactionState:{}})}onCreateRootElement(){let e=["deck-widget",this.className,this.props.className],r=document.createElement("div");return e.filter(i=>typeof i=="string"&&i.length>0).forEach(i=>r.classList.add(i)),Up(r,this.props.style),r}_onAdd(e){return this.onAdd(e)??this.onCreateRootElement()}onAdd(e){}onRemove(){}onViewportChange(e){}onRedraw(e){}onHover(e,r){}onClick(e,r){}onDrag(e,r){}onDragStart(e,r){}onDragEnd(e,r){}};On.defaultProps={id:"widget",style:{},_container:null,className:""};var T4={zIndex:"1",position:"absolute",pointerEvents:"none",color:"#a0a7b4",backgroundColor:"#29323c",padding:"10px",top:"0",left:"0",display:"none"},Ns=class extends On{constructor(e={}){super(e),this.id="default-tooltip",this.placement="fill",this.className="deck-tooltip",this.isVisible=!1,this.setProps(e)}onCreateRootElement(){let e=document.createElement("div");return e.className=this.className,Object.assign(e.style,T4),e}onRenderHTML(e){}onViewportChange(e){this.isVisible&&e.id===this.lastViewport?.id&&!e.equals(this.lastViewport)&&this.setTooltip(null),this.lastViewport=e}onHover(e){let{deck:r}=this,i=r&&r.props.getTooltip;if(!i)return;let n=i(e);this.setTooltip(n,e.x,e.y)}setTooltip(e,r,i){let n=this.rootElement;if(n){if(typeof e=="string")n.innerText=e;else if(e)e.text&&(n.innerText=e.text),e.html&&(n.innerHTML=e.html),e.className&&(n.className=e.className);else{this.isVisible=!1,n.style.display="none";return}this.isVisible=!0,n.style.display="block",n.style.transform=`translate(${r}px, ${i}px)`,e&&typeof e=="object"&&"style"in e&&Object.assign(n.style,e.style)}}};Ns.defaultProps={...On.defaultProps};z();cf();go();function $r(){}var IN=({isDragging:t})=>t?"grabbing":"grab",wT={id:"",width:"100%",height:"100%",style:null,viewState:null,initialViewState:null,pickingRadius:0,pickAsync:"auto",layerFilter:null,parameters:{},parent:null,device:null,deviceProps:{},gl:null,canvas:null,layers:[],effects:[],views:null,controller:null,useDevicePixels:!0,touchAction:"none",eventRecognizerOptions:{},_framebuffer:null,_animate:!1,_pickable:!0,_typedArrayManagerProps:{},_customRender:null,widgets:[],onDeviceInitialized:$r,onWebGLInitialized:$r,onResize:$r,onViewStateChange:$r,onInteractionStateChange:$r,onBeforeRender:$r,onAfterRender:$r,onLoad:$r,onError:t=>F.error(t.message,t.cause)(),onHover:null,onClick:null,onDragStart:null,onDrag:null,onDragEnd:null,_onMetrics:null,getCursor:IN,getTooltip:null,debug:!1,drawPickingColors:!1},Vs=class{constructor(e){this.width=0,this.height=0,this.userData={},this.device=null,this.canvas=null,this.viewManager=null,this.layerManager=null,this.effectManager=null,this.deckRenderer=null,this.deckPicker=null,this.eventManager=null,this.widgetManager=null,this.tooltip=null,this.animationLoop=null,this.cursorState={isHovering:!1,isDragging:!1},this.stats=new it({id:"deck.gl"}),this.metrics={fps:0,setPropsTime:0,layersCount:0,drawLayersCount:0,updateLayersCount:0,updateAttributesCount:0,updateAttributesTime:0,framesRedrawn:0,pickTime:0,pickCount:0,pickLayersCount:0,gpuTime:0,gpuTimePerFrame:0,cpuTime:0,cpuTimePerFrame:0,bufferMemory:0,textureMemory:0,renderbufferMemory:0,gpuMemory:0},this._metricsCounter=0,this._hoverPickSequence=0,this._pointerDownPickSequence=0,this._needsRedraw="Initial render",this._pickRequest={mode:"hover",x:-1,y:-1,radius:0,event:null,unproject3D:!1},this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=null,this._onPointerMove=i=>{let{_pickRequest:n}=this;if(i.type==="pointerleave")n.x=-1,n.y=-1,n.radius=0;else{if(i.leftButton||i.rightButton)return;{let o=i.offsetCenter;if(!o)return;n.x=o.x,n.y=o.y,n.radius=this.props.pickingRadius}}this.layerManager&&(this.layerManager.context.mousePosition={x:n.x,y:n.y}),n.event=i},this._onEvent=i=>{let n=xn[i.type],o=i.offsetCenter;if(!n||!o||!this.layerManager)return;let s=this.layerManager.getLayers(),a=this._getInternalPickingMode();if(!a)return;if(a==="sync"){let l=i.type==="click"&&this._shouldUnproject3D(s)?this._getFirstPickedInfo(this._pickPointSync(this._getPointPickOptions(o.x,o.y,{unproject3D:!0},s))):this._getLastPointerDownPickingInfo(o.x,o.y,s);this._dispatchPickingEvent(l,i);return}(this._lastPointerDownInfoPromise||Promise.resolve(this._getLastPointerDownPickingInfo(o.x,o.y,s))).then(l=>{this._dispatchPickingEvent(l,i)}).catch(l=>this.props.onError?.(l))},this._onPointerDown=i=>{let n=i.offsetCenter;if(!n)return;let o=this._getInternalPickingMode();if(!o)return;let s=this.layerManager?.getLayers()||[],a=++this._pointerDownPickSequence;if(o==="sync"){let l=this._pickPointSync({x:n.x,y:n.y,radius:this.props.pickingRadius}),f=this._getFirstPickedInfo(l);this._lastPointerDownInfo=f,this._lastPointerDownInfoPromise=Promise.resolve(f);return}let c=this._pickPointAsync(this._getPointPickOptions(n.x,n.y,{},s)).then(l=>this._getFirstPickedInfo(l)).then(l=>(a===this._pointerDownPickSequence&&(this._lastPointerDownInfo=l),l)).catch(l=>{this.props.onError?.(l);let f=this.deckPicker&&this.viewManager?this._getLastPointerDownPickingInfo(n.x,n.y,s):{};return a===this._pointerDownPickSequence&&(this._lastPointerDownInfo=f),f});this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=c},this.props={...wT,...e},e=this.props,e.viewState&&e.initialViewState&&F.warn("View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.")(),this.viewState=this.props.initialViewState,e.device&&(this.device=e.device);let r=this.device;if(!r&&e.gl){e.gl instanceof WebGLRenderingContext&&F.error("WebGL1 context not supported.")();let i=this.props.deviceProps?.onResize;r=Ws.attach(e.gl,{_cacheShaders:!0,_cachePipelines:!0,...this.props.deviceProps,onResize:(n,o)=>{let{width:s,height:a}=n.canvas;n.setDrawingBufferSize(s,a),this._needsRedraw="Canvas resized",i?.(n,o)}})}r||(r=this._createDevice(e)),this.animationLoop=this._createAnimationLoop(r,e),this.setProps(e),e._typedArrayManagerProps&&lr.setOptions(e._typedArrayManagerProps),this.animationLoop.start()}finalize(){this.animationLoop?.stop(),this.animationLoop?.destroy(),this.animationLoop=null,this._hoverPickSequence++,this._pointerDownPickSequence++,this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=null,this.layerManager?.finalize(),this.layerManager=null,this.viewManager?.finalize(),this.viewManager=null,this.effectManager?.finalize(),this.effectManager=null,this.deckRenderer?.finalize(),this.deckRenderer=null,this.deckPicker?.finalize(),this.deckPicker=null,this.eventManager?.destroy(),this.eventManager=null,this.widgetManager?.finalize(),this.widgetManager=null,!this.props.canvas&&!this.props.device&&!this.props.gl&&this.canvas&&(this.canvas.parentElement?.removeChild(this.canvas),this.canvas=null)}setProps(e){this.stats.get("setProps Time").timeStart(),"onLayerHover"in e&&F.removed("onLayerHover","onHover")(),"onLayerClick"in e&&F.removed("onLayerClick","onClick")(),e.initialViewState&&!de(this.props.initialViewState,e.initialViewState,3)&&(this.viewState=e.initialViewState),Object.assign(this.props,e),this._validateInternalPickingMode(),this._setCanvasSize(this.props);let r=Object.create(this.props);Object.assign(r,{views:this._getViews(),width:this.width,height:this.height,viewState:this._getViewState()}),e.device&&e.device.id!==this.device?.id&&(this.animationLoop?.stop(),this.canvas!==e.device.canvasContext?.canvas&&(this.canvas?.remove(),this.eventManager?.destroy(),this.canvas=null),F.log(`recreating animation loop for new device! id=${e.device.id}`)(),this.animationLoop=this._createAnimationLoop(e.device,e),this.animationLoop.start()),this.animationLoop?.setProps(r),e.useDevicePixels!==void 0&&this.device?.canvasContext?.setProps&&this.device.canvasContext.setProps({useDevicePixels:e.useDevicePixels}),this.layerManager&&(this.viewManager.setProps(r),this.layerManager.activateViewport(this.getViewports()[0]),this.layerManager.setProps(r),this.effectManager.setProps(r),this.deckRenderer.setProps(r),this.deckPicker.setProps(r),this.widgetManager.setProps(r)),this.stats.get("setProps Time").timeEnd()}needsRedraw(e={clearRedrawFlags:!1}){if(!this.layerManager)return!1;if(this.props._animate)return"Deck._animate";let r=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);let i=this.viewManager.needsRedraw(e),n=this.layerManager.needsRedraw(e),o=this.effectManager.needsRedraw(e),s=this.deckRenderer.needsRedraw(e);return r=r||i||n||o||s,r}redraw(e){if(!this.layerManager)return;let r=this.needsRedraw({clearRedrawFlags:!0});r=e||r,r&&(this.stats.get("Redraw Count").incrementCount(),this.props._customRender?this.props._customRender(r):this._drawLayers(r))}get isInitialized(){return this.viewManager!==null}getViews(){return J(this.viewManager),this.viewManager.views}getView(e){return J(this.viewManager),this.viewManager.getView(e)}getViewports(e){return J(this.viewManager),this.viewManager.getViewports(e)}getCanvas(){return this.canvas}async pickObjectAsync(e){let r=(await this._pickAsync("pickObjectAsync","pickObject Time",e)).result;return r.length?r[0]:null}async pickObjectsAsync(e){return await this._pickAsync("pickObjectsAsync","pickObjects Time",e)}pickObject(e){let r=this._pick("pickObject","pickObject Time",e).result;return r.length?r[0]:null}pickMultipleObjects(e){return e.depth=e.depth||10,this._pick("pickObject","pickMultipleObjects Time",e).result}pickObjects(e){return this._pick("pickObjects","pickObjects Time",e)}_pickPositionForController(e,r){return this._getInternalPickingMode()!=="sync"?null:this.pickObject({x:e,y:r,radius:0,unproject3D:!0})}_addResources(e,r=!1){for(let i in e)this.layerManager.resourceManager.add({resourceId:i,data:e[i],forceUpdate:r})}_removeResources(e){for(let r of e)this.layerManager.resourceManager.remove(r)}_addDefaultEffect(e){this.effectManager.addDefaultEffect(e)}_addDefaultShaderModule(e){this.layerManager.addDefaultShaderModule(e)}_removeDefaultShaderModule(e){this.layerManager?.removeDefaultShaderModule(e)}_resolveInternalPickingMode(){let{pickAsync:e}=this.props,r=this.device?.type||this.props.deviceProps?.type;if(e==="auto")return r==="webgpu"?"async":"sync";if(e==="sync"&&r==="webgpu")throw new Error('`pickAsync: "sync"` is not supported when Deck is using a WebGPU device.');return e}_getInternalPickingMode(){try{return this._resolveInternalPickingMode()}catch(e){return this.props.onError?.(e),null}}_validateInternalPickingMode(){this._getInternalPickingMode()}_getFirstPickedInfo({result:e,emptyInfo:r}){return e[0]||r}_shouldUnproject3D(e=this.layerManager?.getLayers()||[]){return e.some(r=>r.props.pickable==="3d")}_getPointPickOptions(e,r,i={},n=this.layerManager?.getLayers()||[]){return{x:e,y:r,radius:this.props.pickingRadius,unproject3D:this._shouldUnproject3D(n),...i}}_pickPointSync(e){return this._pick("pickObject","pickObject Time",e)}_pickPointAsync(e){return this._pickAsync("pickObjectAsync","pickObject Time",e)}_getLastPointerDownPickingInfo(e,r,i=this.layerManager?.getLayers()||[]){return this.deckPicker.getLastPickedObject({x:e,y:r,layers:i,viewports:this.getViewports({x:e,y:r})},this._lastPointerDownInfo)}_applyHoverCallbacks({result:e,emptyInfo:r},i){if(!this.widgetManager)return;this.cursorState.isHovering=e.length>0;let n=r,o=!1;for(let s of e)n=s,o=s.layer?.onHover(s,i)||o;o||(this.props.onHover?.(n,i),this.widgetManager.onHover(n,i))}_dispatchPickingEvent(e,r){if(!this.layerManager||!this.widgetManager)return;let i=xn[r.type];if(!i)return;let{layer:n}=e,o=n&&(n[i]||n.props[i]),s=this.props[i],a=!1;o&&(a=o.call(n,e,r)),a||(s?.(e,r),this.widgetManager.onEvent(e,r))}_pickAsync(e,r,i){J(this.deckPicker);let{stats:n}=this;n.get("Pick Count").incrementCount(),n.get(r).timeStart();let o=this.deckPicker[e]({layers:this.layerManager.getLayers(i),views:this.viewManager.getViews(),viewports:this.getViewports(i),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...i});return n.get(r).timeEnd(),o}_pick(e,r,i){J(this.deckPicker);let{stats:n}=this;n.get("Pick Count").incrementCount(),n.get(r).timeStart();let o=this.deckPicker[e]({layers:this.layerManager.getLayers(i),views:this.viewManager.getViews(),viewports:this.getViewports(i),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...i});return n.get(r).timeEnd(),o}_createCanvas(e){let r=e.canvas;return typeof r=="string"&&(r=document.getElementById(r),J(r)),r||(r=document.createElement("canvas"),r.id=e.id||"deckgl-overlay",e.width&&typeof e.width=="number"&&(r.width=e.width),e.height&&typeof e.height=="number"&&(r.height=e.height),(e.parent||document.body).appendChild(r)),Object.assign(r.style,e.style),r}_setCanvasSize(e){if(!this.canvas)return;let{width:r,height:i}=e;if(r||r===0){let n=Number.isFinite(r)?`${r}px`:r;this.canvas.style.width=n}if(i||i===0){let n=Number.isFinite(i)?`${i}px`:i;this.canvas.style.position=e.style?.position||"absolute",this.canvas.style.height=n}}_updateCanvasSize(){let{canvas:e}=this;if(!e)return;let r=e.clientWidth??e.width,i=e.clientHeight??e.height;(r!==this.width||i!==this.height)&&(this.width=r,this.height=i,this.viewManager?.setProps({width:r,height:i}),this.layerManager?.activateViewport(this.getViewports()[0]),this.props.onResize({width:r,height:i}))}_createAnimationLoop(e,r){let{gl:i,onError:n}=r;return new gs({device:e,autoResizeDrawingBuffer:!i,autoResizeViewport:!1,onInitialize:o=>this._setDevice(o.device),onRender:this._onRenderFrame.bind(this),onError:n})}_createDevice(e){let r=this.props.deviceProps?.createCanvasContext,i=typeof r=="object"?r:void 0,n={adapters:[],_cacheShaders:!0,_cachePipelines:!0,...e.deviceProps};n.adapters.includes(Ws)||n.adapters.push(Ws);let o={alphaMode:this.props.deviceProps?.type==="webgpu"?"premultiplied":void 0},s=this.props.deviceProps?.onResize;return hn.createDevice({_reuseDevices:!0,type:"webgl",...n,createCanvasContext:{...o,...i,canvas:this._createCanvas(e),useDevicePixels:this.props.useDevicePixels,autoResize:!0},onResize:(a,c)=>{this._needsRedraw="Canvas resized",s?.(a,c)}})}_getViewState(){return this.props.viewState||this.viewState}_getViews(){let{views:e}=this.props,r=Array.isArray(e)?e:e?[e]:[new Cs({id:"default-view"})];return r.length&&this.props.controller&&(r[0].props.controller=this.props.controller),r}_onContextLost(){let{onError:e}=this.props;this.animationLoop&&e&&e(new Error("WebGL context is lost"))}_pickAndCallback(){let{_pickRequest:e}=this;if(e.event){let r=e.event,i=this.layerManager?.getLayers()||[],n=this._getPointPickOptions(e.x,e.y,{radius:e.radius,mode:e.mode},i),o=this._getInternalPickingMode(),s=++this._hoverPickSequence;if(e.event=null,!o)return;if(o==="sync"){this._applyHoverCallbacks(this._pickPointSync(n),r);return}this._pickPointAsync(n).then(({result:a,emptyInfo:c})=>{s===this._hoverPickSequence&&this._applyHoverCallbacks({result:a,emptyInfo:c},r)}).catch(a=>this.props.onError?.(a))}}_updateCursor(){let e=this.props.parent||this.canvas;e&&(e.style.cursor=this.props.getCursor(this.cursorState))}_setDevice(e){if(this.device=e,this._validateInternalPickingMode(),!this.animationLoop)return;this.canvas||(this.canvas=this.device.canvasContext?.canvas,!this.canvas.isConnected&&this.props.parent&&this.props.parent.insertBefore(this.canvas,this.props.parent.firstChild)),this.device.type==="webgl"&&this.device.setParametersWebGL({blend:!0,blendFunc:[770,771,1,771],polygonOffsetFill:!0,depthTest:!0,depthFunc:515}),this.props.onDeviceInitialized(this.device),this.device.type==="webgl"&&this.props.onWebGLInitialized(this.device.gl);let r=new Ai;r.play(),this.animationLoop.attachTimeline(r);let i=this.props.parent?.querySelector(".deck-events-root")||this.canvas;this.eventManager=new ns(i,{touchAction:this.props.touchAction,recognizers:Object.keys(lp).map(s=>{let[a,c,l,f]=lp[s],u=this.props.eventRecognizerOptions?.[s],d={...c,...u,event:s};return{recognizer:new a(d),recognizeWith:l,requestFailure:f}}),events:{pointerdown:this._onPointerDown,pointermove:this._onPointerMove,pointerleave:this._onPointerMove}});for(let s in xn)this.eventManager.on(s,this._onEvent);this.viewManager=new ws({timeline:r,eventManager:this.eventManager,onViewStateChange:this._onViewStateChange.bind(this),onInteractionStateChange:this._onInteractionStateChange.bind(this),pickPosition:this._pickPositionForController.bind(this),views:this._getViews(),viewState:this._getViewState(),width:this.width,height:this.height});let n=this.viewManager.getViewports()[0];this.layerManager=new Ts(this.device,{deck:this,stats:this.stats,viewport:n,timeline:r}),this.effectManager=new Ps({deck:this,device:this.device}),this.deckRenderer=new Is(this.device,{stats:this.stats}),this.deckPicker=new Os(this.device,{stats:this.stats});let o=this.props.parent?.querySelector(".deck-widgets-root")||this.canvas?.parentElement;this.widgetManager=new El({deck:this,parentElement:o}),this.widgetManager.addDefault(new Ns),this.setProps(this.props),this._updateCanvasSize(),this.props.onLoad()}_drawLayers(e,r){let{device:i,gl:n}=this.layerManager.context;this.props.onBeforeRender({device:i,gl:n});let o={target:this.props._framebuffer,layers:this.layerManager.getLayers(),viewports:this.viewManager.getViewports(),onViewportActive:this.layerManager.activateViewport,views:this.viewManager.getViews(),pass:"screen",effects:this.effectManager.getEffects(),...r};this.deckRenderer?.renderLayers(o),o.pass==="screen"&&this.widgetManager.onRedraw({viewports:o.viewports,layers:o.layers}),this.props.onAfterRender({device:i,gl:n})}_onRenderFrame(){this._getFrameStats(),this._metricsCounter++%60===0&&(this._getMetrics(),this.stats.reset(),F.table(4,this.metrics)(),this.props._onMetrics&&this.props._onMetrics(this.metrics)),this._updateCanvasSize(),this._updateCursor(),this.layerManager.updateLayers(),this._pickAndCallback(),this.redraw(),this.viewManager&&this.viewManager.updateViewStates()}_onViewStateChange(e){let r=this.props.onViewStateChange(e)||e.viewState;this.viewState&&(this.viewState={...this.viewState,[e.viewId]:r},this.props.viewState||this.viewManager&&this.viewManager.setProps({viewState:this.viewState}))}_onInteractionStateChange(e){this.cursorState.isDragging=e.isDragging||!1,this.props.onInteractionStateChange(e)}_getFrameStats(){let{stats:e}=this;e.get("frameRate").timeEnd(),e.get("frameRate").timeStart();let r=this.animationLoop.stats;e.get("GPU Time").addTime(r.get("GPU Time").lastTiming),e.get("CPU Time").addTime(r.get("CPU Time").lastTiming)}_getMetrics(){let{metrics:e,stats:r}=this;e.fps=r.get("frameRate").getHz(),e.setPropsTime=r.get("setProps Time").time,e.updateAttributesTime=r.get("Update Attributes").time,e.framesRedrawn=r.get("Redraw Count").count,e.pickTime=r.get("pickObject Time").time+r.get("pickMultipleObjects Time").time+r.get("pickObjects Time").time,e.pickCount=r.get("Pick Count").count,e.layersCount=this.layerManager?.layers.length??0,e.drawLayersCount=r.get("Layers rendered").lastSampleCount,e.pickLayersCount=r.get("Layers picked").lastSampleCount,e.updateAttributesCount=r.get("Layers updated").count,e.updateAttributesCount=r.get("Attributes updated").count,e.gpuTime=r.get("GPU Time").time,e.cpuTime=r.get("CPU Time").time,e.gpuTimePerFrame=r.get("GPU Time").getAverageTime(),e.cpuTimePerFrame=r.get("CPU Time").getAverageTime();let i=hn.stats.get("GPU Time and Memory");e.bufferMemory=i.get("Buffer Memory").count,e.textureMemory=i.get("Texture Memory").count,e.renderbufferMemory=i.get("Renderbuffer Memory").count,e.gpuMemory=i.get("GPU Memory").count}};Vs.defaultProps=wT;Vs.VERSION=y0;var Bn=Vs;z();z();function ST(t){switch(t){case"float64":return Float64Array;case"uint8":case"unorm8":return Uint8ClampedArray;default:return Go(t)}}var AT=ke.getDataType.bind(ke);function js(t,e,r){if(e.size>4)return null;let i=r==="webgpu"&&e.type==="uint8"?"unorm8":e.type;return{attribute:t,format:e.size>1?`${i}x${e.size}`:e.type,byteOffset:e.offset||0}}function Hr(t){return t.stride||t.size*t.bytesPerElement}function vT(t,e){return t.type===e.type&&t.size===e.size&&Hr(t)===Hr(e)&&(t.offset||0)===(e.offset||0)}function dg(t,e){e.offset&&F.removed("shaderAttribute.offset","vertexOffset, elementOffset")();let r=Hr(t),i=e.vertexOffset!==void 0?e.vertexOffset:t.vertexOffset||0,n=e.elementOffset||0,o=i*r+n*t.bytesPerElement+(t.offset||0);return{...e,offset:o,stride:r}}function ON(t,e){let r=dg(t,e);return{high:r,low:{...r,offset:r.offset+t.size*4}}}var $s=class{constructor(e,r,i){this._buffer=null,this.device=e,this.id=r.id||"",this.size=r.size||1;let n=r.logicalType||r.type,o=n==="float64",{defaultValue:s}=r;s=Number.isFinite(s)?[s]:s||new Array(this.size).fill(0);let a;o?a="float32":!n&&r.isIndexed?a="uint32":a=n||"float32";let c=ST(n||a);this.doublePrecision=o,o&&r.fp64===!1&&(c=Float32Array),this.value=null,this.settings={...r,defaultType:c,defaultValue:s,logicalType:n,type:a,normalized:a.includes("norm"),size:this.size,bytesPerElement:c.BYTES_PER_ELEMENT},this.state={...i,externalBuffer:null,bufferAccessor:this.settings,allocatedValue:null,numInstances:0,bounds:null,constant:!1}}get isConstant(){return this.state.constant}get buffer(){return this._buffer}get byteOffset(){let e=this.getAccessor();return e.vertexOffset?e.vertexOffset*Hr(e):0}get numInstances(){return this.state.numInstances}set numInstances(e){this.state.numInstances=e}delete(){this._buffer&&(this._buffer.delete(),this._buffer=null),lr.release(this.state.allocatedValue)}getBuffer(){return this.state.constant?null:this.state.externalBuffer||this._buffer}getValue(e=this.id,r=null){let i={};if(this.state.constant){let n=this.value;if(r){let o=dg(this.getAccessor(),r),s=o.offset/n.BYTES_PER_ELEMENT,a=o.size||this.size;i[e]=n.subarray(s,s+a)}else i[e]=n}else i[e]=this.getBuffer();return this.doublePrecision&&(this.value instanceof Float64Array?i[`${e}64Low`]=i[e]:i[`${e}64Low`]=new Float32Array(this.size)),i}_getBufferLayout(e=this.id,r=null){let i=this.getAccessor(),n=[],o={name:this.id,byteStride:Hr(i)};if(this.doublePrecision){let s=ON(i,r||{});n.push(js(e,{...i,...s.high},this.device.type),js(`${e}64Low`,{...i,...s.low},this.device.type))}else if(r){let s=dg(i,r);n.push(js(e,{...i,...s},this.device.type))}else n.push(js(e,i,this.device.type));return o.attributes=n.filter(Boolean),o}setAccessor(e){this.state.bufferAccessor=e}getAccessor(){return this.state.bufferAccessor}getBounds(){if(this.state.bounds)return this.state.bounds;let e=null;if(this.state.constant&&this.value){let r=Array.from(this.value);e=[r,r]}else{let{value:r,numInstances:i,size:n}=this,o=i*n;if(r&&o&&r.length>=o){let s=new Array(n).fill(1/0),a=new Array(n).fill(-1/0);for(let c=0;ca[l]&&(a[l]=f)}e=[s,a]}}return this.state.bounds=e,e}setData(e){let{state:r}=this,i;ArrayBuffer.isView(e)?i={value:e}:e instanceof j?i={buffer:e}:i=e;let n={...this.settings,...i};if(ArrayBuffer.isView(i.value)){if(!i.type)if(this.doublePrecision&&i.value instanceof Float64Array)n.type="float32";else{let s=AT(i.value);n.type=n.normalized?s.replace("int","norm"):s}n.bytesPerElement=i.value.BYTES_PER_ELEMENT,n.stride=Hr(n)}if(r.bounds=null,i.constant){let o=i.value;if(o=this._normalizeValue(o,[],0),this.settings.normalized&&(o=this.normalizeConstant(o)),!(!r.constant||!this._areValuesEqual(o,this.value)))return!1;r.externalBuffer=null,r.constant=!0,this.value=ArrayBuffer.isView(o)?o:new Float32Array(o)}else if(i.buffer){let o=i.buffer;r.externalBuffer=o,r.constant=!1,this.value=i.value||null}else if(i.value){this._checkExternalBuffer(i);let o=i.value;r.externalBuffer=null,r.constant=!1,this.value=o;let{buffer:s}=this,a=Hr(n),c=(n.vertexOffset||0)*a;if(this.doublePrecision&&o instanceof Float64Array&&(o=ll(o,n)),this.settings.isIndexed){let f=this.settings.defaultType;o.constructor!==f&&(o=new f(o))}let l=o.byteLength+c+a*2;(!s||s.byteLength(r+128)/255*2-1);case"snorm16":return new Float32Array(e).map(r=>(r+32768)/65535*2-1);case"unorm8":return new Float32Array(e).map(r=>r/255);case"unorm16":return new Float32Array(e).map(r=>r/65535);default:return e}}_normalizeValue(e,r,i){let{defaultValue:n,size:o}=this.settings;if(Number.isFinite(e))return r[i]=e,r;if(!e){let s=o;for(;--s>=0;)r[i+s]=n[s];return r}switch(o){case 4:r[i+3]=Number.isFinite(e[3])?e[3]:n[3];case 3:r[i+2]=Number.isFinite(e[2])?e[2]:n[2];case 2:r[i+1]=Number.isFinite(e[1])?e[1]:n[1];case 1:r[i+0]=Number.isFinite(e[0])?e[0]:n[0];break;default:let s=o;for(;--s>=0;)r[i+s]=Number.isFinite(e[s])?e[s]:n[s]}return r}_areValuesEqual(e,r){if(!e||!r)return!1;let{size:i}=this;for(let n=0;n0&&(RT.length=t.length,i=RT):i=ET,(e>0||Number.isFinite(r))&&(i=(Array.isArray(i)?i:Array.from(i)).slice(e,r),n.index=e-1),{iterable:i,objectInfo:n}}function df(t){return t&&t[Symbol.asyncIterator]}function CT(t,e){let{size:r,stride:i,offset:n,startIndices:o,nested:s}=e,a=t.BYTES_PER_ELEMENT,c=i?i/a:r,l=n?n/a:0,f=Math.floor((t.length-l)/c);return(u,{index:d,target:h})=>{if(!o){let _=d*c+l;for(let T=0;T=e[1]))return t;let r=[],i=t.length,n=0;for(let o=0;oe[1]?r.push(s):e=[Math.min(s[0],e[0]),Math.max(s[1],e[1])]}return r.splice(n,0,e),r}var DN={interpolation:{duration:0,easing:t=>t},spring:{stiffness:.05,damping:.5}};function hf(t,e){if(!t)return null;Number.isFinite(t)&&(t={type:"interpolation",duration:t});let r=t.type||"interpolation";return{...DN[r],...e,...t,type:r}}var Ni=class extends $s{constructor(e,r){super(e,r,{startIndices:null,lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,layoutChanged:!1,updateRanges:Hs}),this.constant=!1,this.settings.update=r.update||(r.accessor?this._autoUpdater:void 0),Object.seal(this.settings),Object.seal(this.state),this._validateAttributeUpdaters()}get startIndices(){return this.state.startIndices}set startIndices(e){this.state.startIndices=e}needsUpdate(){return this.state.needsUpdate}needsRedraw({clearChangedFlags:e=!1}={}){let r=this.state.needsRedraw;return this.state.needsRedraw=r&&!e,r}layoutChanged(){return this.state.layoutChanged}setAccessor(e){var r;(r=this.state).layoutChanged||(r.layoutChanged=!vT(e,this.getAccessor())),super.setAccessor(e)}getUpdateTriggers(){let{accessor:e}=this.settings;return[this.id].concat(typeof e!="function"&&e||[])}supportsTransition(){return!!this.settings.transition}getTransitionSetting(e){if(!e||!this.supportsTransition())return null;let{accessor:r}=this.settings,i=this.settings.transition,n=Array.isArray(r)?e[r.find(o=>e[o])]:e[r];return hf(n,i)}setNeedsUpdate(e=this.id,r){if(this.state.needsUpdate=this.state.needsUpdate||e,this.setNeedsRedraw(e),r){let{startRow:i=0,endRow:n=1/0}=r;this.state.updateRanges=MT(this.state.updateRanges,[i,n])}else this.state.updateRanges=Hs}clearNeedsUpdate(){this.state.needsUpdate=!1,this.state.updateRanges=PT}setNeedsRedraw(e=this.id){this.state.needsRedraw=this.state.needsRedraw||e}allocate(e){let{state:r,settings:i}=this;return i.noAlloc?!1:i.update?(super.allocate(e,r.updateRanges!==Hs),!0):!1}updateBuffer({numInstances:e,data:r,props:i,context:n}){if(!this.needsUpdate())return!1;let{state:{updateRanges:o},settings:{update:s,noAlloc:a}}=this,c=!0;if(s){for(let[l,f]of o)s.call(n,this,{data:r,startRow:l,endRow:f,props:i,numInstances:e});if(this.value)if(this.constant||!this.buffer||this.buffer.byteLengthf?l.set(y,g):(e._normalizeValue(y,_.target,0),Ip({target:l,source:_.target,start:g,count:x}));g+=x*f}else e._normalizeValue(y,l,g),g+=f}}_validateAttributeUpdaters(){let{settings:e}=this;if(!(e.noAlloc||typeof e.update=="function"))throw new Error(`Attribute ${this.id} missing update or accessor`)}_checkAttributeArray(){let{value:e}=this,r=Math.min(4,this.size);if(e&&e.length>=r){let i=!0;switch(r){case 4:i=i&&Number.isFinite(e[3]);case 3:i=i&&Number.isFinite(e[2]);case 2:i=i&&Number.isFinite(e[1]);case 1:i=i&&Number.isFinite(e[0]);break;default:i=!1}if(!i)throw new Error(`Illegal attribute generated for ${this.id}`)}}};function hg(t){let{source:e,target:r,start:i=0,size:n,getData:o}=t,s=t.end||r.length,a=e.length,c=s-i;if(a>c){r.set(e.subarray(0,c),i);return}if(r.set(e,i),!o)return;let l=a;for(;li(f+a,u)),l=Math.min(n.length,o.length);for(let f=1;fa}){let a=r.doublePrecision&&r.value instanceof Float64Array?2:1,c=r.size*a,l=r.byteOffset,f=r.settings.bytesPerElement<4?l/r.settings.bytesPerElement*4:l,u=r.startIndices,d=o&&u,h=r.isConstant;if(!d&&e&&i>=n)return e;let p=r.value instanceof Float64Array?Float32Array:r.value.constructor,g=h?r.value:new p(r.getBuffer().readSyncWebGL(l,n*p.BYTES_PER_ELEMENT).buffer);if(r.settings.normalized&&!h){let y=s;s=(x,w)=>r.normalizeConstant(y(x,w))}let m=h?(y,x)=>s(g,x):(y,x)=>s(g.subarray(y+l,y+l+c),x),_=e?new Float32Array(e.readSyncWebGL(f,i*4).buffer):new Float32Array(0),T=new Float32Array(n);return IT({source:_,target:T,sourceStartIndices:o,targetStartIndices:u,size:c,getData:m}),(!e||e.byteLength0||n.end()}delete(){super.delete(),this.transform.destroy(),this.texture.destroy(),this.framebuffer.destroy()}},UN=`layout(std140) uniform springUniforms { + float damping; + float stiffness; +} spring; +`,zN={name:"spring",vs:UN,uniformTypes:{damping:"f32",stiffness:"f32"}},WN=`#version 300 es +#define SHADER_NAME spring-transition-vertex-shader + +#define EPSILON 0.00001 + +in ATTRIBUTE_TYPE aPrev; +in ATTRIBUTE_TYPE aCur; +in ATTRIBUTE_TYPE aTo; +out ATTRIBUTE_TYPE vNext; +out float vIsTransitioningFlag; + +ATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) { + ATTRIBUTE_TYPE velocity = cur - prev; + ATTRIBUTE_TYPE delta = dest - cur; + ATTRIBUTE_TYPE force = delta * spring.stiffness; + ATTRIBUTE_TYPE resistance = velocity * spring.damping; + return force - resistance + velocity + cur; +} + +void main(void) { + bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON; + vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0; + + vNext = getNextValue(aCur, aPrev, aTo); + gl_Position = vec4(0, 0, 0, 1); + gl_PointSize = 100.0; +} +`,VN=`#version 300 es +#define SHADER_NAME spring-transition-is-transitioning-fragment-shader + +in float vIsTransitioningFlag; + +out vec4 fragColor; + +void main(void) { + if (vIsTransitioningFlag == 0.0) { + discard; + } + fragColor = vec4(1.0); +}`;function jN(t,e){let r=pf(e.size),i=gf(e.size);return new zr(t,{vs:WN,fs:VN,bufferLayout:[{name:"aPrev",format:i},{name:"aCur",format:i},{name:"aTo",format:e.getBufferLayout().attributes[0].format}],varyings:["vNext"],modules:[zN],defines:{ATTRIBUTE_TYPE:r},parameters:{depthCompare:"always",blendColorOperation:"max",blendColorSrcFactor:"one",blendColorDstFactor:"one",blendAlphaOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one"}})}function $N(t){return t.createTexture({data:new Uint8Array(4),format:"rgba8unorm",width:1,height:1})}function HN(t,e){return t.createFramebuffer({id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,colorAttachments:[e]})}var YN={interpolation:Ys,spring:Xs},Gs=class{constructor(e,{id:r,timeline:i}){if(!e)throw new Error("AttributeTransitionManager is constructed without device");this.id=r,this.device=e,this.timeline=i,this.transitions={},this.needsRedraw=!1,this.numInstances=1}finalize(){for(let e in this.transitions)this._removeTransition(e)}update({attributes:e,transitions:r,numInstances:i}){this.numInstances=i||1;for(let n in e){let o=e[n],s=o.getTransitionSetting(r);s&&this._updateAttribute(n,o,s)}for(let n in this.transitions){let o=e[n];(!o||!o.getTransitionSetting(r))&&this._removeTransition(n)}}hasAttribute(e){let r=this.transitions[e];return r&&r.inProgress}getAttributes(){let e={};for(let r in this.transitions){let i=this.transitions[r];i.inProgress&&(e[r]=i.attributeInTransition)}return e}run(){if(this.numInstances===0)return!1;for(let r in this.transitions)this.transitions[r].update()&&(this.needsRedraw=!0);let e=this.needsRedraw;return this.needsRedraw=!1,e}_removeTransition(e){this.transitions[e].delete(),delete this.transitions[e]}_updateAttribute(e,r,i){let n=this.transitions[e],o=!n||n.type!==i.type;if(o){n&&this._removeTransition(e);let s=YN[i.type];s?this.transitions[e]=new s({attribute:r,timeline:this.timeline,device:this.device}):(F.error(`unsupported transition type '${i.type}'`)(),o=!1)}(o||r.needsRedraw())&&(this.needsRedraw=!0,this.transitions[e].start(i,this.numInstances))}};var FT="attributeManager.invalidate",XN="attributeManager.updateStart",GN="attributeManager.updateEnd",qN="attribute.updateStart",KN="attribute.allocate",ZN="attribute.updateEnd",qs=class{constructor(e,{id:r="attribute-manager",stats:i,timeline:n}={}){this.mergeBoundsMemoized=kt(bb),this.id=r,this.device=e,this.attributes={},this.updateTriggers={},this.needsRedraw=!0,this.userData={},this.stats=i,this.attributeTransitionManager=new Gs(e,{id:`${r}-transitions`,timeline:n}),Object.seal(this)}finalize(){for(let e in this.attributes)this.attributes[e].delete();this.attributeTransitionManager.finalize()}getNeedsRedraw(e={clearRedrawFlags:!1}){let r=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!e.clearRedrawFlags,r&&this.id}setNeedsRedraw(){this.needsRedraw=!0}add(e){this._add(e)}addInstanced(e){this._add(e,{stepMode:"instance"})}remove(e){for(let r of e)this.attributes[r]!==void 0&&(this.attributes[r].delete(),delete this.attributes[r])}invalidate(e,r){let i=this._invalidateTrigger(e,r);ae(FT,this,e,i)}invalidateAll(e){for(let r in this.attributes)this.attributes[r].setNeedsUpdate(r,e);ae(FT,this,"all")}update({data:e,numInstances:r,startIndices:i=null,transitions:n,props:o={},buffers:s={},context:a={}}){let c=!1;ae(XN,this),this.stats&&this.stats.get("Update Attributes").timeStart();for(let l in this.attributes){let f=this.attributes[l],u=f.settings.accessor;f.startIndices=i,f.numInstances=r,o[l]&&F.removed(`props.${l}`,`data.attributes.${l}`)(),f.setExternalBuffer(s[l])||f.setBinaryValue(typeof u=="string"?s[u]:void 0,e.startIndices)||typeof u=="string"&&!s[u]&&f.setConstantValue(a,o[u])||f.needsUpdate()&&(c=!0,this._updateAttribute({attribute:f,numInstances:r,data:e,props:o,context:a})),this.needsRedraw=this.needsRedraw||f.needsRedraw()}c&&ae(GN,this,r),this.stats&&(this.stats.get("Update Attributes").timeEnd(),c&&this.stats.get("Attributes updated").incrementCount()),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:r,transitions:n})}updateTransition(){let{attributeTransitionManager:e}=this,r=e.run();return this.needsRedraw=this.needsRedraw||r,r}getAttributes(){return{...this.attributes,...this.attributeTransitionManager.getAttributes()}}getBounds(e){let r=e.map(i=>this.attributes[i]?.getBounds());return this.mergeBoundsMemoized(r)}getChangedAttributes(e={clearChangedFlags:!1}){let{attributes:r,attributeTransitionManager:i}=this,n={...i.getAttributes()};for(let o in r){let s=r[o];s.needsRedraw(e)&&!i.hasAttribute(o)&&(n[o]=s)}return n}getBufferLayouts(e){return Object.values(this.getAttributes()).map(r=>r.getBufferLayout(e))}_add(e,r){for(let i in e){let n=e[i],o={...n,id:i,size:n.isIndexed&&1||n.size||1,...r};this.attributes[i]=new Ni(this.device,o)}this._mapUpdateTriggersToAttributes()}_mapUpdateTriggersToAttributes(){let e={};for(let r in this.attributes)this.attributes[r].getUpdateTriggers().forEach(n=>{e[n]||(e[n]=[]),e[n].push(r)});this.updateTriggers=e}_invalidateTrigger(e,r){let{attributes:i,updateTriggers:n}=this,o=n[e];return o&&o.forEach(s=>{let a=i[s];a&&a.setNeedsUpdate(a.id,r)}),o}_updateAttribute(e){let{attribute:r,numInstances:i}=e;if(ae(qN,r),r.constant){r.setConstantValue(e.context,r.value);return}r.allocate(i)&&ae(KN,r,i),r.updateBuffer(e)&&(this.needsRedraw=!0,ae(ZN,r,i))}};z();cf();var Ks=class extends xt{get value(){return this._value}_onUpdate(){let{time:e,settings:{fromValue:r,toValue:i,duration:n,easing:o}}=this,s=o(e/n);this._value=di(r,i,s)}};var BT=1e-5;function kT(t,e,r,i,n){let o=e-t,a=(r-e)*n,c=-o*i;return a+c+o+e}function QN(t,e,r,i,n){if(Array.isArray(r)){let o=[];for(let s=0;s0}add(e,r,i,n){let{transitions:o}=this;if(o.has(e)){let c=o.get(e),{value:l=c.settings.fromValue}=c;r=l,this.remove(e)}if(n=hf(n),!n)return;let s=JN[n.type];if(!s){F.error(`unsupported transition type '${n.type}'`)();return}let a=new s(this.timeline);a.start({...n,fromValue:r,toValue:i}),o.set(e,a)}remove(e){let{transitions:r}=this;r.has(e)&&(r.get(e).cancel(),r.delete(e))}update(){let e={};for(let[r,i]of this.transitions)i.update(),e[r]=i.value,i.inProgress||this.remove(r);return e}clear(){for(let e of this.transitions.keys())this.remove(e)}};function WT(t){let e=t[ct];for(let r in e){let i=e[r],{validate:n}=i;if(n&&!n(t[r],i))throw new Error(`Invalid prop ${r}: ${t[r]}`)}}function VT(t,e){let r=jT({newProps:t,oldProps:e,propTypes:t[ct],ignoreProps:{data:null,updateTriggers:null,extensions:null,transitions:null}}),i=tD(t,e),n=!1;return i||(n=rD(t,e)),{dataChanged:i,propsChanged:r,updateTriggersChanged:n,extensionsChanged:iD(t,e),transitionsChanged:eD(t,e)}}function eD(t,e){if(!t.transitions)return!1;let r={},i=t[ct],n=!1;for(let o in t.transitions){let s=i[o],a=s&&s.type;(a==="number"||a==="color"||a==="array")&&pg(t[o],e[o],s)&&(r[o]=!0,n=!0)}return n?r:!1}function jT({newProps:t,oldProps:e,ignoreProps:r={},propTypes:i={},triggerName:n="props"}){if(e===t)return!1;if(typeof t!="object"||t===null)return`${n} changed shallowly`;if(typeof e!="object"||e===null)return`${n} changed shallowly`;for(let o of Object.keys(t))if(!(o in r)){if(!(o in e))return`${n}.${o} added`;let s=pg(t[o],e[o],i[o]);if(s)return`${n}.${o} ${s}`}for(let o of Object.keys(e))if(!(o in r)){if(!(o in t))return`${n}.${o} dropped`;if(!Object.hasOwnProperty.call(t,o)){let s=pg(t[o],e[o],i[o]);if(s)return`${n}.${o} ${s}`}}return!1}function pg(t,e,r){let i=r&&r.equal;return i&&!i(t,e,r)||!i&&(i=t&&e&&t.equals,i&&!i.call(t,e))?"changed deeply":!i&&e!==t?"changed shallowly":null}function tD(t,e){if(e===null)return"oldProps is null, initial diff";let r=!1,{dataComparator:i,_dataDiff:n}=t;return i?i(t.data,e.data)||(r="Data comparator detected a change"):t.data!==e.data&&(r="A new data container was supplied"),r&&n&&(r=n(t.data,e.data)||r),r}function rD(t,e){if(e===null)return{all:!0};if("all"in t.updateTriggers&&zT(t,e,"all"))return{all:!0};let r={},i=!1;for(let n in t.updateTriggers)n!=="all"&&zT(t,e,n)&&(r[n]=!0,i=!0);return i?r:!1}function iD(t,e){if(e===null)return!0;let r=e.extensions,{extensions:i}=t;if(i===r)return!1;if(!r||!i||i.length!==r.length)return!0;for(let n=0;ni.name==="project64"))){let i=r.modules.findIndex(n=>n.name==="project32");i>=0&&r.modules.splice(i,1)}if("inject"in e)if(!t.inject)r.inject=e.inject;else{let i={...t.inject};for(let n in e.inject)i[n]=(i[n]||"")+e.inject[n];r.inject=i}return r}z();var cD={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},mg={};function HT(t,e,r,i){if(r instanceof $)return r;r.constructor&&r.constructor.name!=="Object"&&(r={data:r});let n=null;r.compressed&&(n={minFilter:"linear",mipmapFilter:r.data.length>1?"nearest":"linear"});let{width:o,height:s}=r.data,a=e.createTexture({...r,sampler:{...cD,...n,...i},mipLevels:e.getMipLevelCount(o,s)});return e.type==="webgl"?a.generateMipmapsWebGL():e.type==="webgpu"&&e.generateMipmapsWebGPU(a),mg[a.id]=t,a}function YT(t,e){!e||!(e instanceof $)||mg[e.id]===t&&(e.delete(),delete mg[e.id])}var lD={boolean:{validate(t,e){return!0},equal(t,e,r){return!!t==!!e}},number:{validate(t,e){return Number.isFinite(t)&&(!("max"in e)||t<=e.max)&&(!("min"in e)||t>=e.min)}},color:{validate(t,e){return e.optional&&!t||_g(t)&&(t.length===3||t.length===4)},equal(t,e,r){return de(t,e,1)}},accessor:{validate(t,e){let r=xf(t);return r==="function"||r===xf(e.value)},equal(t,e,r){return typeof e=="function"?!0:de(t,e,1)}},array:{validate(t,e){return e.optional&&!t||_g(t)},equal(t,e,r){let{compare:i}=r,n=Number.isInteger(i)?i:i?1:0;return i?de(t,e,n):t===e}},object:{equal(t,e,r){if(r.ignore)return!0;let{compare:i}=r,n=Number.isInteger(i)?i:i?1:0;return i?de(t,e,n):t===e}},function:{validate(t,e){return e.optional&&!t||typeof t=="function"},equal(t,e,r){return!r.compare&&r.ignore!==!1||t===e}},data:{transform:(t,e,r)=>{if(!t)return t;let{dataTransform:i}=r.props;return i?i(t):typeof t.shape=="string"&&t.shape.endsWith("-table")&&Array.isArray(t.data)?t.data:t}},image:{transform:(t,e,r)=>{let i=r.context;return!i||!i.device?null:HT(r.id,i.device,t,{...e.parameters,...r.props.textureParameters})},release:(t,e,r)=>{YT(r.id,t)}}};function XT(t){let e={},r={},i={};for(let[n,o]of Object.entries(t)){let s=o?.deprecatedFor;if(s)i[n]=Array.isArray(s)?s:[s];else{let a=fD(n,o);e[n]=a,r[n]=a.value}}return{propTypes:e,defaultProps:r,deprecatedProps:i}}function fD(t,e){switch(xf(e)){case"object":return Js(t,e);case"array":return Js(t,{type:"array",value:e,compare:!1});case"boolean":return Js(t,{type:"boolean",value:e});case"number":return Js(t,{type:"number",value:e});case"function":return Js(t,{type:"function",value:e,compare:!0});default:return{name:t,type:"unknown",value:e}}}function Js(t,e){return"type"in e?{name:t,...lD[e.type],...e}:"value"in e?{name:t,type:xf(e.value),...e}:{name:t,type:"object",value:e}}function _g(t){return Array.isArray(t)||ArrayBuffer.isView(t)}function xf(t){return _g(t)?"array":t===null?"null":typeof t}function GT(t,e){let r;for(let o=e.length-1;o>=0;o--){let s=e[o];"extensions"in s&&(r=s.extensions)}let i=yg(t.constructor,r),n=Object.create(i);n[Mn]=t,n[zt]={},n[yt]={};for(let o=0;o{},this.oldProps=null,this.oldAsyncProps=null}finalize(){for(let e in this.asyncProps){let r=this.asyncProps[e];r&&r.type&&r.type.release&&r.type.release(r.resolvedValue,r.type,this.component)}this.asyncProps={},this.component=null,this.resetOldProps()}getOldProps(){return this.oldAsyncProps||this.oldProps||xD}resetOldProps(){this.oldAsyncProps=null,this.oldProps=this.component?this.component.props:null}hasAsyncProp(e){return e in this.asyncProps}getAsyncProp(e){let r=this.asyncProps[e];return r&&r.resolvedValue}isAsyncPropLoading(e){if(e){let r=this.asyncProps[e];return!!(r&&r.pendingLoadCount>0&&r.pendingLoadCount!==r.resolvedLoadCount)}for(let r in this.asyncProps)if(this.isAsyncPropLoading(r))return!0;return!1}reloadAsyncProp(e,r){this._watchPromise(e,Promise.resolve(r))}setAsyncProps(e){this.component=e[Mn]||this.component;let r=e[yt]||{},i=e[zt]||e,n=e[fr]||{};for(let o in r){let s=r[o];this._createAsyncPropData(o,n[o]),this._updateAsyncProp(o,s),r[o]=this.getAsyncProp(o)}for(let o in i){let s=i[o];this._createAsyncPropData(o,n[o]),this._updateAsyncProp(o,s)}}_fetch(e,r){return null}_onResolve(e,r){}_onError(e,r){}_updateAsyncProp(e,r){if(this._didAsyncInputValueChange(e,r)){if(typeof r=="string"&&(r=this._fetch(e,r)),r instanceof Promise){this._watchPromise(e,r);return}if(df(r)){this._resolveAsyncIterable(e,r);return}this._setPropValue(e,r)}}_freezeAsyncOldProps(){if(!this.oldAsyncProps&&this.oldProps){this.oldAsyncProps=Object.create(this.oldProps);for(let e in this.asyncProps)Object.defineProperty(this.oldAsyncProps,e,{enumerable:!0,value:this.oldProps[e]})}}_didAsyncInputValueChange(e,r){let i=this.asyncProps[e];return r===i.resolvedValue||r===i.lastValue?!1:(i.lastValue=r,!0)}_setPropValue(e,r){this._freezeAsyncOldProps();let i=this.asyncProps[e];i&&(r=this._postProcessValue(i,r),i.resolvedValue=r,i.pendingLoadCount++,i.resolvedLoadCount=i.pendingLoadCount)}_setAsyncPropValue(e,r,i){let n=this.asyncProps[e];n&&i>=n.resolvedLoadCount&&r!==void 0&&(this._freezeAsyncOldProps(),n.resolvedValue=r,n.resolvedLoadCount=i,this.onAsyncPropUpdated(e,r))}_watchPromise(e,r){let i=this.asyncProps[e];if(i){i.pendingLoadCount++;let n=i.pendingLoadCount;r.then(o=>{this.component&&(o=this._postProcessValue(i,o),this._setAsyncPropValue(e,o,n),this._onResolve(e,o))}).catch(o=>{this._onError(e,o)})}}async _resolveAsyncIterable(e,r){if(e!=="data"){this._setPropValue(e,r);return}let i=this.asyncProps[e];if(!i)return;i.pendingLoadCount++;let n=i.pendingLoadCount,o=[],s=0;for await(let a of r){if(!this.component)return;let{dataTransform:c}=this.component.props;c?o=c(a,o):o=o.concat(a),Object.defineProperty(o,"__diff",{enumerable:!1,value:[{startRow:s,endRow:o.length}]}),s=o.length,this._setAsyncPropValue(e,o,n)}this._onResolve(e,o)}_postProcessValue(e,r){let i=e.type;return i&&this.component&&(i.release&&i.release(e.resolvedValue,i,this.component),i.transform)?i.transform(r,i,this.component):r}_createAsyncPropData(e,r){if(!this.asyncProps[e]){let n=this.component&&this.component.props[ct];this.asyncProps[e]={type:n&&n[e],lastValue:null,resolvedValue:r,pendingLoadCount:0,resolvedLoadCount:0}}}};var ra=class extends ta{constructor({attributeManager:e,layer:r}){super(r),this.attributeManager=e,this.needsRedraw=!0,this.needsUpdate=!0,this.subLayers=null,this.usesPickingColorCache=!1}get layer(){return this.component}_fetch(e,r){let i=this.layer,n=i?.props.fetch;return n?n(r,{propName:e,layer:i}):super._fetch(e,r)}_onResolve(e,r){let i=this.layer;if(i){let n=i.props.onDataLoad;e==="data"&&n&&n(r,{propName:e,layer:i})}}_onError(e,r){let i=this.layer;i&&i.raiseError(r,`loading ${e} of ${this.layer}`)}};var bD="layer.changeFlag",TD="layer.initialize",wD="layer.update",SD="layer.finalize",AD="layer.matched",KT=2**24-1,vD=Object.freeze([]),ED=kt(({oldViewport:t,viewport:e})=>t.equals(e)),At=new Uint8ClampedArray(0),RD={data:{type:"data",value:vD,async:!0},dataComparator:{type:"function",value:null,optional:!0},_dataDiff:{type:"function",value:t=>t&&t.__diff,optional:!0},dataTransform:{type:"function",value:null,optional:!0},onDataLoad:{type:"function",value:null,optional:!0},onError:{type:"function",value:null,optional:!0},fetch:{type:"function",value:(t,{propName:e,layer:r,loaders:i,loadOptions:n,signal:o})=>{let{resourceManager:s}=r.context;n=n||r.getLoadOptions(),i=i||r.props.loaders,o&&(n={...n,core:{...n?.core,fetch:{...n?.core?.fetch,signal:o}}});let a=s.contains(t);return!a&&!n&&(s.add({resourceId:t,data:Mr(t,i),persistent:!1}),a=!0),a?s.subscribe({resourceId:t,onChange:c=>r.internalState?.reloadAsyncProp(e,c),consumerId:r.id,requestId:e}):Mr(t,i,n)}},updateTriggers:{},visible:!0,pickable:!1,opacity:{type:"number",min:0,max:1,value:1},operation:"draw",onHover:{type:"function",value:null,optional:!0},onClick:{type:"function",value:null,optional:!0},onDragStart:{type:"function",value:null,optional:!0},onDrag:{type:"function",value:null,optional:!0},onDragEnd:{type:"function",value:null,optional:!0},coordinateSystem:"default",coordinateOrigin:{type:"array",value:[0,0,0],compare:!0},modelMatrix:{type:"array",value:null,compare:!0,optional:!0},wrapLongitude:!1,positionFormat:"XYZ",colorFormat:"RGBA",parameters:{type:"object",value:{},optional:!0,compare:2},loadOptions:{type:"object",value:null,optional:!0,ignore:!0},transitions:null,extensions:[],loaders:{type:"array",value:[],optional:!0,ignore:!0},getPolygonOffset:{type:"function",value:({layerIndex:t})=>[0,-t*100]},highlightedObjectIndex:null,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}},ia=class extends bf{constructor(){super(...arguments),this.internalState=null,this.lifecycle=Wr.NO_STATE,this.parent=null}static get componentName(){return Object.prototype.hasOwnProperty.call(this,"layerName")?this.layerName:""}get root(){let e=this;for(;e.parent;)e=e.parent;return e}toString(){return`${this.constructor.layerName||this.constructor.name}({id: '${this.props.id}'})`}project(e){J(this.internalState);let r=this.internalState.viewport||this.context.viewport,i=dl(e,{viewport:r,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),[n,o,s]=wi(i,r.pixelProjectionMatrix);return e.length===2?[n,o]:[n,o,s]}unproject(e){return J(this.internalState),(this.internalState.viewport||this.context.viewport).unproject(e)}projectPosition(e,r){J(this.internalState);let i=this.internalState.viewport||this.context.viewport;return Sb(e,{viewport:i,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem,...r})}get isComposite(){return!1}get isDrawable(){return!0}setState(e){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,e),this.setNeedsRedraw()}setNeedsRedraw(){this.internalState&&(this.internalState.needsRedraw=!0)}setNeedsUpdate(){this.internalState&&(this.context.layerManager.setNeedsUpdate(String(this)),this.internalState.needsUpdate=!0)}get isLoaded(){return this.internalState?!this.internalState.isAsyncPropLoading():!1}get wrapLongitude(){return this.props.wrapLongitude}isPickable(){return this.props.pickable&&this.props.visible}getModels(){let e=this.state;return e&&(e.models||e.model&&[e.model])||[]}setShaderModuleProps(...e){for(let r of this.getModels())r.shaderInputs.setProps(...e)}getAttributeManager(){return this.internalState&&this.internalState.attributeManager}getCurrentLayer(){return this.internalState&&this.internalState.layer}getLoadOptions(){return this.props.loadOptions}use64bitPositions(){let{coordinateSystem:e}=this.props;return e==="default"||e==="lnglat"||e==="cartesian"}onHover(e,r){return this.props.onHover&&this.props.onHover(e,r)||!1}onClick(e,r){return this.props.onClick&&this.props.onClick(e,r)||!1}nullPickingColor(){return[0,0,0]}encodePickingColor(e,r=[]){return r[0]=e+1&255,r[1]=e+1>>8&255,r[2]=e+1>>8>>8&255,r}decodePickingColor(e){J(e instanceof Uint8Array);let[r,i,n]=e;return r+i*256+n*65536-1}getNumInstances(){return Number.isFinite(this.props.numInstances)?this.props.numInstances:this.state&&this.state.numInstances!==void 0?this.state.numInstances:$T(this.props.data)}getStartIndices(){return this.props.startIndices?this.props.startIndices:this.state&&this.state.startIndices?this.state.startIndices:null}getBounds(){return this.getAttributeManager()?.getBounds(["positions","instancePositions"])}getShaders(e){e=gg(e,{disableWarnings:!0,modules:this.context.defaultShaderModules});for(let r of this.props.extensions)e=gg(e,r.getShaders.call(this,r));return e}shouldUpdateState(e){return e.changeFlags.propsOrDataChanged}updateState(e){let r=this.getAttributeManager(),{dataChanged:i}=e.changeFlags;if(i&&r)if(Array.isArray(i))for(let n of i)r.invalidateAll(n);else r.invalidateAll();if(r){let{props:n}=e,o=this.internalState.hasPickingBuffer,s=Number.isInteger(n.highlightedObjectIndex)||!!n.pickable||n.extensions.some(a=>a.getNeedsPickingBuffer.call(this,a));if(o!==s){this.internalState.hasPickingBuffer=s;let{pickingColors:a,instancePickingColors:c}=r.attributes,l=a||c;l&&(s&&l.constant&&(l.constant=!1,r.invalidate(l.id)),!l.value&&!s&&(l.constant=!0,l.value=[0,0,0]))}}}finalizeState(e){for(let i of this.getModels())i.destroy();let r=this.getAttributeManager();r&&r.finalize(),this.context&&this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState&&(this.internalState.uniformTransitions.clear(),this.internalState.finalize())}draw(e){for(let r of this.getModels())r.draw(e.renderPass)}getPickingInfo({info:e,mode:r,sourceLayer:i}){let{index:n}=e;return n>=0&&Array.isArray(this.props.data)&&(e.object=this.props.data[n]),e}raiseError(e,r){r&&(e=new Error(`${r}: ${e.message}`,{cause:e})),this.props.onError?.(e)||this.context?.onError?.(e,this)}getNeedsRedraw(e={clearRedrawFlags:!1}){return this._getNeedsRedraw(e)}needsUpdate(){return this.internalState?this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams()):!1}hasUniformTransition(){return this.internalState?.uniformTransitions.active||!1}activateViewport(e){if(!this.internalState)return;let r=this.internalState.viewport;this.internalState.viewport=e,(!r||!ED({oldViewport:r,viewport:e}))&&(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}invalidateAttribute(e="all"){let r=this.getAttributeManager();r&&(e==="all"?r.invalidateAll():r.invalidate(e))}updateAttributes(e){let r=!1;for(let i in e)e[i].layoutChanged()&&(r=!0);for(let i of this.getModels())this._setModelAttributes(i,e,r)}_updateAttributes(){let e=this.getAttributeManager();if(!e)return;let r=this.props,i=this.getNumInstances(),n=this.getStartIndices();e.update({data:r.data,numInstances:i,startIndices:n,props:r,transitions:r.transitions,buffers:r.data.attributes,context:this});let o=e.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(o)}_updateAttributeTransition(){let e=this.getAttributeManager();e&&e.updateTransition()}_updateUniformTransition(){let{uniformTransitions:e}=this.internalState;if(e.active){let r=e.update(),i=Object.create(this.props);for(let n in r)Object.defineProperty(i,n,{value:r[n]});return i}return this.props}calculateInstancePickingColors(e,{numInstances:r}){if(e.constant)return;let i=Math.floor(At.length/4);if(this.internalState.usesPickingColorCache=!0,iKT&&F.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),At=lr.allocate(At,r,{size:4,copy:!0,maxCount:Math.max(r,KT)});let n=Math.floor(At.length/4),o=[0,0,0];for(let s=i;s(F.deprecated("layer.state.attributeManager","layer.getAttributeManager()")(),e)}),this.internalState.uniformTransitions=new Qs(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props),this.initializeState(this.context);for(let r of this.props.extensions)r.initializeState.call(this,this.context,r);this.setChangeFlags({dataChanged:"init",propsChanged:"init",viewportChanged:!0,extensionsChanged:!0}),this._update()}_transferState(e){ae(AD,this,this===e);let{state:r,internalState:i}=e;this!==e&&(this.internalState=i,this.state=r,this.internalState.setAsyncProps(this.props),this._diffProps(this.props,this.internalState.getOldProps()))}_update(){let e=this.needsUpdate();if(ae(wD,this,e),!e)return;this.context.stats.get("Layer updates").incrementCount();let r=this.props,i=this.context,n=this.internalState,o=i.viewport,s=this._updateUniformTransition();n.propsInTransition=s,i.viewport=n.viewport||o,this.props=s;try{let a=this._getUpdateParams(),c=this.getModels();if(i.device)this.updateState(a);else try{this.updateState(a)}catch{}for(let f of this.props.extensions)f.updateState.call(this,a,f);this.setNeedsRedraw(),this._updateAttributes();let l=this.getModels()[0]!==c[0];this._postUpdate(a,l)}finally{i.viewport=o,this.props=r,this._clearChangeFlags(),n.needsUpdate=!1,n.resetOldProps()}}_finalize(){ae(SD,this),this.finalizeState(this.context);for(let e of this.props.extensions)e.finalizeState.call(this,this.context,e)}_drawLayer({renderPass:e,shaderModuleProps:r=null,uniforms:i={},parameters:n={}}){this._updateAttributeTransition();let o=this.props,s=this.context;this.props=this.internalState.propsInTransition||o;try{r&&this.setShaderModuleProps(r);let{getPolygonOffset:a}=this.props,c=a&&a(i)||[0,0];s.device instanceof jr&&s.device.setParametersWebGL({polygonOffset:c});let l=s.device instanceof jr?null:CD(n);if(PD(this.getModels(),e,n,l),s.device instanceof jr)s.device.withParametersWebGL(n,()=>{let f={renderPass:e,shaderModuleProps:r,uniforms:i,parameters:n,context:s};for(let u of this.props.extensions)u.draw.call(this,f,u);this.draw(f)});else{l?.renderPassParameters&&e.setParameters(l.renderPassParameters);let f={renderPass:e,shaderModuleProps:r,uniforms:i,parameters:n,context:s};for(let u of this.props.extensions)u.draw.call(this,f,u);this.draw(f)}}finally{this.props=o}}getChangeFlags(){return this.internalState?.changeFlags}setChangeFlags(e){if(!this.internalState)return;let{changeFlags:r}=this.internalState;for(let n in e)if(e[n]){let o=!1;switch(n){case"dataChanged":let s=e[n],a=r[n];s&&Array.isArray(a)&&(r.dataChanged=Array.isArray(s)?a.concat(s):s,o=!0);default:r[n]||(r[n]=e[n],o=!0)}o&&ae(bD,this,n,e)}let i=!!(r.dataChanged||r.updateTriggersChanged||r.propsChanged||r.extensionsChanged);r.propsOrDataChanged=i,r.somethingChanged=i||r.viewportChanged||r.stateChanged}_clearChangeFlags(){this.internalState.changeFlags={dataChanged:!1,propsChanged:!1,updateTriggersChanged:!1,viewportChanged:!1,stateChanged:!1,extensionsChanged:!1,propsOrDataChanged:!1,somethingChanged:!1}}_diffProps(e,r){let i=VT(e,r);if(i.updateTriggersChanged)for(let n in i.updateTriggersChanged)i.updateTriggersChanged[n]&&this.invalidateAttribute(n);if(i.transitionsChanged)for(let n in i.transitionsChanged)this.internalState.uniformTransitions.add(n,r[n],e[n],e.transitions?.[n]);return this.setChangeFlags(i)}validateProps(){WT(this.props)}updateAutoHighlight(e){this.props.autoHighlight&&!Number.isInteger(this.props.highlightedObjectIndex)&&this._updateAutoHighlight(e)}_updateAutoHighlight(e){let r={highlightedObjectColor:e.picked?e.color:null},{highlightColor:i}=this.props;e.picked&&typeof i=="function"&&(r.highlightColor=i(e)),this.setShaderModuleProps({picking:r}),this.setNeedsRedraw()}_getAttributeManager(){let e=this.context;return new qs(e.device,{id:this.props.id,stats:e.stats,timeline:e.timeline})}_postUpdate(e,r){let{props:i,oldProps:n}=e,o=this.state.model;o?.isInstanced&&o.setInstanceCount(this.getNumInstances());let{autoHighlight:s,highlightedObjectIndex:a,highlightColor:c}=i;if(r||n.autoHighlight!==s||n.highlightedObjectIndex!==a||n.highlightColor!==c){let l={};Array.isArray(c)&&(l.highlightColor=c),(r||n.autoHighlight!==s||a!==n.highlightedObjectIndex)&&(l.highlightedObjectColor=Number.isFinite(a)&&a>=0?this.encodePickingColor(a):null),this.setShaderModuleProps({picking:l})}}_getUpdateParams(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}_getNeedsRedraw(e){if(!this.internalState)return!1;let r=!1;r=r||this.internalState.needsRedraw&&this.id;let i=this.getAttributeManager(),n=i?i.getNeedsRedraw(e):!1;if(r=r||n,r)for(let o of this.props.extensions)o.onNeedsRedraw.call(this,o);return this.internalState.needsRedraw=this.internalState.needsRedraw&&!e.clearRedrawFlags,r}_onAsyncPropUpdated(){this._diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}};ia.defaultProps=RD;ia.layerName="Layer";var ve=ia;function CD(t){let{blendConstant:e,...r}=t;return e?{pipelineParameters:r,renderPassParameters:{blendConstant:e}}:{pipelineParameters:r}}function PD(t,e,r,i){for(let n of t)n.device.type==="webgpu"?(MD(n,e),n.setParameters({...n.parameters,...i?.pipelineParameters})):n.setParameters(r)}function MD(t,e){let r=e.props.framebuffer||(e.framebuffer??null);if(!r)return;let i=r.colorAttachments.map(s=>s?.texture?.format??null),n=r.depthStencilAttachment?.texture?.format,o=t;(!ID(o.props.colorAttachmentFormats,i)||o.props.depthStencilAttachmentFormat!==n)&&(o.props.colorAttachmentFormats=i,o.props.depthStencilAttachmentFormat=n,o._setPipelineNeedsUpdate("attachment formats"))}function ID(t,e){if(t===e)return!0;if(!t||!e||t.length!==e.length)return!1;for(let r=0;re.isLoaded)}getSubLayers(){return this.internalState&&this.internalState.subLayers||[]}initializeState(e){}setState(e){super.setState(e),this.setNeedsUpdate()}getPickingInfo({info:e}){let{object:r}=e;return r&&r.__source&&r.__source.parent&&r.__source.parent.id===this.id&&(e.object=r.__source.object,e.index=r.__source.index),e}filterSubLayer(e){return!0}shouldRenderSubLayer(e,r){return r&&r.length}getSubLayerClass(e,r){let{_subLayerProps:i}=this.props;return i&&i[e]&&i[e].type||r}getSubLayerRow(e,r,i){return e.__source={parent:this,object:r,index:i},e}getSubLayerAccessor(e){if(typeof e=="function"){let r={index:-1,data:this.props.data,target:[]};return(i,n)=>i&&i.__source?(r.index=i.__source.index,e(i.__source.object,r)):e(i,n)}return e}getSubLayerProps(e={}){let{opacity:r,pickable:i,visible:n,parameters:o,getPolygonOffset:s,highlightedObjectIndex:a,autoHighlight:c,highlightColor:l,coordinateSystem:f,coordinateOrigin:u,wrapLongitude:d,positionFormat:h,modelMatrix:p,extensions:g,fetch:m,operation:_,_subLayerProps:T}=this.props,y={id:"",updateTriggers:{},opacity:r,pickable:i,visible:n,parameters:o,getPolygonOffset:s,highlightedObjectIndex:a,autoHighlight:c,highlightColor:l,coordinateSystem:f,coordinateOrigin:u,wrapLongitude:d,positionFormat:h,modelMatrix:p,extensions:g,fetch:m,operation:_},x=T&&e.id&&T[e.id],w=x&&x.updateTriggers,b=e.id||"sublayer";if(x){let E=this.props[ct],S=e.type?e.type._propTypes:{};for(let A in x){let C=S[A]||E[A];C&&C.type==="accessor"&&(x[A]=this.getSubLayerAccessor(x[A]))}}Object.assign(y,e,x),y.id=`${this.props.id}-${b}`,y.updateTriggers={all:this.props.updateTriggers?.all,...e.updateTriggers,...w};for(let E of g){let S=E.getSubLayerProps.call(this,E);S&&Object.assign(y,S,{updateTriggers:Object.assign(y.updateTriggers,S.updateTriggers)})}return y}_updateAutoHighlight(e){for(let r of this.getSubLayers())r.updateAutoHighlight(e)}_getAttributeManager(){return null}_postUpdate(e,r){let i=this.internalState.subLayers,n=!i||this.needsUpdate();if(n){let o=this.renderLayers();i=lt(o,Boolean),this.internalState.subLayers=i}ae(OD,this,n,i);for(let o of i)o.parent=this}};Tf.layerName="CompositeLayer";var na=Tf;var bg=Math.PI/180,ND=180/Math.PI;function ZT(t,e=0){let r=Math.min(180,t)*bg;return hr*2*Math.sin(r/2)*Math.pow(2,e)}function QT(t,e=0){let r=t/Math.pow(2,e);return Math.asin(Math.min(1,r/hr/2))*2*ND}var Tg=class extends Es{constructor(e){let{startPanPos:r,...i}=e;i.normalize=!1,super(i),r!==void 0&&(this._state.startPanPos=r)}panStart({pos:e}){let{latitude:r,longitude:i,zoom:n}=this.getViewportProps();return this._getUpdatedState({startPanLngLat:[i,r],startPanPos:e,startZoom:n})}pan({pos:e,startPos:r}){let i=this.getState(),n=i.startPanLngLat||this._unproject(r);if(!n)return this;let o=i.startZoom??this.getViewportProps().zoom,s=i.startPanPos||r,a=[n[0],n[1],o],l=this.makeViewport(this.getViewportProps()).panByPosition(a,e,s);return this._getUpdatedState(l)}panEnd(){return this._getUpdatedState({startPanLngLat:null,startPanPos:null,startZoom:null})}zoom({scale:e}){let i=(this.getState().startZoom||this.getViewportProps().zoom)+Math.log2(e);return this._getUpdatedState({zoom:i})}applyConstraints(e){let{longitude:r,latitude:i,maxBounds:n}=e;if(e.zoom=this._constrainZoom(e.zoom,e),(r<-180||r>180)&&(e.longitude=ps(r+180,360)-180),e.latitude=ce(i,-ze,ze),n&&(e.longitude=ce(e.longitude,n[0][0],n[1][0]),e.latitude=ce(e.latitude,n[0][1],n[1][1])),n){let o=e.zoom-Wt(i),s=n[1][0]-n[0][0],a=n[1][1]-n[0][1];if(a>0&&a0&&s<360){let c=Math.min(QT(e.width/Math.cos(e.latitude*bg),o),s)/2;e.longitude=ce(e.longitude,n[0][0]+c,n[1][0]-c)}}return e.latitude!==i&&(e.zoom+=Wt(e.latitude)-Wt(i)),e}_constrainZoom(e,r){r||(r=this.getViewportProps());let{latitude:i,maxZoom:n,maxBounds:o}=r,{minZoom:s}=r,a=Wt(0),c=Wt(i)-a;if(o!==null&&r.width>0&&r.height>0){let f=o[0][1],u=o[1][1],d=Math.sign(f)===Math.sign(u)?Math.min(Math.abs(f),Math.abs(u)):0,h=ZT(o[1][0]-o[0][0])*Math.cos(d*bg),p=ZT(o[1][1]-o[0][1]);h>0&&(s=Math.max(s,Math.log2(r.width/h)+a)),p>0&&(s=Math.max(s,Math.log2(r.height/p)+a)),s>n&&(s=n)}return ce(e,s+c,n+c)}},oa=class extends Mi{constructor(){super(...arguments),this.ControllerState=Tg,this.transition={transitionDuration:300,transitionInterpolator:new pr(["longitude","latitude","zoom"])},this.dragMode="pan"}setProps(e){super.setProps(e),this.dragRotate=!1,this.touchRotate=!1}};var wf=class extends Ci{constructor(e={}){super(e)}getViewportType(e){return e.zoom>12?Cn:bl}get ControllerType(){return oa}};wf.displayName="GlobeView";var wg=wf;var sa=class{constructor(e){J(e.id,"id is required"),this.id=e.id,this.type="custom",this.renderingMode=e.renderingMode||"3d",this.slot=e.slot,this.beforeId=e.beforeId,this.map=null}onAdd(e,r){this.map=e}render(e,r){this.map&&JT(this.map.__deck,this.map,this,r)}};var Sg="__UNDEFINED__";function Un(t){return t.props.beforeId?`deck-layer-group-before:${t.props.beforeId}`:t.props.slot?`deck-layer-group-slot:${t.props.slot}`:"deck-layer-group-last"}function ew(t,e,r){if(!t||!t.style||!t.style._loaded)return;let i=lt(r,Boolean);if(e!==r){let s=lt(e,Boolean),a=new Set(s.map(l=>Un(l))),c=new Set(i.map(l=>Un(l)));for(let l of a)c.has(l)||t.getLayer(l)&&t.removeLayer(l)}let n={};for(let s of i){let a=Un(s),c=t.getLayer(a);if(c){let l=c.implementation||c;n[a]=l}else{let l=new sa({id:a,slot:s.props.slot,beforeId:s.props.beforeId});n[a]=l,t.addLayer(l,s.props.beforeId)}}let o=t.style._order;for(let[s,a]of Object.entries(n)){let c=a.beforeId||Sg,l=c===Sg?o.length:o.indexOf(c);if(o.indexOf(s)!==l-1){let u=c===Sg?void 0:c;t.moveLayer(s,u)}}}var Di="mapbox",Ag=512,DD=Math.PI/180;function rw({map:t,deck:e}){if(t.__deck)return t.__deck;let r=e.props._customRender,i=e.props.onLoad,n={...e.props,_customRender:()=>{t.triggerRepaint(),r?.("")}};return n.views||(n.views=aa(t)),Object.assign(n,{width:null,height:null,touchAction:"unset",viewState:zn(t)}),e.isInitialized?tw(e,t):n.onLoad=()=>{i?.(),tw(e,t)},e.setProps(n),t.__deck=e,t.on("render",()=>{e.isInitialized&&FD(e,t)}),e}function tw(t,e){let r=()=>{t.isInitialized?BD(t,e):e.off("move",r)};e.on("move",r)}function iw(t){t.__deck?.finalize(),t.__deck=null}function Sf(t,e){let r=e?{depthWriteEnabled:!0,depthCompare:"less-equal",depthBias:0,blend:!0,blendColorSrcFactor:"src-alpha",blendColorDstFactor:"one-minus-src-alpha",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one-minus-src-alpha",blendColorOperation:"add",blendAlphaOperation:"add"}:{};return Af(t)==="globe"&&(r.cullMode="back"),r}function JT(t,e,r,i){if(!t.isInitialized)return;let{currentViewport:n}=t.userData,o=!1;n||(n=nw(t,e,i),t.userData.currentViewport=n,o=!0),n&&t._drawLayers("mapbox-repaint",{viewports:[n],layerFilter:s=>{if(t.props.layerFilter&&!t.props.layerFilter(s))return!1;let a=s.layer;return a.props.beforeId===r.beforeId&&a.props.slot===r.slot},clearStack:o,clearCanvas:!1})}function Af(t){let e=t.getProjection?.(),r=e?.type||e?.name;if(r==="globe")return"globe";if(r&&r!=="mercator")throw new Error("Unsupported projection");return"mercator"}function aa(t){return Af(t)==="globe"?new wg({id:Di}):new Cs({id:Di})}function zn(t){let{lng:e,lat:r}=t.getCenter(),i={longitude:(e+540)%360-180,latitude:r,zoom:t.getZoom(),bearing:t.getBearing(),pitch:t.getPitch(),padding:t.getPadding(),repeat:t.getRenderWorldCopies()};return t.getTerrain?.()&&LD(t,i),i}function LD(t,e){if(t.getFreeCameraOptions){let{position:r}=t.getFreeCameraOptions();if(!r||r.z===void 0)return;let i=t.transform.height,{longitude:n,latitude:o,pitch:s}=e,a=r.x*Ag,c=(1-r.y)*Ag,l=r.z*Ag,f=xe([n,o]),u=a-f[0],d=c-f[1],h=Math.sqrt(u*u+d*d),p=s*DD,g=1.5*i,m=p<.001?g*Math.cos(p)/l:g*Math.sin(p)/h;e.zoom=Math.log2(m);let _=g*Math.cos(p)/m,T=l-_;e.position=[0,0,T/bi(o)]}else typeof t.transform.elevation=="number"&&(e.position=[0,0,t.transform.elevation])}function nw(t,e,r){let i=zn(e),n=t.getView(Di)||aa(e);r&&(n.props.nearZMultiplier=.2);let o=r?.nearZ??e.transform._nearZ,s=r?.farZ??e.transform._farZ;return Number.isFinite(o)&&(i.nearZ=o/e.transform.height,i.farZ=s/e.transform.height),n.makeViewport({width:t.width,height:t.height,viewState:i})}function FD(t,e){let i=lt(t.props.layers,Boolean).some(a=>a&&!e.getLayer(Un(a))),n=t.getViewports(),o=n.findIndex(a=>a.id===Di),s=n.length>1||o<0;if(i||s){if(o>=0){n=n.slice();let a=nw(t,e);a?n[o]=a:n.splice(o,1)}t._drawLayers("mapbox-repaint",{viewports:n,layerFilter:a=>(!t.props.layerFilter||t.props.layerFilter(a))&&(a.viewport.id!==Di||!e.getLayer(Un(a.layer))),clearCanvas:!1})}else{let a=t.device,c=a?.gl;t.props.onBeforeRender?.({device:a,gl:c}),t.props.onAfterRender?.({device:a,gl:c})}t.userData.currentViewport=null}function BD(t,e){t.setProps({viewState:zn(e)}),t.needsRedraw({clearRedrawFlags:!0})}var Wn=class{constructor(e){this._handleStyleChange=()=>{if(this._resolveLayers(this._map,this._deck,this._props.layers,this._props.layers),!this._map)return;Af(this._map)&&this._deck?.setProps({views:this._getViews(this._map)})},this._updateContainerSize=()=>{if(this._map&&this._container){let{clientWidth:i,clientHeight:n}=this._map.getContainer();Object.assign(this._container.style,{width:`${i}px`,height:`${n}px`})}},this._updateViewState=()=>{let i=this._deck,n=this._map;i&&n&&(i.setProps({views:this._getViews(n),viewState:zn(n)}),i.isInitialized&&i.redraw())},this._handleMouseEvent=i=>{let n=this._deck;if(!n||!n.isInitialized)return;let o={type:i.type,offsetCenter:i.point,srcEvent:i},s=this._lastMouseDownPoint;switch(!i.point&&s&&(o.deltaX=i.originalEvent.clientX-s.clientX,o.deltaY=i.originalEvent.clientY-s.clientY,o.offsetCenter={x:s.x+o.deltaX,y:s.y+o.deltaY}),o.type){case"mousedown":n._onPointerDown(o),this._lastMouseDownPoint={...i.point,clientX:i.originalEvent.clientX,clientY:i.originalEvent.clientY};break;case"dragstart":o.type="panstart",n._onEvent(o);break;case"drag":o.type="panmove",n._onEvent(o);break;case"dragend":o.type="panend",n._onEvent(o);break;case"click":o.tapCount=1,n._onEvent(o);break;case"dblclick":o.type="click",o.tapCount=2,n._onEvent(o);break;case"mousemove":o.type="pointermove",n._onPointerMove(o);break;case"mouseout":o.type="pointerleave",n._onPointerMove(o);break;default:return}};let{interleaved:r=!1}=e;this._interleaved=r,this._props=this.filterProps(e)}filterProps(e){let{interleaved:r=!1,useDevicePixels:i,...n}=e;return!r&&i!==void 0&&(n.useDevicePixels=i),n}setProps(e){this._interleaved&&e.layers&&this._resolveLayers(this._map,this._deck,this._props.layers,e.layers),Object.assign(this._props,this.filterProps(e)),this._deck&&this._map&&this._deck.setProps({...this._props,views:this._getViews(this._map),parameters:{...Sf(this._map,this._interleaved),...this._props.parameters}})}onAdd(e){return this._map=e,this._interleaved?this._onAddInterleaved(e):this._onAddOverlaid(e)}_onAddOverlaid(e){let r=document.createElement("div");return Object.assign(r.style,{position:"absolute",left:0,top:0,textAlign:"initial",pointerEvents:"none"}),this._container=r,this._deck=new Bn({...this._props,parent:r,parameters:{...Sf(e,!1),...this._props.parameters},views:this._getViews(e),viewState:zn(e)}),e.on("resize",this._updateContainerSize),e.on("render",this._updateViewState),e.on("mousedown",this._handleMouseEvent),e.on("dragstart",this._handleMouseEvent),e.on("drag",this._handleMouseEvent),e.on("dragend",this._handleMouseEvent),e.on("mousemove",this._handleMouseEvent),e.on("mouseout",this._handleMouseEvent),e.on("click",this._handleMouseEvent),e.on("dblclick",this._handleMouseEvent),this._updateContainerSize(),r}_onAddInterleaved(e){let r=e.painter.context.gl;return r instanceof WebGLRenderingContext&&F.warn("Incompatible basemap library. See: https://deck.gl/docs/api-reference/mapbox/overview#compatibility")(),this._deck=rw({map:e,deck:new Bn({...this._props,views:this._getViews(e),gl:r,parameters:{...Sf(e,!0),...this._props.parameters}})}),e.on("styledata",this._handleStyleChange),this._resolveLayers(e,this._deck,[],this._props.layers),document.createElement("div")}_resolveLayers(e,r,i,n){ew(e,i,n)}onRemove(){let e=this._map;e&&(this._interleaved?this._onRemoveInterleaved(e):this._onRemoveOverlaid(e)),this._deck=void 0,this._map=void 0,this._container=void 0}_onRemoveOverlaid(e){e.off("resize",this._updateContainerSize),e.off("render",this._updateViewState),e.off("mousedown",this._handleMouseEvent),e.off("dragstart",this._handleMouseEvent),e.off("drag",this._handleMouseEvent),e.off("dragend",this._handleMouseEvent),e.off("mousemove",this._handleMouseEvent),e.off("mouseout",this._handleMouseEvent),e.off("click",this._handleMouseEvent),e.off("dblclick",this._handleMouseEvent),this._deck?.finalize()}_onRemoveInterleaved(e){e.off("styledata",this._handleStyleChange),this._resolveLayers(e,this._deck,this._props.layers,[]),iw(e)}getDefaultPosition(){return"top-left"}pickObject(e){return J(this._deck),this._deck.pickObject(e)}pickMultipleObjects(e){return J(this._deck),this._deck.pickMultipleObjects(e)}pickObjects(e){return J(this._deck),this._deck.pickObjects(e)}finalize(){this._map&&this._map.removeControl(this)}getCanvas(){return this._map?this._interleaved?this._map.getCanvas():this._deck.getCanvas():null}_getViews(e){if(!this._props.views)return aa(e);let r=Array.isArray(this._props.views)?this._props.views:[this._props.views];return r.some(n=>n.id===Di)?this._props.views:[aa(e),...r]}};var ow=`#version 300 es +#define SHADER_NAME animated-flow-lines-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in float sourceToTarget; +in vec2 uv; + +out vec4 fragColor; + +void main(void) { + geometry.uv = uv; + + fragColor = vec4(vColor.xyz, vColor.w * smoothstep(1.0 - animatedFlowLines.animationTailLength, 1.0, fract(sourceToTarget))); + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var sw=`#version 300 es +#define SHADER_NAME animated-flow-lines-layer-vertex-shader +#define SPEED 0.015 +#define NUM_PARTS 5.0 + +in vec3 positions; +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec4 instanceColors; +in vec3 instancePickingColors; +in float instanceWidths; +in float instancePickable; +in float instanceStaggering; + +out vec4 vColor; +out float sourceToTarget; +out vec2 uv; + +// offset vector by strokeWidth pixels +// offset_direction is -1 (left) or 1 (right) +vec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) { + // normalized direction of the line + vec2 dir_screenspace = normalize(line_clipspace * project.viewportSize); + // rotate by 90 degrees + dir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x); + + return dir_screenspace * offset_direction * width / 2.0; +} + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + // Position + vec4 source_commonspace; + vec4 target_commonspace; + vec4 source = project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace); + vec4 target = project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace); + + float widthPixels = instanceWidths * animatedFlowLines.thicknessUnit; + + + // linear interpolation of source & target to pick right coord + float segmentIndex = positions.x; + vec4 p = mix(source, target, segmentIndex); + geometry.position = mix(source_commonspace, target_commonspace, segmentIndex); + uv = positions.xy; + geometry.uv = uv; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + // extrude + vec3 offset = vec3( + getExtrusionOffset(target.xy - source.xy, positions.y, widthPixels), + 0.0); + DECKGL_FILTER_SIZE(offset, geometry); + gl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + // Color + vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + DECKGL_FILTER_COLOR(vColor, geometry); + + sourceToTarget = positions.x * length(source - target) * NUM_PARTS - animatedFlowLines.currentTime * SPEED + instanceStaggering; +} +`;var aw=`layout(std140) uniform animatedFlowLinesUniforms { + float thicknessUnit; + float animationTailLength; + float currentTime; +} animatedFlowLines; +`,cw={name:"animatedFlowLines",vs:aw,fs:aw,uniformTypes:{thicknessUnit:"f32",animationTailLength:"f32",currentTime:"f32"}};var kD=[0,132,193,255],fw=1800,UD=20,lw=fw/UD,vf=class extends ve{constructor(e){super(e)}getShaders(){return super.getShaders({vs:sw,fs:ow,modules:[Oe,Ne,cw]})}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{size:3,type:"float64",transition:!0,accessor:"getSourcePosition"},instanceTargetPositions:{size:3,type:"float64",transition:!0,accessor:"getTargetPosition"},instanceColors:{size:4,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:[0,0,0,255]},instanceWidths:{size:1,transition:!0,accessor:"getThickness",defaultValue:1},instanceStaggering:{accessor:"getStaggering",size:1,transition:!1},instancePickable:{accessor:"getPickable",size:1,transition:!1}}),this.setState({model:this._getModel()})}getNeedsRedraw(){return"animation"}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{thicknessUnit:e=30,animationTailLength:r=.7}=this.props,n=Date.now()/1e3%lw/lw*fw,o=this.state.model;o&&(o.shaderInputs.setProps({animatedFlowLines:{thicknessUnit:e*4,animationTailLength:r,currentTime:n}}),o.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props,r=[0,-1,0,0,1,0,1,-1,0,1,1,0];return new he(this.context.device,{...this.getShaders(),id:e,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(r)}}}),isInstanced:!0})}};vf.defaultProps={currentTime:0,animationTailLength:.7,getSourcePosition:{type:"accessor",value:t=>[0,0]},getTargetPosition:{type:"accessor",value:t=>[0,0]},getPickable:{type:"accessor",value:t=>1},getStaggering:{type:"accessor",value:(t,{index:e})=>Math.random()},getColor:{type:"accessor",value:kD},getThickness:{type:"accessor",value:1},thicknessUnit:30,parameters:{depthTest:!1}};var uw=vf;var ca=uw;var dw=`layout(std140) uniform flowLinesUniforms { + vec4 outlineColor; + float thicknessUnit; + float outlineThickness; + float drawOutline; + float gap; + float curviness; +} flowLines; +`,Ef={name:"flowLines",vs:dw,fs:dw,uniformTypes:{outlineColor:"vec4",thicknessUnit:"f32",outlineThickness:"f32",drawOutline:"f32",gap:"f32",curviness:"f32"}};var hw=`#version 300 es +#define SHADER_NAME curved-flow-line-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in vec2 uv; +in vec3 vBarycentrics; +flat in vec3 vEdgeMask; + +out vec4 fragColor; + +void main(void) { + if (vColor.a == 0.0) { + discard; + } + + geometry.uv = uv; + fragColor = vColor; + + if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) { + vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4)); + vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask)); + float minBoundaryDistancePx = min( + maskedDistancePx.x, + min(maskedDistancePx.y, maskedDistancePx.z) + ); + float outlineMix = 1.0 - smoothstep( + max(flowLines.outlineThickness - 1.0, 0.0), + flowLines.outlineThickness, + minBoundaryDistancePx + ); + fragColor = mix( + fragColor, + vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a), + outlineMix + ); + } + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var pw=.9583333333333334.toFixed(8),gw=`#version 300 es +#define SHADER_NAME curved-flow-line-layer-vertex-shader + +in vec3 positions; +in vec3 barycentrics; +in vec3 edgeMasks; +in vec4 instanceColors; +in float instanceThickness; +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec3 instancePickingColors; +in vec2 instanceEndpointOffsets; +in float instancePickable; +in float instanceCurveOffset; + +out vec4 vColor; +out vec2 uv; +out vec3 vBarycentrics; +flat out vec3 vEdgeMask; + +vec3 quadraticBezier(vec3 p0, vec3 p1, vec3 p2, float t) { + float oneMinusT = 1.0 - t; + return + oneMinusT * oneMinusT * p0 + + 2.0 * oneMinusT * t * p1 + + t * t * p2; +} + +vec3 quadraticBezierTangent(vec3 p0, vec3 p1, vec3 p2, float t) { + return 2.0 * (1.0 - t) * (p1 - p0) + 2.0 * t * (p2 - p1); +} + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + vec4 source_commonspace; + vec4 target_commonspace; + project_position_to_clipspace( + instanceSourcePositions, + instanceSourcePositions64Low, + vec3(0.0), + source_commonspace + ); + project_position_to_clipspace( + instanceTargetPositions, + instanceTargetPositions64Low, + vec3(0.0), + target_commonspace + ); + + vec2 chord = target_commonspace.xy - source_commonspace.xy; + float chordLengthCommon = max(length(chord), 1e-6); + float startTrim = clamp( + project_pixel_size(instanceEndpointOffsets.x) / chordLengthCommon, + 0.0, + 0.35 + ); + float endTrim = 1.0 - clamp( + project_pixel_size(instanceEndpointOffsets.y) / chordLengthCommon, + 0.0, + 0.35 + ); + endTrim = max(startTrim + 0.05, endTrim); + float baseHeadBacktrackT = project_pixel_size( + instanceThickness * 3.0 * flowLines.thicknessUnit + ) / chordLengthCommon; + float availableSpanT = max(endTrim - startTrim, 0.0); + float headBacktrackT = min(baseHeadBacktrackT, availableSpanT * 0.45); + float headScale = baseHeadBacktrackT > 1e-6 + ? clamp(headBacktrackT / baseHeadBacktrackT, 0.0, 1.0) + : 1.0; + // A soft nonlinear fade of the head deformation avoids tiny heads folding + // into themselves while still allowing them to collapse back toward the strip. + float headDeformation = smoothstep(0.0, 1.0, headScale); + float shaftEndTrim = max(startTrim + 0.02, endTrim - headBacktrackT); + + float curveT = positions.x < 1.0 + ? mix(startTrim, shaftEndTrim, positions.x / ${pw}) + : endTrim; + float headWeight = smoothstep(${pw}, 1.0, positions.x); + float tangentT = mix(curveT, endTrim, headWeight); + vec2 curveNormal = normalize(vec2(chord.y, -chord.x)); + if (length(curveNormal) < 1e-6) { + curveNormal = vec2(0.0, 1.0); + } + vec3 control_commonspace = mix( + source_commonspace.xyz, + target_commonspace.xyz, + 0.5 + ); + control_commonspace.xy += curveNormal * project_pixel_size(abs(instanceCurveOffset)) * flowLines.curviness; + + vec3 curvePoint = quadraticBezier( + source_commonspace.xyz, + control_commonspace, + target_commonspace.xyz, + curveT + ); + vec3 tangent = quadraticBezierTangent( + source_commonspace.xyz, + control_commonspace, + target_commonspace.xyz, + tangentT + ); + if (length(tangent.xy) < 1e-6) { + tangent = target_commonspace.xyz - source_commonspace.xyz; + } + + vec2 flowlineDir = normalize(tangent.xy); + vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x); + float widthScale = mix(1.0, headScale, headWeight); + float lengthScale = mix(1.0, headScale, headWeight); + float shapeY = mix(min(positions.y, 1.0), positions.y, headDeformation); + float shapeZ = positions.z * headDeformation; + float normalDistanceCommon = clamp( + project_pixel_size( + instanceThickness * shapeY * widthScale * flowLines.thicknessUnit + ), + -chordLengthCommon * 0.8, + chordLengthCommon * 0.8 + ); + float tangentDistanceCommon = clamp( + project_pixel_size( + instanceThickness * shapeZ * lengthScale * flowLines.thicknessUnit + ), + -chordLengthCommon * 0.8, + chordLengthCommon * 0.8 + ); + float gapCommon = project_pixel_size(flowLines.gap); + vec3 offsetCommon = vec3( + flowlineDir * tangentDistanceCommon - + perpendicularDir * (normalDistanceCommon + gapCommon), + 0.0 + ); + + geometry.position = vec4(curvePoint, 1.0); + uv = vec2(curveT, positions.y); + geometry.uv = uv; + vBarycentrics = barycentrics; + vEdgeMask = edgeMasks; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + DECKGL_FILTER_SIZE(offsetCommon, geometry); + vec4 position_commonspace = vec4(curvePoint + offsetCommon, 1.0); + gl_Position = project_common_position_to_clipspace(position_commonspace); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + vColor = fillColor; + DECKGL_FILTER_COLOR(vColor, geometry); +} +`;var zD=[0,132,193,255],Rf=24,vg=1-1/Rf,la=class extends ve{getShaders(){return super.getShaders({vs:gw,fs:hw,modules:[Oe,Ne,Ef]})}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{accessor:"getSourcePosition",size:3,transition:!1,type:"float64"},instanceTargetPositions:{accessor:"getTargetPosition",size:3,transition:!1,type:"float64"},instanceThickness:{accessor:"getThickness",size:1,transition:!1},instanceEndpointOffsets:{accessor:"getEndpointOffsets",size:2,transition:!1},instanceCurveOffset:{accessor:"getCurveOffset",size:1,transition:!1},instanceColors:{accessor:"getColor",size:4,type:"unorm8",transition:!1},instancePickable:{accessor:"getPickable",size:1,transition:!1}}),this.setState({model:this._getModel()})}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{drawOutline:e=!0,outlineColor:r=[255,255,255,255],outlineThickness:i=1,thicknessUnit:n=12,curviness:o=1}=this.props,s=this.state.model;s&&(s.shaderInputs.setProps({flowLines:{outlineColor:r.map(a=>a/255),thicknessUnit:n*2,outlineThickness:i,drawOutline:e?1:0,gap:.5,curviness:o}}),s.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props,r=WD();return new he(this.context.device,{id:e,...this.getShaders(),bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-list",attributes:{positions:{size:3,value:r.positions},barycentrics:{size:3,value:r.barycentrics},edgeMasks:{size:3,value:r.edgeMasks}}}),isInstanced:!0})}};la.layerName="CurvedFlowLinesLayer";la.defaultProps={getSourcePosition:{type:"accessor",value:t=>[0,0]},getTargetPosition:{type:"accessor",value:t=>[0,0]},getColor:{type:"accessor",value:zD},getThickness:{type:"accessor",value:t=>t.count},getPickable:{type:"accessor",value:()=>1},getCurveOffset:{type:"accessor",value:()=>0},drawOutline:!0,thicknessUnit:12,outlineThickness:1,outlineColor:[255,255,255,255],curviness:1,parameters:{depthTest:!1}};var mw=la;function WD(){let t=[],e=[],r=[],i=(n,o,s,a)=>{t.push(...n,...o,...s),e.push(1,0,0,0,1,0,0,0,1),r.push(...a,...a,...a)};for(let n=0;n 0.5 && !bool(picking.isActive)) { + // For barycentric coordinates, each component trends to 0 on one triangle edge. + // Dividing by fwidth converts that into an approximate edge distance in pixels. + vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4)); + // Ignore edges that are only part of the internal triangulation by assigning + // them a large sentinel distance, so only true boundary edges contribute. + vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask)); + float minBoundaryDistancePx = min( + maskedDistancePx.x, + min(maskedDistancePx.y, maskedDistancePx.z) + ); + // The outline is inset: fragments within 'outlineThickness' pixels of an + // active boundary edge are mixed toward the outline color. + float outlineMix = 1.0 - smoothstep( + max(flowLines.outlineThickness - 1.0, 0.0), + flowLines.outlineThickness, + minBoundaryDistancePx + ); + fragColor = mix( + fragColor, + vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a), + outlineMix + ); + } + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var yw=`#version 300 es +#define SHADER_NAME flow-line-layer-vertex-shader + +in vec3 positions; +in vec2 pixelOffsets; +in vec2 outlineOffsetCoefficients; +in vec2 outlineOffsetConstants; +in vec3 barycentrics; +in vec3 edgeMasks; +in vec4 instanceColors; +in float instanceThickness; // 0..0.5 +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec3 instancePickingColors; +in vec2 instanceEndpointOffsets; +in float instancePickable; + +out vec4 vColor; +out vec2 uv; +// Interpolated barycentric coordinates let the fragment shader measure distance +// to triangle edges in screen pixels without extra geometry. +out vec3 vBarycentrics; +// The edge mask is constant per triangle and tells the fragment shader which +// barycentric edges are real outline candidates vs internal triangulation seams. +flat out vec3 vEdgeMask; + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + // Position + vec4 source_commonspace; + vec4 target_commonspace; + project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace); + project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace); + + // linear interpolation of source & target to pick right coord + float sourceOrTarget = positions.x; + geometry.position = mix(source_commonspace, target_commonspace, sourceOrTarget); + uv = positions.xy; + geometry.uv = uv; + vBarycentrics = barycentrics; + vEdgeMask = edgeMasks; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + // set the clamp limits in pixel size + float lengthCommon = length(target_commonspace - source_commonspace); + vec2 limitedOffsetDistances = clamp( + project_pixel_size(positions.yz) * flowLines.thicknessUnit, + -lengthCommon*.8, lengthCommon*.8 + ); + float startOffsetCommon = project_pixel_size(instanceEndpointOffsets[0]); + float endOffsetCommon = project_pixel_size(instanceEndpointOffsets[1]); + float endpointOffset = mix( + clamp(startOffsetCommon, 0.0, lengthCommon*.2), + -clamp(endOffsetCommon, 0.0, lengthCommon*.2), + positions.x + ); + + vec2 flowlineDir = normalize(target_commonspace.xy - source_commonspace.xy); + vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x); + vec2 outlinePixelOffset = ( + outlineOffsetCoefficients * flowLines.outlineThickness + + outlineOffsetConstants + ) * flowLines.drawOutline; + vec2 pixelOffsetCommon = project_pixel_size(pixelOffsets + outlinePixelOffset); + float gapCommon = project_pixel_size(flowLines.gap); + vec3 offsetCommon = vec3( + flowlineDir * (instanceThickness * limitedOffsetDistances[1] + pixelOffsetCommon.y + endpointOffset * 1.05) - + perpendicularDir * (instanceThickness * limitedOffsetDistances[0] + gapCommon + pixelOffsetCommon.x), + 0.0 + ); + + DECKGL_FILTER_SIZE(offsetCommon, geometry); + vec4 position_commonspace = mix(source_commonspace, target_commonspace, sourceOrTarget); + vec4 offset_commonspace = vec4(offsetCommon, 0.0); + gl_Position = project_common_position_to_clipspace(position_commonspace + offset_commonspace); + + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + vColor = fillColor; + DECKGL_FILTER_COLOR(vColor, geometry); +} +`;var VD=[0,132,193,255],jD=[1,0,0,1,2,-3,1,1,-3,1,0,0,1,1,-3,0,1,0,1,0,0,0,1,0,0,0,0],Cf=.5,$D=new Float32Array(18),HD=new Float32Array([0,2,2,-1,1,-1,0,2,1,-1,1,-1,0,2,1,-1,0,-1]),YD=new Float32Array([-Cf,0,0,0,0,0,-Cf,0,0,0,0,0,-Cf,0,0,0,-Cf,0]),XD=new Float32Array([1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1]),GD=new Float32Array([1,0,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,1,1,0,1,1,0,1,1,0]),fa=class extends ve{constructor(e){super(e)}getShaders(){return super.getShaders({vs:yw,fs:_w,modules:[Oe,Ne,Ef]})}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{accessor:"getSourcePosition",size:3,transition:!1,type:"float64"},instanceTargetPositions:{accessor:"getTargetPosition",size:3,transition:!1,type:"float64"},instanceThickness:{accessor:"getThickness",size:1,transition:!1},instanceEndpointOffsets:{accessor:"getEndpointOffsets",size:2,transition:!1},instanceColors:{accessor:"getColor",size:4,type:"unorm8",transition:!1},instancePickable:{accessor:"getPickable",size:1,transition:!1}}),this.setState({model:this._getModel()})}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{drawOutline:e=!0,outlineColor:r=[255,255,255,255],outlineThickness:i=1,thicknessUnit:n=12}=this.props,o=this.state.model;o&&(o.shaderInputs.setProps({flowLines:{outlineColor:r.map(s=>s/255),thicknessUnit:n*2,outlineThickness:i,drawOutline:e?1:0,gap:.5,curviness:1}}),o.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props;return new he(this.context.device,{id:e,...this.getShaders(),bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-list",attributes:{positions:{size:3,value:new Float32Array(jD)},pixelOffsets:{size:2,value:$D},outlineOffsetCoefficients:{size:2,value:HD},outlineOffsetConstants:{size:2,value:YD},barycentrics:{size:3,value:XD},edgeMasks:{size:3,value:GD}}}),isInstanced:!0})}};fa.layerName="FlowLinesLayer";fa.defaultProps={getSourcePosition:{type:"accessor",value:t=>[0,0]},getTargetPosition:{type:"accessor",value:t=>[0,0]},getColor:{type:"accessor",value:VD},getThickness:{type:"accessor",value:t=>t.count},getPickable:{type:"accessor",value:t=>1},drawOutline:!0,thicknessUnit:12,outlineThickness:1,outlineColor:[255,255,255,255],parameters:{depthTest:!1}};var xw=fa;var jn=xw;var bw=`#version 300 es +#define SHADER_NAME flow-circles-layer-fragment-shader +#define SOFT_OUTLINE 0.05 +#define EPS 0.05 +precision highp float; + +in vec4 vColor; +in vec2 unitPosition; +in float unitInRadius; +in float unitOutRadius; + +out vec4 fragColor; + +float when_gt(float x, float y) { + return max(sign(x - y), 0.0); +} + +void main(void) { + geometry.uv = unitPosition; + float distToCenter = length(unitPosition); + if (distToCenter > 1.0) { + discard; + } + + // See https://stackoverflow.com/questions/47285778 + vec4 ringColor = mix( + flowCircles.emptyColor, vColor, + when_gt(unitInRadius, unitOutRadius) + ); + vec4 outlineColor = mix( + mix(vColor, flowCircles.emptyColor, flowCircles.outlineEmptyMix), + vColor, + when_gt(unitInRadius, unitOutRadius) + ); + + float innerR = min(unitInRadius, unitOutRadius) * (1.0 - SOFT_OUTLINE); + + // Inner circle + float step2 = innerR - 2.0 * EPS; + float step3 = innerR - EPS; + + // Ring + float step4 = innerR; + // float step5 = 1.0 - SOFT_OUTLINE - EPS; + // float step6 = 1.0 - SOFT_OUTLINE; + float step5 = 1.0 - 5.0 * EPS; + float step6 = 1.0; + + fragColor = vColor; + fragColor = mix(fragColor, flowCircles.emptyColor, smoothstep(step2, step3, distToCenter)); + fragColor = mix(fragColor, ringColor, smoothstep(step3, step4, distToCenter)); + fragColor = mix(fragColor, outlineColor, smoothstep(step5, step6, distToCenter)); + fragColor.a = vColor.a; + fragColor.a *= smoothstep(0.0, SOFT_OUTLINE, 1.0 - distToCenter); + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var Tw=`#version 300 es +#define SHADER_NAME flow-circles-layer-vertex-shader +#define radiusScale 100 + +in vec3 positions; + +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceInRadius; +in float instanceOutRadius; +in vec4 instanceColors; +in vec3 instancePickingColors; + +out vec4 vColor; +out vec2 unitPosition; +out float unitInRadius; +out float unitOutRadius; + +void main(void) { + geometry.worldPosition = instancePositions; + + float outerRadiusPixels = max(instanceInRadius, instanceOutRadius); + unitInRadius = instanceInRadius / outerRadiusPixels; + unitOutRadius = instanceOutRadius / outerRadiusPixels; + + // position on the containing square in [-1, 1] space + unitPosition = positions.xy; + geometry.uv = unitPosition; + geometry.pickingColor = instancePickingColors; + + // Find the center of the point and add the current vertex + vec3 offset = positions * project_pixel_size(outerRadiusPixels); + DECKGL_FILTER_SIZE(offset, geometry); + gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + // Apply opacity to instance color, or return instance picking color + vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + DECKGL_FILTER_COLOR(vColor, geometry); +} +`;var ww=`layout(std140) uniform flowCirclesUniforms { + vec4 emptyColor; + float outlineEmptyMix; +} flowCircles; +`,Sw={name:"flowCircles",vs:ww,fs:ww,uniformTypes:{emptyColor:"vec4",outlineEmptyMix:"f32"}};var Aw=[0,0,0,255],vw=[255,255,255,255],Ew=.4,ua=class extends ve{constructor(e){super(e)}getShaders(){return super.getShaders({vs:Tw,fs:bw,modules:[Oe,Ne,Sw]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceInRadius:{size:1,transition:!0,accessor:"getInRadius",defaultValue:1},instanceOutRadius:{size:1,transition:!0,accessor:"getOutRadius",defaultValue:1},instanceColors:{size:4,transition:!0,type:"unorm8",accessor:"getColor",defaultValue:Aw}}),this.setState({model:this._getModel()})}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{emptyColor:e=vw,outlineEmptyMix:r=Ew}=this.props,i=this.state.model;i&&(i.shaderInputs.setProps({flowCircles:{emptyColor:e.map(n=>n/255),outlineEmptyMix:r}}),i.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props,r=[-1,-1,0,1,-1,0,-1,1,0,1,1,0];return new he(this.context.device,{...this.getShaders(),id:e,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(r)}}}),isInstanced:!0})}};ua.layerName="FlowCirclesLayer";ua.defaultProps={getColor:{type:"accessor",value:Aw},emptyColor:{type:"accessor",value:vw},outlineEmptyMix:{type:"accessor",value:Ew},getPosition:{type:"accessor",value:t=>t.position},getInRadius:{type:"accessor",value:1},getOutRadius:{type:"accessor",value:1},parameters:{depthTest:!1}};var Rw=ua;var da=Rw;var Cw=`layout(std140) uniform iconUniforms { + float sizeScale; + vec2 iconsTextureDim; + float sizeBasis; + float sizeMinPixels; + float sizeMaxPixels; + bool billboard; + highp int sizeUnits; + float alphaCutoff; +} icon; +`,Pw={name:"icon",vs:Cw,fs:Cw,uniformTypes:{sizeScale:"f32",iconsTextureDim:"vec2",sizeBasis:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",billboard:"f32",sizeUnits:"i32",alphaCutoff:"f32"}};var Mw=`#version 300 es +#define SHADER_NAME icon-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceSizes; +in float instanceAngles; +in vec4 instanceColors; +in vec3 instancePickingColors; +in vec4 instanceIconFrames; +in float instanceColorModes; +in vec2 instanceOffsets; +in vec2 instancePixelOffset; +out float vColorMode; +out vec4 vColor; +out vec2 vTextureCoords; +out vec2 uv; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = angle * PI / 180.0; +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vec2 iconSize = instanceIconFrames.zw; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits), +icon.sizeMinPixels, icon.sizeMaxPixels +); +float iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y; +float instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint; +vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets; +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale; +pixelOffset += instancePixelOffset; +pixelOffset.y *= -1.0; +if (icon.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +DECKGL_FILTER_SIZE(offset_common, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vTextureCoords = mix( +instanceIconFrames.xy, +instanceIconFrames.xy + iconSize, +(positions.xy + 1.0) / 2.0 +) / icon.iconsTextureDim; +vColor = instanceColors; +DECKGL_FILTER_COLOR(vColor, geometry); +vColorMode = instanceColorModes; +} +`;var Iw=`#version 300 es +#define SHADER_NAME icon-layer-fragment-shader +precision highp float; +uniform sampler2D iconsTexture; +in float vColorMode; +in vec4 vColor; +in vec2 vTextureCoords; +in vec2 uv; +out vec4 fragColor; +void main(void) { +geometry.uv = uv; +vec4 texColor = texture(iconsTexture, vTextureCoords); +vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode); +float a = texColor.a * layer.opacity * vColor.a; +if (a < icon.alphaCutoff) { +discard; +} +fragColor = vec4(color, a); +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var Ow=`struct IconUniforms { + sizeScale: f32, + iconsTextureDim: vec2, + sizeBasis: f32, + sizeMinPixels: f32, + sizeMaxPixels: f32, + billboard: i32, + sizeUnits: i32, + alphaCutoff: f32 +}; + +@group(0) @binding(auto) var icon: IconUniforms; +@group(0) @binding(auto) var iconsTexture : texture_2d; +@group(0) @binding(auto) var iconsTextureSampler : sampler; + +fn rotate_by_angle(vertex: vec2, angle_deg: f32) -> vec2 { + let angle_radian = angle_deg * PI / 180.0; + let c = cos(angle_radian); + let s = sin(angle_radian); + let rotation = mat2x2(vec2(c, s), vec2(-s, c)); + return rotation * vertex; +} + +struct Attributes { + @location(0) positions: vec2, + + @location(1) instancePositions: vec3, + @location(2) instancePositions64Low: vec3, + @location(3) instanceSizes: f32, + @location(4) instanceAngles: f32, + @location(5) instanceColors: vec4, + @location(6) instancePickingColors: vec3, + @location(7) instanceIconFrames: vec4, + @location(8) instanceColorModes: f32, + @location(9) instanceOffsets: vec2, + @location(10) instancePixelOffset: vec2, +}; + +struct Varyings { + @builtin(position) position: vec4, + + @location(0) vColorMode: f32, + @location(1) vColor: vec4, + @location(2) vTextureCoords: vec2, + @location(3) uv: vec2, + @location(4) pickingColor: vec3, +}; + +@vertex +fn vertexMain(inp: Attributes) -> Varyings { + // write geometry fields used by filters + FS + geometry.worldPosition = inp.instancePositions; + geometry.uv = inp.positions; + geometry.pickingColor = inp.instancePickingColors; + + var outp: Varyings; + outp.uv = inp.positions; + + let iconSize = inp.instanceIconFrames.zw; + + // convert size in meters to pixels, then clamp + let sizePixels = clamp( + project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits), + icon.sizeMinPixels, icon.sizeMaxPixels + ); + + // scale icon height to match instanceSize + let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0); + let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0); + + // scale and rotate vertex in "pixel" units; then add per-instance pixel offset + var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets; + pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale; + pixelOffset = pixelOffset + inp.instancePixelOffset; + pixelOffset.y = pixelOffset.y * -1.0; + + if (icon.billboard != 0) { + var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3(0.0)); // TODO, &geometry.position); + // DECKGL_FILTER_GL_POSITION(pos, geometry); + + var offset = vec3(pixelOffset, 0.0); + // DECKGL_FILTER_SIZE(offset, geometry); + let clipOffset = project_pixel_size_to_clipspace(offset.xy); + pos = vec4(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w); + outp.position = pos; + } else { + var offset_common = vec3(project_pixel_size_vec2(pixelOffset), 0.0); + // DECKGL_FILTER_SIZE(offset_common, geometry); + var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position); + // DECKGL_FILTER_GL_POSITION(pos, geometry); + outp.position = pos; + } + + let uvMix = (inp.positions.xy + vec2(1.0, 1.0)) * 0.5; + outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim; + + outp.vColor = inp.instanceColors; + // DECKGL_FILTER_COLOR(outp.vColor, geometry); + + outp.vColorMode = inp.instanceColorModes; + outp.pickingColor = inp.instancePickingColors; + + return outp; +} + +@fragment +fn fragmentMain(inp: Varyings) -> @location(0) vec4 { + // expose to deck.gl filter hooks + geometry.uv = inp.uv; + + let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords); + + // if colorMode == 0, use pixel color from the texture + // if colorMode == 1 (or picking), use texture as transparency mask + let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode); + let a = texColor.a * layer.opacity * inp.vColor.a; + + if (a < icon.alphaCutoff) { + discard; + } + + if (picking.isActive > 0.5) { + if (!picking_isColorValid(inp.pickingColor)) { + discard; + } + return vec4(inp.pickingColor, 1.0); + } + + var fragColor = deckgl_premultiplied_alpha(vec4(rgb, a)); + + if (picking.isHighlightActive > 0.5) { + let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) { + let highLightAlpha = picking.highlightColor.a; + let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); + if (blendedAlpha > 0.0) { + let highLightRatio = highLightAlpha / blendedAlpha; + fragColor = vec4( + mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), + blendedAlpha + ); + } else { + fragColor = vec4(fragColor.rgb, 0.0); + } + } + } + + return fragColor; +} +`;var qD=1024,KD=4,Nw=()=>{},Dw={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},ZD={x:0,y:0,width:0,height:0};function QD(t){return Math.pow(2,Math.ceil(Math.log2(t)))}function JD(t,e,r,i){let n=Math.min(r/e.width,i/e.height),o=Math.floor(e.width*n),s=Math.floor(e.height*n);return n===1?{image:e,width:o,height:s}:(t.canvas.height=s,t.canvas.width=o,t.clearRect(0,0,o,s),t.drawImage(e,0,0,e.width,e.height,0,0,o,s),{image:t.canvas,width:o,height:s})}function ha(t){return t&&(t.id||t.url)}function Fw(t){let{device:e}=t;e.type==="webgl"?t.generateMipmapsWebGL():e.type==="webgpu"&&e.generateMipmapsWebGPU(t)}function eL(t,e,r,i){let{width:n,height:o,device:s}=t,a=s.createTexture({format:"rgba8unorm",width:e,height:r,sampler:i,mipLevels:s.getMipLevelCount(e,r)}),c=s.createCommandEncoder();c.copyTextureToTexture({sourceTexture:t,destinationTexture:a,width:n,height:o});let l=c.finish();return s.submit(l),Fw(a),t.destroy(),a}function Lw(t,e,r){for(let i=0;is&&(Lw(r,a,n),i=0,n=o+n+e,o=0,a=[]),a.push({icon:l,xOffset:i}),i=i+d+e,o=Math.max(o,u)}}return a.length>0&&Lw(r,a,n),{mapping:r,rowHeight:o,xOffset:i,yOffset:n,canvasWidth:s,canvasHeight:QD(o+n+e)}}function rL(t,e,r){if(!t||!e)return null;r=r||{};let i={},{iterable:n,objectInfo:o}=mr(t);for(let s of n){o.index++;let a=e(s,o),c=ha(a);if(!a)throw new Error("Icon is missing.");if(!a.url)throw new Error("Icon url is missing.");!i[c]&&(!r[c]||a.url!==r[c].url)&&(i[c]={...a,source:s,sourceIndex:o.index})}return i}var pa=class{constructor(e,{onUpdate:r=Nw,onError:i=Nw}){this._loadOptions=null,this._texture=null,this._externalTexture=null,this._mapping={},this._samplerParameters=null,this._pendingCount=0,this._autoPacking=!1,this._xOffset=0,this._yOffset=0,this._rowHeight=0,this._buffer=KD,this._canvasWidth=qD,this._canvasHeight=0,this._canvas=null,this.device=e,this.onUpdate=r,this.onError=i}finalize(){this._texture?.delete()}getTexture(){return this._texture||this._externalTexture}getIconMapping(e){let r=this._autoPacking?ha(e):e;return this._mapping[r]||ZD}setProps({loadOptions:e,autoPacking:r,iconAtlas:i,iconMapping:n,textureParameters:o}){e&&(this._loadOptions=e),r!==void 0&&(this._autoPacking=r),n&&(this._mapping=n),i&&(this._texture?.delete(),this._texture=null,this._externalTexture=i),o&&(this._samplerParameters=o)}get isLoaded(){return this._pendingCount===0}packIcons(e,r){if(!this._autoPacking||typeof document>"u")return;let i=Object.values(rL(e,r,this._mapping)||{});if(i.length>0){let{mapping:n,xOffset:o,yOffset:s,rowHeight:a,canvasHeight:c}=tL({icons:i,buffer:this._buffer,canvasWidth:this._canvasWidth,mapping:this._mapping,rowHeight:this._rowHeight,xOffset:this._xOffset,yOffset:this._yOffset});this._rowHeight=a,this._mapping=n,this._xOffset=o,this._yOffset=s,this._canvasHeight=c,this._texture||(this._texture=this.device.createTexture({format:"rgba8unorm",data:null,width:this._canvasWidth,height:this._canvasHeight,sampler:this._samplerParameters||Dw,mipLevels:this.device.getMipLevelCount(this._canvasWidth,this._canvasHeight)})),this._texture.height!==this._canvasHeight&&(this._texture=eL(this._texture,this._canvasWidth,this._canvasHeight,this._samplerParameters||Dw)),this.onUpdate(!0),this._canvas=this._canvas||document.createElement("canvas"),this._loadIcons(i)}}_loadIcons(e){let r=this._canvas.getContext("2d",{willReadFrequently:!0});for(let i of e)this._pendingCount++,Mr(i.url,this._loadOptions).then(n=>{let o=ha(i),s=this._mapping[o],{x:a,y:c,width:l,height:f}=s,{image:u,width:d,height:h}=JD(r,n,l,f),p=a+(l-d)/2,g=c+(f-h)/2;this._texture?.copyExternalImage({image:u,x:p,y:g,width:d,height:h}),s.x=p,s.y=g,s.width=d,s.height=h,this._texture&&Fw(this._texture),this.onUpdate(d!==l||h!==f)}).catch(n=>{this.onError({url:i.url,source:i.source,sourceIndex:i.sourceIndex,loadOptions:this._loadOptions,error:n})}).finally(()=>{this._pendingCount--})}};var Bw=[0,0,0,255],iL={iconAtlas:{type:"image",value:null,async:!0},iconMapping:{type:"object",value:{},async:!0},sizeScale:{type:"number",value:1,min:0},billboard:!0,sizeUnits:"pixels",sizeBasis:"height",sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},alphaCutoff:{type:"number",value:.05,min:0,max:1},getPosition:{type:"accessor",value:t=>t.position},getIcon:{type:"accessor",value:t=>t.icon},getColor:{type:"accessor",value:Bw},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},onIconError:{type:"function",value:null,optional:!0},textureParameters:{type:"object",ignore:!0,value:null}},ga=class extends ve{getShaders(){return super.getShaders({vs:Mw,fs:Iw,source:Ow,modules:[Oe,mn,Ne,Pw]})}initializeState(){this.state={iconManager:new pa(this.context.device,{onUpdate:this._onUpdate.bind(this),onError:this._onError.bind(this)})},this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,accessor:"getSize",defaultValue:1},instanceIconDefs:{size:7,accessor:"getIcon",transform:this.getInstanceIconDef,shaderAttributes:{instanceOffsets:{size:2,elementOffset:0},instanceIconFrames:{size:4,elementOffset:2},instanceColorModes:{size:1,elementOffset:6}}},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:Bw},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instancePixelOffset:{size:2,transition:!0,accessor:"getPixelOffset"}})}updateState(e){super.updateState(e);let{props:r,oldProps:i,changeFlags:n}=e,o=this.getAttributeManager(),{iconAtlas:s,iconMapping:a,data:c,getIcon:l,textureParameters:f}=r,{iconManager:u}=this.state;if(typeof s=="string")return;let d=s||this.internalState.isAsyncPropLoading("iconAtlas");u.setProps({loadOptions:r.loadOptions,autoPacking:!d,iconAtlas:s,iconMapping:d?a:null,textureParameters:f}),d?i.iconMapping!==r.iconMapping&&o.invalidate("getIcon"):(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getIcon))&&u.packIcons(c,l),n.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),o.invalidateAll())}get isLoaded(){return super.isLoaded&&this.state.iconManager.isLoaded}finalizeState(e){super.finalizeState(e),this.state.iconManager.finalize()}draw({uniforms:e}){let{sizeScale:r,sizeBasis:i,sizeMinPixels:n,sizeMaxPixels:o,sizeUnits:s,billboard:a,alphaCutoff:c}=this.props,{iconManager:l}=this.state,f=l.getTexture();if(f){let u=this.state.model,d={iconsTexture:f,iconsTextureDim:[f.width,f.height],sizeUnits:je[s],sizeScale:r,sizeBasis:i==="height"?1:0,sizeMinPixels:n,sizeMaxPixels:o,billboard:a,alphaCutoff:c};u.shaderInputs.setProps({icon:d}),u.draw(this.context.renderPass)}}_getModel(){let e=[-1,-1,1,-1,-1,1,1,1];return new he(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array(e)}}}),isInstanced:!0})}_onUpdate(e){e?(this.getAttributeManager()?.invalidate("getIcon"),this.setNeedsUpdate()):this.setNeedsRedraw()}_onError(e){let r=this.getCurrentLayer()?.props.onIconError;r?r(e):F.error(e.error.message)()}getInstanceIconDef(e){let{x:r,y:i,width:n,height:o,mask:s,anchorX:a=n/2,anchorY:c=o/2}=this.state.iconManager.getIconMapping(e);return[n/2-a,o/2-c,r,i,n,o,s?1:0]}};ga.defaultProps=iL;ga.layerName="IconLayer";var kw=ga;var Uw=`layout(std140) uniform scatterplotUniforms { + float radiusScale; + float radiusMinPixels; + float radiusMaxPixels; + float lineWidthScale; + float lineWidthMinPixels; + float lineWidthMaxPixels; + float stroked; + float filled; + bool antialiasing; + bool billboard; + highp int radiusUnits; + highp int lineWidthUnits; +} scatterplot; +`,zw={name:"scatterplot",vs:Uw,fs:Uw,source:"",uniformTypes:{radiusScale:"f32",radiusMinPixels:"f32",radiusMaxPixels:"f32",lineWidthScale:"f32",lineWidthMinPixels:"f32",lineWidthMaxPixels:"f32",stroked:"f32",filled:"f32",antialiasing:"f32",billboard:"f32",radiusUnits:"i32",lineWidthUnits:"i32"}};var Ww=`#version 300 es +#define SHADER_NAME scatterplot-layer-vertex-shader +in vec3 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceRadius; +in float instanceLineWidths; +in vec4 instanceFillColors; +in vec4 instanceLineColors; +in vec3 instancePickingColors; +out vec4 vFillColor; +out vec4 vLineColor; +out vec2 unitPosition; +out float innerUnitRadius; +out float outerRadiusPixels; +void main(void) { +geometry.worldPosition = instancePositions; +outerRadiusPixels = clamp( +project_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits), +scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels +); +float lineWidthPixels = clamp( +project_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits), +scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels +); +outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; +float edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0; +unitPosition = edgePadding * positions.xy; +geometry.uv = unitPosition; +geometry.pickingColor = instancePickingColors; +innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels; +if (scatterplot.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = edgePadding * positions * outerRadiusPixels; +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vFillColor, geometry); +vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vLineColor, geometry); +} +`;var Vw=`#version 300 es +#define SHADER_NAME scatterplot-layer-fragment-shader +precision highp float; +in vec4 vFillColor; +in vec4 vLineColor; +in vec2 unitPosition; +in float innerUnitRadius; +in float outerRadiusPixels; +out vec4 fragColor; +void main(void) { +geometry.uv = unitPosition; +float distToCenter = length(unitPosition) * outerRadiusPixels; +float inCircle = scatterplot.antialiasing ? +smoothedge(distToCenter, outerRadiusPixels) : +step(distToCenter, outerRadiusPixels); +if (inCircle == 0.0) { +discard; +} +if (scatterplot.stroked > 0.5) { +float isLine = scatterplot.antialiasing ? +smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) : +step(innerUnitRadius * outerRadiusPixels, distToCenter); +if (scatterplot.filled > 0.5) { +fragColor = mix(vFillColor, vLineColor, isLine); +} else { +if (isLine == 0.0) { +discard; +} +fragColor = vec4(vLineColor.rgb, vLineColor.a * isLine); +} +} else if (scatterplot.filled < 0.5) { +discard; +} else { +fragColor = vFillColor; +} +fragColor.a *= inCircle; +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var jw=`// Main shaders + +struct ScatterplotUniforms { + radiusScale: f32, + radiusMinPixels: f32, + radiusMaxPixels: f32, + lineWidthScale: f32, + lineWidthMinPixels: f32, + lineWidthMaxPixels: f32, + stroked: f32, + filled: i32, + antialiasing: i32, + billboard: i32, + radiusUnits: i32, + lineWidthUnits: i32, +}; + +struct ConstantAttributeUniforms { + instancePositions: vec3, + instancePositions64Low: vec3, + instanceRadius: f32, + instanceLineWidths: f32, + instanceFillColors: vec4, + instanceLineColors: vec4, + instancePickingColors: vec3, + + instancePositionsConstant: i32, + instancePositions64LowConstant: i32, + instanceRadiusConstant: i32, + instanceLineWidthsConstant: i32, + instanceFillColorsConstant: i32, + instanceLineColorsConstant: i32, + instancePickingColorsConstant: i32 +}; + +@group(0) @binding(0) var scatterplot: ScatterplotUniforms; + +struct ConstantAttributes { + instancePositions: vec3, + instancePositions64Low: vec3, + instanceRadius: f32, + instanceLineWidths: f32, + instanceFillColors: vec4, + instanceLineColors: vec4, + instancePickingColors: vec3 +}; + +const constants = ConstantAttributes( + vec3(0.0), + vec3(0.0), + 0.0, + 0.0, + vec4(0.0, 0.0, 0.0, 1.0), + vec4(0.0, 0.0, 0.0, 1.0), + vec3(0.0) +); + +struct Attributes { + @builtin(instance_index) instanceIndex : u32, + @builtin(vertex_index) vertexIndex : u32, + @location(0) positions: vec3, + @location(1) instancePositions: vec3, + @location(2) instancePositions64Low: vec3, + @location(3) instanceRadius: f32, + @location(4) instanceLineWidths: f32, + @location(5) instanceFillColors: vec4, + @location(6) instanceLineColors: vec4, + @location(7) instancePickingColors: vec3, +}; + +struct Varyings { + @builtin(position) position: vec4, + @location(0) vFillColor: vec4, + @location(1) vLineColor: vec4, + @location(2) unitPosition: vec2, + @location(3) innerUnitRadius: f32, + @location(4) outerRadiusPixels: f32, + @location(5) pickingColor: vec3, +}; + +@vertex +fn vertexMain(attributes: Attributes) -> Varyings { + var varyings: Varyings; + + // Draw an inline geometry constant array clip space triangle to verify that rendering works. + // var positions = array, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5)); + // if (attributes.instanceIndex == 0) { + // varyings.position = vec4(positions[attributes.vertexIndex], 0.0, 1.0); + // return varyings; + // } + + geometry.worldPosition = attributes.instancePositions; + + // Multiply out radius and clamp to limits + varyings.outerRadiusPixels = clamp( + project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits), + scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels + ); + + // Multiply out line width and clamp to limits + let lineWidthPixels = clamp( + project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits), + scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels + ); + + // outer radius needs to offset by half stroke width + varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; + // Expand geometry to accommodate edge smoothing + let edgePadding = select( + (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels, + 1.0, + scatterplot.antialiasing != 0 + ); + + // position on the containing square in [-1, 1] space + varyings.unitPosition = edgePadding * attributes.positions.xy; + geometry.uv = varyings.unitPosition; + geometry.pickingColor = attributes.instancePickingColors; + + varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels; + + if (scatterplot.billboard != 0) { + varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3(0.0)); // TODO , geometry.position); + // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); + let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels; + // DECKGL_FILTER_SIZE(offset, geometry); + let clipPixels = project_pixel_size_to_clipspace(offset.xy); + varyings.position.x = clipPixels.x; + varyings.position.y = clipPixels.y; + } else { + let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels); + // DECKGL_FILTER_SIZE(offset, geometry); + varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position); + // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); + } + + // Apply opacity to instance color, or return instance picking color + varyings.vFillColor = vec4(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity); + // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry); + varyings.vLineColor = vec4(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity); + // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry); + varyings.pickingColor = attributes.instancePickingColors; + + return varyings; +} + +@fragment +fn fragmentMain(varyings: Varyings) -> @location(0) vec4 { + // var geometry: Geometry; + // geometry.uv = unitPosition; + + let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels; + let inCircle = select( + smoothedge(distToCenter, varyings.outerRadiusPixels), + step(distToCenter, varyings.outerRadiusPixels), + scatterplot.antialiasing != 0 + ); + + if (inCircle == 0.0) { + discard; + } + + var fragColor: vec4; + + if (scatterplot.stroked != 0) { + let isLine = select( + smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), + step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), + scatterplot.antialiasing != 0 + ); + + if (scatterplot.filled != 0) { + fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine); + } else { + if (isLine == 0.0) { + discard; + } + fragColor = vec4(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine); + } + } else if (scatterplot.filled == 0) { + discard; + } else { + fragColor = varyings.vFillColor; + } + + fragColor.a *= inCircle; + + if (picking.isActive > 0.5) { + if (!picking_isColorValid(varyings.pickingColor)) { + discard; + } + return vec4(varyings.pickingColor, 1.0); + } + + if (picking.isHighlightActive > 0.5) { + let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) { + let highLightAlpha = picking.highlightColor.a; + let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); + if (blendedAlpha > 0.0) { + let highLightRatio = highLightAlpha / blendedAlpha; + fragColor = vec4( + mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), + blendedAlpha + ); + } else { + fragColor = vec4(fragColor.rgb, 0.0); + } + } + } + + // Apply premultiplied alpha as required by transparent canvas + fragColor = deckgl_premultiplied_alpha(fragColor); + + return fragColor; + // return vec4(0, 0, 1, 1); +} +`;var $w=[0,0,0,255],nL={radiusUnits:"meters",radiusScale:{type:"number",min:0,value:1},radiusMinPixels:{type:"number",min:0,value:0},radiusMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},lineWidthUnits:"meters",lineWidthScale:{type:"number",min:0,value:1},lineWidthMinPixels:{type:"number",min:0,value:0},lineWidthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},stroked:!1,filled:!0,billboard:!1,antialiasing:!0,getPosition:{type:"accessor",value:t=>t.position},getRadius:{type:"accessor",value:1},getFillColor:{type:"accessor",value:$w},getLineColor:{type:"accessor",value:$w},getLineWidth:{type:"accessor",value:1},strokeWidth:{deprecatedFor:"getLineWidth"},outline:{deprecatedFor:"stroked"},getColor:{deprecatedFor:["getFillColor","getLineColor"]}},ma=class extends ve{getShaders(){return super.getShaders({vs:Ww,fs:Vw,source:jw,modules:[Oe,mn,Ne,zw]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceRadius:{size:1,transition:!0,accessor:"getRadius",defaultValue:1},instanceFillColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e),e.changeFlags.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){let{radiusUnits:r,radiusScale:i,radiusMinPixels:n,radiusMaxPixels:o,stroked:s,filled:a,billboard:c,antialiasing:l,lineWidthUnits:f,lineWidthScale:u,lineWidthMinPixels:d,lineWidthMaxPixels:h}=this.props,p={stroked:s,filled:a,billboard:c,antialiasing:l,radiusUnits:je[r],radiusScale:i,radiusMinPixels:n,radiusMaxPixels:o,lineWidthUnits:je[f],lineWidthScale:u,lineWidthMinPixels:d,lineWidthMaxPixels:h},g=this.state.model;g.shaderInputs.setProps({scatterplot:p}),g.draw(this.context.renderPass)}_getModel(){let e=[-1,-1,0,1,-1,0,-1,1,0,1,1,0];return new he(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(e)}}}),isInstanced:!0})}};ma.defaultProps=nL;ma.layerName="ScatterplotLayer";var Eg=ma;var Hw=`layout(std140) uniform sdfUniforms { + float gamma; + bool enabled; + float buffer; + float outlineBuffer; + vec4 outlineColor; +} sdf; +`,Yw={name:"sdf",vs:Hw,fs:Hw,uniformTypes:{gamma:"f32",enabled:"f32",buffer:"f32",outlineBuffer:"f32",outlineColor:"vec4"}};var _a={none:0,start:1,center:2,end:3},oL=`layout(std140) uniform textUniforms { + highp vec2 cutoffPixels; + highp ivec2 align; + highp float fontSize; + bool flipY; +} text; + +#define ALIGN_MODE_START ${_a.start} +#define ALIGN_MODE_CENTER ${_a.center} +#define ALIGN_MODE_END ${_a.end} +`,Pf={name:"text",vs:oL,getUniforms:({contentCutoffPixels:t=[0,0],contentAlignHorizontal:e="none",contentAlignVertical:r="none",fontSize:i,viewport:n})=>({cutoffPixels:t,align:[_a[e],_a[r]],fontSize:i,flipY:n?.flipY??!1}),uniformTypes:{cutoffPixels:"vec2",align:"vec2",fontSize:"f32",flipY:"f32"}};var Xw=`#version 300 es +#define SHADER_NAME multi-icon-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceSizes; +in float instanceAngles; +in vec4 instanceColors; +in vec3 instancePickingColors; +in vec4 instanceIconFrames; +in float instanceColorModes; +in vec2 instanceOffsets; +in vec2 instancePixelOffset; +in vec4 instanceClipRect; +out float vColorMode; +out vec4 vColor; +out vec2 vTextureCoords; +out vec2 uv; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = angle * PI / 180.0; +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +float getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) { +if (clipEnd < clipStart) return 0.0; +if (mode == ALIGN_MODE_START) { +return max(- (anchor + clipStart), 0.0); +} +if (mode == ALIGN_MODE_CENTER) { +float _min = max(0., anchor + clipStart); +float _max = min(extent, anchor + clipEnd); +return _min < _max ? (_min + _max) / 2.0 - anchor : 0.0; +} +if (mode == ALIGN_MODE_END) { +return min(extent - (anchor + clipEnd), 0.); +} +return 0.0; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vec2 iconSize = instanceIconFrames.zw; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits), +icon.sizeMinPixels, icon.sizeMaxPixels +); +float instanceScale = sizePixels / text.fontSize; +vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets; +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale; +pixelOffset += instancePixelOffset; +pixelOffset.y *= -1.0; +vec2 anchorPosScreen; +if (icon.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +anchorPosScreen = gl_Position.xy / gl_Position.w; +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +if (text.flipY) { +offset_common.y *= -1.; +} +DECKGL_FILTER_SIZE(offset_common, geometry); +vec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0)); +anchorPosScreen = anchorPos.xy / anchorPos.w; +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +anchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio; +vec2 xy = project_size_to_pixel(instanceClipRect.xy); +vec2 wh = project_size_to_pixel(instanceClipRect.zw); +if (text.flipY) { +xy.y = -xy.y - wh.y; +} +if (text.align.x > 0 || text.align.y > 0) { +vec2 viewportPixels = project.viewportSize / project.devicePixelRatio; +vec2 scrollPixels = vec2( +getPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x), +-getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y) +); +pixelOffset += scrollPixels; +gl_Position.xy += project_pixel_size_to_clipspace(scrollPixels); +} +if (instanceClipRect.z >= 0.) { +if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) { +gl_Position = vec4(0.0); +} +else if (text.cutoffPixels.x > 0.) { +float vpWidth = project.viewportSize.x / project.devicePixelRatio; +float l = max(anchorPosScreen.x + xy.x, 0.0); +float r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth); +if (r - l < text.cutoffPixels.x) { +gl_Position = vec4(0.0); +} +} +} +if (instanceClipRect.w >= 0.) { +if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) { +gl_Position = vec4(0.0); +} +else if (text.cutoffPixels.y > 0.) { +float vpHeight = project.viewportSize.y / project.devicePixelRatio; +float t = max(anchorPosScreen.y - xy.y - wh.y, 0.0); +float b = min(anchorPosScreen.y - xy.y, vpHeight); +if (b - t < text.cutoffPixels.y) { +gl_Position = vec4(0.0); +} +} +} +vTextureCoords = mix( +instanceIconFrames.xy, +instanceIconFrames.xy + iconSize, +(positions.xy + 1.0) / 2.0 +) / icon.iconsTextureDim; +vColor = instanceColors; +DECKGL_FILTER_COLOR(vColor, geometry); +vColorMode = instanceColorModes; +} +`;var Gw=`#version 300 es +#define SHADER_NAME multi-icon-layer-fragment-shader +precision highp float; +uniform sampler2D iconsTexture; +in vec4 vColor; +in vec2 vTextureCoords; +in vec2 uv; +out vec4 fragColor; +void main(void) { +geometry.uv = uv; +if (!bool(picking.isActive)) { +float alpha = texture(iconsTexture, vTextureCoords).a; +vec4 color = vColor; +if (sdf.enabled) { +float distance = alpha; +alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance); +if (sdf.outlineBuffer > 0.0) { +float inFill = alpha; +float inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance); +color = mix(sdf.outlineColor, vColor, inFill); +alpha = inBorder; +} +} +float a = alpha * color.a; +if (a < icon.alphaCutoff) { +discard; +} +fragColor = vec4(color.rgb, a * layer.opacity); +} +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var Rg=192/256;var sL={getIconOffsets:{type:"accessor",value:t=>t.offsets},getContentBox:{type:"accessor",value:[0,0,-1,-1]},fontSize:1,alphaCutoff:.001,smoothing:.1,outlineWidth:0,outlineColor:{type:"color",value:[0,0,0,255]},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none"},ya=class extends kw{getShaders(){let e=super.getShaders();return{...e,modules:[...e.modules,Pf,Yw],vs:Xw,fs:Gw}}initializeState(){super.initializeState();let e=this.getAttributeManager(),r=e.attributes.instanceIconDefs;r.settings.update=this.calculateInstanceIconDefs,e.addInstanced({instancePickingColors:{type:"uint8",size:4,accessor:(i,{index:n,target:o})=>this.encodePickingColor(n,o)},instanceClipRect:{size:4,accessor:"getContentBox",defaultValue:[0,0,-1,-1]}})}updateState(e){super.updateState(e);let{props:r,oldProps:i,changeFlags:n}=e,{outlineColor:o}=r;if(n.updateTriggersChanged&&(n.updateTriggersChanged.getIcon||n.updateTriggersChanged.getIconOffsets)&&this.getAttributeManager().invalidate("instanceIconDefs"),o!==i.outlineColor){let s=[o[0]/255,o[1]/255,o[2]/255,(o[3]??255)/255];this.setState({outlineColor:s})}!r.sdf&&r.outlineWidth&&F.warn(`${this.id}: fontSettings.sdf is required to render outline`)()}draw(e){let{sdf:r,smoothing:i,fontSize:n,outlineWidth:o,contentCutoffPixels:s,contentAlignHorizontal:a,contentAlignVertical:c}=this.props,{outlineColor:l}=this.state,f=o?Math.max(i,Rg*(1-o)):-1,u=this.state.model,d={buffer:Rg,outlineBuffer:f,gamma:i,enabled:!!r,outlineColor:l},h={contentCutoffPixels:s,contentAlignHorizontal:a,contentAlignVertical:c,fontSize:n,viewport:this.context.viewport};if(u.shaderInputs.setProps({sdf:d,text:h}),super.draw(e),r&&o){let{iconManager:p}=this.state;p.getTexture()&&(u.shaderInputs.setProps({sdf:{...d,outlineBuffer:Rg}}),u.draw(this.context.renderPass))}}calculateInstanceIconDefs(e,{startRow:r,endRow:i}){let{data:n,getIcon:o,getIconOffsets:s}=this.props,a=e.getVertexOffset(r),c=e.value,{iterable:l,objectInfo:f}=mr(n,r,i);for(let u of l){f.index++;let d=o(u,f),h=s(u,f);if(d){let p=0;for(let g of Array.from(d)){let m=super.getInstanceIconDef(g);m[0]=h[p*2],m[1]+=h[p*2+1],m[6]=1,c.set(m,a),a+=e.size,p++}}}}};ya.defaultProps=sL;ya.layerName="MultiIconLayer";var qw=ya;var Cg=new Float64Array(256);for(let t=0;t<256;t++){let e=.5-Math.pow(t/255,.45454545454545453);Cg[t]=e*Math.abs(e)}Cg[255]=-1e20;var xa=class{constructor({fontSize:e=24,buffer:r=3,radius:i=8,cutoff:n=.25,fontFamily:o="sans-serif",fontWeight:s="normal",fontStyle:a="normal",lang:c=null}={}){this.buffer=r,this.radius=i,this.cutoff=n,this.lang=c;let l=this.size=e+r*4,f=this._createCanvas(l),u=this.ctx=f.getContext("2d",{willReadFrequently:!0});u.font=`${a} ${s} ${e}px ${o}`,u.textBaseline="alphabetic",u.textAlign="left",u.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l)}_createCanvas(e){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,e);let r=document.createElement("canvas");return r.width=r.height=e,r}draw(e){let{width:r,actualBoundingBoxAscent:i,actualBoundingBoxDescent:n,actualBoundingBoxLeft:o,actualBoundingBoxRight:s}=this.ctx.measureText(e),a=Math.ceil(i),c=Math.floor(-o),l=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(s)-c)),f=Math.max(0,Math.min(this.size-this.buffer,a+Math.ceil(n))),u=l+2*this.buffer,d=f+2*this.buffer,h=Math.max(u*d,0),p=new Uint8ClampedArray(h),g={data:p,width:u,height:d,glyphWidth:l,glyphHeight:f,glyphTop:a,glyphLeft:c,glyphAdvance:r};if(l===0||f===0)return g;let{ctx:m,buffer:_,gridInner:T,gridOuter:y}=this;this.lang&&(m.lang=this.lang),m.clearRect(_,_,l,f),m.fillText(e,_-c,_+a);let x=m.getImageData(_,_,l,f);y.fill(1e20,0,h),T.fill(0,0,h);let w=3;for(let A=0;A-1);c++,o[c]=a,s[c]=l,s[c+1]=1e20}for(let a=0,c=0;ai&&(l=0,f=u),n[d]={x:l+r,y:f+r,width:p,height:_,advance:h,anchorX:p/2,anchorY:g},l+=p+r*2,u=Math.max(u,f+_+r*2)}return{mapping:n,xOffset:l,yOffsetMin:f,yOffsetMax:u,canvasHeight:lL(u)}}function Jw(t,e,r,i){let n=0;for(let o=e;oi&&(sa){let u=Jw(t,a,c,n);l+u>i&&(si&&(u=eS(t,a,c,i,n,o),s=o[o.length-1])),a=c,l+=u}return l}function uL(t,e,r,i,n=0,o){o===void 0&&(o=t.length);let s=[];return e==="break-all"?eS(t,n,o,r,i,s):fL(t,n,o,r,i,s),s}function dL(t,e,r,i,n,o){let s=0,a=0;for(let c=e;c0,d=[0,0],h=[0,0],p=0,g=e+r/2,m=0,_=0;for(let T=0;T<=a;T++){let y=s[T];if((y===` +`||T===a)&&(_=T),_>m){let x=u?uL(s,i,n,o,m,_):cL;for(let w=0;w<=x.length;w++){let b=w===0?m:x[w-1],E=w1||c>0){let h=t.constructor;d=new h(l);for(let p=0;p=0&&this._order.splice(r,1)}_appendOrder(e){this._order.push(e)}};function hL(){let t=[];for(let e=32;e<128;e++)t.push(String.fromCharCode(e));return t}var Li={fontFamily:"Monaco, monospace",fontWeight:"normal",characterSet:hL(),fontSize:64,buffer:4,sdf:!1,cutoff:.25,radius:12,smoothing:.1},iS=1024,nS=.9,oS=.3,aS=3,Mf=new $n(aS);function pL(t,e){let r;typeof e=="string"?r=new Set(Array.from(e)):r=new Set(e);let i=Mf.get(t);if(!i)return r;for(let n in i.mapping)r.has(n)&&r.delete(n);return r}function gL(t,e){for(let r=0;r=aS,"Invalid cache limit"),Mf=new $n(t)}var ba=class{constructor(){this.props={...Li}}get atlas(){return this._atlas}get mapping(){return this._atlas&&this._atlas.mapping}setProps(e={}){Object.assign(this.props,e),e._getFontRenderer&&(this._getFontRenderer=e._getFontRenderer),this._key=this._getKey();let r=pL(this._key,this.props.characterSet),i=Mf.get(this._key);if(i&&r.size===0){this._atlas!==i&&(this._atlas=i);return}let n=this._generateFontAtlas(r,i);this._atlas=n,Mf.set(this._key,n)}_generateFontAtlas(e,r){let{fontFamily:i,fontWeight:n,fontSize:o,buffer:s,sdf:a,radius:c,cutoff:l}=this.props,f=r&&r.data;f||(f=document.createElement("canvas"),f.width=iS);let u=f.getContext("2d",{willReadFrequently:!0});sS(u,i,o,n);let d=x=>mL(u,o,x),h;this._getFontRenderer?h=this._getFontRenderer(this.props):a&&(h={measure:d,draw:_L(this.props)});let{mapping:p,canvasHeight:g,xOffset:m,yOffsetMin:_,yOffsetMax:T}=Qw({measureText:x=>h?h.measure(x):d(x),buffer:s,characterSet:e,maxCanvasWidth:iS,...r&&{mapping:r.mapping,xOffset:r.xOffset,yOffsetMin:r.yOffsetMin,yOffsetMax:r.yOffsetMax}});if(f.height!==g){let x=f.height>0?u.getImageData(0,0,f.width,f.height):null;f.height=g,x&&u.putImageData(x,0,0)}if(sS(u,i,o,n),h)for(let x of e){let w=p[x],{data:b,left:E=0,top:S=0}=h.draw(x),A=w.x-E,C=w.y-S,I=Math.max(0,Math.round(A)),R=Math.max(0,Math.round(C)),N=Math.min(b.width,f.width-I),O=Math.min(b.height,f.height-R);u.putImageData(b,I,R,0,0,N,O),w.x+=I-A,w.y+=R-C}else for(let x of e){let w=p[x];u.fillText(x,w.x,w.y+w.anchorY)}let y=h?h.measure():d();return{baselineOffset:(y.ascent-y.descent)/2,xOffset:m,yOffsetMin:_,yOffsetMax:T,mapping:p,data:f,width:f.width,height:f.height}}_getKey(){let{fontFamily:e,fontWeight:r,fontSize:i,buffer:n,sdf:o,radius:s,cutoff:a}=this.props;return o?`${e} ${r} ${i} ${n} ${s} ${a}`:`${e} ${r} ${i} ${n}`}};function _L({fontSize:t,buffer:e,radius:r,cutoff:i,fontFamily:n,fontWeight:o}){let s=new xa({fontSize:t,buffer:e,radius:r,cutoff:i,fontFamily:n,fontWeight:`${o}`});return a=>{let{data:c,width:l,height:f}=s.draw(a),u=new ImageData(l,f);return gL(c,u),{data:u,left:e,top:e}}}var lS=`layout(std140) uniform textBackgroundUniforms { + bool billboard; + float sizeScale; + float sizeMinPixels; + float sizeMaxPixels; + vec4 borderRadius; + vec4 padding; + highp int sizeUnits; + bool stroked; +} textBackground; +`,fS={name:"textBackground",vs:lS,fs:lS,uniformTypes:{billboard:"f32",sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",borderRadius:"vec4",padding:"vec4",sizeUnits:"i32",stroked:"f32"}};var uS=`#version 300 es +#define SHADER_NAME text-background-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in vec4 instanceRects; +in vec4 instanceClipRect; +in float instanceSizes; +in float instanceAngles; +in vec2 instancePixelOffsets; +in float instanceLineWidths; +in vec4 instanceFillColors; +in vec4 instanceLineColors; +in vec3 instancePickingColors; +out vec4 vFillColor; +out vec4 vLineColor; +out float vLineWidth; +out vec2 uv; +out vec2 dimensions; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = radians(angle); +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vLineWidth = instanceLineWidths; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits), +textBackground.sizeMinPixels, textBackground.sizeMaxPixels +); +float instanceScale = sizePixels / text.fontSize; +dimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw; +vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions); +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles); +pixelOffset += instancePixelOffsets; +pixelOffset.y *= -1.0; +vec2 xy = project_size_to_pixel(instanceClipRect.xy); +vec2 wh = project_size_to_pixel(instanceClipRect.zw); +if (text.flipY) { +xy.y = -xy.y - wh.y; +} +if (instanceClipRect.z >= 0.0) { +dimensions.x = wh.x; +pixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x); +} +if (instanceClipRect.w >= 0.0) { +dimensions.y = wh.y; +pixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y); +} +if (textBackground.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +if (text.flipY) { +offset_common.y *= -1.; +} +DECKGL_FILTER_SIZE(offset_common, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vFillColor, geometry); +vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vLineColor, geometry); +} +`;var dS=`#version 300 es +#define SHADER_NAME text-background-layer-fragment-shader +precision highp float; +in vec4 vFillColor; +in vec4 vLineColor; +in float vLineWidth; +in vec2 uv; +in vec2 dimensions; +out vec4 fragColor; +float round_rect(vec2 p, vec2 size, vec4 radii) { +vec2 pixelPositionCB = (p - 0.5) * size; +vec2 sizeCB = size * 0.5; +float maxBorderRadius = min(size.x, size.y) * 0.5; +vec4 borderRadius = vec4(min(radii, maxBorderRadius)); +borderRadius.xy = +(pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw; +borderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y; +vec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x; +return -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x); +} +float rect(vec2 p, vec2 size) { +vec2 pixelPosition = p * size; +return min(min(pixelPosition.x, size.x - pixelPosition.x), +min(pixelPosition.y, size.y - pixelPosition.y)); +} +vec4 get_stroked_fragColor(float dist) { +float isBorder = smoothedge(dist, vLineWidth); +return mix(vFillColor, vLineColor, isBorder); +} +void main(void) { +geometry.uv = uv; +if (textBackground.borderRadius != vec4(0.0)) { +float distToEdge = round_rect(uv, dimensions, textBackground.borderRadius); +float shapeAlpha = smoothedge(-distToEdge, 0.0); +if (shapeAlpha == 0.0) { +discard; +} +if (textBackground.stroked) { +fragColor = get_stroked_fragColor(distToEdge); +} else { +fragColor = vFillColor; +} +fragColor.a *= shapeAlpha; +} else { +if (textBackground.stroked) { +float distToEdge = rect(uv, dimensions); +fragColor = get_stroked_fragColor(distToEdge); +} else { +fragColor = vFillColor; +} +} +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var yL={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,fontSize:1,borderRadius:{type:"object",value:0},padding:{type:"array",value:[0,0,0,0]},getPosition:{type:"accessor",value:t=>t.position},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},getBoundingRect:{type:"accessor",value:[0,0,0,0]},getClipRect:{type:"accessor",value:[0,0,-1,-1]},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:[0,0,0,255]},getLineWidth:{type:"accessor",value:1}},Ta=class extends ve{getShaders(){return super.getShaders({vs:uS,fs:dS,modules:[Oe,Ne,fS,Pf]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,accessor:"getSize",defaultValue:1},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instanceRects:{size:4,accessor:"getBoundingRect"},instanceClipRect:{size:4,accessor:"getClipRect",defaultValue:[0,0,-1,-1]},instancePixelOffsets:{size:2,transition:!0,accessor:"getPixelOffset"},instanceFillColors:{size:4,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:4,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e);let{changeFlags:r}=e;r.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){let{billboard:r,sizeScale:i,sizeUnits:n,sizeMinPixels:o,sizeMaxPixels:s,getLineWidth:a,fontSize:c}=this.props,{padding:l,borderRadius:f}=this.props;l.length<4&&(l=[l[0],l[1],l[0],l[1]]),Array.isArray(f)||(f=[f,f,f,f]);let u=this.state.model,d={billboard:r,stroked:!!a,borderRadius:f,padding:l,sizeUnits:je[n],sizeScale:i,sizeMinPixels:o,sizeMaxPixels:s},h={fontSize:c,viewport:this.context.viewport};u.shaderInputs.setProps({textBackground:d,text:h}),u.draw(this.context.renderPass)}_getModel(){let e=[0,0,1,0,0,1,1,1];return new he(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",vertexCount:4,attributes:{positions:{size:2,value:new Float32Array(e)}}}),isInstanced:!0})}};Ta.defaultProps=yL;Ta.layerName="TextBackgroundLayer";var hS=Ta;var pS={start:1,middle:0,end:-1},gS={top:1,center:0,bottom:-1},Pg=[0,0,0,255],xL=1,bL={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,background:!1,getBackgroundColor:{type:"accessor",value:[255,255,255,255]},getBorderColor:{type:"accessor",value:Pg},getBorderWidth:{type:"accessor",value:0},backgroundBorderRadius:{type:"object",value:0},backgroundPadding:{type:"array",value:[0,0,0,0]},characterSet:{type:"object",value:Li.characterSet},fontFamily:Li.fontFamily,fontWeight:Li.fontWeight,lineHeight:xL,outlineWidth:{type:"number",value:0,min:0},outlineColor:{type:"color",value:Pg},fontSettings:{type:"object",value:{},compare:1},wordBreak:"break-word",maxWidth:{type:"number",value:-1},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none",getText:{type:"accessor",value:t=>t.text},getPosition:{type:"accessor",value:t=>t.position},getColor:{type:"accessor",value:Pg},getSize:{type:"accessor",value:32},getAngle:{type:"accessor",value:0},getTextAnchor:{type:"accessor",value:"middle"},getAlignmentBaseline:{type:"accessor",value:"center"},getPixelOffset:{type:"accessor",value:[0,0]},getContentBox:{type:"accessor",value:[0,0,-1,-1]},backgroundColor:{deprecatedFor:["background","getBackgroundColor"]}},wa=class extends na{constructor(){super(...arguments),this.getBoundingRect=(e,r)=>{let{size:[i,n]}=this.transformParagraph(e,r),{getTextAnchor:o,getAlignmentBaseline:s}=this.props,a=pS[typeof o=="function"?o(e,r):o],c=gS[typeof s=="function"?s(e,r):s];return[(a-1)*i/2,(c-1)*n/2,i,n]},this.getIconOffsets=(e,r)=>{let{getTextAnchor:i,getAlignmentBaseline:n}=this.props,{x:o,y:s,rowWidth:a,size:[,c]}=this.transformParagraph(e,r),l=pS[typeof i=="function"?i(e,r):i],f=gS[typeof n=="function"?n(e,r):n],u=o.length,d=new Array(u*2),h=0;for(let p=0;p0&&F.once(1,"v8.9 breaking change: TextLayer maxWidth is now relative to text size")()}updateState(e){let{props:r,oldProps:i,changeFlags:n}=e;(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getText))&&this._updateText(),(this._updateFontAtlas()||r.lineHeight!==i.lineHeight||r.wordBreak!==i.wordBreak||r.maxWidth!==i.maxWidth)&&this.setState({styleVersion:this.state.styleVersion+1})}getPickingInfo({info:e}){return e.object=e.index>=0?this.props.data[e.index]:null,e}_updateFontAtlas(){let{fontSettings:e,fontFamily:r,fontWeight:i,_getFontRenderer:n}=this.props,{fontAtlasManager:o,characterSet:s}=this.state,a={...e,characterSet:s,fontFamily:r,fontWeight:i,_getFontRenderer:n};if(!o.mapping)return o.setProps(a),!0;for(let c in a)if(a[c]!==o.props[c])return o.setProps(a),!0;return!1}_updateText(){let{data:e,characterSet:r}=this.props,i=e.attributes?.getText,{getText:n}=this.props,o=e.startIndices,s,a=r==="auto"&&new Set;if(i&&o){let{texts:c,characterCount:l}=rS({...ArrayBuffer.isView(i)?{value:i}:i,length:e.length,startIndices:o,characterSet:a});s=l,n=(f,{index:u})=>c[u]}else{let{iterable:c,objectInfo:l}=mr(e);o=[0],s=0;for(let f of c){l.index++;let u=Array.from(n(f,l)||"");a&&u.forEach(a.add,a),s+=u.length,o.push(s)}}this.setState({getText:n,startIndices:o,numInstances:s,characterSet:a||r})}transformParagraph(e,r){let{fontAtlasManager:i}=this.state,n=i.mapping,{baselineOffset:o}=i.atlas,{fontSize:s}=i.props,a=this.state.getText,{wordBreak:c,lineHeight:l,maxWidth:f}=this.props,u=a(e,r)||"";return tS(u,o,l*s,c,f*s,n)}renderLayers(){let{startIndices:e,numInstances:r,getText:i,fontAtlasManager:{atlas:n,mapping:o},styleVersion:s}=this.state,{data:a,_dataDiff:c,getPosition:l,getColor:f,getSize:u,getAngle:d,getPixelOffset:h,getBackgroundColor:p,getBorderColor:g,getBorderWidth:m,getContentBox:_,backgroundBorderRadius:T,backgroundPadding:y,background:x,billboard:w,fontSettings:b,outlineWidth:E,outlineColor:S,sizeScale:A,sizeUnits:C,sizeMinPixels:I,sizeMaxPixels:R,contentCutoffPixels:N,contentAlignHorizontal:O,contentAlignVertical:W,transitions:G,updateTriggers:L}=this.props,H=this.getSubLayerClass("characters",qw),Re=this.getSubLayerClass("background",hS),{fontSize:We}=this.state.fontAtlasManager.props;return[x&&new Re({getFillColor:p,getLineColor:g,getLineWidth:m,borderRadius:T,padding:y,getPosition:l,getSize:u,getAngle:d,getPixelOffset:h,getClipRect:_,billboard:w,sizeScale:A,sizeUnits:C,sizeMinPixels:I,sizeMaxPixels:R,fontSize:We,transitions:G&&{getPosition:G.getPosition,getAngle:G.getAngle,getSize:G.getSize,getFillColor:G.getBackgroundColor,getLineColor:G.getBorderColor,getLineWidth:G.getBorderWidth,getPixelOffset:G.getPixelOffset}},this.getSubLayerProps({id:"background",updateTriggers:{getPosition:L.getPosition,getAngle:L.getAngle,getSize:L.getSize,getFillColor:L.getBackgroundColor,getLineColor:L.getBorderColor,getLineWidth:L.getBorderWidth,getPixelOffset:L.getPixelOffset,getBoundingRect:{getText:L.getText,getTextAnchor:L.getTextAnchor,getAlignmentBaseline:L.getAlignmentBaseline,styleVersion:s}}}),{data:a.attributes&&a.attributes.background?{length:a.length,attributes:a.attributes.background}:a,_dataDiff:c,autoHighlight:!1,getBoundingRect:this.getBoundingRect}),new H({sdf:b.sdf,smoothing:Number.isFinite(b.smoothing)?b.smoothing:Li.smoothing,outlineWidth:E/(b.radius||Li.radius),outlineColor:S,iconAtlas:n,iconMapping:o,getPosition:l,getColor:f,getSize:u,getAngle:d,getPixelOffset:h,getContentBox:_,billboard:w,sizeScale:A,sizeUnits:C,sizeMinPixels:I,sizeMaxPixels:R,fontSize:We,contentCutoffPixels:N,contentAlignHorizontal:O,contentAlignVertical:W,transitions:G&&{getPosition:G.getPosition,getAngle:G.getAngle,getColor:G.getColor,getSize:G.getSize,getPixelOffset:G.getPixelOffset,getContentBox:G.getContentBox}},this.getSubLayerProps({id:"characters",updateTriggers:{all:L.getText,getPosition:L.getPosition,getAngle:L.getAngle,getColor:L.getColor,getSize:L.getSize,getPixelOffset:L.getPixelOffset,getContentBox:L.getContentBox,getIconOffsets:{getTextAnchor:L.getTextAnchor,getAlignmentBaseline:L.getAlignmentBaseline,styleVersion:s}}}),{data:a,_dataDiff:c,startIndices:e,numInstances:r,getIconOffsets:this.getIconOffsets,getIcon:i})]}static set fontAtlasCacheLimit(e){cS(e)}};wa.defaultProps=bL;wa.layerName="TextLayer";var Mg=wa;function Hn(t){let{children:e}=t;return e&&e.length>0}function Bi(t){let{zoom:e}=t;return e!==void 0}function If(t){return t&&!!t.aggregate}var Fi;(function(t){t.ALL="ALL",t.INCOMING="INCOMING",t.OUTGOING="OUTGOING",t.BETWEEN="BETWEEN"})(Fi||(Fi={}));function V(t){for(var e=t.length/6|0,r=new Array(e),i=0;i>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?Of(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?Of(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=wL.exec(t))?new ge(e[1],e[2],e[3],1):(e=SL.exec(t))?new ge(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=AL.exec(t))?Of(e[1],e[2],e[3],e[4]):(e=vL.exec(t))?Of(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=EL.exec(t))?wS(e[1],e[2]/100,e[3]/100,1):(e=RL.exec(t))?wS(e[1],e[2]/100,e[3]/100,e[4]):mS.hasOwnProperty(t)?xS(mS[t]):t==="transparent"?new ge(NaN,NaN,NaN,0):null}function xS(t){return new ge(t>>16&255,t>>8&255,t&255,1)}function Of(t,e,r,i){return i<=0&&(t=e=r=NaN),new ge(t,e,r,i)}function Aa(t){return t instanceof Gt||(t=Et(t)),t?(t=t.rgb(),new ge(t.r,t.g,t.b,t.opacity)):new ge}function Gr(t,e,r,i){return arguments.length===1?Aa(t):new ge(t,e,r,i??1)}function ge(t,e,r,i){this.r=+t,this.g=+e,this.b=+r,this.opacity=+i}_r(ge,Gr,Yr(Gt,{brighter(t){return t=t==null?zi:Math.pow(zi,t),new ge(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Xr:Math.pow(Xr,t),new ge(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new ge(Ui(this.r),Ui(this.g),Ui(this.b),Df(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:bS,formatHex:bS,formatHex8:ML,formatRgb:TS,toString:TS}));function bS(){return`#${ki(this.r)}${ki(this.g)}${ki(this.b)}`}function ML(){return`#${ki(this.r)}${ki(this.g)}${ki(this.b)}${ki((isNaN(this.opacity)?1:this.opacity)*255)}`}function TS(){let t=Df(this.opacity);return`${t===1?"rgb(":"rgba("}${Ui(this.r)}, ${Ui(this.g)}, ${Ui(this.b)}${t===1?")":`, ${t})`}`}function Df(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Ui(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function ki(t){return t=Ui(t),(t<16?"0":"")+t.toString(16)}function wS(t,e,r,i){return i<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new vt(t,e,r,i)}function AS(t){if(t instanceof vt)return new vt(t.h,t.s,t.l,t.opacity);if(t instanceof Gt||(t=Et(t)),!t)return new vt;if(t instanceof vt)return t;t=t.rgb();var e=t.r/255,r=t.g/255,i=t.b/255,n=Math.min(e,r,i),o=Math.max(e,r,i),s=NaN,a=o-n,c=(o+n)/2;return a?(e===o?s=(r-i)/a+(r0&&c<1?0:s,new vt(s,a,c,t.opacity)}function vS(t,e,r,i){return arguments.length===1?AS(t):new vt(t,e,r,i??1)}function vt(t,e,r,i){this.h=+t,this.s=+e,this.l=+r,this.opacity=+i}_r(vt,vS,Yr(Gt,{brighter(t){return t=t==null?zi:Math.pow(zi,t),new vt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Xr:Math.pow(Xr,t),new vt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,i=r+(r<.5?r:1-r)*e,n=2*r-i;return new ge(Ig(t>=240?t-240:t+120,n,i),Ig(t,n,i),Ig(t<120?t+240:t-120,n,i),this.opacity)},clamp(){return new vt(SS(this.h),Nf(this.s),Nf(this.l),Df(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=Df(this.opacity);return`${t===1?"hsl(":"hsla("}${SS(this.h)}, ${Nf(this.s)*100}%, ${Nf(this.l)*100}%${t===1?")":`, ${t})`}`}}));function SS(t){return t=(t||0)%360,t<0?t+360:t}function Nf(t){return Math.max(0,Math.min(1,t||0))}function Ig(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}var Lf=Math.PI/180,Ff=180/Math.PI;var Bf=18,ES=.96422,RS=1,CS=.82521,PS=4/29,Xn=6/29,MS=3*Xn*Xn,IL=Xn*Xn*Xn;function IS(t){if(t instanceof qt)return new qt(t.l,t.a,t.b,t.opacity);if(t instanceof yr)return OS(t);t instanceof ge||(t=Aa(t));var e=Lg(t.r),r=Lg(t.g),i=Lg(t.b),n=Og((.2225045*e+.7168786*r+.0606169*i)/RS),o,s;return e===r&&r===i?o=s=n:(o=Og((.4360747*e+.3850649*r+.1430804*i)/ES),s=Og((.0139322*e+.0971045*r+.7141733*i)/CS)),new qt(116*n-16,500*(o-n),200*(n-s),t.opacity)}function Fg(t,e,r,i){return arguments.length===1?IS(t):new qt(t,e,r,i??1)}function qt(t,e,r,i){this.l=+t,this.a=+e,this.b=+r,this.opacity=+i}_r(qt,Fg,Yr(Gt,{brighter(t){return new qt(this.l+Bf*(t??1),this.a,this.b,this.opacity)},darker(t){return new qt(this.l-Bf*(t??1),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return e=ES*Ng(e),t=RS*Ng(t),r=CS*Ng(r),new ge(Dg(3.1338561*e-1.6168667*t-.4906146*r),Dg(-.9787684*e+1.9161415*t+.033454*r),Dg(.0719453*e-.2289914*t+1.4052427*r),this.opacity)}}));function Og(t){return t>IL?Math.pow(t,1/3):t/MS+PS}function Ng(t){return t>Xn?t*t*t:MS*(t-PS)}function Dg(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Lg(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function OL(t){if(t instanceof yr)return new yr(t.h,t.c,t.l,t.opacity);if(t instanceof qt||(t=IS(t)),t.a===0&&t.b===0)return new yr(NaN,0=1?(r=1,e-1):Math.floor(r*e),n=t[i],o=t[i+1],s=i>0?t[i-1]:2*n-o,a=i()=>t;function kS(t,e){return function(r){return t+r*e}}function DL(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(i){return Math.pow(t+i*e,r)}}function US(t,e){var r=e-t;return r?kS(t,r>180||r<-180?r-360*Math.round(r/360):r):qn(isNaN(t)?e:t)}function zS(t){return(t=+t)==1?xr:function(e,r){return r-e?DL(e,r,t):qn(isNaN(e)?r:e)}}function xr(t,e){var r=e-t;return r?kS(t,r):qn(isNaN(t)?e:t)}var Uf=(function t(e){var r=zS(e);function i(n,o){var s=r((n=Gr(n)).r,(o=Gr(o)).r),a=r(n.g,o.g),c=r(n.b,o.b),l=xr(n.opacity,o.opacity);return function(f){return n.r=s(f),n.g=a(f),n.b=c(f),n.opacity=l(f),n+""}}return i.gamma=t,i})(1);function WS(t){return function(e){var r=e.length,i=new Array(r),n=new Array(r),o=new Array(r),s,a;for(s=0;sr&&(o=e.slice(r,o),a[s]?a[s]+=o:a[++s]=o),(i=i[0])===(n=n[0])?a[s]?a[s]+=n:a[++s]=n:(a[++s]=null,c.push({i:s,x:qr(i,n)})),r=zg.lastIndex;return rRa(t[t.length-1]);var Wf=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(V),UL=X(Wf);var Vf=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(V),zL=X(Vf);var jf=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(V),WL=X(jf);var $f=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(V),VL=X($f);var Hf=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(V),jL=X(Hf);var Yf=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(V),$L=X(Yf);var Xf=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(V),HL=X(Xf);var Gf=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(V),YL=X(Gf);var qf=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(V),XL=X(qf);var Kf=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(V),GL=X(Kf);var Zf=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(V),qL=X(Zf);var Qf=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(V),KL=X(Qf);var Jf=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(V),ZL=X(Jf);var eu=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(V),QL=X(eu);var tu=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(V),JL=X(tu);var ru=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(V),e6=X(ru);var iu=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(V),t6=X(iu);var nu=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(V),r6=X(nu);var Vg=zf(ft(-100,.75,.35),ft(80,1.5,.8)),jg=zf(ft(260,.75,.35),ft(80,1.5,.8)),Aae=ft();function ou(t){var e=t.length;return function(r){return t[Math.max(0,Math.min(e-1,Math.floor(r*e)))]}}var $g=ou(V("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),Hg=ou(V("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Yg=ou(V("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Xg=ou(V("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function ut(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function Kt(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function su(t){let e,r,i;t.length!==2?(e=ut,r=(a,c)=>ut(t(a),c),i=(a,c)=>t(a)-c):(e=t===ut||t===Kt?t:i6,r=t,i=t);function n(a,c,l=0,f=a.length){if(l>>1;r(a[u],c)<0?l=u+1:f=u}while(l>>1;r(a[u],c)<=0?l=u+1:f=u}while(ll&&i(a[u-1],c)>-i(a[u],c)?u-1:u}return{left:n,center:s,right:o}}function i6(){return 0}function Gg(t){return t===null?NaN:+t}var qS=su(ut),KS=qS.right,qg=qS.left,n6=su(Gg).center,Kg=KS;function Kn(t,e){let r,i;if(e===void 0)for(let n of t)n!=null&&(r===void 0?n>=n&&(r=i=n):(r>n&&(r=n),i=o&&(r=i=o):(r>o&&(r=o),i0){for(s=e[--r];r>0&&(i=s,n=e[--r],s=i+n,o=n-(s-i),!o););r>0&&(o<0&&e[r-1]<0||o>0&&e[r-1]>0)&&(n=o*2,i=s+n,n==i-s&&(s=i))}return s}};var au=class extends Map{constructor(e,r=a6){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),e!=null)for(let[i,n]of e)this.set(i,n)}get(e){return super.get(ZS(this,e))}has(e){return super.has(ZS(this,e))}set(e,r){return super.set(o6(this,e),r)}delete(e){return super.delete(s6(this,e))}};function ZS({_intern:t,_key:e},r){let i=e(r);return t.has(i)?t.get(i):r}function o6({_intern:t,_key:e},r){let i=e(r);return t.has(i)?t.get(i):(t.set(i,r),r)}function s6({_intern:t,_key:e},r){let i=e(r);return t.has(i)&&(r=t.get(i),t.delete(i)),r}function a6(t){return t!==null&&typeof t=="object"?t.valueOf():t}function Zg(t){return t}function Pa(t,e,...r){return c6(t,Zg,e,r)}function c6(t,e,r,i){return(function n(o,s){if(s>=i.length)return r(o);let a=new au,c=i[s++],l=-1;for(let f of o){let u=c(f,++l,o),d=a.get(u);d?d.push(f):a.set(u,[f])}for(let[f,u]of a)a.set(f,n(u,s));return e(a)})(t,0)}var l6=Math.sqrt(50),f6=Math.sqrt(10),u6=Math.sqrt(2);function cu(t,e,r){let i=(e-t)/Math.max(0,r),n=Math.floor(Math.log10(i)),o=i/Math.pow(10,n),s=o>=l6?10:o>=f6?5:o>=u6?2:1,a,c,l;return n<0?(l=Math.pow(10,-n)/s,a=Math.round(t*l),c=Math.round(e*l),a/le&&--c,l=-l):(l=Math.pow(10,n)*s,a=Math.round(t/l),c=Math.round(e/l),a*le&&--c),c0))return[];if(t===e)return[t];let i=e=n))return[];let a=o-n+1,c=new Array(a);if(i)if(s<0)for(let l=0;li||r===void 0&&i>=i)&&(r=i);else{let i=-1;for(let n of t)(n=e(n,++i,t))!=null&&(r>n||r===void 0&&n>=n)&&(r=n)}return r}function Ia(t,e,r){t=+t,e=+e,r=(n=arguments.length)<2?(e=t,t=0,1):n<3?1:+r;for(var i=-1,n=Math.max(0,Math.ceil((e-t)/r))|0,o=new Array(n);++ie&&(r=t,t=e,e=r),function(i){return Math.max(t,Math.min(e,i))}}function h6(t,e,r){var i=t[0],n=t[1],o=e[0],s=e[1];return n2?p6:h6,c=l=null,u}function u(d){return d==null||isNaN(d=+d)?o:(c||(c=a(t.map(i),e,r)))(i(s(d)))}return u.invert=function(d){return s(n((l||(l=a(e,t.map(i),qr)))(d)))},u.domain=function(d){return arguments.length?(t=Array.from(d,tm),f()):t.slice()},u.range=function(d){return arguments.length?(e=Array.from(d),f()):e.slice()},u.rangeRound=function(d){return e=Array.from(d),r=Ca,f()},u.clamp=function(d){return arguments.length?(s=d?!0:$e,f()):s!==$e},u.interpolate=function(d){return arguments.length?(r=d,f()):r},u.unknown=function(d){return arguments.length?(o=d,u):o},function(d,h){return i=d,n=h,f()}}function nm(){return im()($e,$e)}function JS(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function Vi(t,e){if(!isFinite(t)||t===0)return null;var r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),i=t.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+t.slice(r+1)]}function Zt(t){return t=Vi(Math.abs(t)),t?t[1]:NaN}function eA(t,e){return function(r,i){for(var n=r.length,o=[],s=0,a=t[0],c=0;n>0&&a>0&&(c+a+1>i&&(a=Math.max(1,i-c)),o.push(r.substring(n-=a,n+a)),!((c+=a+1)>i));)a=t[s=(s+1)%t.length];return o.reverse().join(e)}}function tA(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var g6=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Kr(t){if(!(e=g6.exec(t)))throw new Error("invalid format: "+t);var e;return new du({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Kr.prototype=du.prototype;function du(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}du.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function rA(t){e:for(var e=t.length,r=1,i=-1,n;r0&&(i=0);break}return i>0?t.slice(0,i)+t.slice(n+1):t}var Oa;function iA(t,e){var r=Vi(t,e);if(!r)return Oa=void 0,t.toPrecision(e);var i=r[0],n=r[1],o=n-(Oa=Math.max(-8,Math.min(8,Math.floor(n/3)))*3)+1,s=i.length;return o===s?i:o>s?i+new Array(o-s+1).join("0"):o>0?i.slice(0,o)+"."+i.slice(o):"0."+new Array(1-o).join("0")+Vi(t,Math.max(0,e+o-1))[0]}function om(t,e){var r=Vi(t,e);if(!r)return t+"";var i=r[0],n=r[1];return n<0?"0."+new Array(-n).join("0")+i:i.length>n+1?i.slice(0,n+1)+"."+i.slice(n+1):i+new Array(n-i.length+2).join("0")}var sm={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:JS,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>om(t*100,e),r:om,s:iA,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function am(t){return t}var nA=Array.prototype.map,oA=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function sA(t){var e=t.grouping===void 0||t.thousands===void 0?am:eA(nA.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",i=t.currency===void 0?"":t.currency[1]+"",n=t.decimal===void 0?".":t.decimal+"",o=t.numerals===void 0?am:tA(nA.call(t.numerals,String)),s=t.percent===void 0?"%":t.percent+"",a=t.minus===void 0?"\u2212":t.minus+"",c=t.nan===void 0?"NaN":t.nan+"";function l(u,d){u=Kr(u);var h=u.fill,p=u.align,g=u.sign,m=u.symbol,_=u.zero,T=u.width,y=u.comma,x=u.precision,w=u.trim,b=u.type;b==="n"?(y=!0,b="g"):sm[b]||(x===void 0&&(x=12),w=!0,b="g"),(_||h==="0"&&p==="=")&&(_=!0,h="0",p="=");var E=(d&&d.prefix!==void 0?d.prefix:"")+(m==="$"?r:m==="#"&&/[boxX]/.test(b)?"0"+b.toLowerCase():""),S=(m==="$"?i:/[%p]/.test(b)?s:"")+(d&&d.suffix!==void 0?d.suffix:""),A=sm[b],C=/[defgprs%]/.test(b);x=x===void 0?6:/[gprs]/.test(b)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function I(R){var N=E,O=S,W,G,L;if(b==="c")O=A(R)+O,R="";else{R=+R;var H=R<0||1/R<0;if(R=isNaN(R)?c:A(Math.abs(R),x),w&&(R=rA(R)),H&&+R==0&&g!=="+"&&(H=!1),N=(H?g==="("?g:a:g==="-"||g==="("?"":g)+N,O=(b==="s"&&!isNaN(R)&&Oa!==void 0?oA[8+Oa/3]:"")+O+(H&&g==="("?")":""),C){for(W=-1,G=R.length;++WL||L>57){O=(L===46?n+R.slice(W+1):R.slice(W))+O,R=R.slice(0,W);break}}}y&&!_&&(R=e(R,1/0));var Re=N.length+R.length+O.length,We=Re>1)+N+R+O+We.slice(Re);break;default:R=We+N+R+O;break}return o(R)}return I.toString=function(){return u+""},I}function f(u,d){var h=Math.max(-8,Math.min(8,Math.floor(Zt(d)/3)))*3,p=Math.pow(10,-h),g=l((u=Kr(u),u.type="f",u),{suffix:oA[8+h/3]});return function(m){return g(p*m)}}return{format:l,formatPrefix:f}}var hu,pu,gu;cm({thousands:",",grouping:[3],currency:["$",""]});function cm(t){return hu=sA(t),pu=hu.format,gu=hu.formatPrefix,hu}function lm(t){return Math.max(0,-Zt(Math.abs(t)))}function fm(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Zt(e)/3)))*3-Zt(Math.abs(t)))}function um(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Zt(e)-Zt(t))+1}function dm(t,e,r,i){var n=Qg(t,e,r),o;switch(i=Kr(i??",f"),i.type){case"s":{var s=Math.max(Math.abs(t),Math.abs(e));return i.precision==null&&!isNaN(o=fm(n,s))&&(i.precision=o),gu(i,s)}case"":case"e":case"g":case"p":case"r":{i.precision==null&&!isNaN(o=um(n,Math.max(Math.abs(t),Math.abs(e))))&&(i.precision=o-(i.type==="e"));break}case"f":case"%":{i.precision==null&&!isNaN(o=lm(n))&&(i.precision=o-(i.type==="%")*2);break}}return pu(i)}function Na(t){var e=t.domain;return t.ticks=function(r){var i=e();return lu(i[0],i[i.length-1],r??10)},t.tickFormat=function(r,i){var n=e();return dm(n[0],n[n.length-1],r??10,i)},t.nice=function(r){r==null&&(r=10);var i=e(),n=0,o=i.length-1,s=i[n],a=i[o],c,l,f=10;for(a0;){if(l=Ma(s,a,r),l===c)return i[n]=s,i[o]=a,e(i);if(l>0)s=Math.floor(s/l)*l,a=Math.ceil(a/l)*l;else if(l<0)s=Math.ceil(s*l)/l,a=Math.floor(a*l)/l;else break;c=l}return t},t}function Da(){var t=nm();return t.copy=function(){return uu(t,Da())},fu.apply(t,arguments),Na(t)}function aA(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function m6(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function _6(t){return t<0?-t*t:t*t}function hm(t){var e=t($e,$e),r=1;function i(){return r===1?t($e,$e):r===.5?t(m6,_6):t(aA(r),aA(1/r))}return e.exponent=function(n){return arguments.length?(r=+n,i()):r},Na(e)}function Qn(){var t=hm(im());return t.copy=function(){return uu(t,Qn()).exponent(t.exponent())},fu.apply(t,arguments),t}function pm(){return Qn.apply(null,arguments).exponent(.5)}var gm=new Date,mm=new Date;function ne(t,e,r,i){function n(o){return t(o=arguments.length===0?new Date:new Date(+o)),o}return n.floor=o=>(t(o=new Date(+o)),o),n.ceil=o=>(t(o=new Date(o-1)),e(o,1),t(o),o),n.round=o=>{let s=n(o),a=n.ceil(o);return o-s(e(o=new Date(+o),s==null?1:Math.floor(s)),o),n.range=(o,s,a)=>{let c=[];if(o=n.ceil(o),a=a==null?1:Math.floor(a),!(o0))return c;let l;do c.push(l=new Date(+o)),e(o,a),t(o);while(lne(s=>{if(s>=s)for(;t(s),!o(s);)s.setTime(s-1)},(s,a)=>{if(s>=s)if(a<0)for(;++a<=0;)for(;e(s,-1),!o(s););else for(;--a>=0;)for(;e(s,1),!o(s););}),r&&(n.count=(o,s)=>(gm.setTime(+o),mm.setTime(+s),t(gm),t(mm),Math.floor(r(gm,mm))),n.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?n.filter(i?s=>i(s)%o===0:s=>n.count(0,s)%o===0):n)),n}var La=ne(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*1e3)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds()),cA=La.range;var mu=ne(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getMinutes()),y6=mu.range,lA=ne(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes()),x6=lA.range;var _u=ne(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3-t.getMinutes()*6e4)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getHours()),b6=_u.range,fA=ne(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours()),T6=fA.range;var ji=ne(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1),w6=ji.range,Fa=ne(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1),S6=Fa.range,uA=ne(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5)),A6=uA.range;function $i(t){return ne(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*6e4)/6048e5)}var eo=$i(0),to=$i(1),dA=$i(2),hA=$i(3),Zr=$i(4),pA=$i(5),gA=$i(6),mA=eo.range,E6=to.range,R6=dA.range,C6=hA.range,P6=Zr.range,M6=pA.range,I6=gA.range;function Hi(t){return ne(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/6048e5)}var Ba=Hi(0),ro=Hi(1),_A=Hi(2),yA=Hi(3),Qr=Hi(4),xA=Hi(5),bA=Hi(6),TA=Ba.range,O6=ro.range,N6=_A.range,D6=yA.range,L6=Qr.range,F6=xA.range,B6=bA.range;var yu=ne(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth()),k6=yu.range,wA=ne(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth()),U6=wA.range;var Rt=ne(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Rt.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:ne(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});var z6=Rt.range,wr=ne(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());wr.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:ne(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});var W6=wr.range;function bm(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function Tm(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function ka(t,e,r){return{y:t,m:e,d:r,H:0,M:0,S:0,L:0}}function wm(t){var e=t.dateTime,r=t.date,i=t.time,n=t.periods,o=t.days,s=t.shortDays,a=t.months,c=t.shortMonths,l=Ua(n),f=za(n),u=Ua(o),d=za(o),h=Ua(s),p=za(s),g=Ua(a),m=za(a),_=Ua(c),T=za(c),y={a:L,A:H,b:Re,B:We,c:null,d:CA,e:CA,f:fF,g:bF,G:wF,H:aF,I:cF,j:lF,L:NA,m:uF,M:dF,p:l2,q:f2,Q:IA,s:OA,S:hF,u:pF,U:gF,V:mF,w:_F,W:yF,x:null,X:null,y:xF,Y:TF,Z:SF,"%":MA},x={a:u2,A:d2,b:h2,B:p2,c:null,d:PA,e:PA,f:RF,g:BF,G:UF,H:AF,I:vF,j:EF,L:LA,m:CF,M:PF,p:g2,q:m2,Q:IA,s:OA,S:MF,u:IF,U:OF,V:NF,w:DF,W:LF,x:null,X:null,y:FF,Y:kF,Z:zF,"%":MA},w={a:C,A:I,b:R,B:N,c:O,d:EA,e:EA,f:iF,g:vA,G:AA,H:RA,I:RA,j:J6,L:rF,m:Q6,M:eF,p:A,q:Z6,Q:oF,s:sF,S:tF,u:Y6,U:X6,V:G6,w:H6,W:q6,x:W,X:G,y:vA,Y:AA,Z:K6,"%":nF};y.x=b(r,y),y.X=b(i,y),y.c=b(e,y),x.x=b(r,x),x.X=b(i,x),x.c=b(e,x);function b(D,Y){return function(K){var M=[],Ve=-1,re=0,Ye=D.length,Xe,ii,Qm;for(K instanceof Date||(K=new Date(+K));++Ve53)return null;"w"in M||(M.w=1),"Z"in M?(re=Tm(ka(M.y,0,1)),Ye=re.getUTCDay(),re=Ye>4||Ye===0?ro.ceil(re):ro(re),re=Fa.offset(re,(M.V-1)*7),M.y=re.getUTCFullYear(),M.m=re.getUTCMonth(),M.d=re.getUTCDate()+(M.w+6)%7):(re=bm(ka(M.y,0,1)),Ye=re.getDay(),re=Ye>4||Ye===0?to.ceil(re):to(re),re=ji.offset(re,(M.V-1)*7),M.y=re.getFullYear(),M.m=re.getMonth(),M.d=re.getDate()+(M.w+6)%7)}else("W"in M||"U"in M)&&("w"in M||(M.w="u"in M?M.u%7:"W"in M?1:0),Ye="Z"in M?Tm(ka(M.y,0,1)).getUTCDay():bm(ka(M.y,0,1)).getDay(),M.m=0,M.d="W"in M?(M.w+6)%7+M.W*7-(Ye+5)%7:M.w+M.U*7-(Ye+6)%7);return"Z"in M?(M.H+=M.Z/100|0,M.M+=M.Z%100,Tm(M)):bm(M)}}function S(D,Y,K,M){for(var Ve=0,re=Y.length,Ye=K.length,Xe,ii;Ve=Ye)return-1;if(Xe=Y.charCodeAt(Ve++),Xe===37){if(Xe=Y.charAt(Ve++),ii=w[Xe in SA?Y.charAt(Ve++):Xe],!ii||(M=ii(D,K,M))<0)return-1}else if(Xe!=K.charCodeAt(M++))return-1}return M}function A(D,Y,K){var M=l.exec(Y.slice(K));return M?(D.p=f.get(M[0].toLowerCase()),K+M[0].length):-1}function C(D,Y,K){var M=h.exec(Y.slice(K));return M?(D.w=p.get(M[0].toLowerCase()),K+M[0].length):-1}function I(D,Y,K){var M=u.exec(Y.slice(K));return M?(D.w=d.get(M[0].toLowerCase()),K+M[0].length):-1}function R(D,Y,K){var M=_.exec(Y.slice(K));return M?(D.m=T.get(M[0].toLowerCase()),K+M[0].length):-1}function N(D,Y,K){var M=g.exec(Y.slice(K));return M?(D.m=m.get(M[0].toLowerCase()),K+M[0].length):-1}function O(D,Y,K){return S(D,e,Y,K)}function W(D,Y,K){return S(D,r,Y,K)}function G(D,Y,K){return S(D,i,Y,K)}function L(D){return s[D.getDay()]}function H(D){return o[D.getDay()]}function Re(D){return c[D.getMonth()]}function We(D){return a[D.getMonth()]}function l2(D){return n[+(D.getHours()>=12)]}function f2(D){return 1+~~(D.getMonth()/3)}function u2(D){return s[D.getUTCDay()]}function d2(D){return o[D.getUTCDay()]}function h2(D){return c[D.getUTCMonth()]}function p2(D){return a[D.getUTCMonth()]}function g2(D){return n[+(D.getUTCHours()>=12)]}function m2(D){return 1+~~(D.getUTCMonth()/3)}return{format:function(D){var Y=b(D+="",y);return Y.toString=function(){return D},Y},parse:function(D){var Y=E(D+="",!1);return Y.toString=function(){return D},Y},utcFormat:function(D){var Y=b(D+="",x);return Y.toString=function(){return D},Y},utcParse:function(D){var Y=E(D+="",!0);return Y.toString=function(){return D},Y}}}var SA={"-":"",_:" ",0:"0"},be=/^\s*\d+/,V6=/^%/,j6=/[\\^$*+?|[\]().{}]/g;function Z(t,e,r){var i=t<0?"-":"",n=(i?-t:t)+"",o=n.length;return i+(o[e.toLowerCase(),r]))}function H6(t,e,r){var i=be.exec(e.slice(r,r+1));return i?(t.w=+i[0],r+i[0].length):-1}function Y6(t,e,r){var i=be.exec(e.slice(r,r+1));return i?(t.u=+i[0],r+i[0].length):-1}function X6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.U=+i[0],r+i[0].length):-1}function G6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.V=+i[0],r+i[0].length):-1}function q6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.W=+i[0],r+i[0].length):-1}function AA(t,e,r){var i=be.exec(e.slice(r,r+4));return i?(t.y=+i[0],r+i[0].length):-1}function vA(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.y=+i[0]+(+i[0]>68?1900:2e3),r+i[0].length):-1}function K6(t,e,r){var i=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return i?(t.Z=i[1]?0:-(i[2]+(i[3]||"00")),r+i[0].length):-1}function Z6(t,e,r){var i=be.exec(e.slice(r,r+1));return i?(t.q=i[0]*3-3,r+i[0].length):-1}function Q6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.m=i[0]-1,r+i[0].length):-1}function EA(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.d=+i[0],r+i[0].length):-1}function J6(t,e,r){var i=be.exec(e.slice(r,r+3));return i?(t.m=0,t.d=+i[0],r+i[0].length):-1}function RA(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.H=+i[0],r+i[0].length):-1}function eF(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.M=+i[0],r+i[0].length):-1}function tF(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.S=+i[0],r+i[0].length):-1}function rF(t,e,r){var i=be.exec(e.slice(r,r+3));return i?(t.L=+i[0],r+i[0].length):-1}function iF(t,e,r){var i=be.exec(e.slice(r,r+6));return i?(t.L=Math.floor(i[0]/1e3),r+i[0].length):-1}function nF(t,e,r){var i=V6.exec(e.slice(r,r+1));return i?r+i[0].length:-1}function oF(t,e,r){var i=be.exec(e.slice(r));return i?(t.Q=+i[0],r+i[0].length):-1}function sF(t,e,r){var i=be.exec(e.slice(r));return i?(t.s=+i[0],r+i[0].length):-1}function CA(t,e){return Z(t.getDate(),e,2)}function aF(t,e){return Z(t.getHours(),e,2)}function cF(t,e){return Z(t.getHours()%12||12,e,2)}function lF(t,e){return Z(1+ji.count(Rt(t),t),e,3)}function NA(t,e){return Z(t.getMilliseconds(),e,3)}function fF(t,e){return NA(t,e)+"000"}function uF(t,e){return Z(t.getMonth()+1,e,2)}function dF(t,e){return Z(t.getMinutes(),e,2)}function hF(t,e){return Z(t.getSeconds(),e,2)}function pF(t){var e=t.getDay();return e===0?7:e}function gF(t,e){return Z(eo.count(Rt(t)-1,t),e,2)}function DA(t){var e=t.getDay();return e>=4||e===0?Zr(t):Zr.ceil(t)}function mF(t,e){return t=DA(t),Z(Zr.count(Rt(t),t)+(Rt(t).getDay()===4),e,2)}function _F(t){return t.getDay()}function yF(t,e){return Z(to.count(Rt(t)-1,t),e,2)}function xF(t,e){return Z(t.getFullYear()%100,e,2)}function bF(t,e){return t=DA(t),Z(t.getFullYear()%100,e,2)}function TF(t,e){return Z(t.getFullYear()%1e4,e,4)}function wF(t,e){var r=t.getDay();return t=r>=4||r===0?Zr(t):Zr.ceil(t),Z(t.getFullYear()%1e4,e,4)}function SF(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+Z(e/60|0,"0",2)+Z(e%60,"0",2)}function PA(t,e){return Z(t.getUTCDate(),e,2)}function AF(t,e){return Z(t.getUTCHours(),e,2)}function vF(t,e){return Z(t.getUTCHours()%12||12,e,2)}function EF(t,e){return Z(1+Fa.count(wr(t),t),e,3)}function LA(t,e){return Z(t.getUTCMilliseconds(),e,3)}function RF(t,e){return LA(t,e)+"000"}function CF(t,e){return Z(t.getUTCMonth()+1,e,2)}function PF(t,e){return Z(t.getUTCMinutes(),e,2)}function MF(t,e){return Z(t.getUTCSeconds(),e,2)}function IF(t){var e=t.getUTCDay();return e===0?7:e}function OF(t,e){return Z(Ba.count(wr(t)-1,t),e,2)}function FA(t){var e=t.getUTCDay();return e>=4||e===0?Qr(t):Qr.ceil(t)}function NF(t,e){return t=FA(t),Z(Qr.count(wr(t),t)+(wr(t).getUTCDay()===4),e,2)}function DF(t){return t.getUTCDay()}function LF(t,e){return Z(ro.count(wr(t)-1,t),e,2)}function FF(t,e){return Z(t.getUTCFullYear()%100,e,2)}function BF(t,e){return t=FA(t),Z(t.getUTCFullYear()%100,e,2)}function kF(t,e){return Z(t.getUTCFullYear()%1e4,e,4)}function UF(t,e){var r=t.getUTCDay();return t=r>=4||r===0?Qr(t):Qr.ceil(t),Z(t.getUTCFullYear()%1e4,e,4)}function zF(){return"+0000"}function MA(){return"%"}function IA(t){return+t}function OA(t){return Math.floor(+t/1e3)}var io,Ee,Jr,BA,kA;Sm({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function Sm(t){return io=wm(t),Ee=io.format,Jr=io.parse,BA=io.utcFormat,kA=io.utcParse,io}function UA(){var t=0,e=1,r,i,n,o,s=$e,a=!1,c;function l(u){return u==null||isNaN(u=+u)?c:s(n===0?.5:(u=(o(u)-r)*n,a?Math.max(0,Math.min(1,u)):u))}l.domain=function(u){return arguments.length?([t,e]=u,r=o(t=+t),i=o(e=+e),n=r===i?0:1/(i-r),l):[t,e]},l.clamp=function(u){return arguments.length?(a=!!u,l):a},l.interpolator=function(u){return arguments.length?(s=u,l):s};function f(u){return function(d){var h,p;return arguments.length?([h,p]=d,s=u(h,p),l):[s(0),s(1)]}}return l.range=f(br),l.rangeRound=f(Ca),l.unknown=function(u){return arguments.length?(c=u,l):c},function(u){return o=u,r=u(t),i=u(e),n=r===i?0:1/(i-r),l}}function zA(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function Wa(){var t=Na(UA()($e));return t.copy=function(){return zA(t,Wa())},Jg.apply(t,arguments)}function xu(){var t=hm(UA());return t.copy=function(){return zA(t,xu()).exponent(t.exponent())},Jg.apply(t,arguments)}var WF="#fff",VF=.4,Cm="rgba(240,240,240,0.5)",jF=[Cm,"#137CBD"],$F="rgba(220,220,220,0.5)",HF=[Cm,"#f6654e"],YF=[Cm,"#00a9cc"],XF=[255,255,255,255];function GF(t){return Math.round(t*255)}function WA(t,e){let r=Et(t);if(!r)return console.warn("Invalid color: ",t),`rgba(255, 255, 255, ${e})`;let i=r.rgb();return`rgba(${i.r}, ${i.g}, ${i.b}, ${e})`}function dt(t){if(Array.isArray(t))return t;let e=Et(t);if(!e)return console.warn("Invalid color: ",t),XF;let r=e.rgb();return[Math.floor(r.r),Math.floor(r.g),Math.floor(r.b),GF(e.opacity)]}function Qt(t,e){return t?dt(t):typeof e=="string"?dt(e):e}var Te=t=>t[t.length-1],vm;(function(t){t.primary="#162d3c"})(vm||(vm={}));var VA=20,no=t=>Ia(0,VA+1).map(e=>t(e/VA)).reverse(),Em="rgba(240,240,240,0.5)",qF=[Em,vm.primary],KF=["#f7feae","#b7e6a5","#7ccba2","#46aea0","#089099","#00718b","#045275"],ZF=["#d3f2a3","#97e196","#6cc08b","#4c9b82","#217a79","#105965","#074050"],jA=["#d1eeea","#a8dbd9","#85c4c9","#68abb8","#4f90a6","#3b738f","#2a5674"],QF=jA,$A={Blues:Te(Jf),BluGrn:["#c4e6c3","#96d2a4","#6dbc90","#4da284","#36877a","#266b6e","#1d4f60"],BluYl:KF,BrwnYl:["#ede5cf","#e0c2a2","#d39c83","#c1766f","#a65461","#813753","#541f3f"],BuGn:Te(Wf),BuPu:Te(Vf),Burg:["#ffc6c4","#f4a3a8","#e38191","#cc607d","#ad466c","#8b3058","#672044"],BurgYl:["#fbe6c5","#f5ba98","#ee8a82","#dc7176","#c8586c","#9c3f5d","#70284a"],Cool:no(jg),DarkMint:["#d2fbd4","#a5dbc2","#7bbcb0","#559c9e","#3a7c89","#235d72","#123f5a"],Emrld:ZF,GnBu:Te(jf),Grayish:qF,Greens:Te(eu),Greys:Te(tu),Inferno:no(Yg),Magenta:["#f3cbd3","#eaa9bd","#dd88ac","#ca699d","#b14d8e","#91357d","#6c2167"],Magma:no(Hg),Mint:["#e4f1e1","#b4d9cc","#89c0b6","#63a6a0","#448c8a","#287274","#0d585f"],Oranges:Te(nu),OrRd:Te($f),OrYel:["#ecda9a","#efc47e","#f3ad6a","#f7945d","#f97b57","#f66356","#ee4d5a"],Peach:["#fde0c5","#facba6","#f8b58b","#f59e72","#f2855d","#ef6a4c","#eb4a40"],Plasma:no(Xg),PinkYl:["#fef6b5","#ffdd9a","#ffc285","#ffa679","#fa8a76","#f16d7a","#e15383"],PuBu:Te(Yf),PuBuGn:Te(Hf),PuRd:Te(Xf),Purp:["#f3e0f7","#e4c7f1","#d1afe8","#b998dd","#9f82ce","#826dba","#63589f"],Purples:Te(ru),PurpOr:["#f9ddda","#f2b9c4","#e597b9","#ce78b3","#ad5fad","#834ba0","#573b88"],RdPu:Te(Gf),RedOr:["#f6d2a9","#f5b78e","#f19c7c","#ea8171","#dd686c","#ca5268","#b13f64"],Reds:Te(iu),Sunset:["#f3e79b","#fac484","#f8a07e","#eb7f86","#ce6693","#a059a0","#5c53a5"],SunsetDark:["#fcde9c","#faa476","#f0746e","#e34f6f","#dc3977","#b9257a","#7c1d6f"],Teal:jA,TealGrn:["#b0f2bc","#89e8ac","#67dba5","#4cc8a3","#38b2a3","#2c98a0","#257d98"],Viridis:no($g),Warm:no(Vg),YlGn:Te(Kf),YlGnBu:Te(qf),YlOrBr:Te(Zf),YlOrRd:Te(Qf)},Nfe=Object.keys($A),JF="#f52020",eB="#17a5be",tB={negative:{flows:{scheme:[Em,eB]}},positive:{flows:{scheme:[Em,JF]}},locationAreas:{outline:"rgba(92,112,128,0.5)",normal:"rgba(220,220,220,0.5)"},outlineColor:"rgb(230,233,237)"};function HA(t){return YA(!1,t.colorScheme,t.darkMode,t.fadeEnabled,t.fadeOpacityEnabled,t.fadeAmount,rB(t.flowLinesRenderingMode))}function rB(t){return t==="animated-straight"}function YA(t,e,r,i,n,o,s){if(t)return tB;let a;Array.isArray(e)?a=e:(a=e&&$A[e]||QF,r&&(a=a.slice().reverse()));{let c=Ia(0,Math.max(10,a.length)),l=c.length-1,f=Wa(Ra(a)).domain([0,l]);if(!i||o===0)a=c.map((u,d)=>f(d));else{let u=Qn().exponent(1.5).domain([l,0]).range([0,2*o/100]);a=c.map((d,h)=>{let p=f(h),g=u(h);if(p==null||g==null)return"#000";let m=Gn(p);return m.l=r?m.l-m.l*g:m.l+(100-m.l)*g,m.c=m.c-m.c*(g/4),n&&(m.opacity=m.opacity*(1-g)),m.toString()})}}return{darkMode:r,flows:{scheme:a},locationCircles:{outgoing:r?"#000":"#fff"},outlineColor:r?"#000":"rgba(255, 255, 255, 0.5)"}}function iB(t){let e=Ea,r=t.length,i=new Array(r),n=new Array(r),o=new Array(r),s=new Array(r),a,c;for(a=0;adt(i(n))}function XA(t,e,r){let i=e?e[0]:0,n=e?e[1]:0;if(Pm(t)){let s=Am([0,n],t.positive.flows.scheme,r),a=Am([0,i],t.negative.flows.scheme,r);return c=>c>=0?s(c):a(c)}let o=Am([0,n||0],t.flows.scheme,r);return s=>o(s)}function GA(t){return t.positive!==void 0}function Pm(t){return t.positive!==void 0}function nB(t,e){let r=t&&t.normal||$F,i=Gn(r),n=dt(r);return{normal:n,connected:Qt(t&&t.connected,n),highlighted:Qt(t&&t.highlighted,WA(i[e?"brighter":"darker"](1).toString(),.5)),selected:Qt(t&&t.selected,WA(i[e?"brighter":"darker"](2).toString(),.8)),outline:Qt(t&&t.outline,dt(i[e?"brighter":"darker"](4).toString()))}}function Rm(t,e,r){let i=t&&t.flows&&t.flows.scheme||e,n=Gn(i[i.length-1]),o=Qt(t&&t.flows&&t.flows.highlighted,dt(n[r?"brighter":"darker"](.7).toString())),s=Qt(t?.locationCircles?.empty,r?"#000":"#fff"),a=Qt(t&&t.locationCircles&&t.locationCircles.inner,n.toString());return{flows:{scheme:i,highlighted:o},locationCircles:{inner:a,outgoing:Qt(t&&t.locationCircles&&t.locationCircles.outgoing,r?"#000":"#fff"),incoming:Qt(t&&t.locationCircles&&t.locationCircles.incoming,n[r?"brighter":"darker"](1.25).toString()),highlighted:Qt(t&&t.locationCircles&&t.locationCircles.highlighted,o),empty:s,outlineEmptyMix:t?.locationCircles?.outlineEmptyMix??.4}}}function qA(t){let e=!!(t&&t.darkMode);return{darkMode:e,locationAreas:nB(t&&t.locationAreas,e),outlineColor:dt(t&&t.outlineColor||WF),dimmedOpacity:t&&t.dimmedOpacity!=null?t.dimmedOpacity:VF}}function KA(t){let e=qA(t);return{...e,...Rm(t,jF,e.darkMode)}}function ZA(t){let e=qA(t);return{...e,positive:Rm(t&&t.positive,HF,e.darkMode),negative:Rm(t&&t.negative,YF,e.darkMode)}}var QA=YA;var JA=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Mm=1,Va=8,oe=new Uint32Array(96),Yi=class t{static from(e){if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[r,i]=new Uint8Array(e,0,2);if(r!==219)throw new Error("Data does not appear to be in a KDBush format.");let n=i>>4;if(n!==Mm)throw new Error(`Got v${n} data when expected v${Mm}.`);let o=JA[i&15];if(!o)throw new Error("Unrecognized array type.");let[s]=new Uint16Array(e,2,1),[a]=new Uint32Array(e,4,1);return new t(a,s,o,void 0,e)}constructor(e,r=64,i=Float64Array,n=ArrayBuffer,o){if(isNaN(e)||e<0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+r,2),65535),this.ArrayType=i,this.IndexArrayType=e<65536?Uint16Array:Uint32Array;let s=JA.indexOf(this.ArrayType),a=e*2*this.ArrayType.BYTES_PER_ELEMENT,c=e*this.IndexArrayType.BYTES_PER_ELEMENT,l=(8-c%8)%8;if(s<0)throw new Error(`Unexpected typed array class: ${i}.`);if(o)this.data=o,this.ids=new this.IndexArrayType(o,Va,e),this.coords=new i(o,Va+c+l,e*2),this._pos=e*2,this._finished=!0;else{let f=this.data=new n(Va+a+c+l);this.ids=new this.IndexArrayType(f,Va,e),this.coords=new i(f,Va+c+l,e*2),this._pos=0,this._finished=!1,new Uint8Array(f,0,2).set([219,(Mm<<4)+s]),new Uint16Array(f,2,1)[0]=r,new Uint32Array(f,4,1)[0]=e}}add(e,r){let i=this._pos>>1;return this.ids[i]=i,this.coords[this._pos++]=e,this.coords[this._pos++]=r,i}finish(){let e=this._pos>>1;if(e!==this.numItems)throw new Error(`Added ${e} items when expected ${this.numItems}.`);return Om(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(e,r,i,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:o,coords:s,nodeSize:a}=this;oe[0]=0,oe[1]=o.length-1,oe[2]=0;let c=3,l=[];for(;c>0;){let f=oe[--c],u=oe[--c],d=oe[--c];if(u-d<=a){for(let m=d;m<=u;m++){let _=s[2*m],T=s[2*m+1];_>=e&&_<=i&&T>=r&&T<=n&&l.push(o[m])}continue}let h=d+u>>1,p=s[2*h],g=s[2*h+1];p>=e&&p<=i&&g>=r&&g<=n&&l.push(o[h]),(f===0?e<=p:r<=g)&&(oe[c++]=d,oe[c++]=h-1,oe[c++]=1-f),(f===0?i>=p:n>=g)&&(oe[c++]=h+1,oe[c++]=u,oe[c++]=1-f)}return l}within(e,r,i){let n=[];return this.withinInto(e,r,i,n),n}withinInto(e,r,i,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:o,coords:s,nodeSize:a}=this;oe[0]=0,oe[1]=o.length-1,oe[2]=0;let c=3,l=0,f=i*i;for(;c>0;){let u=oe[--c],d=oe[--c],h=oe[--c];if(d-h<=a){for(let _=h;_<=d;_++)ev(s[2*_],s[2*_+1],e,r)<=f&&(n[l++]=o[_]);continue}let p=h+d>>1,g=s[2*p],m=s[2*p+1];ev(g,m,e,r)<=f&&(n[l++]=o[p]),(u===0?e-i<=g:r-i<=m)&&(oe[c++]=h,oe[c++]=p-1,oe[c++]=1-u),(u===0?e+i>=g:r+i>=m)&&(oe[c++]=p+1,oe[c++]=d,oe[c++]=1-u)}return l}};function Om(t,e,r,i,n,o){if(n-i<=r)return;let s=i+n>>1;tv(t,e,s,i,n,o),Om(t,e,r,i,s-1,1-o),Om(t,e,r,s+1,n,1-o)}function tv(t,e,r,i,n,o){for(;n>i;){if(n-i>600){let l=n-i+1,f=r-i+1,u=Math.log(l),d=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*d*(l-d)/l)*(f-l/2<0?-1:1),p=Math.max(i,Math.floor(r-f*d/l+h)),g=Math.min(n,Math.floor(r+(l-f)*d/l+h));tv(t,e,r,p,g,o)}let s=e[2*r+o],a=i,c=n;for(ja(t,e,i,r),e[2*n+o]>s&&ja(t,e,i,n);as;)c--}e[2*i+o]===s?ja(t,e,i,c):(c++,ja(t,e,c,n)),c<=r&&(i=c+1),r<=c&&(n=c-1)}}function ja(t,e,r,i){Im(t,r,i),Im(e,2*r,2*i),Im(e,2*r+1,2*i+1)}function Im(t,e,r){let i=t[e];t[e]=t[r],t[r]=i}function ev(t,e,r,i){let n=t-r,o=e-i;return n*n+o*o}var Tu=Symbol("NOT_FOUND");function oB(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function sB(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(r=>typeof r=="function")){let r=t.map(i=>typeof i=="function"?`function ${i.name||"unnamed"}()`:typeof i).join(", ");throw new TypeError(`${e}[${r}]`)}}var rv=t=>Array.isArray(t)?t:[t];function aB(t){let e=Array.isArray(t[0])?t[0]:t;return sB(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function cB(t,e){let r=[],{length:i}=t;for(let n=0;ne(a,l.key));if(c>-1){let l=r[c];return c>0&&(r.splice(c,1),r.unshift(l)),l.value}return Tu}function n(a,c){i(a)===Tu&&(r.unshift({key:a,value:c}),r.length>t&&r.pop())}function o(){return r}function s(){r=[]}return{get:i,put:n,getEntries:o,clear:s}}var uB=(t,e)=>t===e;function dB(t){return function(r,i){if(r===null||i===null||r.length!==i.length)return!1;let{length:n}=r;for(let o=0;oo(h.value,f));d&&(f=d.value,a!==0&&a--)}c.put(arguments,f)}return f}return l.clearCache=()=>{c.clear(),l.resetResultsCount()},l.resultsCount=()=>a,l.resetResultsCount=()=>{a=0},l}var hB=class{constructor(t){this.value=t}deref(){return this.value}},pB=()=>typeof WeakRef>"u"?hB:WeakRef,ov=pB(),gB=0,iv=1;function bu(){return{s:gB,v:void 0,o:null,p:null}}function mB(t){return t instanceof ov?t.deref():t}function sv(t,e={}){let r=bu(),{resultEqualityCheck:i}=e,n,o=0;function s(){let a=r,{length:c}=arguments;for(let u=0,d=c;u{r=bu(),s.resetResultsCount()},s.resultsCount=()=>o,s.resetResultsCount=()=>{o=0},s}function Nm(t,...e){let r=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,i=(...n)=>{let o=0,s=0,a,c={},l=n.pop();typeof l=="object"&&(c=l,l=n.pop()),oB(l,`createSelector expects an output function after the inputs, but received: [${typeof l}]`);let f={...r,...c},{memoize:u,memoizeOptions:d=[],argsMemoize:h=sv,argsMemoizeOptions:p=[]}=f,g=rv(d),m=rv(p),_=aB(n),T=u(function(){return o++,l.apply(null,arguments)},...g),y=!0,x=h(function(){s++;let b=cB(_,arguments);return a=T.apply(null,b),a},...m);return Object.assign(x,{resultFunc:l,memoizedResultFunc:T,dependencies:_,dependencyRecomputations:()=>s,resetDependencyRecomputations:()=>{s=0},lastResult:()=>a,recomputations:()=>o,resetRecomputations:()=>{o=0},memoize:u,argsMemoize:h})};return Object.assign(i,{withTypes:()=>i}),i}var U=Nm(sv);var Bv=S2(Sv(),1);var Sr=class{constructor(e){this.getLocationId=r=>Bi(r)?r.id:this.accessors.getLocationId(r),this.getLocationName=r=>{let i;return Bi(r)&&Hn(r)?i=r.name:this.accessors.getLocationName&&(i=this.accessors.getLocationName(r)),i||(i=`${this.getLocationId(r)}`),i},this.getLocationLat=r=>Bi(r)?r.lat:this.accessors.getLocationLat(r),this.getLocationLon=r=>Bi(r)?r.lon:this.accessors.getLocationLon(r),this.getFlowOriginId=r=>If(r)?r.origin:this.accessors.getFlowOriginId(r),this.getFlowDestId=r=>If(r)?r.dest:this.accessors.getFlowDestId(r),this.getFlowMagnitude=r=>If(r)?r.count:this.accessors.getFlowMagnitude(r),this.getFlowTime=r=>{let{getFlowTime:i}=this.accessors;return i?i(r):void 0},this.accessors=e}setAccessors(e){this.accessors=e}getFlowmapDataAccessors(){return this.accessors}};function Av(t){let e=new Map,r=new Map,i=new Map;for(let{zoom:u,nodes:d}of t){e.set(u,d);for(let h of d)if(Hn(h))r.set(h.id,h);else{let{id:p}=h,g=i.get(p);(g==null||g>u)&&i.set(p,u)}}let[n,o]=Kn(t,u=>u.zoom);if(n==null||o==null)throw new Error("Could not determine minZoom or maxZoom");let s=new Map;for(let u of r.values()){let{zoom:d}=u,h=s.get(d);h||(h=new Map,s.set(d,h)),a(u,p=>{h?.set(p,u)})}function a(u,d){for(let h of u.children){let p=r.get(h);p?a(p,d):d(h)}}let c=(u,d=o)=>{let h=[],p=(g,m)=>{if(d>g.zoom)for(let _ of g.children){let T=r.get(_);T?p(T,m):m.push(_)}else m.push(g.id)};return p(u,h),h};function l(u,d){let h=s.get(d);if(!h)return;let p=h.get(u);return p?p.id:void 0}return{availableZoomLevels:t.map(u=>+u.zoom).sort((u,d)=>ut(u,d)),getClusterNodesFor:u=>{if(u!==void 0)return e.get(u)},getClusterById:u=>r.get(u),getMinZoomForLocation:u=>i.get(u)||n,expandCluster:c,findClusterFor:l,aggregateFlows:(u,d,{getFlowOriginId:h,getFlowDestId:p,getFlowMagnitude:g},m={})=>{if(d>o)return u;let _=[],T=new Map,y=(w,b)=>`${w}:${b}`,{flowCountsMapReduce:x={map:g,reduce:(w,b)=>(w||0)+b}}=m;for(let w of u){let b=h(w),E=p(w),S=l(b,d)||b,A=l(E,d)||E,C=y(S,A);if(S===b&&A===E)_.push(w);else{let I=T.get(C);I?I.count=x.reduce(I.count,x.map(w)):(I={origin:S,dest:A,count:x.map(w),aggregate:!0},_.push(I),T.set(C,I))}}return _}}}function vv(t,{getFlowOriginId:e,getFlowDestId:r,getFlowMagnitude:i}){let n={incoming:new Map,outgoing:new Map};for(let o of t){let s=e(o),a=r(o),c=i(o);n.incoming.set(a,(n.incoming.get(a)||0)+c),n.outgoing.set(s,(n.outgoing.get(s)||0)+c)}return o=>Math.max(Math.abs(n.incoming.get(o)||0),Math.abs(n.outgoing.get(o)||0))}function Ev(t,e){if(!t.length)throw new Error("No available zoom levels");return t[Math.min(qg(t,Math.floor(e)),t.length-1)]}var SB={minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,makeClusterName:(t,e)=>{},makeClusterId:t=>`{[${t}]}`};function AB(t){let{index:e}=t;return e!=null}function Rv(t){let{id:e}=t;return e!=null}function Cv(t,e,r,i){let{getLocationLon:n,getLocationLat:o,getLocationId:s}=e,a={...SB,...i},{minZoom:c,maxZoom:l,nodeSize:f,makeClusterName:u,makeClusterId:d}=a,h=new Array(l+1),p=new Array,g=0;for(let S of t){let A=n(S),C=o(S);p.push({x:PB(A),y:MB(C),weight:r(s(S)),zoom:1/0,index:g,parentId:-1,location:S}),g++}let m=S=>{let A=new Yi(S.length,f,Float32Array);for(let C=0;C=c;S--){let A=EB(p,S,h[_],a);A.length===p.length?(h[S]=h[_],h[_]=void 0,_=S,p=A):(_=S,p=A,h[S]=m(p))}if(h.length===0)return[];let T=h.map(S=>S?.points.length),y=Zn(T.filter(S=>S>0)),x=OB(T)??T.length-1,w=IB(t,e);if(wA<=w);S>=0&&(S=b;S--){let A,C=h[S];if(!C)continue;h[_]&&SR.map(N=>N.id?d(N.id):s(N.location)),R=>R.parentId));let I=[];for(let R of C.points){let{x:N,y:O,numPoints:W,location:G}=R;if(AB(R))I.push({id:s(G),zoom:S,lat:o(G),lon:n(G)});else if(Rv(R)){let{id:L}=R,H=A&&A.get(L);if(!H){console.warn("Omitting cluster with no children, point:",R);continue}let Re={id:d(L),name:u(L,W),zoom:S,lat:CB(O),lon:RB(N),children:H??[]};I.push(Re)}}E.push({zoom:S,nodes:I}),_=S}return E}function vB(t,e,r,i,n){return{x:t,y:e,zoom:1/0,id:r,parentId:-1,numPoints:i,weight:n}}function EB(t,e,r,i){let n=[],{radius:o,extent:s}=i,a=o/(s*Math.pow(2,e));for(let c=0;c1?1:r}function IB(t,e){let{getLocationLon:r,getLocationLat:i}=e,n=new Map,o=0;for(let s of t){let a=r(s),c=i(s),l=`${a},${c}`,f=n.get(l);f||o++,n.set(l,f?f+1:1)}return o}function OB(t){let e=-1/0,r;for(let i=0;ie&&(e=n,r=i)}return r}function NB(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r],r,t))return r;return-1}var Pv=(t,e=0)=>{let r=e,i=new Sn({...t,width:t.width+r*2,height:t.height+r*2}).getBounds();return[i[0][0],i[0][1],i[1][0],i[1][1]]};var Mv=t=>{if(t)return Da().range([.025,.5]).domain([0,Math.max.apply(null,t.map(e=>Math.abs(e||0)))])};function Iv(t,e,r,i,n){let{getLocationId:o,getLocationName:s,getLocationClusterName:a}=i,c=l=>{let f=r.get(l);return f?s?s(f):o(f)||l:`"${l}"`};for(let l of e)for(let f of l.nodes)if(Hn(f)){let u=t.expandCluster(f);if(u.sort((d,h)=>Kt(n(d),n(h))),a)f.name=a(u);else{let d=u[0],h=u.length===2?u[1]:void 0;f.name=`"${c(d)}" and ${h?`"${c(h)}"`:`${u.length-1} others`}`}}else f.name=c(f.id)}var rue=[Jr("%Y-%m-%d"),Jr("%Y-%m-%d %H:%M"),Jr("%Y-%m-%d %H:%M:%S"),Jr("%Y"),Jr("%Y-%m")];var ei;(function(t){t.SECOND="SECOND",t.MINUTE="MINUTE",t.HOUR="HOUR",t.DAY="DAY",t.MONTH="MONTH",t.YEAR="YEAR"})(ei||(ei={}));var iue=Ee(".%L"),DB=Ee(":%S"),LB=Ee("%I:%M"),FB=Ee("%I %p"),BB=Ee("%a %d"),nue=Ee("%b %d"),kB=Ee("%b"),UB=Ee("%Y");var $a=[{order:0,key:ei.SECOND,interval:La,format:DB,formatFull:Ee("%Y-%m-%d %H:%M:%S")},{order:1,key:ei.MINUTE,interval:mu,format:LB,formatFull:Ee("%Y-%m-%d %H:%M")},{order:2,key:ei.HOUR,interval:_u,format:FB,formatFull:Ee("%a %d %b %Y, %I %p")},{order:3,key:ei.DAY,interval:ji,format:BB,formatFull:Ee("%a %d %b %Y")},{order:4,key:ei.MONTH,interval:yu,format:kB,formatFull:Ee("%b %Y")},{order:5,key:ei.YEAR,interval:Rt,format:UB,formatFull:Ee("%Y")}];function zm(t){return $a.find(e=>e.key===t)}function Ov(t){return $a.find(e=>e.order===t)}function Nv(t){let e;for(let r of $a){let{interval:i}=r;if(i(t)i.flows,this.getLocationsFromProps=(r,i)=>i.locations,this.getClusterLevelsFromProps=(r,i)=>i.clusterLevels,this.getMaxTopFlowsDisplayNum=(r,i)=>r.settings.maxTopFlowsDisplayNum,this.getFlowEndpointsInViewportMode=(r,i)=>r.settings.flowEndpointsInViewportMode,this.getSelectedLocations=(r,i)=>r.filter?.selectedLocations,this.getLocationFilterMode=(r,i)=>r.filter?.locationFilterMode,this.getClusteringEnabled=(r,i)=>r.settings.clusteringEnabled,this.getLocationTotalsEnabled=(r,i)=>r.settings.locationTotalsEnabled,this.getLocationLabelsEnabled=(r,i)=>r.settings.locationLabelsEnabled,this.getZoom=(r,i)=>r.viewport.zoom,this.getViewport=(r,i)=>r.viewport,this.getSelectedTimeRange=(r,i)=>r.filter?.selectedTimeRange,this.getSelectedTimeRanges=(r,i)=>r.filter?.selectedTimeRanges,this.getTemporalScaleDomain=(r,i)=>r.settings.temporalScaleDomain,this.getColorScheme=(r,i)=>r.settings.colorScheme,this.getDarkMode=(r,i)=>r.settings.darkMode,this.getFadeEnabled=(r,i)=>r.settings.fadeEnabled,this.getFadeOpacityEnabled=(r,i)=>r.settings.fadeOpacityEnabled,this.getFadeAmount=(r,i)=>r.settings.fadeAmount,this.getFlowLinesRenderingMode=(r,i)=>r.settings.flowLinesRenderingMode,this.getAnimate=U(this.getFlowLinesRenderingMode,r=>r==="animated-straight"),this.getInvalidLocationIds=U(this.getLocationsFromProps,r=>{if(!r)return;let i=[];for(let n of r){let o=this.accessors.getLocationId(n),s=this.accessors.getLocationLon(n),a=this.accessors.getLocationLat(n);(!(-90<=a&&a<=90)||!(-180<=s&&s<=180))&&i.push(o)}return i.length>0?i:void 0}),this.getLocations=U(this.getLocationsFromProps,this.getInvalidLocationIds,(r,i)=>{if(!r)return;if(!i||i.length===0)return r;let n=new Set(i),o=[];for(let s of r){let a=this.accessors.getLocationId(s);n.has(a)||o.push(s)}return o}),this.getLocationIds=U(this.getLocations,r=>{if(!r)return;let i=new Set;for(let n of r)i.add(this.accessors.getLocationId(n));return i}),this.getSelectedLocationsSet=U(this.getSelectedLocations,r=>r&&r.length>0?new Set(r):void 0),this.getSortedFlowsForKnownLocations=U(this.getFlowsFromProps,this.getLocationIds,(r,i)=>{if(!i||!r)return;let n=[];for(let o of r){let s=this.accessors.getFlowOriginId(o),a=this.accessors.getFlowDestId(o);i.has(s)&&i.has(a)&&n.push(o)}return n.sort((o,s)=>Kt(Math.abs(this.accessors.getFlowMagnitude(o)),Math.abs(this.accessors.getFlowMagnitude(s))))}),this.getActualTimeExtent=U(this.getSortedFlowsForKnownLocations,r=>{if(!r)return;let i=null,n=null;for(let o of r){let s=this.accessors.getFlowTime(o);s&&((i==null||i>s)&&(i=s),(n==null||n{if(!r||!i)return;let n=Zn(r,s=>{let a=this.accessors.getFlowTime(s);return a?Nv(a).order:null});if(n==null)return;let o=Ov(n);return o?o.key:void 0}),this.getTimeExtent=U(this.getActualTimeExtent,this.getTimeGranularityKey,(r,i)=>{let n=i?zm(i):void 0;if(!r||!n?.interval)return;let{interval:o}=n;return[r[0],o.offset(o.floor(r[1]),1)]}),this.getSortedFlowsForKnownLocationsFilteredByTime=U(this.getSortedFlowsForKnownLocations,this.getTimeExtent,this.getSelectedTimeRange,this.getSelectedTimeRanges,(r,i,n,o)=>{if(!r)return;let s=Array.isArray(o)&&o.length>0?o:n?[n]:null;return!i||!s||s.length===0||s.length===1&&i[0]===s[0][0]&&i[1]===s[0][1]?r:r.filter(a=>{let c=this.accessors.getFlowTime(a);return c&&s.some(l=>l[0]<=c&&c{if(!i||!r)return i;let n=new Set;for(let s of r)n.add(this.accessors.getFlowOriginId(s)),n.add(this.accessors.getFlowDestId(s));let o=[];for(let s of i)n.has(this.accessors.getLocationId(s))&&o.push(s);return o}),this.getLocationsById=U(this.getLocationsHavingFlows,r=>{if(!r)return;let i=new Map;for(let n of r)i.set(this.accessors.getLocationId(n),n);return i}),this.getLocationWeightGetter=U(this.getSortedFlowsForKnownLocations,r=>r?vv(r,this.accessors.getFlowmapDataAccessors()):void 0),this.getClusterLevels=U(this.getClusterLevelsFromProps,this.getLocationsHavingFlows,this.getLocationWeightGetter,(r,i,n)=>r||(!i||!n?void 0:Cv(i,this.accessors.getFlowmapDataAccessors(),n,{maxZoom:zB}))),this.getClusterIndex=U(this.getLocationsById,this.getLocationWeightGetter,this.getClusterLevels,(r,i,n)=>{if(!r||!i||!n)return;let o=Av(n);return Iv(o,n,r,this.accessors.getFlowmapDataAccessors(),i),o}),this.getAvailableClusterZoomLevels=U(this.getClusterIndex,this.getSelectedLocations,(r,i)=>{if(!r)return;let n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=a=>{let c=r.getClusterById(a);if(c)o=Math.max(o,c.zoom),n=Math.min(n,c.zoom);else{let l=r.getMinZoomForLocation(a);o=Math.max(o,l)}};if(i)for(let a of i)s(a);return r.availableZoomLevels.filter(a=>o<=a&&a<=n)}),this._getClusterZoom=U(this.getClusterIndex,this.getZoom,this.getAvailableClusterZoomLevels,(r,i,n)=>!r||!n||i==null?void 0:Ev(n,i)),this.getClusterZoom=(r,i)=>{let{settings:n}=r;if(n.clusteringEnabled)return n.clusteringAuto||n.clusteringLevel==null?this._getClusterZoom(r,i):n.clusteringLevel},this.getLocationsForSearchBox=U(this.getClusteringEnabled,this.getLocationsHavingFlows,this.getSelectedLocations,this.getClusterZoom,this.getClusterIndex,(r,i,n,o,s)=>{if(!i)return;let a=Array.from(i);if(s&&n){let c=[];for(let l of n){let f=s.getClusterById(l);f&&!a.find(u=>(Bi(u)?u.id:this.accessors.getLocationId(u))===l)&&c.push(f)}c.length>0&&(a=a.concat(c))}return a}),this.getDiffMode=U(this.getFlowsFromProps,r=>{if(r){for(let i of r)if(this.accessors.getFlowMagnitude(i)<0)return!0}return!1}),this._getFlowmapColors=U(this.getDiffMode,this.getColorScheme,this.getDarkMode,this.getFadeEnabled,this.getFadeOpacityEnabled,this.getFadeAmount,this.getAnimate,QA),this.getFlowmapColorsRGBA=U(this._getFlowmapColors,r=>GA(r)?ZA(r):KA(r)),this.getUnknownLocations=U(this.getLocationIds,this.getFlowsFromProps,this.getSortedFlowsForKnownLocations,(r,i,n)=>{if(!r||!i||n)return;let o=new Set;for(let s of i)r.has(this.accessors.getFlowOriginId(s))||o.add(this.accessors.getFlowOriginId(s)),r.has(this.accessors.getFlowDestId(s))||o.add(this.accessors.getFlowDestId(s));return o}),this.getSortedAggregatedFlows=U(this.getClusterIndex,this.getClusteringEnabled,this.getSortedFlowsForKnownLocations,this.getClusterZoom,(r,i,n,o)=>{if(!n)return;let s;return i&&r&&o!=null?s=r.aggregateFlows(n,o,this.accessors.getFlowmapDataAccessors()):s=Lv(n,this.accessors.getFlowmapDataAccessors()),s.sort((a,c)=>Kt(Math.abs(this.accessors.getFlowMagnitude(a)),Math.abs(this.accessors.getFlowMagnitude(c)))),s}),this.getSortedAggregatedFilteredFlows=U(this.getClusterIndex,this.getClusteringEnabled,this.getSortedFlowsForKnownLocationsFilteredByTime,this.getClusterZoom,this.getTimeExtent,(r,i,n,o,s)=>{if(!n)return;let a;return i&&r&&o!=null?a=r.aggregateFlows(n,o,this.accessors.getFlowmapDataAccessors()):a=Lv(n,this.accessors.getFlowmapDataAccessors()),a.sort((c,l)=>Kt(Math.abs(this.accessors.getFlowMagnitude(c)),Math.abs(this.accessors.getFlowMagnitude(l)))),a}),this.getFlowsForScaleDomain=U(this.getTemporalScaleDomain,this.getSortedAggregatedFlows,this.getSortedAggregatedFilteredFlows,(r,i,n)=>r==="all"?i:n),this.getExpandedSelectedLocationsSet=U(this.getClusteringEnabled,this.getSelectedLocationsSet,this.getClusterIndex,(r,i,n)=>{if(!i||!n)return i;let o=new Set;for(let s of i){let a=n.getClusterById(s);if(a){let c=n.expandCluster(a);for(let l of c)o.add(l)}else o.add(s)}return o}),this.getTotalCountsByTime=U(this.getSortedFlowsForKnownLocations,this.getTimeGranularityKey,this.getTimeExtent,this.getExpandedSelectedLocationsSet,this.getLocationFilterMode,(r,i,n,o,s)=>{let a=i?zm(i):void 0;if(!r||!a||!n)return;let c=r.reduce((l,f)=>{if(this.isFlowInSelection(f,o,s)){let u=a.interval(this.accessors.getFlowTime(f)).getTime();l.set(u,(l.get(u)??0)+this.accessors.getFlowMagnitude(f))}return l},new Map);return Array.from(c.entries()).map(([l,f])=>({time:new Date(l),count:f}))}),this.getMaxLocationCircleSize=U(this.getLocationTotalsEnabled,r=>r?17:1),this.getViewportBoundingBox=U(this.getViewport,this.getMaxLocationCircleSize,Pv),this.getLocationsForZoom=U(this.getClusteringEnabled,this.getLocationsHavingFlows,this.getClusterIndex,this.getClusterZoom,(r,i,n,o)=>r&&n?n.getClusterNodesFor(o):i),this.getLocationTotals=U(this.getLocationsForZoom,this.getSortedAggregatedFilteredFlows,this.getSelectedLocationsSet,this.getLocationFilterMode,(r,i,n,o)=>{if(!i)return;let s=new Map,a=(c,l)=>{let f=s.get(c)??{incomingCount:0,outgoingCount:0,internalCount:0};return l.incomingCount!=null&&(f.incomingCount+=l.incomingCount),l.outgoingCount!=null&&(f.outgoingCount+=l.outgoingCount),l.internalCount!=null&&(f.internalCount+=l.internalCount),f};for(let c of i)if(this.isFlowInSelection(c,n,o)){let l=this.accessors.getFlowOriginId(c),f=this.accessors.getFlowDestId(c),u=this.accessors.getFlowMagnitude(c);l===f?s.set(l,a(l,{internalCount:u})):(s.set(l,a(l,{outgoingCount:u})),s.set(f,a(f,{incomingCount:u})))}return s}),this.getLocationsTree=U(this.getLocationsForZoom,r=>{if(!r)return;let i=Array.isArray(r)?r:Array.from(r),n=new Yi(i.length,64,Float32Array);for(let o=0;o{let n=this._getLocationsInBboxIndices(r,i);if(n)return new Set(n.map(o=>this.accessors.getLocationId(r.points[o])))}),this.getLocationIdsInViewport=Nm({memoize:nv,memoizeOptions:{equalityCheck:(r,i)=>{if(r===i)return!0;if(r==null||i==null||r.size!==i.size)return!1;for(let n of r)if(!i.has(n))return!1;return!0}}})(this._getLocationIdsInViewport,r=>{if(r)return r}),this.getTotalUnfilteredCount=U(this.getSortedFlowsForKnownLocations,r=>{if(r)return r.reduce((i,n)=>i+this.accessors.getFlowMagnitude(n),0)}),this.getTotalFilteredCount=U(this.getSortedAggregatedFilteredFlows,this.getSelectedLocationsSet,this.getLocationFilterMode,(r,i,n)=>r?r.reduce((s,a)=>this.isFlowInSelection(a,i,n)?s+this.accessors.getFlowMagnitude(a):s,0):void 0),this._getLocationTotalsExtent=U(this.getLocationTotals,r=>Dv(r,void 0)),this._getLocationTotalsForViewportExtent=U(this.getLocationTotals,this.getLocationIdsInViewport,(r,i)=>Dv(r,i)),this.getLocationTotalsExtent=(r,i)=>r.settings.adaptiveScalesEnabled?this._getLocationTotalsForViewportExtent(r,i):this._getLocationTotalsExtent(r,i),this.getFlowsForFlowmapLayer=U(this.getSortedAggregatedFilteredFlows,this.getLocationIdsInViewport,this.getSelectedLocationsSet,this.getLocationFilterMode,this.getMaxTopFlowsDisplayNum,this.getFlowEndpointsInViewportMode,(r,i,n,o,s,a)=>{if(!r||!i)return;let c=[],l=0;for(let f of r){let u=this.accessors.getFlowOriginId(f),d=this.accessors.getFlowDestId(f),h=i.has(u),p=i.has(d);if((a==="both"?h&&p:h||p)&&this.isFlowInSelection(f,n,o)&&u!==d&&(c.push(f),l++),l>s)break}return c.reverse()}),this._getFlowMagnitudeExtent=U(this.getFlowsForScaleDomain,this.getSelectedLocationsSet,this.getLocationFilterMode,(r,i,n)=>{if(!r)return;let o;for(let s of r)if(this.accessors.getFlowOriginId(s)!==this.accessors.getFlowDestId(s)&&this.isFlowInSelection(s,i,n)){let a=this.accessors.getFlowMagnitude(s);o==null?o=[a,a]:(ao[1]&&(o[1]=a))}return o}),this._getAdaptiveFlowMagnitudeExtent=U(this.getFlowsForScaleDomain,this.getLocationIdsInViewport,this.getSelectedLocationsSet,this.getLocationFilterMode,this.getMaxTopFlowsDisplayNum,this.getFlowEndpointsInViewportMode,(r,i,n,o,s,a)=>{if(!r||!i)return;let c=[],l=0;for(let u of r){let d=this.accessors.getFlowOriginId(u),h=this.accessors.getFlowDestId(u),p=i.has(d),g=i.has(h);if((a==="both"?p&&g:p||g)&&this.isFlowInSelection(u,n,o)&&d!==h&&(c.push(u),l++),l>s)break}let f=Kn(c,this.accessors.getFlowMagnitude);return f[0]!==void 0&&f[1]!==void 0?f:void 0}),this.getFlowMagnitudeExtent=(r,i)=>r.settings.adaptiveScalesEnabled?this._getAdaptiveFlowMagnitudeExtent(r,i):this._getFlowMagnitudeExtent(r,i),this.getLocationMaxAbsTotalGetter=U(this.getLocationTotals,r=>i=>{let n=r?.get(i);if(n)return Math.max(Math.abs(n.incomingCount+n.internalCount),Math.abs(n.outgoingCount+n.internalCount))}),this.getFlowThicknessScale=U(this.getFlowMagnitudeExtent,Mv),this.getCircleSizeScale=U(this.getMaxLocationCircleSize,this.getLocationTotalsEnabled,this.getLocationTotalsExtent,(r,i,n)=>{if(!i)return()=>r;if(n)return pm().range([0,r]).domain([0,Math.max.apply(null,n.map(o=>Math.abs(o||0)))])}),this.getInCircleSizeGetter=U(this.getCircleSizeScale,this.getLocationTotals,(r,i)=>n=>{let o=i?.get(n);return o&&r&&r(Math.abs(o.incomingCount+o.internalCount))||0}),this.getOutCircleSizeGetter=U(this.getCircleSizeScale,this.getLocationTotals,(r,i)=>n=>{let o=i?.get(n);return o&&r&&r(Math.abs(o.outgoingCount+o.internalCount))||0}),this.getSortedLocationsForZoom=U(this.getLocationsForZoom,this.getInCircleSizeGetter,this.getOutCircleSizeGetter,(r,i,n)=>r?[...r].sort((s,a)=>{let c=this.accessors.getLocationId(s),l=this.accessors.getLocationId(a);return ut(Math.max(i(c),n(c)),Math.max(i(l),n(l)))}):void 0),this.getLocationsForFlowmapLayer=U(this.getSortedLocationsForZoom,r=>r),this.getLocationsForFlowmapLayerById=U(this.getLocationsForFlowmapLayer,r=>{if(r)return r.reduce((i,n)=>(i.set(this.accessors.getLocationId(n),n),i),new Map)}),this.getLocationOrClusterByIdGetter=U(this.getClusterIndex,this.getLocationsById,(r,i)=>n=>r?.getClusterById(n)??i?.get(n)),this.getLayersData=U(this.getLocationsForFlowmapLayer,this.getFlowsForFlowmapLayer,this.getFlowmapColorsRGBA,this.getLocationsForFlowmapLayerById,this.getLocationIdsInViewport,this.getInCircleSizeGetter,this.getOutCircleSizeGetter,this.getFlowThicknessScale,this.getFlowMagnitudeExtent,this.getViewport,this.getFlowLinesRenderingMode,this.getLocationLabelsEnabled,(r,i,n,o,s,a,c,l,f,u,d,h)=>this._prepareLayersData(r,i,n,o,s,a,c,l,f,u,d,h)),this.accessors=new Sr(e),this.setAccessors(e)}setAccessors(e){this.accessors=new Sr(e)}getAggregateAccessors(){return this.accessors}prepareLayersData(e,r){let i=this.getLocationsForFlowmapLayer(e,r)||[],n=this.getFlowsForFlowmapLayer(e,r)||[],o=this.getFlowmapColorsRGBA(e,r),s=this.getLocationsForFlowmapLayerById(e,r),a=this.getLocationIdsInViewport(e,r),c=this.getInCircleSizeGetter(e,r),l=this.getOutCircleSizeGetter(e,r),f=this.getFlowThicknessScale(e,r),u=this.getFlowMagnitudeExtent(e,r),d=this.getLocationLabelsEnabled(e,r),h=this.getViewport(e,r);return this._prepareLayersData(i,n,o,s,a,c,l,f,u,h,e.settings.flowLinesRenderingMode,d)}_prepareLayersData(e,r,i,n,o,s,a,c,l,f,u,d){e||(e=[]),r||(r=[]);let{getFlowOriginId:h,getFlowDestId:p,getFlowMagnitude:g,getLocationId:m,getLocationLon:_,getLocationLat:T,getLocationName:y}=this.accessors,x=XA(i,l,u==="animated-straight"),w=Float64Array.from((function*(){for(let L of e)yield _(L),yield T(L),yield 0})()),b=Pm(i)?i.positive.locationCircles.inner:i.locationCircles.inner,E=Uint8Array.from((function*(){for(let L of e)yield*b})()),S=Float32Array.from((function*(){for(let L of e){let H=m(L);yield o?.has(H)?s(H):1}})()),A=Float32Array.from((function*(){for(let L of e){let H=m(L);yield o?.has(H)?a(H):1}})()),C=Float64Array.from((function*(){for(let L of r){let H=n?.get(h(L));yield H?_(H):0,yield H?T(H):0,yield 0}})()),I=Float64Array.from((function*(){for(let L of r){let H=n?.get(p(L));yield H?_(H):0,yield H?T(H):0,yield 0}})()),R=Float32Array.from((function*(){for(let L of r)yield c&&c(g(L))||0})()),N=Float32Array.from((function*(){for(let L of r){let H=h(L),Re=p(L);yield Math.max(s(H),a(H)),yield Math.max(s(Re),a(Re))}})()),O=Uint8Array.from((function*(){for(let L of r)yield*x(g(L))})()),W=u==="animated-straight"?Float32Array.from((function*(){for(let L of r)yield new Bv.alea(`${h(L)}-${p(L)}`)()})()):void 0,G=u==="curved"?WB(r,f,n,h,p,_,T):void 0;return{circleAttributes:{length:e.length,attributes:{getPosition:{value:w,size:3},getColor:{value:E,size:4},getInRadius:{value:S,size:1},getOutRadius:{value:A,size:1}}},lineAttributes:{length:r.length,attributes:{getSourcePosition:{value:C,size:3},getTargetPosition:{value:I,size:3},getThickness:{value:R,size:1},getColor:{value:O,size:4},getEndpointOffsets:{value:N,size:2},...W?{getStaggering:{value:W,size:1}}:{},...G?{getCurveOffset:{value:G,size:1}}:{}}},...d?{locationLabels:e.map(y)}:void 0}}getLocationsInBbox(e,r){if(e)return this._getLocationsInBboxIndices(e,r).map(i=>e.points[i])}_getLocationsInBboxIndices(e,r){if(!e)return;let[i,n,o,s]=r,[a,c,l,f]=[Ha(i),Ya(n),Ha(o),Ya(s)];return e.range(Math.min(a,l),Math.min(c,f),Math.max(a,l),Math.max(c,f))}isFlowInSelection(e,r,i){let n=this.accessors.getFlowOriginId(e),o=this.accessors.getFlowDestId(e);if(r)switch(i){case Fi.ALL:return r.has(n)||r.has(o);case Fi.BETWEEN:return r.has(n)&&r.has(o);case Fi.INCOMING:return r.has(o);case Fi.OUTGOING:return r.has(n)}return!0}};function Dv(t,e){if(!t)return;let r;for(let[i,{incomingCount:n,outgoingCount:o,internalCount:s}]of t.entries())if(e==null||e.has(i)){let a=Math.min(n+s,o+s,s),c=Math.max(n+s,o+s,s);r?(ar[1]&&(r[1]=c)):r=[a,c]}return r}function Ha(t){return t/360+.5}function Ya(t){let e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function Lv(t,e){let r=Pa(t,n=>{let o=e.getFlowOriginId(n[0]),s=e.getFlowDestId(n[0]);return{aggregate:!0,origin:o,dest:s,count:n.reduce((c,l)=>{let f=e.getFlowMagnitude(l);return f&&!isNaN(f)&&isFinite(f)?c+f:c},0)}},e.getFlowOriginId,e.getFlowDestId),i=[];for(let n of r.values())for(let o of n.values())i.push(o);return i}function Su(t,e){let{getInRadius:r,getOutRadius:i}=t.attributes;return Math.max(r.value[e],i.value[e])}function Wm(t,e){let{getPosition:r}=t.attributes,i=e*r.size;return[r.value[i],r.value[i+1]]}function kv(t,e){let{getColor:r,getCurveOffset:i,getEndpointOffsets:n,getSourcePosition:o,getTargetPosition:s,getThickness:a,getStaggering:c}=t.attributes;return{length:1,attributes:{getColor:{value:r.value.subarray(e*4,(e+1)*4),size:4},getEndpointOffsets:{value:n.value.subarray(e*2,(e+1)*2),size:2},getSourcePosition:{value:o.value.subarray(e*o.size,(e+1)*o.size),size:o.size},getTargetPosition:{value:s.value.subarray(e*s.size,(e+1)*s.size),size:s.size},getThickness:{value:a.value.subarray(e,e+1),size:1},...c?{getStaggering:{value:c.value.subarray(e,e+1),size:1}}:void 0,...i?{getCurveOffset:{value:i.value.subarray(e,e+1),size:1}}:void 0}}}function WB(t,e,r,i,n,o,s){let a=new Float32Array(t.length),c=new Map,l=512*Math.pow(2,e.zoom??0);return t.forEach((f,u)=>{let d=i(f),h=n(f),p=r?.get(d),g=r?.get(h);if(!p||!g)return;let m=o(p),_=s(p),T=o(g),y=s(g),x=Ha(m)*l,w=Ya(_)*l,b=Ha(T)*l,E=Ya(y)*l,S=x,A=w,C=b,I=E;(S>C||S===C&&A>I)&&([S,C]=[C,S],[A,I]=[I,A]);let R=C-S,N=I-A,O=Math.hypot(R,N);if(!isFinite(O)||O<1)return;let W=(Math.atan2(N,R)%Math.PI+Math.PI)%Math.PI,G=(S*I-A*C)/O,L=[Math.round(W/(6*Math.PI/180)),Math.round(G/18),Math.round(O/24)].join(":"),H=c.get(L)??[];H.push({index:u,originId:d,destId:h,sx:x,sy:w,tx:b,ty:E,chordLengthPx:O}),c.set(L,H)}),c.forEach(f=>{f.sort((u,d)=>{let h=Fv(u.originId,d.originId);if(h!==0)return h;let p=Fv(u.destId,d.destId);return p!==0?p:u.index-d.index}).forEach((u,d)=>{let h=Math.min(72,u.chordLengthPx*.35);a[u.index]=Math.min(h,(d+1)*18)})}),a}function Fv(t,e){if(typeof t=="number"&&typeof e=="number")return t-e;let r=String(t),i=String(e);return ri?1:0}var Au=1e-6;var Ga=Math.PI,Uv=Ga/2,Vm=Ga/4,jm=Ga*2,vu=180/Ga,ti=Ga/180,Eu=Math.abs;var Ru=Math.atan2,Gi=Math.cos;var qi=Math.sin;var zv=Math.sqrt;function Wv(t){return t>1?Uv:t<-1?-Uv:Math.asin(t)}function oo(){}function Cu(t,e){t&&jv.hasOwnProperty(t.type)&&jv[t.type](t,e)}var Vv={Feature:function(t,e){Cu(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,i=-1,n=r.length;++i=0?1:-1,n=i*r,o=Gi(e),s=qi(e),a=Xm*s,c=Ym*o+a*Gi(n),l=a*i*qi(n);qa.add(Ru(l,c)),Hm=t,Ym=o,Xm=s}function Kv(t){return[Ru(t[1],t[0]),Wv(t[2])]}function Zv(t){var e=t[0],r=t[1],i=Gi(r);return[i*Gi(e),i*qi(e),qi(r)]}function Gm(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Qv(t){var e=zv(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}var se,He,ue,tt,Ki,r2,i2,so,Ka,ri,vr,Ar={point:qm,lineStart:Jv,lineEnd:e2,polygonStart:function(){Ar.point=o2,Ar.lineStart=HB,Ar.lineEnd=YB,Ka=new Tr,Jt.polygonStart()},polygonEnd:function(){Jt.polygonEnd(),Ar.point=qm,Ar.lineStart=Jv,Ar.lineEnd=e2,qa<0?(se=-(ue=180),He=-(tt=90)):Ka>Au?tt=90:Ka<-Au&&(He=-90),vr[0]=se,vr[1]=ue},sphere:function(){se=-(ue=180),He=-(tt=90)}};function qm(t,e){ri.push(vr=[se=t,ue=t]),ett&&(tt=e)}function n2(t,e){var r=Zv([t*ti,e*ti]);if(so){var i=Gm(so,r),n=[i[1],-i[0],0],o=Gm(n,i);Qv(o),o=Kv(o);var s=t-Ki,a=s>0?1:-1,c=o[0]*vu*a,l,f=Eu(s)>180;f^(a*Kitt&&(tt=l)):(c=(c+360)%360-180,f^(a*Kitt&&(tt=e))),f?tet(se,ue)&&(ue=t):et(t,ue)>et(se,ue)&&(se=t):ue>=se?(tue&&(ue=t)):t>Ki?et(se,t)>et(se,ue)&&(ue=t):et(t,ue)>et(se,ue)&&(se=t)}else ri.push(vr=[se=t,ue=t]);ett&&(tt=e),so=r,Ki=t}function Jv(){Ar.point=n2}function e2(){vr[0]=se,vr[1]=ue,Ar.point=qm,so=null}function o2(t,e){if(so){var r=t-Ki;Ka.add(Eu(r)>180?r+(r>0?360:-360):r)}else r2=t,i2=e;Jt.point(t,e),n2(t,e)}function HB(){Jt.lineStart()}function YB(){o2(r2,i2),Jt.lineEnd(),Eu(Ka)>Au&&(se=-(ue=180)),vr[0]=se,vr[1]=ue,so=null}function et(t,e){return(e-=t)<0?e+360:e}function XB(t,e){return t[0]-e[0]}function t2(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:eet(i[0],i[1])&&(i[1]=n[1]),et(n[0],i[1])>et(i[0],i[1])&&(i[0]=n[0])):o.push(i=n);for(s=-1/0,r=o.length-1,e=0,i=o[r];e<=r;i=n,++e)n=o[e],(a=et(i[1],n[0]))>s&&(s=a,se=n[0],ue=i[1])}return ri=vr=null,se===1/0||He===1/0?[[NaN,NaN],[NaN,NaN]]:[[se,He],[ue,tt]]}function GB(t,e,r){let{pad:i=.05,maxZoom:n=100}=r||{},o=Km(t),[[s,a],[c,l]]=o,f=i?[[s-i*(c-s),a-i*(l-a)],[c+i*(c-s),l+i*(l-a)]]:o,[u,d]=e;return{...Si({width:u,height:d,bounds:f,padding:r?.padding,maxZoom:n}),width:u,height:d,bearing:0,pitch:0}}function s2(t,e,r,i){let n=s=>({type:"Point",coordinates:e(s)}),o;if(Array.isArray(t))o=t.map(n);else{o=[];for(let s of t)o.push(n(s))}return GB({type:"GeometryCollection",geometries:o},r,i)}function a2(t){return t&&t.locations&&t.flows}function c2(t){return t&&typeof t.setFlowmapState=="function"&&typeof t.getViewportForLocations=="function"&&typeof t.getFlowByIndex=="function"&&typeof t.getLocationById=="function"&&typeof t.getLocationByIndex=="function"&&typeof t.getLayersData=="function"}var ao=class{constructor(e){this.selectors=new Xa(e),this.flowmapData=void 0,this.flowmapState=void 0}setAccessors(e){this.selectors.setAccessors(e)}setFlowmapData(e){this.flowmapData=e}getSelectors(){return this.selectors}getFlowmapData(){return this.flowmapData}async setFlowmapState(e){this.flowmapState=e}getFlowmapState(){return this.flowmapState}async getFlowByIndex(e){return!this.flowmapState||!this.flowmapData?void 0:this.selectors.getFlowsForFlowmapLayer(this.flowmapState,this.flowmapData)?.[e]}async getLocationByIndex(e){return!this.flowmapState||!this.flowmapData?void 0:this.selectors.getLocationsForFlowmapLayer(this.flowmapState,this.flowmapData)?.[e]}async getLayersData(){if(!(!this.flowmapState||!this.flowmapData))return this.selectors.getLayersData(this.flowmapState,this.flowmapData)}async getLocationById(e){if(!this.flowmapState||!this.flowmapData)return;let r=this.selectors.getClusterIndex(this.flowmapState,this.flowmapData);if(r){let n=r.getClusterById(e);if(n)return n}return this.selectors.getLocationsById(this.flowmapState,this.flowmapData)?.get(e)}async getTotalsForLocation(e){if(!(!this.flowmapState||!this.flowmapData))return this.selectors.getLocationTotals(this.flowmapState,this.flowmapData)?.get(e)}async getViewportForLocations(e,r){if(this.flowmapData?.locations)return s2(this.flowmapData.locations,i=>[this.selectors.accessors.getLocationLon(i),this.selectors.accessors.getLocationLat(i)],e,r)}async updateLayersData(e){e(await this.getLayersData())}getClusterZoom(){return this.flowmapState&&this.flowmapData?this.selectors.getClusterZoom(this.flowmapState,this.flowmapData):void 0}getClusterIndex(){return this.flowmapState&&this.flowmapData?this.selectors.getClusterIndex(this.flowmapState,this.flowmapData):void 0}getLocationsById(){return this.flowmapState&&this.flowmapData?this.selectors.getLocationsById(this.flowmapState,this.flowmapData):void 0}getLocationTotals(){return this.flowmapState&&this.flowmapData?this.selectors.getLocationTotals(this.flowmapState,this.flowmapData):void 0}getFlowsForFlowmapLayer(){return this.flowmapState&&this.flowmapData?this.selectors.getFlowsForFlowmapLayer(this.flowmapState,this.flowmapData):void 0}};var Za;(function(t){t.LOCATION="location",t.FLOW="flow"})(Za||(Za={}));var qB=["filter","locationsEnabled","locationTotalsEnabled","locationLabelsEnabled","adaptiveScalesEnabled","flowLinesRenderingMode","animationEnabled","clusteringEnabled","clusteringLevel","fadeEnabled","fadeOpacityEnabled","clusteringAuto","darkMode","fadeAmount","colorScheme","highlightColor","temporalScaleDomain","maxTopFlowsDisplayNum","flowEndpointsInViewportMode"],KB="straight",co;(function(t){t.LOCATION="location",t.FLOW="flow"})(co||(co={}));var Pu=class t extends na{get typedProps(){return this.props}constructor(e){super({...e,onHover:((r,i)=>{let n=Date.now();this.setState({highlightedObject:this._getHighlightedObject(r),lastHoverTime:n});let{onHover:o}=e;o&&this._getFlowmapLayerPickingInfo(r).then(s=>{(this.state?.lastHoverTime??0)<=n&&(this.setState({pickingInfo:s}),o(s,i))})}),onClick:((r,i)=>{let{onClick:n}=e,o=Date.now();this.setState({lastClickTime:o}),n&&this._getFlowmapLayerPickingInfo(r).then(s=>{(this.state?.lastClickTime??0)<=o&&(this.setState({pickingInfo:s}),s&&n(s,i))})})}),this._didWarnAboutAnimationEnabledDeprecation=!1,this._didWarnAboutAnimationEnabledConflict=!1}initializeState(){this.state={accessors:new Sr(this.typedProps),dataProvider:this._getOrMakeDataProvider(),layersData:void 0,highlightedObject:void 0,pickingInfo:void 0,lastHoverTime:void 0,lastClickTime:void 0}}getPickingInfo({info:e}){if(!e.object){let r=this.state?.pickingInfo?.object;if(r)return{...e,object:r,picked:!0}}return e}_getOrMakeDataProvider(){let{data:e,dataProvider:r}=this.typedProps;if(r&&c2(r))return r;if(e&&a2(e)){let i=new ao(this.typedProps);return i.setFlowmapData(e),i}throw new Error("FlowmapLayer: data must be a FlowmapDataProvider or FlowmapData")}_updateDataProvider(){this.setState({dataProvider:this._getOrMakeDataProvider()})}shouldUpdateState(e){let{changeFlags:r}=e;return r.viewportChanged?!0:super.shouldUpdateState(e)}updateState(e){super.updateState(e);let{oldProps:r,props:i,changeFlags:n}=e;if(n.propsChanged,n.dataChanged&&this._updateDataProvider(),(n.viewportChanged||n.dataChanged)&&this.setState({highlightedObject:void 0}),n.viewportChanged||n.dataChanged||n.propsChanged&&qB.some(o=>r[o]!==i[o])){let{dataProvider:o}=this.state||{};o&&(o.setFlowmapState(this._getFlowmapState()),o.updateLayersData(s=>{this.setState({layersData:s,highlightedObject:void 0})},n))}}_getSettingsState(){let e=this.typedProps,r=t.defaultProps,{locationsEnabled:i,locationTotalsEnabled:n,locationLabelsEnabled:o,adaptiveScalesEnabled:s,flowLinesRenderingMode:a,clusteringEnabled:c,clusteringLevel:l,fadeEnabled:f,fadeOpacityEnabled:u,clusteringAuto:d,darkMode:h,fadeAmount:p,colorScheme:g,highlightColor:m,temporalScaleDomain:_,maxTopFlowsDisplayNum:T,flowEndpointsInViewportMode:y}=e;return{locationsEnabled:i??r.locationsEnabled,locationTotalsEnabled:n??r.locationTotalsEnabled,locationLabelsEnabled:o??r.locationLabelsEnabled,adaptiveScalesEnabled:s??r.adaptiveScalesEnabled,flowLinesRenderingMode:a??this._getResolvedFlowLinesRenderingMode(),clusteringEnabled:c??r.clusteringEnabled,clusteringLevel:l,fadeEnabled:f??r.fadeEnabled,fadeOpacityEnabled:u??r.fadeOpacityEnabled,clusteringAuto:d??r.clusteringAuto,darkMode:h??r.darkMode,fadeAmount:p??r.fadeAmount,colorScheme:g,highlightColor:m??r.highlightColor,temporalScaleDomain:_??r.temporalScaleDomain,maxTopFlowsDisplayNum:T??r.maxTopFlowsDisplayNum,flowEndpointsInViewportMode:y??r.flowEndpointsInViewportMode}}_getResolvedFlowLinesRenderingMode(){let{animationEnabled:e,flowLinesRenderingMode:r}=this.typedProps;return r!==void 0?(e!==void 0&&!this._didWarnAboutAnimationEnabledConflict&&(this._didWarnAboutAnimationEnabledConflict=!0,console.warn("FlowmapLayer: `animationEnabled` is deprecated and ignored when `flowLinesRenderingMode` is provided.")),r):e!==void 0?(this._didWarnAboutAnimationEnabledDeprecation||(this._didWarnAboutAnimationEnabledDeprecation=!0,console.warn("FlowmapLayer: `animationEnabled` is deprecated; use `flowLinesRenderingMode` instead.")),e?"animated-straight":"straight"):KB}_getFlowmapState(){let e=this.typedProps;return{viewport:ZB(this.context.viewport),filter:e.filter,settings:this._getSettingsState()}}async _getFlowmapLayerPickingInfo(e){let{index:r,sourceLayer:i}=e,{dataProvider:n,accessors:o}=this.state||{};if(!n||!o)return;let s={...e,picked:e.picked,layer:e.layer,index:e.index,x:e.x,y:e.y,coordinate:e.coordinate,event:e.event};if(i instanceof jn||i instanceof ca||i instanceof Vn){let a=r===-1?void 0:await n.getFlowByIndex(r);if(a){let c=await n.getLocationById(o.getFlowOriginId(a)),l=await n.getLocationById(o.getFlowDestId(a));if(c&&l)return{...s,object:{type:Za.FLOW,flow:a,origin:c,dest:l,count:o.getFlowMagnitude(a)}}}}else if(i instanceof da){let a=r===-1?void 0:await n.getLocationByIndex(r);if(a){let c=o.getLocationId(a),l=o.getLocationName(a),f=await n.getTotalsForLocation(c),{circleAttributes:u}=this.state?.layersData||{};if(f&&u){let d=Su(u,e.index);return{...s,object:{type:Za.LOCATION,location:a,id:c,name:l,totals:f,circleRadius:d}}}}}}_getHighlightedObject(e){let{index:r,sourceLayer:i}=e;if(!(r<0)){if(i instanceof jn||i instanceof ca||i instanceof Vn){let{lineAttributes:n}=this.state?.layersData||{};if(n){let o=kv(n,r);return this.typedProps.fadeOpacityEnabled&&(o={...o,attributes:{...o.attributes,getColor:{...o.attributes.getColor,value:new Uint8Array([...o.attributes.getColor.value.slice(0,3),255])}}}),{type:co.FLOW,lineAttributes:o}}}else if(i instanceof da){let{circleAttributes:n}=this.state?.layersData||{};if(n)return{type:co.LOCATION,coords:Wm(n,r),radius:Su(n,r)}}}}renderLayers(){let e=this.typedProps,r=this._getResolvedFlowLinesRenderingMode(),i=e.highlightColor??t.defaultProps.highlightColor,n=e.flowLineThicknessScale??t.defaultProps.flowLineThicknessScale,o=e.flowLineCurviness??t.defaultProps.flowLineCurviness,s=[];if(this.state?.layersData){let{layersData:a,highlightedObject:c}=this.state,{circleAttributes:l,lineAttributes:f,locationLabels:u}=a||{};if(l&&f){let d=HA(this._getSettingsState()),h=dt(d.outlineColor||(e.darkMode?"#000":"#fff")),p={data:f,parameters:{...e.parameters??{},depthTest:!1}};switch(r){case"animated-straight":s.push(new ca({...this.getSubLayerProps({...p,id:"animated-flow-lines",drawOutline:!1,thicknessUnit:10*n})}));break;case"curved":s.push(new Vn({...this.getSubLayerProps({...p,id:"curved-flow-lines",drawOutline:!0,outlineColor:h,thicknessUnit:12*n,curviness:o})}));break;default:s.push(new jn({...this.getSubLayerProps({...p,id:"flow-lines",drawOutline:!0,outlineColor:h,thicknessUnit:12*n})}));break}if(s.push(new da(this.getSubLayerProps({id:"circles",data:l,emptyColor:e.darkMode?[0,0,0,255]:[255,255,255,255],outlineEmptyMix:.4}))),c)switch(c.type){case co.LOCATION:s.push(new Eg({...this.getSubLayerProps({id:"location-highlight",data:[c],pickable:!1,antialiasing:!0,stroked:!0,filled:!1,lineWidthUnits:"pixels",getLineWidth:2,radiusUnits:"pixels",getRadius:g=>g.radius,getLineColor:dt(i),getPosition:g=>g.coords})}));break;case co.FLOW:r==="curved"?s.push(new Vn({...this.getSubLayerProps({id:"flow-highlight",data:c.lineAttributes,drawOutline:!0,pickable:!1,outlineColor:dt(i),outlineThickness:1.5,thicknessUnit:12*n,curviness:o,parameters:{depthTest:!1}})})):s.push(new jn({...this.getSubLayerProps({id:"flow-highlight",data:c.lineAttributes,drawOutline:!0,pickable:!1,outlineColor:dt(i),outlineThickness:1.5,thicknessUnit:12*n,parameters:{depthTest:!1}})}));break}}u&&s.push(new Mg(this.getSubLayerProps({id:"location-labels",data:u,maxWidth:1e3,pickable:!1,fontFamily:"Helvetica",getPixelOffset:(d,{index:h})=>[0,Su(l,h)+5],getPosition:(d,{index:h})=>Wm(l,h),getText:d=>d,getSize:10,getColor:[255,255,255,255],getAngle:0,getTextAnchor:"middle",getAlignmentBaseline:"top"})))}return s}};Pu.defaultProps={darkMode:!0,fadeAmount:50,locationsEnabled:!0,locationTotalsEnabled:!0,locationLabelsEnabled:!1,clusteringEnabled:!0,fadeEnabled:!0,fadeOpacityEnabled:!1,clusteringAuto:!0,clusteringLevel:void 0,adaptiveScalesEnabled:!0,temporalScaleDomain:"selected",flowLineThicknessScale:1,flowLineCurviness:1,colorScheme:"Teal",highlightColor:"orange",maxTopFlowsDisplayNum:5e3,flowEndpointsInViewportMode:"any"};var Zm=Pu;function ZB(t){let{width:e,height:r,longitude:i,latitude:n,zoom:o,pitch:s,bearing:a}=t;return{width:e,height:r,longitude:i,latitude:n,zoom:o,pitch:s,bearing:a}}window.FlowmapGL={Deck:Bn,FlowmapLayer:Zm,MapboxOverlay:Wn};})(); +//# sourceMappingURL=flowmap-gl-bundle.min.js.map diff --git a/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json new file mode 100644 index 00000000..5f264b2e --- /dev/null +++ b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json @@ -0,0 +1,764 @@ +{ + "schemaVersion": 1, + "source": "npm release packages", + "build": { + "command": "data-raw/flowmap-vendor/build-flowmap.sh build", + "node": "v26.0.0", + "npm": "11.14.1", + "esbuild": "0.28.0" + }, + "bundle": { + "path": "inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js", + "sha256": "6ee7d9f48276e5ff94a81333b8006590e7a3dba9cdb26c8802a9adf61a380fda", + "bytes": 811231 + }, + "patches": [ + { + "path": "data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch", + "sha256": "4643c406fdd4c82175f5cbda27d414d5b1e65b08d7270b98eef9b3dc1045b7e7", + "bytes": 19025, + "purpose": "Add temporalScaleDomain so temporal flow width/color domains can use selected-time or all-time flows." + } + ], + "copyrights": { + "path": "LICENSE.note" + }, + "colorSchemes": { + "source": "FlowMapGL 9.3.0 vendored bundle", + "names": [ + "Blues", + "BluGrn", + "BluYl", + "BrwnYl", + "BuGn", + "BuPu", + "Burg", + "BurgYl", + "Cool", + "DarkMint", + "Emrld", + "GnBu", + "Grayish", + "Greens", + "Greys", + "Inferno", + "Magenta", + "Magma", + "Mint", + "Oranges", + "OrRd", + "OrYel", + "Peach", + "Plasma", + "PinkYl", + "PuBu", + "PuBuGn", + "PuRd", + "Purp", + "Purples", + "PurpOr", + "RdPu", + "RedOr", + "Reds", + "Sunset", + "SunsetDark", + "Teal", + "TealGrn", + "Viridis", + "Warm", + "YlGn", + "YlGnBu", + "YlOrBr", + "YlOrRd" + ] + }, + "directDependencies": [ + { + "name": "@deck.gl/core", + "version": "9.3.2", + "license": "MIT", + "integrity": "sha512-32Va3np0Zdlz/LBNtDWCs4EkKqdHmXcbGmVp4+7i1Cpdza8y8CFmJs2VPOmSX1fwHvNCGkAZV/SFZOfDb2INsg==", + "resolved": "https://registry.npmjs.org/@deck.gl/core/-/core-9.3.2.tgz", + "gitHead": "09af8de8d18a9cb9a31d064cae8f9e7239df7f53", + "homepage": null, + "repository": "https://github.com/visgl/deck.gl.git" + }, + { + "name": "@deck.gl/layers", + "version": "9.3.2", + "license": "MIT", + "integrity": "sha512-TeVfhQ/cQU1oTlTn16mCp7268d1uBJ6dwfgmKXThe2TzW9hql3iJaxbYTKg2phDg5YSiGmeEOpXbeBh59jyUcA==", + "resolved": "https://registry.npmjs.org/@deck.gl/layers/-/layers-9.3.2.tgz", + "gitHead": "09af8de8d18a9cb9a31d064cae8f9e7239df7f53", + "homepage": null, + "repository": "https://github.com/visgl/deck.gl.git" + }, + { + "name": "@deck.gl/mapbox", + "version": "9.3.2", + "license": "MIT", + "integrity": "sha512-+T9pJwsOXwjUxyGN6oiBMfIs28VtDIG1V1Rqz4qqn4TjjNEFFw+xO0olJIg8FO5IAqw2OtePdsrMj0tX8tHdGQ==", + "resolved": "https://registry.npmjs.org/@deck.gl/mapbox/-/mapbox-9.3.2.tgz", + "gitHead": "09af8de8d18a9cb9a31d064cae8f9e7239df7f53", + "homepage": null, + "repository": "https://github.com/visgl/deck.gl.git" + }, + { + "name": "@flowmap.gl/data", + "version": "9.3.0", + "license": "Apache-2.0", + "integrity": "sha512-1a4EZJdK13q5Mj3bVurFSpuYVBLSaByJJ9B4LMd7XvuD/ovB6JArDjdJetsA9jVHdA89lZli7f8ALX+oek+WtA==", + "resolved": "https://registry.npmjs.org/@flowmap.gl/data/-/data-9.3.0.tgz", + "gitHead": "ed581e11ca674ed1e17457a9526c864f8def678b", + "homepage": null, + "repository": "git@github.com:visgl/flowmap.gl.git" + }, + { + "name": "@flowmap.gl/layers", + "version": "9.3.0", + "license": "Apache-2.0", + "integrity": "sha512-kARLb28BYK58O4iuiZK0IdNO+W1EX4+MaLbufRU1O0LTMM0Aoe2lET7y4QcrOifQT0dV6cAjzjw4GDnbogOxJg==", + "resolved": "https://registry.npmjs.org/@flowmap.gl/layers/-/layers-9.3.0.tgz", + "gitHead": "ed581e11ca674ed1e17457a9526c864f8def678b", + "homepage": null, + "repository": "git@github.com:visgl/flowmap.gl.git" + }, + { + "name": "@luma.gl/core", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-jCFm2htvrVpcXIy85TBTF1ROgMfknKnfw2OH+Vydr41hiCFd6nqr79gM3f2uhaNkal0BghFNqF3qDioKiUWtew==", + "resolved": "https://registry.npmjs.org/@luma.gl/core/-/core-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "@luma.gl/engine", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-StmMTzUcUlpKMU3wvWU48A6OQyphptD9zVGBsSkK6iHIBdtBKlOcmqRkyfvRouo8JHtlrnoJDHLVKhxorwhGAg==", + "resolved": "https://registry.npmjs.org/@luma.gl/engine/-/engine-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "@luma.gl/shadertools", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-4ZfG4/Utix951vqyiG/JIx+Eg+GMNwOxgr/07/i0gf7bK1gJZIEQ5BxVcDw4MCQfdoVlGPGzl0cQKbdqBvaCAQ==", + "resolved": "https://registry.npmjs.org/@luma.gl/shadertools/-/shadertools-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "esbuild", + "version": "0.28.0", + "license": "MIT", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/evanw/esbuild.git" + } + ], + "transitiveDependencies": [ + { + "name": "@esbuild/darwin-arm64", + "version": "0.28.0", + "license": "MIT", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/evanw/esbuild.git" + }, + { + "name": "@loaders.gl/core", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-DZmsTwxdKh3q+mS1vSOW2EXFgwxZ4nIBte4H5g6e4VyQoQ6jAOkk0M6V+Asgy/eqjGTNjhfBA1HIkyBl0A9hcA==", + "resolved": "https://registry.npmjs.org/@loaders.gl/core/-/core-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/images", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-b+1keNvPlyLniWtX4ZaThz2dF2aohi8Q+OEsDF2hJNZYyZJOqP9b/72UhlVk+inxTJfTLRBNARs2TJ2ssBlelg==", + "resolved": "https://registry.npmjs.org/@loaders.gl/images/-/images-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/loader-utils", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-kqwBbyRC7rrQVsnJyKeoaig9hxaa5oj91OKqWm27HPuVn4q2dD67SEhiG0ND62eRp0tLY6jTqEcI5kDzHBZ6MA==", + "resolved": "https://registry.npmjs.org/@loaders.gl/loader-utils/-/loader-utils-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/schema", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-mJTZehTHIFl8ed+03nebuPAMnLP8Yp00DKTzCnKT2HNy/uV4+Sw+GrGIuhPHGU8tdQmtBXRURGM2ZxUAxMfGKg==", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema/-/schema-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/schema-utils", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-yYYRD/POBEO72rhIyLASrqKUUhfIOQuFk/fgInN6Td2qvFgsHbo5UaCM4sTqVUWwNxNvXDQi8ezpbnCa/yi+OQ==", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema-utils/-/schema-utils-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/worker-utils", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-oiZ0SoC1QKrOkhYPlVZ6Q06CtmuFRyZw2rwzmT08ZyaGtOArIJHDjlhxzwWiv+6fdws47Ub5uIGsdI1Ab1xYsA==", + "resolved": "https://registry.npmjs.org/@loaders.gl/worker-utils/-/worker-utils-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@luma.gl/webgl", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-X+aavdP5o6VFHSA0es9gKZTT145jfcFbhKJt/gwJrptnKNoIW4+Y37ZEpCo1AzAnr+FQCxjgcM2kOCpoWMfSVA==", + "resolved": "https://registry.npmjs.org/@luma.gl/webgl/-/webgl-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "@mapbox/tiny-sdf", + "version": "2.2.0", + "license": "BSD-2-Clause", + "integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==", + "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz", + "gitHead": null, + "homepage": "https://github.com/mapbox/tiny-sdf#readme", + "repository": "git+https://github.com/mapbox/tiny-sdf.git" + }, + { + "name": "@math.gl/core", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-FrdHBCVG3QdrworwrUSzXIaK+/9OCRLscxI2OUy6sLOHyHgBMyfnEGs99/m3KNvs+95BsnQLWklVfpKfQzfwKA==", + "resolved": "https://registry.npmjs.org/@math.gl/core/-/core-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/polygon", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-YA/9PzaCRHbIP5/0E9uTYrqe+jsYTQoqoDWhf6/b0Ixz8bPZBaGDEafLg3z7ffBomZLacUty9U3TlPjqMtzPjA==", + "resolved": "https://registry.npmjs.org/@math.gl/polygon/-/polygon-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/sun", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-i3q6OCBLSZ5wgZVhXg+X7gsjY/TUtuFW/2KBiq/U1ypLso3S4sEykoU/MGjxUv1xiiGtr+v8TeMbO1OBIh/HmA==", + "resolved": "https://registry.npmjs.org/@math.gl/sun/-/sun-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/types", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-clYZdHcmRvMzVK5fjeDkQlHUzXQSNdZ7s4xOqC3nJPgz4C/TZkUecTo9YS4PruZqtDda/ag4erndP0MIn40dGA==", + "resolved": "https://registry.npmjs.org/@math.gl/types/-/types-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/web-mercator", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-HZo3vO5GCMkXJThxRJ5/QYUYRr3XumfT8CzNNCwoJfinxy5NtKUd7dusNTXn7yJ40UoB8FMIwkVwNlqaiRZZAw==", + "resolved": "https://registry.npmjs.org/@math.gl/web-mercator/-/web-mercator-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@probe.gl/env", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-+68seNDMVsEegRB47pFA/Ws1Fjy8agcFYXxzorKToyPcD6zd+gZ5uhwoLd7TzsSw6Ydns//2KEszWn+EnNHTbA==", + "resolved": "https://registry.npmjs.org/@probe.gl/env/-/env-4.1.1.tgz", + "gitHead": "bd33a0cf48fe0bcc56941272e3a760d13df65b4e", + "homepage": null, + "repository": "https://github.com/visgl/probe.gl.git" + }, + { + "name": "@probe.gl/log", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-kcZs9BT44pL7hS1OkRGKYRXI/SN9KejUlPD+BY40DguRLzdC5tLG/28WGMyfKdn/51GT4a0p+0P8xvDn1Ez+Kg==", + "resolved": "https://registry.npmjs.org/@probe.gl/log/-/log-4.1.1.tgz", + "gitHead": "bd33a0cf48fe0bcc56941272e3a760d13df65b4e", + "homepage": null, + "repository": "https://github.com/visgl/probe.gl.git" + }, + { + "name": "@probe.gl/stats", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-4VpAyMHOqydSvPlEyHwXaE+AkIdR03nX+Qhlxsk2D/IW4OVmDZgIsvJB1cDzyEEtcfKcnaEbfXeiPgejBceT6g==", + "resolved": "https://registry.npmjs.org/@probe.gl/stats/-/stats-4.1.1.tgz", + "gitHead": "bd33a0cf48fe0bcc56941272e3a760d13df65b4e", + "homepage": null, + "repository": "https://github.com/visgl/probe.gl.git" + }, + { + "name": "@swc/helpers", + "version": "0.5.23", + "license": "Apache-2.0", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "gitHead": null, + "homepage": "https://swc.rs", + "repository": "git+https://github.com/swc-project/swc.git" + }, + { + "name": "@types/command-line-args", + "version": "5.2.3", + "license": "MIT", + "integrity": "sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.3.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/command-line-args", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/command-line-usage", + "version": "5.0.4", + "license": "MIT", + "integrity": "sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.4.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/command-line-usage", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/geojson", + "version": "7946.0.16", + "license": "MIT", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/geojson", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/node", + "version": "24.12.4", + "license": "MIT", + "integrity": "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/offscreencanvas", + "version": "2019.7.3", + "license": "MIT", + "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/offscreencanvas", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "ansi-styles", + "version": "4.3.0", + "license": "MIT", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/ansi-styles" + }, + { + "name": "apache-arrow", + "version": "21.1.0", + "license": "Apache-2.0", + "integrity": "sha512-kQrYLxhC+NTVVZ4CCzGF6L/uPVOzJmD1T3XgbiUnP7oTeVFOFgEUu6IKNwCDkpFoBVqDKQivlX4RUFqqnWFlEA==", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.1.0.tgz", + "gitHead": null, + "homepage": "https://arrow.apache.org/js/", + "repository": "git+https://github.com/apache/arrow-js.git" + }, + { + "name": "array-back", + "version": "6.2.3", + "license": "MIT", + "integrity": "sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.3.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/75lb/array-back.git" + }, + { + "name": "chalk", + "version": "4.1.2", + "license": "MIT", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/chalk" + }, + { + "name": "chalk-template", + "version": "0.4.0", + "license": "MIT", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/chalk-template" + }, + { + "name": "color-convert", + "version": "2.0.1", + "license": "MIT", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "gitHead": null, + "homepage": null, + "repository": "Qix-/color-convert" + }, + { + "name": "color-name", + "version": "1.1.4", + "license": "MIT", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "gitHead": null, + "homepage": "https://github.com/colorjs/color-name", + "repository": "git@github.com:colorjs/color-name.git" + }, + { + "name": "command-line-args", + "version": "6.0.2", + "license": "MIT", + "integrity": "sha512-AIjYVxrV9X752LmPDLbVYv8aMCuHPSLZJXEo2qo/xJfv+NYhaZ4sMSF01rM+gHPaMgvPM0l5D/F+Qx+i2WfSmQ==", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-6.0.2.tgz", + "gitHead": null, + "homepage": "https://github.com/75lb/command-line-args#readme", + "repository": "git+https://github.com/75lb/command-line-args.git" + }, + { + "name": "command-line-usage", + "version": "7.0.4", + "license": "MIT", + "integrity": "sha512-85UdvzTNx/+s5CkSgBm/0hzP80RFHAa7PsfeADE5ezZF3uHz3/Tqj9gIKGT9PTtpycc3Ua64T0oVulGfKxzfqg==", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.4.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/75lb/command-line-usage" + }, + { + "name": "d3-array", + "version": "3.2.4", + "license": "ISC", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-array/", + "repository": "https://github.com/d3/d3-array.git" + }, + { + "name": "d3-color", + "version": "3.1.0", + "license": "ISC", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-color/", + "repository": "https://github.com/d3/d3-color.git" + }, + { + "name": "d3-format", + "version": "3.1.2", + "license": "ISC", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-format/", + "repository": "https://github.com/d3/d3-format.git" + }, + { + "name": "d3-geo", + "version": "3.1.1", + "license": "ISC", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-geo/", + "repository": "https://github.com/d3/d3-geo.git" + }, + { + "name": "d3-interpolate", + "version": "3.0.1", + "license": "ISC", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-interpolate/", + "repository": "https://github.com/d3/d3-interpolate.git" + }, + { + "name": "d3-scale", + "version": "4.0.2", + "license": "ISC", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-scale/", + "repository": "https://github.com/d3/d3-scale.git" + }, + { + "name": "d3-scale-chromatic", + "version": "3.1.0", + "license": "ISC", + "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==", + "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-scale-chromatic/", + "repository": "https://github.com/d3/d3-scale-chromatic.git" + }, + { + "name": "d3-time", + "version": "3.1.0", + "license": "ISC", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-time/", + "repository": "https://github.com/d3/d3-time.git" + }, + { + "name": "d3-time-format", + "version": "4.1.0", + "license": "ISC", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-time-format/", + "repository": "https://github.com/d3/d3-time-format.git" + }, + { + "name": "earcut", + "version": "2.2.4", + "license": "ISC", + "integrity": "sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==", + "resolved": "https://registry.npmjs.org/earcut/-/earcut-2.2.4.tgz", + "gitHead": null, + "homepage": null, + "repository": "git://github.com/mapbox/earcut.git" + }, + { + "name": "find-replace", + "version": "5.0.2", + "license": "MIT", + "integrity": "sha512-Y45BAiE3mz2QsrN2fb5QEtO4qb44NcS7en/0y9PEVsg351HsLeVclP8QPMH79Le9sH3rs5RSwJu99W0WPZO43Q==", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-5.0.2.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/75lb/find-replace.git" + }, + { + "name": "flatbuffers", + "version": "25.9.23", + "license": "Apache-2.0", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "gitHead": null, + "homepage": "https://google.github.io/flatbuffers/", + "repository": "git+https://github.com/google/flatbuffers.git" + }, + { + "name": "gl-matrix", + "version": "3.4.4", + "license": "MIT", + "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==", + "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz", + "gitHead": null, + "homepage": "http://glmatrix.net", + "repository": "https://github.com/toji/gl-matrix.git" + }, + { + "name": "has-flag", + "version": "4.0.0", + "license": "MIT", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "sindresorhus/has-flag" + }, + { + "name": "internmap", + "version": "2.0.3", + "license": "ISC", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "gitHead": null, + "homepage": "https://github.com/mbostock/internmap/", + "repository": "https://github.com/mbostock/internmap.git" + }, + { + "name": "json-bignum", + "version": "0.0.3", + "license": [ + { + "type": "MIT", + "url": "https://github.com/datalanche/json-bignum/raw/master/LICENSE" + } + ], + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "gitHead": null, + "homepage": "https://github.com/datalanche/json-bignum", + "repository": "https://github.com/datalanche/json-bignum.git" + }, + { + "name": "kdbush", + "version": "4.1.0", + "license": "ISC", + "integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==", + "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git://github.com/mourner/kdbush.git" + }, + { + "name": "lodash.camelcase", + "version": "4.3.0", + "license": "MIT", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "gitHead": null, + "homepage": "https://lodash.com/", + "repository": "lodash/lodash" + }, + { + "name": "mjolnir.js", + "version": "3.0.0", + "license": "MIT", + "integrity": "sha512-siX3YCG7N2HnmN1xMH3cK4JkUZJhbkhRFJL+G5N1vH0mh1t5088rJknIoqDFWDIU6NPGvRRgLnYW3ZHjSMEBLA==", + "resolved": "https://registry.npmjs.org/mjolnir.js/-/mjolnir.js-3.0.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/visgl/mjolnir.js" + }, + { + "name": "reselect", + "version": "5.2.0", + "license": "MIT", + "integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/reduxjs/reselect.git" + }, + { + "name": "seedrandom", + "version": "3.0.5", + "license": "MIT", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "gitHead": null, + "homepage": "http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html", + "repository": "git://github.com/davidbau/seedrandom.git" + }, + { + "name": "supports-color", + "version": "7.2.0", + "license": "MIT", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/supports-color" + }, + { + "name": "table-layout", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/75lb/table-layout" + }, + { + "name": "tslib", + "version": "2.8.1", + "license": "0BSD", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "gitHead": null, + "homepage": "https://www.typescriptlang.org/", + "repository": "https://github.com/Microsoft/tslib.git" + }, + { + "name": "typical", + "version": "7.3.0", + "license": "MIT", + "integrity": "sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.3.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/75lb/typical.git" + }, + { + "name": "undici-types", + "version": "7.16.0", + "license": "MIT", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "gitHead": null, + "homepage": "https://undici.nodejs.org", + "repository": "git+https://github.com/nodejs/undici.git" + }, + { + "name": "wordwrapjs", + "version": "5.1.1", + "license": "MIT", + "integrity": "sha512-0yweIbkINJodk27gX9LBGMzyQdBDan3s/dEAiwBOj+Mf0PPyWL6/rikalkv8EeD0E8jm4o5RXEOrFTP3NXbhJg==", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.1.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/75lb/wordwrapjs" + } + ] +} diff --git a/inst/htmlwidgets/lib/legend-interactivity/legend-interactivity.js b/inst/htmlwidgets/lib/legend-interactivity/legend-interactivity.js index 9f605eec..1ef4f1de 100644 --- a/inst/htmlwidgets/lib/legend-interactivity/legend-interactivity.js +++ b/inst/htmlwidgets/lib/legend-interactivity/legend-interactivity.js @@ -20,28 +20,30 @@ function initializeLegendInteractivity(map, mapId, config) { return; } - // Ensure layer state tracking exists - if (!window._mapglLayerState) { - window._mapglLayerState = {}; - } - if (!window._mapglLayerState[mapId]) { - window._mapglLayerState[mapId] = { - filters: {}, - paintProperties: {}, - layoutProperties: {}, - tooltips: {}, - popups: {}, - legends: {}, - interactiveFilters: {} - }; - } - - var layerState = window._mapglLayerState[mapId]; - - // Ensure interactiveFilters exists (state object may have been created - // by map init code without this property) - if (!layerState.interactiveFilters) { - layerState.interactiveFilters = {}; + // Ensure layer state tracking exists via the shared helper that the + // main binding files install on window. Falls back to a local init if + // the helper isn't available (e.g. legacy load order), keeping the + // interactiveFilters field the legend UI depends on. + var layerState; + if (typeof window._mapglEnsureLayerState === "function") { + layerState = window._mapglEnsureLayerState(map); + } else { + if (!window._mapglLayerState) window._mapglLayerState = {}; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, + paintProperties: {}, + layoutProperties: {}, + tooltips: {}, + popups: {}, + legends: {}, + interactiveFilters: {}, + filterStack: {} + }; + } + layerState = window._mapglLayerState[mapId]; + if (!layerState.interactiveFilters) layerState.interactiveFilters = {}; + if (!layerState.filterStack) layerState.filterStack = {}; } // Normalize layerId to array for multi-layer support @@ -564,13 +566,21 @@ function initCategoricalLegend(map, mapId, legendElement, filterColumn, config) // Reset filter to original for all layers layerIds.forEach(function(lid) { - var interactiveState = layerState.interactiveFilters[lid]; - if (interactiveState.originalFilter) { - map.setFilter(lid, interactiveState.originalFilter); + // Release the legend slot from the filter registry; the composer + // restores base/user/slider automatically. + layerState.filterStack[lid] = layerState.filterStack[lid] || {}; + layerState.filterStack[lid].legend = null; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(map, lid); } else { - map.setFilter(lid, null); + var _is = layerState.interactiveFilters[lid]; + if (_is && _is.originalFilter) { + map.setFilter(lid, _is.originalFilter); + } else { + map.setFilter(lid, null); + } + layerState.filters[lid] = _is ? _is.originalFilter : null; } - layerState.filters[lid] = interactiveState.originalFilter; }); updateResetButton(legendElement, false); @@ -779,8 +789,15 @@ function initContinuousLegend(map, mapId, legendElement, filterColumn, config) { interactiveState.rangeMax = maxVal; if (isAtFullRange) { - map.setFilter(lid, interactiveState.originalFilter); - layerState.filters[lid] = interactiveState.originalFilter; + // Release the legend slot; composer restores base/user/slider. + layerState.filterStack[lid] = layerState.filterStack[lid] || {}; + layerState.filterStack[lid].legend = null; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(map, lid); + } else { + map.setFilter(lid, interactiveState.originalFilter); + layerState.filters[lid] = interactiveState.originalFilter; + } } else { applyRangeFilter( map, @@ -961,12 +978,19 @@ function initContinuousLegend(map, mapId, legendElement, filterColumn, config) { interactiveState.rangeMin = minValue; interactiveState.rangeMax = maxValue; - if (interactiveState.originalFilter) { - map.setFilter(lid, interactiveState.originalFilter); + // Release the legend slot; composer handles base/user/slider. + layerState.filterStack[lid] = layerState.filterStack[lid] || {}; + layerState.filterStack[lid].legend = null; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(map, lid); } else { - map.setFilter(lid, null); + if (interactiveState.originalFilter) { + map.setFilter(lid, interactiveState.originalFilter); + } else { + map.setFilter(lid, null); + } + layerState.filters[lid] = interactiveState.originalFilter; } - layerState.filters[lid] = interactiveState.originalFilter; }); updateResetButton(legendElement, false); @@ -1026,11 +1050,17 @@ function applyCategoricalFilter( ]; } - // Combine with original filter if exists - var finalFilter = combineFilters(originalFilter, interactiveFilter); - - map.setFilter(layerId, finalFilter); - layerState.filters[layerId] = finalFilter; + // Write to the legend slot of the filter registry; the composer + // handles merging with base/user/slider slots. + layerState.filterStack[layerId] = layerState.filterStack[layerId] || {}; + layerState.filterStack[layerId].legend = interactiveFilter || null; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(map, layerId); + } else { + var finalFilter = combineFilters(originalFilter, interactiveFilter); + map.setFilter(layerId, finalFilter); + layerState.filters[layerId] = finalFilter; + } } /** @@ -1088,11 +1118,16 @@ function applyRangeBasedCategoricalFilter( } } - // Combine with original filter if exists - var finalFilter = combineFilters(originalFilter, interactiveFilter); - - map.setFilter(layerId, finalFilter); - layerState.filters[layerId] = finalFilter; + // Write to the legend slot of the filter registry; composer merges. + layerState.filterStack[layerId] = layerState.filterStack[layerId] || {}; + layerState.filterStack[layerId].legend = interactiveFilter || null; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(map, layerId); + } else { + var finalFilter = combineFilters(originalFilter, interactiveFilter); + map.setFilter(layerId, finalFilter); + layerState.filters[layerId] = finalFilter; + } } /** @@ -1123,11 +1158,16 @@ function applyRangeFilter( ["<=", ["get", column], filterMax] ]; - // Combine with original filter if exists - var finalFilter = combineFilters(originalFilter, interactiveFilter); - - map.setFilter(layerId, finalFilter); - layerState.filters[layerId] = finalFilter; + // Write to the legend slot of the filter registry; composer merges. + layerState.filterStack[layerId] = layerState.filterStack[layerId] || {}; + layerState.filterStack[layerId].legend = interactiveFilter || null; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(map, layerId); + } else { + var finalFilter = combineFilters(originalFilter, interactiveFilter); + map.setFilter(layerId, finalFilter); + layerState.filters[layerId] = finalFilter; + } } /** diff --git a/inst/htmlwidgets/lib/slider/slider.js b/inst/htmlwidgets/lib/slider/slider.js new file mode 100644 index 00000000..eb55bf33 --- /dev/null +++ b/inst/htmlwidgets/lib/slider/slider.js @@ -0,0 +1,1370 @@ +/** + * Time Slider Control for mapgl (Mapbox GL JS and MapLibre GL JS). + * + * Implements the IControl interface so it participates in the native + * control positioning system (stacks beside navigation, scale, etc). + * + * Composes with the shared per-layer filter registry installed by + * mapboxgl.js / maplibregl.js: + * - window._mapglEnsureLayerState(map) + * - window._mapglComposeFilter(map, layerId) + * Writes the slider's filter to filterStack[layer].slider; base / user / + * legend slots from other sources continue to compose on every tick. + * + * Public surface: + * new SliderControl(options) + * .onAdd(map), .onRemove() + * .targetsLayer(layerId) -- bool; for proxy add_layer wiring + * .currentFilter() -- returns the current slider expression + * .update({ value, playing, animation_duration }) -- proxy updater + */ +(function () { + "use strict"; + + // Inline SVG icons. currentColor lets CSS theme them. + var ICON_PLAY = + ''; + var ICON_PAUSE = + ''; + + function buildFilter(mode, property, value) { + if (mode === "cumulative") { + return ["<=", ["get", property], value]; + } + // default: sequential / equality + return ["==", ["get", property], value]; + } + + function cssSize(value, unit) { + if (value == null || value === "") return null; + unit = unit || "px"; + if (typeof value === "number" && isFinite(value)) return value + unit; + if (typeof value === "string" && /^-?\d+(\.\d+)?$/.test(value.trim())) { + return value.trim() + unit; + } + return String(value); + } + + function setStyle(el, prop, value) { + if (value != null && value !== "") el.style[prop] = String(value); + } + + function setVar(el, name, value, unit) { + var size = unit ? cssSize(value, unit) : value; + if (size != null && size !== "") el.style.setProperty(name, String(size)); + } + + function withOpacity(color, opacity) { + if (color == null || opacity == null || opacity === "") return color; + opacity = Math.max(0, Math.min(1, Number(opacity))); + if (!isFinite(opacity)) return color; + + var hex = String(color).trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i); + if (hex) { + var raw = hex[1]; + if (raw.length === 3) raw = raw.replace(/(.)/g, "$1$1"); + var r = parseInt(raw.slice(0, 2), 16); + var g = parseInt(raw.slice(2, 4), 16); + var b = parseInt(raw.slice(4, 6), 16); + return "rgba(" + r + ", " + g + ", " + b + ", " + opacity + ")"; + } + + var rgb = String(color).trim().match(/^rgba?\((.*)\)$/i); + if (rgb) { + var parts = rgb[1].split(",").map(function (x) { return x.trim(); }); + if (parts.length >= 3) { + return "rgba(" + parts.slice(0, 3).join(", ") + ", " + opacity + ")"; + } + } + + return "color-mix(in srgb, " + color + " " + (opacity * 100) + "%, transparent)"; + } + + function SliderControl(options) { + this.options = options || {}; + this._layers = (options.layers || []).slice(); + this._property = options.property; + this._values = (options.values || []).slice(); + this._labels = (options.labels && options.labels.length === this._values.length) + ? options.labels.slice() + : this._values.map(function (v) { return String(v); }); + this._mode = (options.mode === "cumulative" || options.mode === "window") + ? options.mode + : "sequential"; + this._presentation = + options.presentation === "timeline" ? "timeline" : "compact"; + // Window mode interaction: "fixed" pins the width and pans the band; + // "resizable" lets either edge move. (Back-compat: accept the old + // window_control/window_ui payloads.) + this._windowBehavior = + options.window_behavior === "fixed" || + options.window_control === "fixed" || + options.window_ui === "playhead" + ? "fixed" + : "resizable"; + // Window mode only: size of the moving [start, end] range. null => + // cumulative range [min, T]; number => sliding range [T - window, T]. + this._window = (options.window != null) ? options.window : null; + // Absolute time unit used to convert numeric values to a flowmap + // selectedTimeRange (window mode + flowmap target only). + this._timeUnit = options.time_unit || null; + this._index = this._clampIndex(options.initial_index || 0); + // Window mode tracks an explicit [start, end] range over the value + // grid. _endIndex is the window end and mirrors _index so paint and + // the value label reuse the same machinery; _startIndex is derived + // from `window` (initial width in value units), or 0 for a [min, end] + // range when `window` is NULL. + this._endIndex = this._index; + this._startIndex = this._computeStartIndex(this._endIndex); + // Optional density histogram (d3, loaded on demand). `counts` is one + // bar height per value, binned in R against the value axis. + // The timeline presentation IS the histogram, so it implies it even if + // the histogram flag wasn't passed explicitly. + this._histogram = !!options.histogram || this._presentation === "timeline"; + this._counts = (options.counts || []).map(Number); + this._playButton = !!options.play_button; + this._draggable = !!options.draggable; + this._animationDuration = Math.max(50, options.animation_duration || 1000); + this._loop = options.loop !== false; + this._title = options.title || null; + this._showValue = options.show_value !== false; + this._style = (options.slider_style && typeof options.slider_style === "object") + ? options.slider_style + : {}; + this._width = this._style.width || options.width || 280; + this._background = withOpacity( + this._style.background_color || options.background_color || "#ffffffcc", + this._style.background_opacity + ); + this._textColor = this._style.text_color || options.text_color || "#404040"; + this._accent = this._style.accent_color || options.accent_color || "#4a90e2"; + this._activeColor = this._style.active_color || this._accent; + this._trackColor = this._style.track_color || "rgba(0, 0, 0, 0.15)"; + this._thumbColor = this._style.thumb_color || this._accent; + this._thumbBorderColor = this._style.thumb_border_color || "#ffffff"; + this._histogramHeight = Number(this._style.histogram_height) || + (this._presentation === "timeline" ? 88 : 46); + this._histogramBarColor = this._style.histogram_bar_color || this._accent; + this._histActiveOpacity = this._style.histogram_active_opacity != null + ? Number(this._style.histogram_active_opacity) + : 1; + this._histInactiveOpacity = this._style.histogram_inactive_opacity != null + ? Number(this._style.histogram_inactive_opacity) + : 0.28; + if (!isFinite(this._histActiveOpacity)) this._histActiveOpacity = 1; + if (!isFinite(this._histInactiveOpacity)) this._histInactiveOpacity = 0.28; + this._playing = false; + this._timer = null; + // Shiny input name: either explicitly provided or derived from the + // map container id in onAdd as `_slider`. + this._shinyInputName = options.shiny_input_name || null; + // Paint-property animation (optional). The R side normalizes both + // the single-form (paint_property + paint_expressions) and the + // multi-form (paint_properties) into a single dict shape: + // paint_properties: { "fill-color": [expr0, expr1, ...], ... } + // For backwards compat with any payload still in the single form, + // we also accept paint_property + paint_expressions here. + this._paintProperties = {}; + if (options.paint_properties && typeof options.paint_properties === "object") { + for (var pn in options.paint_properties) { + if (Object.prototype.hasOwnProperty.call(options.paint_properties, pn)) { + this._paintProperties[pn] = (options.paint_properties[pn] || []).slice(); + } + } + } else if (options.paint_property && options.paint_expressions) { + this._paintProperties[options.paint_property] = + (options.paint_expressions || []).slice(); + } + // Per-layer, per-property baseline captured on first apply. + // Shape: { layer_id: { property_name: } } + this._paintBaseline = {}; + } + + SliderControl.prototype._clampIndex = function (i) { + if (!this._values.length) return 0; + if (i < 0) return 0; + if (i >= this._values.length) return this._values.length - 1; + return i; + }; + + // Initial start index for window mode: smallest index whose value is + // >= (values[endIdx] - window). NULL window => 0 (range spans [min, T]). + // Works for non-uniform value grids. + SliderControl.prototype._computeStartIndex = function (endIdx) { + if (this._window == null) return 0; + var endVal = this._values[endIdx]; + var lo = endVal - this._window; + for (var i = 0; i < this._values.length; i++) { + if (this._values[i] >= lo) return Math.min(i, endIdx); + } + return endIdx; + }; + + SliderControl.prototype.targetsLayer = function (layerId) { + return this._layers.indexOf(layerId) !== -1; + }; + + // Current window bounds as [startValue, endValue] (window mode only), + // read from the explicit start/end handle positions. + SliderControl.prototype._windowBounds = function () { + return [this._values[this._startIndex], this._values[this._endIndex]]; + }; + + // Convert a numeric slider value to epoch milliseconds for a flowmap + // selectedTimeRange, using the R-supplied time_unit. Returns null for + // non-absolute units (month/day) or a missing unit, signalling the + // caller to skip the flowmap target rather than emit a bad range. + SliderControl.prototype._toTime = function (v) { + if (v == null || isNaN(v)) return null; + switch (this._timeUnit) { + case "seconds": return v * 1000; + case "date": return v * 86400000; + case "year": return Date.UTC(v, 0, 1); + default: return null; + } + }; + + SliderControl.prototype.currentFilter = function () { + if (!this._values.length || !this._property) return null; + if (this._mode === "window") { + // Inclusive both ends: values are instants, so [start, end] + // keeps a single-step range non-empty (a half-open `< end` + // would empty a zero-width selection and cause off-by-one). + var b = this._windowBounds(); + return [ + "all", + [">=", ["get", this._property], b[0]], + ["<=", ["get", this._property], b[1]] + ]; + } + return buildFilter(this._mode, this._property, this._values[this._index]); + }; + + // Return { property: expression } for the current step, or null if + // paint isn't configured. + SliderControl.prototype._currentPaintOverrides = function () { + var props = Object.keys(this._paintProperties); + if (!props.length) return null; + var out = {}; + for (var i = 0; i < props.length; i++) { + var list = this._paintProperties[props[i]]; + if (list && list.length) out[props[i]] = list[this._index]; + } + return out; + }; + + // Capture baseline(s) and apply current paint expression(s) for a + // single layer. Safe to call multiple times for the same layer (the + // per-property baseline is captured only on first sighting). Called + // from the late-added-layer hook in the binding files and indirectly + // from the main apply path via the same per-layer branch. + SliderControl.prototype.captureAndApplyPaintForLayer = function (layerId) { + if (!this._map) return; + var props = Object.keys(this._paintProperties); + if (!props.length) return; + if (!this._map.getLayer || !this._map.getLayer(layerId)) return; + if (!this._paintBaseline[layerId]) this._paintBaseline[layerId] = {}; + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + var list = this._paintProperties[prop]; + if (!list || !list.length) continue; + if (!Object.prototype.hasOwnProperty.call(this._paintBaseline[layerId], prop)) { + // undefined = no explicit value; setPaintProperty(..., undefined) + // restores the style default on removal. + this._paintBaseline[layerId][prop] = this._map.getPaintProperty(layerId, prop); + } + this._map.setPaintProperty(layerId, prop, list[this._index]); + } + }; + + SliderControl.prototype.onAdd = function (map) { + this._map = map; + // Enforce one-slider-per-map: quietly replace any prior instance. + if (map._mapglSliderControl && map._mapglSliderControl !== this) { + try { map.removeControl(map._mapglSliderControl); } catch (e) { /* noop */ } + } + map._mapglSliderControl = this; + // Derive the Shiny input name from the map container id if not + // supplied explicitly. + if (!this._shinyInputName) { + var _cid = (map.getContainer && map.getContainer().id) || null; + if (_cid) this._shinyInputName = _cid + "_slider"; + } + + var self = this; + + // Build DOM. + // The outer node uses .mapboxgl-ctrl so native positioning applies; + // the inner wrapper is what we style. Inline width/colors come from + // options so we don't need a style injection step for each instance. + var root = document.createElement("div"); + root.className = "mapboxgl-ctrl maplibregl-ctrl mapgl-slider"; + root.style.width = cssSize(this._width) || "280px"; + root.style.background = this._background; + root.style.color = this._textColor; + setStyle(root, "fontFamily", this._style.font_family); + setStyle(root, "fontSize", cssSize(this._style.font_size)); + setStyle(root, "fontWeight", this._style.font_weight); + setStyle(root, "padding", cssSize(this._style.padding)); + if (this._style.border_radius != null) { + root.style.borderRadius = cssSize(this._style.border_radius); + } + if (this._style.border_width != null || this._style.border_color) { + root.style.border = + (cssSize(this._style.border_width != null ? this._style.border_width : 1) || "1px") + + " solid " + + (this._style.border_color || "rgba(0, 0, 0, 0.15)"); + } + if (this._style.shadow === false) { + root.style.boxShadow = "none"; + } else if ( + this._style.shadow === true || + this._style.shadow_color || + this._style.shadow_size != null + ) { + root.style.boxShadow = + "0 2px " + + (cssSize(this._style.shadow_size != null ? this._style.shadow_size : 6) || "6px") + + " " + + (this._style.shadow_color || "rgba(0, 0, 0, 0.15)"); + } + + // CSS custom properties power the native range pieces, including + // browser pseudo-elements that cannot be styled directly inline. + root.style.setProperty("--mapgl-slider-accent", this._accent); + root.style.setProperty("--mapgl-slider-active-color", this._activeColor); + root.style.setProperty("--mapgl-slider-track-color", this._trackColor); + root.style.setProperty("--mapgl-slider-thumb-color", this._thumbColor); + root.style.setProperty("--mapgl-slider-thumb-border-color", this._thumbBorderColor); + root.style.setProperty("--mapgl-slider-play-background", this._style.play_button_background || "#ffffff"); + root.style.setProperty("--mapgl-slider-play-color", this._style.play_button_color || this._accent); + root.style.setProperty("--mapgl-slider-play-border-color", this._style.play_button_border_color || "rgba(0, 0, 0, 0.15)"); + setVar(root, "--mapgl-slider-track-height", this._style.track_height, "px"); + setVar(root, "--mapgl-slider-thumb-size", this._style.thumb_size, "px"); + + var body; + if (this._presentation === "timeline") { + root.classList.add("mapgl-slider-timeline-root"); + body = this._buildTimeline(); + } else { + body = document.createElement("div"); + body.className = "mapgl-slider-body"; + + if (this._title) { + var titleEl = document.createElement("div"); + titleEl.className = "mapgl-slider-title"; + titleEl.textContent = this._title; + setStyle(titleEl, "color", this._style.title_color); + setStyle(titleEl, "fontSize", cssSize(this._style.title_size)); + setStyle(titleEl, "fontWeight", this._style.title_weight); + body.appendChild(titleEl); + } + + var header = document.createElement("div"); + header.className = "mapgl-slider-header"; + + var valueEl = document.createElement("div"); + valueEl.className = "mapgl-slider-value"; + if (!this._showValue) valueEl.style.display = "none"; + valueEl.textContent = this._labels[this._index] || ""; + setStyle(valueEl, "color", this._style.value_color); + setStyle(valueEl, "fontSize", cssSize(this._style.value_size)); + setStyle(valueEl, "fontWeight", this._style.value_weight); + header.appendChild(valueEl); + this._valueEl = valueEl; + + body.appendChild(header); + + // Density strip sits between the label and the slider row, sharing + // the body width so bars align above the handles/band below. + if (this._histogram && this._counts.length) { + body.appendChild(this._buildHistogram()); + } + + var row = document.createElement("div"); + row.className = "mapgl-slider-row"; + + if (this._playButton) { + var playBtn = document.createElement("button"); + playBtn.type = "button"; + playBtn.className = "mapgl-slider-play"; + playBtn.setAttribute("aria-label", "Play"); + playBtn.innerHTML = ICON_PLAY; + playBtn.addEventListener("click", function () { + self._togglePlay(); + }); + row.appendChild(playBtn); + this._playBtn = playBtn; + } + + // Window mode can render either a two-handle resizable range or a + // fixed-duration single-handle control. Both use the same [start, end] + // state and filtering. + if (this._mode === "window") { + row.appendChild( + this._windowBehavior === "fixed" + ? this._buildFixedWindowInput() + : this._buildRangeInput() + ); + } else { + row.appendChild(this._buildSingleInput()); + } + + body.appendChild(row); + } + root.appendChild(body); + this._root = root; + + // Optionally let the user drag the panel off its docked corner. + if (this._draggable) { + root.classList.add("mapgl-slider-draggable"); + this._setupDrag(map); + } + + // Seed filter registry slots for each target layer and apply. + // Initial mount uses the synchronous path so the first paint + // already has the filter applied (no flash of unfiltered data). + this._applyFilterNow(); + + // Fire initial Shiny input value if applicable. + this._fireShinyInput(); + + // Draw the density strip once d3 has loaded and the control has a + // measurable width (it mounts at 0px until the control framework + // inserts it into the corner). + if (this._histogram && this._counts.length) { + this._ensureHistogram(); + } + + // Keep the slider filter applied even if the style reloads. + this._onStyleData = function () { + // Style reloads re-run the replay in state.filters, which + // includes our composed expression. But filterStack persists + // on window so composeAndApplyFilter remains correct; just + // re-trigger to be safe in case any layer got re-created with + // only its `base` filter. Immediate rather than coalesced so + // we never leave a stale filter visible. + self._applyFilterNow(); + }; + map.on("styledata", this._onStyleData); + + return root; + }; + + // ---- Draggable panel ---- + // Mirrors the interactive-legend drag (legend-interactivity.js + // makeLegendDraggable): grab the panel body and reposition it freely, + // but never start a drag from an interactive control (the range input, + // play button, window handles, or timeline brush/chart). + var DRAG_SKIP_SELECTOR = + "input, button, .mapgl-slider-play, .mapgl-slider-range, " + + ".mapgl-slider-brush, .mapgl-slider-brush-grip, " + + ".mapgl-slider-histogram, .mapgl-slider-timeline-chart"; + + SliderControl.prototype._setupDrag = function (map) { + if (this._dragInit) return; + this._dragInit = true; + + var root = this._root; + var container = map.getContainer(); + var dragging = false; + var startX, startY, startLeft, startTop; + + var onDown = function (e) { + if (e.button != null && e.button !== 0) return; + if (e.target.closest(DRAG_SKIP_SELECTOR)) return; + + // Switch from the native corner docking to absolute positioning + // relative to the map container, so left/top math is correct. + var rect = root.getBoundingClientRect(); + var cRect = container.getBoundingClientRect(); + if (root.parentNode !== container) container.appendChild(root); + startLeft = rect.left - cRect.left; + startTop = rect.top - cRect.top; + root.style.position = "absolute"; + root.style.left = startLeft + "px"; + root.style.top = startTop + "px"; + root.style.right = "auto"; + root.style.bottom = "auto"; + + dragging = true; + startX = e.clientX; + startY = e.clientY; + root.classList.add("is-dragging"); + try { root.setPointerCapture(e.pointerId); } catch (err) { /* noop */ } + e.preventDefault(); + e.stopPropagation(); + }; + + var onMove = function (e) { + if (!dragging) return; + var newLeft = startLeft + (e.clientX - startX); + var newTop = startTop + (e.clientY - startY); + var maxLeft = container.clientWidth - root.offsetWidth; + var maxTop = container.clientHeight - root.offsetHeight; + root.style.left = Math.max(0, Math.min(newLeft, maxLeft)) + "px"; + root.style.top = Math.max(0, Math.min(newTop, maxTop)) + "px"; + e.preventDefault(); + }; + + var onUp = function (e) { + if (!dragging) return; + dragging = false; + root.classList.remove("is-dragging"); + try { root.releasePointerCapture(e.pointerId); } catch (err) { /* noop */ } + }; + + // Listeners live on the panel itself (pointer capture keeps move/up + // flowing during the drag), so they are torn down with the node in + // onRemove — no document-level leak. + root.addEventListener("pointerdown", onDown); + root.addEventListener("pointermove", onMove); + root.addEventListener("pointerup", onUp); + root.addEventListener("pointercancel", onUp); + }; + + // ---- Histogram density strip (adapted from Egor Kotov's PR #205) ---- + // The bar + accent rendering and CSS classes (.mapgl-bar) come from his + // time-control; the data source (R-binned `counts` on the value axis) + // and the index-aligned x-scale are the mapgl-specific rewiring, and the + // range selection is the slider's own two-handle control rather than his + // d3 brush. + SliderControl.prototype._buildHistogram = function () { + var host = document.createElement("div"); + host.className = "mapgl-slider-histogram"; + this._histEl = host; + return host; + }; + + // Poll until d3 is present and the strip has a real width, then draw. + SliderControl.prototype._ensureHistogram = function () { + var self = this; + var tries = 0; + function attempt() { + if (!self._histEl) return; + var ready = typeof window.d3 !== "undefined" && + self._histEl.clientWidth > 20; + if (ready) { + self._renderHistogramBars(); + return; + } + if (tries++ > 120) { // ~6s + if (typeof console !== "undefined" && console.warn) { + console.warn( + "[mapgl] slider histogram needs d3; it did not load — " + + "showing the slider without the density strip. " + + "(Declare histogram = TRUE at initial render so d3 is bundled.)" + ); + } + return; + } + setTimeout(attempt, 50); + } + attempt(); + }; + + SliderControl.prototype._renderHistogramBars = function () { + var d3 = window.d3; + if (!d3 || !this._histEl || !this._counts.length) return; + var width = this._histEl.clientWidth || this._width; + var height = Math.max(8, this._histogramHeight); + var n = this._counts.length; + var maxIdx = Math.max(1, n - 1); + var maxC = d3.max(this._counts) || 1; + var y = d3.scaleLinear().domain([0, maxC]).range([height - 1, 4]); + var barW = Math.max(1, (width / n) * 0.7); + var self = this; + + var svg = d3.select(this._histEl).select("svg"); + if (svg.empty()) svg = d3.select(this._histEl).append("svg"); + svg.attr("width", width).attr("height", height); + svg.selectAll("*").remove(); + + svg + .selectAll(".mapgl-bar") + .data(this._counts) + .enter() + .append("rect") + .attr("class", "mapgl-bar") + // Spread bars across the full width so the first and last sit + // flush with the edges (no half-bars), while the extreme bars + // still line up with the index 0 / maxIdx ends of the band below. + .attr("x", function (d, i) { return (i / maxIdx) * (width - barW); }) + .attr("y", function (d) { return y(d); }) + .attr("width", barW) + .attr("height", function (d) { return Math.max(0, height - y(d)); }) + .attr("rx", 1) + .attr("fill", self._histogramBarColor); + + this._renderedHist = true; + this._updateHistogramHighlight(); + }; + + // Index range of "active" bars for the current selection/value. + SliderControl.prototype._histActiveRange = function () { + if (this._mode === "window") return [this._startIndex, this._endIndex]; + if (this._mode === "cumulative") return [0, this._index]; + return [this._index, this._index]; + }; + + // Bars inside the active range are full opacity; the rest are dimmed, + // so the density strip reads as a "brush over the histogram". + SliderControl.prototype._updateHistogramHighlight = function () { + if (!this._renderedHist || typeof window.d3 === "undefined") return; + var r = this._histActiveRange(); + var lo = r[0], hi = r[1]; + var activeOpacity = this._histActiveOpacity; + var inactiveOpacity = this._histInactiveOpacity; + window.d3 + .select(this._histEl) + .selectAll(".mapgl-bar") + .attr("opacity", function (d, i) { + return i >= lo && i <= hi + ? activeOpacity + : inactiveOpacity; + }); + }; + + // ---- Timeline presentation (brushable histogram) ---------------------- + // Egor Kotov's time-control idea: a prominent histogram IS the control. + // Drag the selected window across the bars, drag its edges to resize it + // (resizable mode), and read the range in the header. + SliderControl.prototype._buildTimeline = function () { + var self = this; + var panel = document.createElement("div"); + panel.className = "mapgl-slider-body mapgl-slider-timeline"; + + var header = document.createElement("div"); + header.className = "mapgl-slider-timeline-header"; + + if (this._playButton) { + var playBtn = document.createElement("button"); + playBtn.type = "button"; + playBtn.className = "mapgl-slider-play"; + playBtn.setAttribute("aria-label", "Play"); + playBtn.innerHTML = ICON_PLAY; + playBtn.addEventListener("click", function () { self._togglePlay(); }); + header.appendChild(playBtn); + this._playBtn = playBtn; + } + + if (this._title) { + var titleEl = document.createElement("div"); + titleEl.className = "mapgl-slider-title mapgl-slider-timeline-title"; + titleEl.textContent = this._title; + setStyle(titleEl, "color", this._style.title_color); + setStyle(titleEl, "fontWeight", this._style.title_weight); + header.appendChild(titleEl); + } + + panel.appendChild(header); + + // The selected-range readout sits on its own line so a long date range + // never squeezes out the title (matches Egor Kotov's layout). + var readout = document.createElement("div"); + readout.className = "mapgl-slider-value mapgl-slider-timeline-readout"; + if (!this._showValue) readout.style.display = "none"; + setStyle(readout, "color", this._style.value_color); + setStyle(readout, "fontSize", cssSize(this._style.value_size)); + panel.appendChild(readout); + this._valueEl = readout; + + var chart = document.createElement("div"); + chart.className = "mapgl-slider-timeline-chart"; + chart.style.height = Math.max(8, this._histogramHeight) + "px"; + + var histHost = document.createElement("div"); + histHost.className = "mapgl-slider-histogram mapgl-slider-timeline-hist"; + this._histEl = histHost; + chart.appendChild(histHost); + + var band = document.createElement("div"); + band.className = "mapgl-slider-brush"; + var gripStart = document.createElement("div"); + gripStart.className = "mapgl-slider-brush-grip mapgl-slider-brush-grip-start"; + var gripEnd = document.createElement("div"); + gripEnd.className = "mapgl-slider-brush-grip mapgl-slider-brush-grip-end"; + band.appendChild(gripStart); + band.appendChild(gripEnd); + chart.appendChild(band); + this._brushBand = band; + this._brushGripStart = gripStart; + this._brushGripEnd = gripEnd; + if (this._windowBehavior === "fixed" || this._mode !== "window") { + band.classList.add("mapgl-slider-brush-fixed"); + } + + panel.appendChild(chart); + + var axis = document.createElement("div"); + axis.className = "mapgl-slider-axis"; + this._axisEl = axis; + panel.appendChild(axis); + + this._attachBrush(chart, band, gripStart, gripEnd); + this._renderBrush(); + this._renderAxisTicks(); + this._updateWindowLabel(); + return panel; + }; + + // Position the brush band + grips over the chart (percent of width). + SliderControl.prototype._renderBrush = function () { + if (!this._brushBand) return; + var maxIdx = Math.max(1, this._values.length - 1); + var r = this._histActiveRange(); + var lo = r[0], hi = r[1]; + this._brushBand.style.left = ((lo / maxIdx) * 100) + "%"; + this._brushBand.style.width = Math.max(0, ((hi - lo) / maxIdx) * 100) + "%"; + this._updateHistogramHighlight(); + }; + + // A handful of evenly spaced value labels under the bars. + SliderControl.prototype._renderAxisTicks = function () { + if (!this._axisEl) return; + var n = this._values.length; + if (!n) return; + var maxTicks = Math.min(4, n); + this._axisEl.innerHTML = ""; + for (var t = 0; t < maxTicks; t++) { + var idx = maxTicks === 1 ? 0 : Math.round((t / (maxTicks - 1)) * (n - 1)); + var tick = document.createElement("span"); + tick.className = "mapgl-slider-axis-tick"; + tick.style.left = ((idx / Math.max(1, n - 1)) * 100) + "%"; + // Compact the label for the axis: drop a leading 4-digit year so + // long timestamps ("2019-07-01 20:00" -> "07-01 20:00") fit. + tick.textContent = (this._labels[idx] || "").replace(/^\d{4}-/, ""); + this._axisEl.appendChild(tick); + } + }; + + // Brush interaction: drag the band body to pan at fixed width, drag the + // edge grips to resize (resizable window mode), or click the bars to scrub + // the window end. In non-window modes a drag/click moves the single cursor. + SliderControl.prototype._attachBrush = function (chart, band, gripStart, gripEnd) { + var self = this; + var mode = null; + var startClientX = 0; + var startStart = 0; + var width = 0; + function maxIdx() { return Math.max(1, self._values.length - 1); } + function idxAt(clientX) { + var rect = chart.getBoundingClientRect(); + var frac = rect.width ? (clientX - rect.left) / rect.width : 0; + return self._clampIndex(Math.round(frac * maxIdx())); + } + function setEndOrCursor(idx) { + if (self._mode === "window") self._setEnd(idx, { pause: true }); + else self._setIndex(idx, { pause: true, fromUser: true }); + } + function onMove(e) { + if (!mode) return; + if (mode === "resize-start") { + self._setStart(idxAt(e.clientX), { pause: true }); + } else if (mode === "resize-end") { + setEndOrCursor(idxAt(e.clientX)); + } else if (mode === "pan") { + var rect = chart.getBoundingClientRect(); + var deltaIdx = Math.round( + ((e.clientX - startClientX) / (rect.width || 1)) * maxIdx() + ); + var ns = startStart + deltaIdx; + if (ns < 0) ns = 0; + if (ns + width > maxIdx()) ns = maxIdx() - width; + self._setBand(ns, ns + width, { pause: true }); + } + } + function onUp() { + mode = null; + band.classList.remove("is-dragging"); + document.removeEventListener("pointermove", onMove); + document.removeEventListener("pointerup", onUp); + } + function begin(e, m) { + mode = m; + startClientX = e.clientX; + startStart = self._startIndex; + width = self._endIndex - self._startIndex; + self._stopLoop(); + band.classList.add("is-dragging"); + document.addEventListener("pointermove", onMove); + document.addEventListener("pointerup", onUp); + e.preventDefault(); + } + var canResize = function () { + return self._windowBehavior !== "fixed" && self._mode === "window"; + }; + gripStart.addEventListener("pointerdown", function (e) { + e.stopPropagation(); + begin(e, canResize() ? "resize-start" : (self._mode === "window" ? "pan" : "resize-end")); + }); + gripEnd.addEventListener("pointerdown", function (e) { + e.stopPropagation(); + begin(e, canResize() ? "resize-end" : (self._mode === "window" ? "pan" : "resize-end")); + }); + band.addEventListener("pointerdown", function (e) { + if (e.target === gripStart || e.target === gripEnd) return; + begin(e, self._mode === "window" ? "pan" : "resize-end"); + }); + chart.addEventListener("pointerdown", function (e) { + if (e.target === band || e.target === gripStart || e.target === gripEnd) return; + // Clicked on the bars: scrub the window end (or the cursor) here. + if (self._mode === "window") { + self._setWindowEnd(idxAt(e.clientX), { pause: true }); + } else { + self._setIndex(idxAt(e.clientX), { pause: true, fromUser: true }); + } + begin(e, self._mode === "window" ? "pan" : "resize-end"); + }); + }; + + // Single-thumb input for sequential/cumulative modes. + SliderControl.prototype._buildSingleInput = function () { + var self = this; + var input = document.createElement("input"); + input.type = "range"; + input.className = "mapgl-slider-input"; + input.min = "0"; + input.max = String(Math.max(0, this._values.length - 1)); + input.step = "1"; + input.value = String(this._index); + // Pause when the user scrubs. + input.addEventListener("input", function (e) { + self._setIndex(parseInt(e.target.value, 10), { pause: true, fromUser: true }); + }); + this._input = input; + return input; + }; + + // Two-handle range input for window mode: a shared track, a filled band + // between the handles, and two overlaid native range inputs (the + // pointer-events trick in the CSS keeps both thumbs grabbable). + SliderControl.prototype._buildRangeInput = function () { + var self = this; + var maxIdx = Math.max(0, this._values.length - 1); + + var wrap = document.createElement("div"); + wrap.className = "mapgl-slider-range"; + + var track = document.createElement("div"); + track.className = "mapgl-slider-range-track"; + wrap.appendChild(track); + + var fill = document.createElement("div"); + fill.className = "mapgl-slider-range-fill"; + wrap.appendChild(fill); + this._rangeFill = fill; + this._rangeWrap = wrap; + // The band itself is grabbable: dragging it pans the whole window at + // fixed width (mirrors the interactive legend's draggable middle). + this._attachBandDrag(fill, wrap); + + var startInput = document.createElement("input"); + startInput.type = "range"; + startInput.className = "mapgl-slider-range-start"; + startInput.min = "0"; + startInput.max = String(maxIdx); + startInput.step = "1"; + startInput.value = String(this._startIndex); + startInput.addEventListener("input", function (e) { + self._setStart(parseInt(e.target.value, 10), { pause: true }); + }); + + var endInput = document.createElement("input"); + endInput.type = "range"; + endInput.className = "mapgl-slider-range-end"; + endInput.min = "0"; + endInput.max = String(maxIdx); + endInput.step = "1"; + endInput.value = String(this._endIndex); + endInput.addEventListener("input", function (e) { + self._setEnd(parseInt(e.target.value, 10), { pause: true }); + }); + + wrap.appendChild(startInput); + wrap.appendChild(endInput); + this._startInput = startInput; + this._endInput = endInput; + + this._renderRangeFill(); + this._updateWindowLabel(); + return wrap; + }; + + // Fixed-duration window UI: the thumb controls the end time; the filled + // band shows [end - window, end]. This is the temporal playback affordance + // for fixed-width windows where two handles would visually overlap. + SliderControl.prototype._buildFixedWindowInput = function () { + var self = this; + var maxIdx = Math.max(0, this._values.length - 1); + + var wrap = document.createElement("div"); + wrap.className = "mapgl-slider-range mapgl-slider-range-fixed"; + + var track = document.createElement("div"); + track.className = "mapgl-slider-range-track"; + wrap.appendChild(track); + + var fill = document.createElement("div"); + fill.className = "mapgl-slider-range-fill"; + wrap.appendChild(fill); + this._rangeFill = fill; + this._rangeWrap = wrap; + + var input = document.createElement("input"); + input.type = "range"; + input.className = "mapgl-slider-fixed-input"; + input.min = "0"; + input.max = String(maxIdx); + input.step = "1"; + input.value = String(this._endIndex); + input.addEventListener("input", function (e) { + self._setWindowEnd(parseInt(e.target.value, 10), { pause: true }); + }); + + wrap.appendChild(input); + this._endInput = input; + + this._renderRangeFill(); + this._updateWindowLabel(); + return wrap; + }; + + // Position the filled band between the two handles (percent of track). + SliderControl.prototype._renderRangeFill = function () { + // Timeline presentation has no native range track; the brush band is + // the selection, so reposition it instead. + if (this._brushBand) { + this._renderBrush(); + return; + } + if (!this._rangeFill) return; + var maxIdx = Math.max(1, this._values.length - 1); + var a = (this._startIndex / maxIdx) * 100; + var b = (this._endIndex / maxIdx) * 100; + this._rangeFill.style.left = a + "%"; + this._rangeFill.style.width = Math.max(0, b - a) + "%"; + this._updateHistogramHighlight(); + }; + + // Window value label shows the range, collapsing to one label when the + // band is zero-width. + SliderControl.prototype._updateWindowLabel = function () { + if (!this._valueEl) return; + var a = this._labels[this._startIndex] || ""; + var b = this._labels[this._endIndex] || ""; + this._valueEl.textContent = a === b ? a : a + " – " + b; + }; + + // Set both handles at once (used by band drag, play slide, and the + // proxy updater). Centralizes the input/fill/label sync + apply. + SliderControl.prototype._setBand = function (s, e, opts) { + opts = opts || {}; + s = this._clampIndex(s); + e = this._clampIndex(e); + if (s > e) { var t = s; s = e; e = t; } + var changed = s !== this._startIndex || e !== this._endIndex; + this._startIndex = s; + this._endIndex = e; + this._index = e; + if (this._startInput) this._startInput.value = String(s); + if (this._endInput) this._endInput.value = String(e); + this._renderRangeFill(); + this._updateWindowLabel(); + if (changed || opts.force) { + this._applyFilterToLayers(); + this._fireShinyInput(); + } + }; + + // Drag the filled band to pan the window left/right at a fixed width. + SliderControl.prototype._attachBandDrag = function (fill, wrap) { + var self = this; + var dragging = false; + var startX = 0; + var startStartIdx = 0; + var width = 0; + function maxIdx() { + return Math.max(1, self._values.length - 1); + } + function onMove(e) { + if (!dragging) return; + var rectW = wrap.getBoundingClientRect().width || 1; + var deltaIdx = Math.round(((e.clientX - startX) / rectW) * maxIdx()); + var ns = startStartIdx + deltaIdx; + if (ns < 0) ns = 0; + if (ns + width > maxIdx()) ns = maxIdx() - width; + self._setBand(ns, ns + width); + } + function onUp() { + dragging = false; + fill.classList.remove("is-dragging"); + document.removeEventListener("pointermove", onMove); + document.removeEventListener("pointerup", onUp); + } + fill.addEventListener("pointerdown", function (e) { + dragging = true; + startX = e.clientX; + startStartIdx = self._startIndex; + width = self._endIndex - self._startIndex; + self._stopLoop(); + fill.classList.add("is-dragging"); + document.addEventListener("pointermove", onMove); + document.addEventListener("pointerup", onUp); + e.preventDefault(); + }); + }; + + SliderControl.prototype._setStart = function (idx, opts) { + opts = opts || {}; + idx = this._clampIndex(idx); + if (idx > this._endIndex) idx = this._endIndex; // start cannot pass end + var changed = idx !== this._startIndex; + this._startIndex = idx; + // Resizing redefines the window duration (in value units) so playback + // and later end-scrubbing preserve the user's new width instead of + // snapping back to the original `window`. + this._syncWindowFromBand(); + if (this._startInput) this._startInput.value = String(idx); + this._renderRangeFill(); + this._updateWindowLabel(); + if (opts.pause) this._stopLoop(); + if (changed || opts.force) { + this._applyFilterToLayers(); + this._fireShinyInput(); + } + }; + + // After a resize, store the window width in value units so the fixed-window + // playback path (_setWindowEnd -> _computeStartIndex) keeps it. + SliderControl.prototype._syncWindowFromBand = function () { + if (this._mode !== "window") return; + if (!this._values.length) return; + this._window = + this._values[this._endIndex] - this._values[this._startIndex]; + }; + + SliderControl.prototype._setEnd = function (idx, opts) { + opts = opts || {}; + idx = this._clampIndex(idx); + if (idx < this._startIndex) idx = this._startIndex; // end cannot pass start + var changed = idx !== this._endIndex; + this._endIndex = idx; + this._index = idx; // keep _index synced to the end for paint/label reuse + this._syncWindowFromBand(); + if (this._endInput) this._endInput.value = String(idx); + this._renderRangeFill(); + this._updateWindowLabel(); + if (opts.pause) this._stopLoop(); + if (changed || opts.force) { + this._applyFilterToLayers(); + this._fireShinyInput(); + } + }; + + // Slide the band so its end sits at idx. For a fixed `window`, recompute + // the start from value units (`end - window`) rather than preserving index + // distance; this keeps temporal windows correct when the value grid has + // missing hours/days. + SliderControl.prototype._setWindowEnd = function (idx, opts) { + opts = opts || {}; + idx = this._clampIndex(idx); + var startIdx = this._computeStartIndex(idx); + if (opts.pause) this._stopLoop(); + this._setBand(startIdx, idx, { force: true }); + }; + + // Advance the window one step to the right, preserving width; wrap or + // stop at the end depending on `loop`. Called by the play loop. + SliderControl.prototype._advanceWindow = function () { + var maxIdx = this._values.length - 1; + var width = this._endIndex - this._startIndex; + if (this._endIndex >= maxIdx) { + if (!this._loop) { + this._stopLoop(); + return; + } + this._setWindowEnd(Math.min(width, maxIdx), { force: true }); + } else { + this._setWindowEnd(this._endIndex + 1, { force: true }); + } + }; + + SliderControl.prototype.onRemove = function () { + this._stopLoop(); + if (this._map) { + if (this._onStyleData) { + try { this._map.off("styledata", this._onStyleData); } catch (e) { /* noop */ } + } + // Release slider slot for every targeted layer. + var state = (typeof window._mapglEnsureLayerState === "function") + ? window._mapglEnsureLayerState(this._map) + : null; + if (state) { + for (var i = 0; i < this._layers.length; i++) { + var lid = this._layers[i]; + if (state.filterStack[lid]) { + state.filterStack[lid].slider = null; + } + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(this._map, lid); + } + } + } + // Restore every captured paint baseline, across all layers + // and all configured paint properties. Passing undefined to + // setPaintProperty restores the style default, which matches + // the original "no explicit value" state. + for (var baseLid in this._paintBaseline) { + if ( + !Object.prototype.hasOwnProperty.call( + this._paintBaseline, + baseLid + ) + ) continue; + if (!this._map.getLayer || !this._map.getLayer(baseLid)) continue; + var layerBaselines = this._paintBaseline[baseLid]; + for (var bProp in layerBaselines) { + if ( + Object.prototype.hasOwnProperty.call(layerBaselines, bProp) + ) { + this._map.setPaintProperty( + baseLid, + bProp, + layerBaselines[bProp] + ); + } + } + } + if (this._map._mapglSliderControl === this) { + delete this._map._mapglSliderControl; + } + } + if (this._root && this._root.parentNode) { + this._root.parentNode.removeChild(this._root); + } + this._map = null; + }; + + // Coalesce filter applies to one-per-animation-frame. On dense + // vector tile / PMTiles layers, map.setFilter triggers a repaint + // that can queue up faster than the renderer paints; without this, + // fast dragging leaves the map trailing the slider. rAF coalescing + // collapses multiple drag ticks into a single setFilter per paint + // tick, reading the most recent index when the frame actually fires. + SliderControl.prototype._applyFilterToLayers = function () { + if (!this._map || !this._values.length) return; + if (this._rafPending) return; + var self = this; + this._rafPending = true; + var raf = + (typeof window !== "undefined" && window.requestAnimationFrame) || + function (fn) { return setTimeout(fn, 16); }; + raf(function () { + self._rafPending = false; + self._applyFilterNow(); + }); + }; + + // Synchronous application path. Called from the rAF callback and on + // onAdd / styledata / onRemove where we want immediate effect. + // Applies filter (if `property` is configured) and/or paint (if + // paint properties are configured). Either, both, or neither may run + // per tick depending on how the slider was configured. + SliderControl.prototype._applyFilterNow = function () { + if (!this._map || !this._values.length) return; + var hasFilter = this._property != null; + var paintProps = Object.keys(this._paintProperties); + var hasPaint = paintProps.length > 0; + var filter = this.currentFilter(); + var state = (typeof window._mapglEnsureLayerState === "function") + ? window._mapglEnsureLayerState(this._map) + : null; + for (var i = 0; i < this._layers.length; i++) { + var lid = this._layers[i]; + + // ---- filter branch ---- + if (hasFilter) { + // Flowmap layers consume an absolute time range via their + // own plugin, not a Mapbox filter expression. Feature-detect + // the plugin (absent until the flowmap feature is loaded) and + // route window-mode ranges to selectedTimeRange. + var isFlowmap = + typeof window.MapGLFlowmapPlugin !== "undefined" && + window.MapGLFlowmapPlugin.hasLayer && + window.MapGLFlowmapPlugin.hasLayer(this._map, lid); + if (isFlowmap && this._mode === "window") { + var _b = this._windowBounds(); + var loT = this._toTime(_b[0]); + var hiT = this._toTime(_b[1]); + if (loT == null || hiT == null) { + if (typeof console !== "undefined" && console.warn) { + console.warn( + "[mapgl] slider window on flowmap layer '" + + lid + + "' needs an absolute time_unit ('seconds','date','year'); skipping." + ); + } + } else { + window.MapGLFlowmapPlugin.setFilter(this._map, lid, { + selectedTimeRange: [loT, hiT] + }); + } + } else if (state) { + state.filterStack[lid] = state.filterStack[lid] || {}; + state.filterStack[lid].slider = filter; + if (typeof window._mapglComposeFilter === "function") { + window._mapglComposeFilter(this._map, lid); + } else if (this._map.getLayer && this._map.getLayer(lid)) { + // Legacy fallback: no composition with other sources. + this._map.setFilter(lid, filter); + } + } + } + + // ---- paint branch ---- + // Loop every configured paint property; capture baseline per + // (layer, property) on first sighting, then apply current expr. + if (hasPaint && this._map.getLayer && this._map.getLayer(lid)) { + if (!this._paintBaseline[lid]) this._paintBaseline[lid] = {}; + for (var p = 0; p < paintProps.length; p++) { + var prop = paintProps[p]; + var list = this._paintProperties[prop]; + if (!list || !list.length) continue; + if ( + !Object.prototype.hasOwnProperty.call( + this._paintBaseline[lid], + prop + ) + ) { + this._paintBaseline[lid][prop] = + this._map.getPaintProperty(lid, prop); + } + this._map.setPaintProperty(lid, prop, list[this._index]); + } + } + } + }; + + SliderControl.prototype._setIndex = function (index, opts) { + opts = opts || {}; + var clamped = this._clampIndex(index); + var changed = clamped !== this._index; + this._index = clamped; + if (this._input) this._input.value = String(clamped); + if (this._valueEl) this._valueEl.textContent = this._labels[clamped] || ""; + this._updateHistogramHighlight(); + if (this._brushBand) this._renderBrush(); + if (opts.pause) this._stopLoop(); + if (changed || opts.force) { + this._applyFilterToLayers(); + this._fireShinyInput(); + } + }; + + SliderControl.prototype._fireShinyInput = function () { + if (!this._shinyInputName) return; + if (typeof Shiny === "undefined" || !Shiny.setInputValue) return; + var payload; + if (this._mode === "window") { + payload = { + start: this._values[this._startIndex], + end: this._values[this._endIndex], + start_index: this._startIndex, + end_index: this._endIndex, + start_label: this._labels[this._startIndex], + end_label: this._labels[this._endIndex], + playing: this._playing + }; + } else { + payload = { + value: this._values[this._index], + index: this._index, + label: this._labels[this._index], + playing: this._playing + }; + } + Shiny.setInputValue(this._shinyInputName, payload, { priority: "event" }); + }; + + SliderControl.prototype._togglePlay = function () { + if (this._playing) this._stopLoop(); else this._startLoop(); + }; + + SliderControl.prototype._startLoop = function () { + if (this._playing || this._values.length < 2) return; + this._playing = true; + this._setPlayIcon(true); + var self = this; + var step = function () { + if (!self._playing) return; + if (self._mode === "window") { + // Slide the whole band forward, preserving width. + self._advanceWindow(); + } else { + var next = self._index + 1; + if (next >= self._values.length) { + if (!self._loop) { self._stopLoop(); return; } + next = 0; + } + self._setIndex(next, { force: true }); + } + self._timer = setTimeout(step, self._animationDuration); + }; + this._timer = setTimeout(step, this._animationDuration); + this._fireShinyInput(); + }; + + SliderControl.prototype._stopLoop = function () { + if (this._timer) { clearTimeout(this._timer); this._timer = null; } + if (!this._playing) return; + this._playing = false; + this._setPlayIcon(false); + this._fireShinyInput(); + }; + + SliderControl.prototype._setPlayIcon = function (playing) { + if (!this._playBtn) return; + this._playBtn.innerHTML = playing ? ICON_PAUSE : ICON_PLAY; + this._playBtn.setAttribute("aria-label", playing ? "Pause" : "Play"); + }; + + // Proxy-driven updates from R's update_slider_control(). + SliderControl.prototype.update = function (msg) { + if (msg == null) return; + if (msg.animation_duration != null) { + this._animationDuration = Math.max(50, msg.animation_duration); + } + if (msg.value != null) { + // Find the matching index for this value. Use strict equality; + // values are expected to be numeric. + var idx = -1; + for (var i = 0; i < this._values.length; i++) { + if (this._values[i] === msg.value) { idx = i; break; } + } + // Fallback: if exact match fails (e.g., float imprecision), pick + // the nearest numeric value. + if (idx === -1) { + var bestDelta = Infinity; + for (var j = 0; j < this._values.length; j++) { + var d = Math.abs(Number(this._values[j]) - Number(msg.value)); + if (d < bestDelta) { bestDelta = d; idx = j; } + } + } + if (idx >= 0) { + if (this._mode === "window") { + this._setWindowEnd(idx, { force: true }); + } else { + this._setIndex(idx, { force: true }); + } + } + } + if (msg.playing === true && !this._playing) this._startLoop(); + if (msg.playing === false && this._playing) this._stopLoop(); + }; + + // Expose globally for the binding files to instantiate. + window.MapglSliderControl = SliderControl; +})(); diff --git a/inst/htmlwidgets/mapboxgl.js b/inst/htmlwidgets/mapboxgl.js index d8566494..01d31283 100644 --- a/inst/htmlwidgets/mapboxgl.js +++ b/inst/htmlwidgets/mapboxgl.js @@ -565,6 +565,57 @@ function initializeDrawAttributeEditor(map, drawControl, options) { }; } +// Shared layer-state and filter-composition helpers. +// +// `window._mapglLayerState[mapId]` is the cross-file state object used by +// the main binding, the proxy handler, and legend-interactivity. These +// helpers are the single entry point for populating and composing filters +// across multiple filter sources (layer-initial, proxy set_filter, +// interactive legend, slider). +function _mapglEnsureLayerState(map) { + if (!window._mapglLayerState) window._mapglLayerState = {}; + const mapId = map.getContainer().id; + const s = + window._mapglLayerState[mapId] || + (window._mapglLayerState[mapId] = {}); + if (!s.filters) s.filters = {}; + if (!s.paintProperties) s.paintProperties = {}; + if (!s.layoutProperties) s.layoutProperties = {}; + if (!s.tooltips) s.tooltips = {}; + if (!s.popups) s.popups = {}; + // Parallel maps holding the (optional) tooltip/popup style spec for proxy + // set_tooltip()/set_popup() so theming survives a style reload. + if (!s.tooltipStyles) s.tooltipStyles = {}; + if (!s.popupStyles) s.popupStyles = {}; + if (!s.legends) s.legends = {}; + if (!s.interactiveFilters) s.interactiveFilters = {}; + if (!s.filterStack) s.filterStack = {}; + return s; +} + +// Compose active filter slots for a layer and apply the result. +// Slots: base (layer-initial), user (proxy set_filter), legend +// (interactive legend), slider (slider). Writes the composed +// expression back to state.filters so the style-reload replay path +// continues to work. +function _mapglComposeAndApplyFilter(map, layerId) { + const state = _mapglEnsureLayerState(map); + const stack = state.filterStack[layerId] || {}; + const active = [stack.base, stack.user, stack.legend, stack.slider].filter( + (f) => f != null, + ); + const composed = + active.length === 0 ? null : active.length === 1 ? active[0] : ["all", ...active]; + if (map.getLayer && map.getLayer(layerId)) { + map.setFilter(layerId, composed); + } + state.filters[layerId] = composed; +} + +// Expose for cross-file consumers (legend-interactivity, slider). +window._mapglEnsureLayerState = _mapglEnsureLayerState; +window._mapglComposeFilter = _mapglComposeAndApplyFilter; + // Measurement functionality function createMeasurementBox(map) { const box = document.createElement("div"); @@ -1020,6 +1071,186 @@ function evaluateExpression(expression, properties) { } } +// Escape a value for safe insertion as tooltip/popup text. Used by the brace +// template renderer so substituted values cannot inject markup. +function escapeTemplateValue(value) { + return String(value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +// Render a {brace} template against a properties object. Each {key} (dotted +// paths like {origin.id} supported) is replaced by the HTML-escaped value; +// literal text/markup in the template is emitted as-is. Shared, package-wide +// tooltip/popup syntax. NOTE: duplicated verbatim in maplibregl.js, +// mapboxgl_compare.js, maplibregl_compare.js, and flowmap.js — keep in sync. +function renderTemplate(template, properties) { + if (typeof template !== "string") { + return template; + } + return template.replace(/\{([^}]+)\}/g, function (match, path) { + const value = path + .trim() + .split(".") + .reduce(function (acc, key) { + return acc == null ? undefined : acc[key]; + }, properties); + return value == null ? "" : escapeTemplateValue(value); + }); +} + +// Resolve a tooltip/popup content spec against a feature's properties: +// array -> Mapbox-style expression (concat/number_format/get) via evaluateExpression +// "{..}" -> brace template via renderTemplate +// string -> a column name (direct property lookup) +function resolveTooltipContent(spec, properties) { + if (Array.isArray(spec)) { + return evaluateExpression(spec, properties); + } + if (typeof spec === "string" && spec.indexOf("{") !== -1) { + return renderTemplate(spec, properties); + } + return properties[spec]; +} + +// Convert "#rgb"/"#rrggbb" + alpha to rgba(); pass other color strings through. +function tooltipHexToRgba(color, alpha) { + if (typeof color !== "string" || color.charAt(0) !== "#") { + return color; + } + let h = color.slice(1); + if (h.length === 3) { + h = h + .split("") + .map(function (c) { + return c + c; + }) + .join(""); + } + const r = parseInt(h.slice(0, 2), 16); + const g = parseInt(h.slice(2, 4), 16); + const b = parseInt(h.slice(4, 6), 16); + return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; +} + +// Build (and cache) a scoped CSS class from a tooltip/popup style spec, so a +// themed popup needs only a className. Returns null for an empty/absent spec +// (native appearance). One