@npm9912/v-map 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +185 -0
- package/dist/cjs/_commonjsHelpers-B83fTs8d.js +36 -0
- package/dist/cjs/app-globals-V2Kpy_OQ.js +5 -0
- package/dist/cjs/cesium-provider-BiFFyAl9.js +2598 -0
- package/dist/cjs/deck-provider-Ctq3Q8a1.js +47824 -0
- package/dist/cjs/geotiff-CEwvF9cG.js +47 -0
- package/dist/cjs/geotiff-source-RaNzzWkC.js +1522 -0
- package/dist/cjs/index-B1oGO1g-.js +10658 -0
- package/dist/cjs/index-B8LHqjyg.js +1765 -0
- package/dist/cjs/index-BIL4VsgP.js +310 -0
- package/dist/cjs/index-Blku2QY8.js +167 -0
- package/dist/cjs/index-CJvvX4yx.js +21 -0
- package/dist/cjs/index-CbVT-Con.js +699 -0
- package/dist/cjs/index-ISOEpMC3.js +20478 -0
- package/dist/cjs/index-JSwBbvGA.js +1621 -0
- package/dist/cjs/index.browser-DQhD8Jwl.js +6873 -0
- package/dist/cjs/index.cjs.js +2 -0
- package/dist/cjs/layer-extension-B_olS0rc.js +65 -0
- package/dist/cjs/leaflet-provider-DOqfs7g5.js +1815 -0
- package/dist/cjs/loader.cjs.js +13 -0
- package/dist/cjs/main-dist-7TykwFci.js +2655 -0
- package/dist/cjs/messages-D7h4m8Tx.js +186 -0
- package/dist/cjs/openlayers-provider-Dfeg6L4n.js +1604 -0
- package/dist/cjs/polygon-layer-B9PrN7vr.js +1300 -0
- package/dist/cjs/scenegraph-layer-DwNoxQdi.js +2530 -0
- package/dist/cjs/styleconfig-CVRqArk-.js +23 -0
- package/dist/cjs/v-map-builder.cjs.entry.js +3786 -0
- package/dist/cjs/v-map-layer-geojson_12.cjs.entry.js +40894 -0
- package/dist/cjs/v-map-layer-helper-iAzxAg9I.js +285 -0
- package/dist/cjs/v-map-layer-terrain-geotiff.cjs.entry.js +258 -0
- package/dist/cjs/v-map-layercontrol.cjs.entry.js +247 -0
- package/dist/cjs/v-map.cjs.js +25 -0
- package/dist/cjs/v-map.v-map-layer-osm.v-map-layergroup-BsXp3BoL.js +582 -0
- package/dist/cjs/v-map_3.cjs.entry.js +12 -0
- package/dist/collection/collection-manifest.json +30 -0
- package/dist/collection/components/v-map/v-map.css +3 -0
- package/dist/collection/components/v-map/v-map.js +467 -0
- package/dist/collection/components/v-map/v-map.test.js +33 -0
- package/dist/collection/components/v-map-builder/v-map-builder.css +1 -0
- package/dist/collection/components/v-map-builder/v-map-builder.js +913 -0
- package/dist/collection/components/v-map-builder/v-map-builder.test.js +56 -0
- package/dist/collection/components/v-map-layer-geojson/v-map-layer-geojson.js +862 -0
- package/dist/collection/components/v-map-layer-geojson/v-map-layer-geojson.test.js +42 -0
- package/dist/collection/components/v-map-layer-geotiff/v-map-layer-geotiff.css +4 -0
- package/dist/collection/components/v-map-layer-geotiff/v-map-layer-geotiff.js +500 -0
- package/dist/collection/components/v-map-layer-geotiff/v-map-layer-geotiff.test.js +38 -0
- package/dist/collection/components/v-map-layer-google/v-map-layer-google.css +1 -0
- package/dist/collection/components/v-map-layer-google/v-map-layer-google.js +442 -0
- package/dist/collection/components/v-map-layer-osm/error-api.test.js +108 -0
- package/dist/collection/components/v-map-layer-osm/v-map-layer-osm.css +4 -0
- package/dist/collection/components/v-map-layer-osm/v-map-layer-osm.js +311 -0
- package/dist/collection/components/v-map-layer-osm/v-map-layer-osm.test.js +36 -0
- package/dist/collection/components/v-map-layer-scatterplot/v-map-layer-scatterplot.css +1 -0
- package/dist/collection/components/v-map-layer-scatterplot/v-map-layer-scatterplot.js +305 -0
- package/dist/collection/components/v-map-layer-terrain/v-map-layer-terrain.css +3 -0
- package/dist/collection/components/v-map-layer-terrain/v-map-layer-terrain.js +548 -0
- package/dist/collection/components/v-map-layer-terrain/v-map-layer-terrain.test.js +36 -0
- package/dist/collection/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.css +3 -0
- package/dist/collection/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.js +735 -0
- package/dist/collection/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.test.js +42 -0
- package/dist/collection/components/v-map-layer-tile3d/v-map-layer-tile3d.css +3 -0
- package/dist/collection/components/v-map-layer-tile3d/v-map-layer-tile3d.js +449 -0
- package/dist/collection/components/v-map-layer-tile3d/v-map-layer-tile3d.test.js +50 -0
- package/dist/collection/components/v-map-layer-wcs/v-map-layer-wcs.css +1 -0
- package/dist/collection/components/v-map-layer-wcs/v-map-layer-wcs.js +448 -0
- package/dist/collection/components/v-map-layer-wcs/v-map-layer-wcs.test.js +39 -0
- package/dist/collection/components/v-map-layer-wfs/v-map-layer-wfs.css +1 -0
- package/dist/collection/components/v-map-layer-wfs/v-map-layer-wfs.js +489 -0
- package/dist/collection/components/v-map-layer-wfs/v-map-layer-wfs.test.js +43 -0
- package/dist/collection/components/v-map-layer-wkt/v-map-layer-wkt.css +1 -0
- package/dist/collection/components/v-map-layer-wkt/v-map-layer-wkt.js +811 -0
- package/dist/collection/components/v-map-layer-wkt/v-map-layer-wkt.test.js +34 -0
- package/dist/collection/components/v-map-layer-wms/v-map-layer-wms.css +1 -0
- package/dist/collection/components/v-map-layer-wms/v-map-layer-wms.js +453 -0
- package/dist/collection/components/v-map-layer-wms/v-map-layer-wms.test.js +36 -0
- package/dist/collection/components/v-map-layer-xyz/v-map-layer-xyz.css +1 -0
- package/dist/collection/components/v-map-layer-xyz/v-map-layer-xyz.js +331 -0
- package/dist/collection/components/v-map-layer-xyz/v-map-layer-xyz.test.js +28 -0
- package/dist/collection/components/v-map-layercontrol/v-map-layercontrol.css +74 -0
- package/dist/collection/components/v-map-layercontrol/v-map-layercontrol.js +277 -0
- package/dist/collection/components/v-map-layercontrol/v-map-layercontrol.test.js +134 -0
- package/dist/collection/components/v-map-layergroup/v-map-layergroup.css +4 -0
- package/dist/collection/components/v-map-layergroup/v-map-layergroup.js +212 -0
- package/dist/collection/components/v-map-layergroup/v-map-layergroup.test.js +39 -0
- package/dist/collection/components/v-map-style/v-map-style.css +38 -0
- package/dist/collection/components/v-map-style/v-map-style.js +492 -0
- package/dist/collection/components/v-map-style/v-map-style.unit.js +62 -0
- package/dist/collection/index.js +1 -0
- package/dist/collection/layer/v-map-layer-helper.js +281 -0
- package/dist/collection/layer/v-map-layer-helper.unit.js +234 -0
- package/dist/collection/lib/cesium-loader.js +58 -0
- package/dist/collection/lib/ensure-importmap.js +12 -0
- package/dist/collection/lib/ensure-importmap.unit.js +57 -0
- package/dist/collection/lib/versions.gen.js +6 -0
- package/dist/collection/lib/vstyle.js +8 -0
- package/dist/collection/map-provider/cesium/CesiumGeoTIFFTerrainProvider.js +285 -0
- package/dist/collection/map-provider/cesium/CesiumLayerGroups.js +159 -0
- package/dist/collection/map-provider/cesium/GeoTIFFImageryProvider.js +192 -0
- package/dist/collection/map-provider/cesium/GeoTIFFImageryProvider.test.js +57 -0
- package/dist/collection/map-provider/cesium/cesium-provider.js +1408 -0
- package/dist/collection/map-provider/cesium/i-layer.js +1 -0
- package/dist/collection/map-provider/cesium/layer-manager.js +467 -0
- package/dist/collection/map-provider/deck/DeckGLGeoTIFFLayer.js +483 -0
- package/dist/collection/map-provider/deck/DeckGLGeoTIFFTerrainLayer.js +410 -0
- package/dist/collection/map-provider/deck/LayerGroupWithModel.js +169 -0
- package/dist/collection/map-provider/deck/LayerGroups.js +192 -0
- package/dist/collection/map-provider/deck/LayerModel.js +1 -0
- package/dist/collection/map-provider/deck/RenderableGroup.js +1 -0
- package/dist/collection/map-provider/deck/deck-provider.js +1563 -0
- package/dist/collection/map-provider/geotiff/geotiff-source.js +172 -0
- package/dist/collection/map-provider/geotiff/utils/AABB2D.js +24 -0
- package/dist/collection/map-provider/geotiff/utils/BVHNode2D.js +166 -0
- package/dist/collection/map-provider/geotiff/utils/GeoTIFFTileProcessor.js +484 -0
- package/dist/collection/map-provider/geotiff/utils/Triangle.js +1 -0
- package/dist/collection/map-provider/geotiff/utils/Triangulation.js +321 -0
- package/dist/collection/map-provider/geotiff/utils/colormap-utils.js +190 -0
- package/dist/collection/map-provider/geotiff/utils/normalization-utils.js +122 -0
- package/dist/collection/map-provider/geotiff/utils/sampling-utils.js +108 -0
- package/dist/collection/map-provider/leaflet/GeoTIFFGridLayer.js +147 -0
- package/dist/collection/map-provider/leaflet/WCSGridLayer.js +124 -0
- package/dist/collection/map-provider/leaflet/google-map-tiles-layer.js +352 -0
- package/dist/collection/map-provider/leaflet/leaflet-helpers.js +94 -0
- package/dist/collection/map-provider/leaflet/leaflet-provider.js +1095 -0
- package/dist/collection/map-provider/ol/CustomGeoTiff.js +145 -0
- package/dist/collection/map-provider/ol/openlayers-helper.js +26 -0
- package/dist/collection/map-provider/ol/openlayers-provider.js +1427 -0
- package/dist/collection/map-provider/provider-factory.js +44 -0
- package/dist/collection/map-provider/provider-factory.unit.js +66 -0
- package/dist/collection/testing/browser-test-utils.js +49 -0
- package/dist/collection/testing/e2e-testing.js +122 -0
- package/dist/collection/testing/e2e-utils.js +70 -0
- package/dist/collection/testing/geotiff-test-server.js +100 -0
- package/dist/collection/testing/mocks/geostyler-lyrx-parser.js +12 -0
- package/dist/collection/testing/mocks/geostyler-mapbox-parser.js +12 -0
- package/dist/collection/testing/mocks/geostyler-qgis-parser.js +12 -0
- package/dist/collection/testing/mocks/geostyler-sld-parser.js +13 -0
- package/dist/collection/testing/mocks/geostyler-style.js +5 -0
- package/dist/collection/testing/setupTests.browser.js +1 -0
- package/dist/collection/testing/setupTests.stencil.js +20 -0
- package/dist/collection/testing/setupTests.vitest.js +59 -0
- package/dist/collection/testing/stencil-testing-wrapper.js +43 -0
- package/dist/collection/testing/styleMock.js +1 -0
- package/dist/collection/types/color.js +1 -0
- package/dist/collection/types/cssmode.js +1 -0
- package/dist/collection/types/flavour.js +1 -0
- package/dist/collection/types/layerconfig.js +1 -0
- package/dist/collection/types/lonlat.js +1 -0
- package/dist/collection/types/mapinitoptions.js +1 -0
- package/dist/collection/types/mapprovider.js +1 -0
- package/dist/collection/types/provideroptions.js +1 -0
- package/dist/collection/types/styleconfig.js +19 -0
- package/dist/collection/types/styling.js +13 -0
- package/dist/collection/types/styling.unit.js +37 -0
- package/dist/collection/types/vmaplayer.js +1 -0
- package/dist/collection/utils/async-mutex.js +28 -0
- package/dist/collection/utils/diff.js +142 -0
- package/dist/collection/utils/diff.unit.js +59 -0
- package/dist/collection/utils/dom-env.js +43 -0
- package/dist/collection/utils/dom-env.unit.js +92 -0
- package/dist/collection/utils/events.js +8 -0
- package/dist/collection/utils/logger.js +183 -0
- package/dist/collection/utils/logger.unit.js +98 -0
- package/dist/collection/utils/messages.js +12 -0
- package/dist/collection/utils/spatial-utils.js +27 -0
- package/dist/collection/utils/spatial-utils.unit.js +24 -0
- package/dist/components/_commonjsHelpers.js +1 -0
- package/dist/components/cesium-provider.js +1 -0
- package/dist/components/deck-provider.js +1 -0
- package/dist/components/events.js +1 -0
- package/dist/components/geotiff-source.js +1 -0
- package/dist/components/geotiff.js +4 -0
- package/dist/components/index.browser.js +15 -0
- package/dist/components/index.d.ts +35 -0
- package/dist/components/index.js +1 -0
- package/dist/components/index2.js +1 -0
- package/dist/components/index3.js +1 -0
- package/dist/components/index4.js +1 -0
- package/dist/components/index5.js +1 -0
- package/dist/components/index6.js +1 -0
- package/dist/components/index7.js +1 -0
- package/dist/components/index8.js +7 -0
- package/dist/components/layer-extension.js +1 -0
- package/dist/components/leaflet-provider.js +1 -0
- package/dist/components/main-dist.js +1 -0
- package/dist/components/messages.js +1 -0
- package/dist/components/openlayers-provider.js +1 -0
- package/dist/components/polygon-layer.js +1 -0
- package/dist/components/scenegraph-layer.js +1 -0
- package/dist/components/styleconfig.js +1 -0
- package/dist/components/styling.js +1 -0
- package/dist/components/v-map-builder.d.ts +11 -0
- package/dist/components/v-map-builder.js +2 -0
- package/dist/components/v-map-layer-geojson.d.ts +11 -0
- package/dist/components/v-map-layer-geojson.js +1 -0
- package/dist/components/v-map-layer-geojson2.js +1 -0
- package/dist/components/v-map-layer-geotiff.d.ts +11 -0
- package/dist/components/v-map-layer-geotiff.js +1 -0
- package/dist/components/v-map-layer-geotiff2.js +1 -0
- package/dist/components/v-map-layer-google.d.ts +11 -0
- package/dist/components/v-map-layer-google.js +1 -0
- package/dist/components/v-map-layer-google2.js +1 -0
- package/dist/components/v-map-layer-helper.js +1 -0
- package/dist/components/v-map-layer-osm.d.ts +11 -0
- package/dist/components/v-map-layer-osm.js +1 -0
- package/dist/components/v-map-layer-osm2.js +1 -0
- package/dist/components/v-map-layer-scatterplot.d.ts +11 -0
- package/dist/components/v-map-layer-scatterplot.js +1 -0
- package/dist/components/v-map-layer-scatterplot2.js +1 -0
- package/dist/components/v-map-layer-terrain-geotiff.d.ts +11 -0
- package/dist/components/v-map-layer-terrain-geotiff.js +1 -0
- package/dist/components/v-map-layer-terrain.d.ts +11 -0
- package/dist/components/v-map-layer-terrain.js +1 -0
- package/dist/components/v-map-layer-terrain2.js +1 -0
- package/dist/components/v-map-layer-tile3d.d.ts +11 -0
- package/dist/components/v-map-layer-tile3d.js +1 -0
- package/dist/components/v-map-layer-tile3d2.js +1 -0
- package/dist/components/v-map-layer-wcs.d.ts +11 -0
- package/dist/components/v-map-layer-wcs.js +1 -0
- package/dist/components/v-map-layer-wcs2.js +1 -0
- package/dist/components/v-map-layer-wfs.d.ts +11 -0
- package/dist/components/v-map-layer-wfs.js +1 -0
- package/dist/components/v-map-layer-wfs2.js +1 -0
- package/dist/components/v-map-layer-wkt.d.ts +11 -0
- package/dist/components/v-map-layer-wkt.js +1 -0
- package/dist/components/v-map-layer-wkt2.js +1 -0
- package/dist/components/v-map-layer-wms.d.ts +11 -0
- package/dist/components/v-map-layer-wms.js +1 -0
- package/dist/components/v-map-layer-wms2.js +1 -0
- package/dist/components/v-map-layer-xyz.d.ts +11 -0
- package/dist/components/v-map-layer-xyz.js +1 -0
- package/dist/components/v-map-layer-xyz2.js +1 -0
- package/dist/components/v-map-layercontrol.d.ts +11 -0
- package/dist/components/v-map-layercontrol.js +1 -0
- package/dist/components/v-map-layergroup.d.ts +11 -0
- package/dist/components/v-map-layergroup.js +1 -0
- package/dist/components/v-map-layergroup2.js +1 -0
- package/dist/components/v-map-style.d.ts +11 -0
- package/dist/components/v-map-style.js +1 -0
- package/dist/components/v-map-style2.js +10 -0
- package/dist/components/v-map.d.ts +11 -0
- package/dist/components/v-map.js +1 -0
- package/dist/components/v-map2.js +1 -0
- package/dist/esm/_commonjsHelpers-E-ZsRS8r.js +32 -0
- package/dist/esm/app-globals-DQuL1Twl.js +3 -0
- package/dist/esm/cesium-provider-BJfAup3w.js +2596 -0
- package/dist/esm/deck-provider-C7U9VDEq.js +47709 -0
- package/dist/esm/geotiff-BEWxTIfH.js +45 -0
- package/dist/esm/geotiff-source-esnDnC-u.js +1516 -0
- package/dist/esm/index-B1zwA4IC.js +685 -0
- package/dist/esm/index-BBpiaTpT.js +165 -0
- package/dist/esm/index-BIEmlzCf.js +1697 -0
- package/dist/esm/index-BUHa4Jj0.js +307 -0
- package/dist/esm/index-DbSdn93t.js +20461 -0
- package/dist/esm/index-RpJarvr_.js +10656 -0
- package/dist/esm/index-jN06TXUp.js +14 -0
- package/dist/esm/index-jzneDarq.js +1613 -0
- package/dist/esm/index.browser-DhQAXuA7.js +6860 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/layer-extension-CZXK5goK.js +63 -0
- package/dist/esm/leaflet-provider-Q41TB6ku.js +1794 -0
- package/dist/esm/loader.js +11 -0
- package/dist/esm/main-dist-CwnA7_Xn.js +2652 -0
- package/dist/esm/messages-CMKJzsgL.js +180 -0
- package/dist/esm/openlayers-provider-CMsDsQTQ.js +1602 -0
- package/dist/esm/polygon-layer-ByhxGhWC.js +1295 -0
- package/dist/esm/scenegraph-layer-09K_B6DT.js +2526 -0
- package/dist/esm/styleconfig-B-bAcABs.js +21 -0
- package/dist/esm/v-map-builder.entry.js +3784 -0
- package/dist/esm/v-map-layer-geojson_12.entry.js +40881 -0
- package/dist/esm/v-map-layer-helper-Dys44Cgo.js +283 -0
- package/dist/esm/v-map-layer-terrain-geotiff.entry.js +256 -0
- package/dist/esm/v-map-layercontrol.entry.js +245 -0
- package/dist/esm/v-map.js +21 -0
- package/dist/esm/v-map.v-map-layer-osm.v-map-layergroup-B4pFHuSf.js +572 -0
- package/dist/esm/v-map_3.entry.js +4 -0
- package/dist/index.cjs.js +1 -0
- package/dist/index.js +1 -0
- package/dist/types/cesium-augment.d.ts +5 -0
- package/dist/types/components/v-map/v-map.d.ts +70 -0
- package/dist/types/components/v-map/v-map.test.d.ts +1 -0
- package/dist/types/components/v-map-builder/v-map-builder.d.ts +48 -0
- package/dist/types/components/v-map-builder/v-map-builder.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-geojson/v-map-layer-geojson.d.ts +129 -0
- package/dist/types/components/v-map-layer-geojson/v-map-layer-geojson.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-geotiff/v-map-layer-geotiff.d.ts +74 -0
- package/dist/types/components/v-map-layer-geotiff/v-map-layer-geotiff.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-google/v-map-layer-google.d.ts +78 -0
- package/dist/types/components/v-map-layer-osm/error-api.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-osm/v-map-layer-osm.d.ts +50 -0
- package/dist/types/components/v-map-layer-osm/v-map-layer-osm.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-scatterplot/v-map-layer-scatterplot.d.ts +54 -0
- package/dist/types/components/v-map-layer-terrain/v-map-layer-terrain.d.ts +74 -0
- package/dist/types/components/v-map-layer-terrain/v-map-layer-terrain.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.d.ts +117 -0
- package/dist/types/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-tile3d/v-map-layer-tile3d.d.ts +69 -0
- package/dist/types/components/v-map-layer-tile3d/v-map-layer-tile3d.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-wcs/v-map-layer-wcs.d.ts +47 -0
- package/dist/types/components/v-map-layer-wcs/v-map-layer-wcs.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-wfs/v-map-layer-wfs.d.ts +59 -0
- package/dist/types/components/v-map-layer-wfs/v-map-layer-wfs.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-wkt/v-map-layer-wkt.d.ts +132 -0
- package/dist/types/components/v-map-layer-wkt/v-map-layer-wkt.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-wms/v-map-layer-wms.d.ts +76 -0
- package/dist/types/components/v-map-layer-wms/v-map-layer-wms.test.d.ts +1 -0
- package/dist/types/components/v-map-layer-xyz/v-map-layer-xyz.d.ts +59 -0
- package/dist/types/components/v-map-layer-xyz/v-map-layer-xyz.test.d.ts +1 -0
- package/dist/types/components/v-map-layercontrol/v-map-layercontrol.d.ts +44 -0
- package/dist/types/components/v-map-layercontrol/v-map-layercontrol.test.d.ts +1 -0
- package/dist/types/components/v-map-layergroup/v-map-layergroup.d.ts +31 -0
- package/dist/types/components/v-map-layergroup/v-map-layergroup.test.d.ts +1 -0
- package/dist/types/components/v-map-style/v-map-style.d.ts +75 -0
- package/dist/types/components/v-map-style/v-map-style.unit.d.ts +1 -0
- package/dist/types/components.d.ts +2391 -0
- package/dist/types/globals.d.ts +16 -0
- package/dist/types/index.d.ts +10 -0
- package/dist/types/layer/v-map-layer-helper.d.ts +45 -0
- package/dist/types/layer/v-map-layer-helper.unit.d.ts +1 -0
- package/dist/types/leaflet-augment.d.ts +15 -0
- package/dist/types/lib/cesium-loader.d.ts +3 -0
- package/dist/types/lib/ensure-importmap.d.ts +3 -0
- package/dist/types/lib/ensure-importmap.unit.d.ts +1 -0
- package/dist/types/lib/versions.gen.d.ts +5 -0
- package/dist/types/lib/vstyle.d.ts +44 -0
- package/dist/types/map-provider/cesium/CesiumGeoTIFFTerrainProvider.d.ts +92 -0
- package/dist/types/map-provider/cesium/CesiumLayerGroups.d.ts +64 -0
- package/dist/types/map-provider/cesium/GeoTIFFImageryProvider.d.ts +75 -0
- package/dist/types/map-provider/cesium/GeoTIFFImageryProvider.test.d.ts +1 -0
- package/dist/types/map-provider/cesium/cesium-provider.d.ts +87 -0
- package/dist/types/map-provider/cesium/i-layer.d.ts +11 -0
- package/dist/types/map-provider/cesium/layer-manager.d.ts +31 -0
- package/dist/types/map-provider/deck/DeckGLGeoTIFFLayer.d.ts +91 -0
- package/dist/types/map-provider/deck/DeckGLGeoTIFFTerrainLayer.d.ts +82 -0
- package/dist/types/map-provider/deck/LayerGroupWithModel.d.ts +55 -0
- package/dist/types/map-provider/deck/LayerGroups.d.ts +63 -0
- package/dist/types/map-provider/deck/LayerModel.d.ts +8 -0
- package/dist/types/map-provider/deck/RenderableGroup.d.ts +20 -0
- package/dist/types/map-provider/deck/deck-provider.d.ts +92 -0
- package/dist/types/map-provider/geotiff/geotiff-source.d.ts +30 -0
- package/dist/types/map-provider/geotiff/utils/AABB2D.d.ts +28 -0
- package/dist/types/map-provider/geotiff/utils/BVHNode2D.d.ts +36 -0
- package/dist/types/map-provider/geotiff/utils/GeoTIFFTileProcessor.d.ts +116 -0
- package/dist/types/map-provider/geotiff/utils/Triangle.d.ts +5 -0
- package/dist/types/map-provider/geotiff/utils/Triangulation.d.ts +94 -0
- package/dist/types/map-provider/geotiff/utils/colormap-utils.d.ts +47 -0
- package/dist/types/map-provider/geotiff/utils/normalization-utils.d.ts +39 -0
- package/dist/types/map-provider/geotiff/utils/sampling-utils.d.ts +13 -0
- package/dist/types/map-provider/leaflet/GeoTIFFGridLayer.d.ts +34 -0
- package/dist/types/map-provider/leaflet/WCSGridLayer.d.ts +38 -0
- package/dist/types/map-provider/leaflet/google-map-tiles-layer.d.ts +73 -0
- package/dist/types/map-provider/leaflet/leaflet-helpers.d.ts +6 -0
- package/dist/types/map-provider/leaflet/leaflet-provider.d.ts +73 -0
- package/dist/types/map-provider/ol/CustomGeoTiff.d.ts +14 -0
- package/dist/types/map-provider/ol/openlayers-helper.d.ts +2 -0
- package/dist/types/map-provider/ol/openlayers-provider.d.ts +80 -0
- package/dist/types/map-provider/provider-factory.d.ts +12 -0
- package/dist/types/map-provider/provider-factory.unit.d.ts +1 -0
- package/dist/types/namespaces.d.ts +3 -0
- package/dist/types/ol-augment.d.ts +3 -0
- package/dist/types/ol-override.d.ts +7 -0
- package/dist/types/ol.d.ts +10 -0
- package/dist/types/stencil-public-runtime.d.ts +1860 -0
- package/dist/types/testing/browser-test-utils.d.ts +6 -0
- package/dist/types/testing/e2e-testing.d.ts +5 -0
- package/dist/types/testing/e2e-utils.d.ts +4 -0
- package/dist/types/testing/geotiff-test-server.d.ts +5 -0
- package/dist/types/testing/mocks/geostyler-lyrx-parser.d.ts +11 -0
- package/dist/types/testing/mocks/geostyler-mapbox-parser.d.ts +11 -0
- package/dist/types/testing/mocks/geostyler-qgis-parser.d.ts +11 -0
- package/dist/types/testing/mocks/geostyler-sld-parser.d.ts +11 -0
- package/dist/types/testing/mocks/geostyler-style.d.ts +5 -0
- package/dist/types/testing/setupTests.browser.d.ts +1 -0
- package/dist/types/testing/setupTests.stencil.d.ts +1 -0
- package/dist/types/testing/setupTests.vitest.d.ts +1 -0
- package/dist/types/testing/stencil-testing-wrapper.d.ts +3 -0
- package/dist/types/types/color.d.ts +1 -0
- package/dist/types/types/cssmode.d.ts +1 -0
- package/dist/types/types/flavour.d.ts +1 -0
- package/dist/types/types/layerconfig.d.ts +207 -0
- package/dist/types/types/lonlat.d.ts +1 -0
- package/dist/types/types/mapinitoptions.d.ts +4 -0
- package/dist/types/types/mapprovider.d.ts +46 -0
- package/dist/types/types/provideroptions.d.ts +8 -0
- package/dist/types/types/styleconfig.d.ts +27 -0
- package/dist/types/types/styling.d.ts +24 -0
- package/dist/types/types/styling.unit.d.ts +1 -0
- package/dist/types/types/vmaplayer.d.ts +10 -0
- package/dist/types/utils/async-mutex.d.ts +7 -0
- package/dist/types/utils/diff.d.ts +64 -0
- package/dist/types/utils/diff.unit.d.ts +1 -0
- package/dist/types/utils/dom-env.d.ts +5 -0
- package/dist/types/utils/dom-env.unit.d.ts +1 -0
- package/dist/types/utils/events.d.ts +29 -0
- package/dist/types/utils/logger.d.ts +47 -0
- package/dist/types/utils/logger.unit.d.ts +1 -0
- package/dist/types/utils/messages.d.ts +12 -0
- package/dist/types/utils/spatial-utils.d.ts +6 -0
- package/dist/types/utils/spatial-utils.unit.d.ts +1 -0
- package/dist/types/versions.d.ts +7 -0
- package/dist/v-map/index.esm.js +0 -0
- package/dist/v-map/p--vVleK-M.js +1 -0
- package/dist/v-map/p-09d10db0.entry.js +1 -0
- package/dist/v-map/p-5eba6058.entry.js +10 -0
- package/dist/v-map/p-6b102336.entry.js +1 -0
- package/dist/v-map/p-B-bAcABs.js +1 -0
- package/dist/v-map/p-BBpiaTpT.js +1 -0
- package/dist/v-map/p-BdijL4Av.js +1 -0
- package/dist/v-map/p-Be3r33VF.js +4 -0
- package/dist/v-map/p-BeFu0ap4.js +1 -0
- package/dist/v-map/p-BxFJezdK.js +1 -0
- package/dist/v-map/p-CMKJzsgL.js +1 -0
- package/dist/v-map/p-CXfA_q8m.js +1 -0
- package/dist/v-map/p-CZqY0yW4.js +1 -0
- package/dist/v-map/p-CafTHT9i.js +1 -0
- package/dist/v-map/p-DCTHyf58.js +1 -0
- package/dist/v-map/p-DQuL1Twl.js +1 -0
- package/dist/v-map/p-DR9McdNX.js +1 -0
- package/dist/v-map/p-Dckgonw8.js +1 -0
- package/dist/v-map/p-DhQAXuA7.js +15 -0
- package/dist/v-map/p-DmICdG34.js +7 -0
- package/dist/v-map/p-DrOQ9V4h.js +1 -0
- package/dist/v-map/p-DvHXtWUg.js +1 -0
- package/dist/v-map/p-E-ZsRS8r.js +1 -0
- package/dist/v-map/p-MyTSFnEk.js +1 -0
- package/dist/v-map/p-RpJarvr_.js +1 -0
- package/dist/v-map/p-WaMDUuAz.js +1 -0
- package/dist/v-map/p-aa410e64.entry.js +2 -0
- package/dist/v-map/p-c21c93fe.entry.js +1 -0
- package/dist/v-map/p-jzneDarq.js +2 -0
- package/dist/v-map/p-uiIP-taz.js +1 -0
- package/dist/v-map/v-map.esm.js +1 -0
- package/loader/cdn.js +1 -0
- package/loader/index.cjs.js +1 -0
- package/loader/index.d.ts +24 -0
- package/loader/index.es2017.js +1 -0
- package/loader/index.js +2 -0
- package/package.json +193 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as t}from"./styleconfig.js";import{GmlParser as e}from"./index.browser.js";import{w as n}from"./index5.js";import{l as i,e as s,w as r}from"./events.js";import{l as o,b as a,G as c,g as l}from"./geotiff-source.js";import{registerLoaders as h,load as u}from"@loaders.gl/core";import{ImageLoader as f}from"@loaders.gl/images";import{RequestScheduler as d}from"@loaders.gl/loader-utils";import{g as p}from"./_commonjsHelpers.js";import{TerrainWorkerLoader as g}from"@loaders.gl/terrain";import{getMeshBoundingBox as m}from"@loaders.gl/schema";const _="v-map - deck - geotiff - ";const v="v-map - deck - terrain-geotiff - ",b=globalThis,y=globalThis.process||{},w=globalThis.navigator||{};function x(){if("undefined"!=typeof window&&"renderer"===window.process?.type)return!0;if("undefined"!=typeof process&&Boolean(process.versions?.electron))return!0;const t="undefined"!=typeof navigator&&navigator.userAgent;return Boolean(t&&t.indexOf("Electron")>=0)}function E(){return!("object"==typeof process&&"[object process]"===String(process)&&!process?.browser)||x()}const T="4.1.1";function A(t){if(!t)throw new Error("Assertion failed")}function S(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 A(Number.isFinite(e)&&e>=0),e}const C=()=>{};class P{constructor({level:t=0}={}){this.userData={},this._onceCache=new Set,this._level=t}set level(t){this.setLevel(t)}get level(){return this.getLevel()}setLevel(t){return this._level=t,this}getLevel(){return this._level}warn(t,...e){return this._log("warn",0,t,e,{once:!0})}error(t,...e){return this._log("error",0,t,e)}log(t,e,...n){return this._log("log",t,e,n)}info(t,e,...n){return this._log("info",t,e,n)}once(t,e,...n){return this._log("once",t,e,n,{once:!0})}_log(t,e,n,i,s={}){const r=function(t){const{logLevel:e,message:n}=t;t.logLevel=S(e);const i=t.args?Array.from(t.args):[];for(;i.length&&i.shift()!==n;);switch(typeof e){case"string":case"function":void 0!==n&&i.unshift(n),t.message=e;break;case"object":Object.assign(t,e)}"function"==typeof t.message&&(t.message=t.message());const s=typeof t.message;return A("string"===s||"object"===s),Object.assign(t,{args:i},t.opts)}({logLevel:e,message:n,args:this._buildArgs(e,n,i),opts:s});return this._createLogFunction(t,r,s)}_buildArgs(t,e,n){return[t,e,...n]}_createLogFunction(t,e,n){if(!this._shouldLog(e.logLevel))return C;const i=this._getOnceTag(n.tag??e.tag??e.message);if((n.once||e.once)&&void 0!==i){if(this._onceCache.has(i))return C;this._onceCache.add(i)}return this._emit(t,e)}_shouldLog(t){return this.getLevel()>=S(t)}_getOnceTag(t){if(void 0!==t)try{return"string"==typeof t?t:String(t)}catch{return}}}class M{constructor(t,e,n="sessionStorage"){this.storage=function(t){try{const e=window[t],n="__storage_test__";return e.setItem(n,n),e.removeItem(n),e}catch(t){return null}}(n),this.id=t,this.config=e,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(t){if(Object.assign(this.config,t),this.storage){const t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let t={};if(this.storage){const e=this.storage.getItem(this.id);t=e?JSON.parse(e):{}}return Object.assign(this.config,t),this}}var R;function L(t){return"string"!=typeof t?t:(t=t.toUpperCase(),R[t]||R.WHITE)}function O(){let t;if(E()&&b.performance)t=b?.performance?.now?.();else if("hrtime"in y){const e=y?.hrtime?.();t=1e3*e[0]+e[1]/1e6}else t=Date.now();return t}!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"}(R||(R={}));const I={debug:E()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},k={enabled:!0,level:0};class D extends P{constructor({id:t}={id:""}){super({level:0}),this.VERSION=T,this._startTs=O(),this._deltaTs=O(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=t,this.userData={},this._storage=new M(`__probe-${this.id}__`,{[this.id]:k}),this.timeStamp(`${this.id} started`),function(t,e=["constructor"]){const n=Object.getPrototypeOf(t),i=Object.getOwnPropertyNames(n),s=t;for(const n of i){const i=s[n];"function"==typeof i&&(e.find((t=>n===t))||(s[n]=i.bind(t)))}}(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((O()-this._startTs).toPrecision(10))}getDelta(){return Number((O()-this._deltaTs).toPrecision(10))}set priority(t){this.level=t}get priority(){return this.level}getPriority(){return this.level}enable(t=!0){return this._updateConfiguration({enabled:t}),this}setLevel(t){return this._updateConfiguration({level:t}),this}get(t){return this._getConfiguration()[t]}set(t,e){this._updateConfiguration({[t]:e})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(t,e){if(!t)throw new Error(e||"Assertion failed")}warn(t,...e){return this._log("warn",0,t,e,{method:I.warn,once:!0})}error(t,...e){return this._log("error",0,t,e,{method:I.error})}deprecated(t,e){return this.warn(`\`${t}\` is deprecated and will be removed in a later version. Use \`${e}\` instead`)}removed(t,e){return this.error(`\`${t}\` has been removed. Use \`${e}\` instead`)}probe(t,e,...n){return this._log("log",t,e,n,{method:I.log,time:!0,once:!0})}log(t,e,...n){return this._log("log",t,e,n,{method:I.debug})}info(t,e,...n){return this._log("info",t,e,n,{method:console.info})}once(t,e,...n){return this._log("once",t,e,n,{method:I.debug||I.info,once:!0})}table(t,e,n){return e?this._log("table",t,e,n&&[n]||[],{method:console.table||C,tag:N(e)}):C}time(t,e){return this._log("time",t,e,[],{method:console.time?console.time:console.info})}timeEnd(t,e){return this._log("time",t,e,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(t,e){return this._log("time",t,e,[],{method:console.timeStamp||C})}group(t,e,n={collapsed:!1}){const i=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",t,e,[],{method:i})}groupCollapsed(t,e,n={}){return this.group(t,e,Object.assign({},n,{collapsed:!0}))}groupEnd(t){return this._log("groupEnd",t,"",[],{method:console.groupEnd||C})}withGroup(t,e,n){this.group(t,e)();try{n()}finally{this.groupEnd(t)()}}trace(){console.trace&&console.trace()}_shouldLog(t){return this.isEnabled()&&super._shouldLog(t)}_emit(t,e){const n=e.method;A(n),e.total=this.getTotal(),e.delta=this.getDelta(),this._deltaTs=O();const i=function(t,e,n){if("string"==typeof e){const i=n.time?function(t,e=8){const n=Math.max(e-t.length,0);return`${" ".repeat(n)}${t}`}(function(t){let e;return e=t<10?`${t.toFixed(2)}ms`:t<100?`${t.toFixed(1)}ms`:t<1e3?`${t.toFixed(0)}ms`:`${(t/1e3).toFixed(2)}s`,e}(n.total)):"";e=function(t,e,n){return E||"string"!=typeof t||(e&&(t=`[${L(e)}m${t}[39m`),n&&(t=`[${L(n)+10}m${t}[49m`)),t}(e=n.time?`${t}: ${i} ${e}`:`${t}: ${e}`,n.color,n.background)}return e}(this.id,e.message,e);return n.bind(console,i,...e.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(k),this._storage.config[this.id]}_updateConfiguration(t){const e=this._storage.config[this.id]||{...k};this._storage.setConfiguration({[this.id]:{...e,...t}})}}function N(t){for(const e in t)for(const n in t[e])return n||"untitled";return"empty"}D.VERSION=T;const F=new D({id:"deck"});let B={};function $(t){B=t}function U(t,e,n,i){F.level>0&&B[t]&&B[t].call(null,e,n,i)}var z={dataType:null,batchType:null,id:"JSON",name:"JSON",module:"",version:"",options:{},extensions:["json","geojson"],mimeTypes:["application/json","application/geo+json"],testText:function(t){const e=t[0],n=t[t.length-1];return"{"===e&&"}"===n||"["===e&&"]"===n},parseTextSync:JSON.parse};const j=function(){const t="9.2.11",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:$},h([z,[f,{imagebitmap:{premultiplyAlpha:"none"}}]])),t}();function G(t,e){if(!t)throw new Error(e||"shadertools: assertion failed.")}const W={number:{type:"number",validate:(t,e)=>Number.isFinite(t)&&"object"==typeof e&&(void 0===e.max||t<=e.max)&&(void 0===e.min||t>=e.min)},array:{type:"array",validate:t=>Array.isArray(t)||ArrayBuffer.isView(t)}};function V(t){let e=H(t);if("object"!==e)return{value:t,...W[e],type:e};if("object"==typeof t)return t?void 0!==t.type?{...t,...W[t.type],type:t.type}:void 0===t.value?{type:"object",value:t}:(e=H(t.value),{...t,...W[e],type:e}):{type:"object",value:null};throw new Error("props")}function H(t){return Array.isArray(t)||ArrayBuffer.isView(t)?"array":typeof t}const X={vertex:"#ifdef MODULE_LOGDEPTH\n logdepth_adjustPosition(gl_Position);\n#endif\n",fragment:"#ifdef MODULE_MATERIAL\n fragColor = material_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_LIGHTING\n fragColor = lighting_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_FOG\n fragColor = fog_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_PICKING\n fragColor = picking_filterHighlightColor(fragColor);\n fragColor = picking_filterPickingColor(fragColor);\n#endif\n\n#ifdef MODULE_LOGDEPTH\n logdepth_setFragDepth();\n#endif\n"},Z=/void\s+main\s*\([^)]*\)\s*\{\n?/,K=/}\n?[^{}]*$/,q=[],Y="__LUMA_INJECT_DECLARATIONS__";function J(t){const e={vertex:{},fragment:{}};for(const n in t){let i=t[n];"string"==typeof i&&(i={order:0,injection:i}),e[Q(n)][n]=i}return e}function Q(t){const e=t.slice(0,2);switch(e){case"vs":return"vertex";case"fs":return"fragment";default:throw new Error(e)}}function tt(t,e,n,i=!1){const s="vertex"===e;for(const e in n){const i=n[e];i.sort(((t,e)=>t.order-e.order)),q.length=i.length;for(let t=0,e=i.length;t<e;++t)q[t]=i[t].injection;const r=`${q.join("\n")}\n`;switch(e){case"vs:#decl":s&&(t=t.replace(Y,r));break;case"vs:#main-start":s&&(t=t.replace(Z,(t=>t+r)));break;case"vs:#main-end":s&&(t=t.replace(K,(t=>r+t)));break;case"fs:#decl":s||(t=t.replace(Y,r));break;case"fs:#main-start":s||(t=t.replace(Z,(t=>t+r)));break;case"fs:#main-end":s||(t=t.replace(K,(t=>r+t)));break;default:t=t.replace(e,(t=>t+r))}}return t=t.replace(Y,""),i&&(t=t.replace(/\}\s*$/,(t=>t+X[e]))),t}function et(t){t.map((t=>nt(t)))}function nt(t){if(t.instance)return;et(t.dependencies||[]);const{propTypes:e={},deprecations:n=[],inject:i={}}=t,s={normalizedInjections:J(i),parsedDeprecations:st(n)};e&&(s.propValidators=function(t){const e={};for(const[n,i]of Object.entries(t))e[n]=V(i);return e}(e)),t.instance=s;let r={};e&&(r=Object.entries(e).reduce(((t,[e,n])=>{const i=n?.value;return i&&(t[e]=i),t}),{})),t.defaultUniforms={...t.defaultUniforms,...r}}function it(t,e,n){t.deprecations?.forEach((t=>{t.regex?.test(e)&&(t.deprecated?n.deprecated(t.old,t.new)():n.removed(t.old,t.new)())}))}function st(t){return t.forEach((t=>{t.regex="function"===t.type?new RegExp(`\\b${t.old}\\(`):new RegExp(`${t.type} ${t.old};`)})),t}function rt(t){et(t);const e={},n={};ot({modules:t,level:0,moduleMap:e,moduleDepth:n});const i=Object.keys(n).sort(((t,e)=>n[e]-n[t])).map((t=>e[t]));return et(i),i}function ot(t){const{modules:e,level:n,moduleMap:i,moduleDepth:s}=t;if(n>=5)throw new Error("Possible loop in shader dependency graph");for(const t of e)i[t.name]=t,(void 0===s[t.name]||s[t.name]<n)&&(s[t.name]=n);for(const t of e)t.dependencies&&ot({modules:t.dependencies,level:n+1,moduleMap:i,moduleDepth:s})}const at=[[/^(#version[ \t]+(100|300[ \t]+es))?[ \t]*\n/,"#version 300 es\n"],[/\btexture(2D|2DProj|Cube)Lod(EXT)?\(/g,"textureLod("],[/\btexture(2D|2DProj|Cube)(EXT)?\(/g,"texture("]],ct=[...at,[ut("attribute"),"in $1"],[ut("varying"),"out $1"]],lt=[...at,[ut("varying"),"in $1"]];function ht(t,e){for(const[n,i]of e)t=t.replace(n,i);return t}function ut(t){return new RegExp(`\\b${t}[ \\t]+(\\w+[ \\t]+\\w+(\\[\\w+\\])?;)`,"g")}function ft(t,e){let n="";for(const i in t){const s=t[i];if(n+=`void ${s.signature} {\n`,s.header&&(n+=` ${s.header}`),e[i]){const t=e[i];t.sort(((t,e)=>t.order-e.order));for(const e of t)n+=` ${e.injection}\n`}s.footer&&(n+=` ${s.footer}`),n+="}\n"}return n}function dt(t){const e={vertex:{},fragment:{}};for(const n of t){let t,i;"string"!=typeof n?(t=n,i=t.hook):(t={},i=n),i=i.trim();const[s,r]=i.split(":"),o=i.replace(/\(.+/,""),a=Object.assign(t,{signature:r});switch(s){case"vs":e.vertex[o]=a;break;case"fs":e.fragment[o]=a;break;default:throw new Error(s)}}return e}function pt(t,e="unnamed"){const n=/#define[^\S\r\n]*SHADER_NAME[^\S\r\n]*([A-Za-z0-9_-]+)\s*/.exec(t);return n?n[1]:e}function gt(t){let e=100;const n=t.match(/[^\s]+/g);if(n&&n.length>=2&&"#version"===n[0]){const t=parseInt(n[1],10);Number.isFinite(t)&&(e=t)}if(100!==e&&300!==e)throw new Error(`Invalid GLSL version ${e}`);return e}const mt=`\n\n${Y}\n`;function _t(t,e){const{source:n,stage:i,modules:s,hookFunctions:r=[],inject:o={},log:a}=e;G("string"==typeof n,"shader source must be a string");const c=n;let l="";const h=dt(r),u={},f={},d={};for(const t in o){const e="string"==typeof o[t]?{injection:o[t],order:0}:o[t],n=/^(v|f)s:(#)?([\w-]+)$/.exec(t);n?n[2]?"decl"===n[3]?f[t]=[e]:d[t]=[e]:u[t]=[e]:d[t]=[e]}const p=s;for(const t of p){a&&it(t,c,a),l+=yt(t,"wgsl");const e=t.injections?.[i]||{};for(const t in e){const n=/^(v|f)s:#([\w-]+)$/.exec(t);if(n){const i="decl"===n[2]?f:d;i[t]=i[t]||[],i[t].push(e[t])}else u[t]=u[t]||[],u[t].push(e[t])}}return l+=mt,l=tt(l,i,f),l+=ft(h[i],u),l+=c,l=tt(l,i,d),l}function vt(t,e){const{source:n,stage:i,language:s="glsl",modules:r,defines:o={},hookFunctions:a=[],inject:c={},prologue:l=!0,log:h}=e;G("string"==typeof n,"shader source must be a string");const u="glsl"===s?function(t){return{name:pt(t,void 0),language:"glsl",version:gt(t)}}(n).version:-1,f=t.shaderLanguageVersion,d=100===u?"#version 100":"#version 300 es",p=n.split("\n").slice(1).join("\n"),g={};r.forEach((t=>{Object.assign(g,t.defines)})),Object.assign(g,o);let m="";switch(s){case"wgsl":break;case"glsl":m=l?`${d}\n\n// ----- PROLOGUE -------------------------\n#define SHADER_TYPE_${i.toUpperCase()}\n\n${function(t){switch(t?.gpu.toLowerCase()){case"apple":return"#define APPLE_GPU\n// Apple optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n";case"nvidia":return"#define NVIDIA_GPU\n// Nvidia optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n";case"intel":return"#define INTEL_GPU\n// Intel optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n// Intel's built-in 'tan' function doesn't have acceptable precision\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n";case"amd":return"#define AMD_GPU\n";default:return"#define DEFAULT_GPU\n// Prevent driver from optimizing away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n// Headless Chrome's software shader 'tan' function doesn't have acceptable precision\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// If the GPU doesn't have full 32 bits precision, will causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n"}}(t)}\n${"fragment"===i?"precision highp float;\n":""}\n\n// ----- APPLICATION DEFINES -------------------------\n\n${function(t={}){let e="";for(const n in t){const i=t[n];(i||Number.isFinite(i))&&(e+=`#define ${n.toUpperCase()} ${t[n]}\n`)}return e}(g)}\n\n`:`${d}\n`}const _=dt(a),v={},b={},y={};for(const t in c){const e="string"==typeof c[t]?{injection:c[t],order:0}:c[t],n=/^(v|f)s:(#)?([\w-]+)$/.exec(t);n?n[2]?"decl"===n[3]?b[t]=[e]:y[t]=[e]:v[t]=[e]:y[t]=[e]}for(const t of r){h&&it(t,p,h),m+=yt(t,i);const e=t.instance?.normalizedInjections[i]||{};for(const t in e){const n=/^(v|f)s:#([\w-]+)$/.exec(t);if(n){const i="decl"===n[2]?b:y;i[t]=i[t]||[],i[t].push(e[t])}else v[t]=v[t]||[],v[t].push(e[t])}}return m+="// ----- MAIN SHADER SOURCE -------------------------",m+=mt,m=tt(m,i,b),m+=ft(_[i],v),m+=p,m=tt(m,i,y),"glsl"===s&&u!==f&&(m=function(t,e){if(300!==Number(t.match(/^#version[ \t]+(\d+)/m)?.[1]||100))throw new Error("luma.gl v9 only supports GLSL 3.00 shader sources");switch(e){case"vertex":return ht(t,ct);case"fragment":return ht(t,lt);default:throw new Error(e)}}(m,i)),m.trim()}function bt(t){return function(e){const n={};for(const i of t){const t=i.getUniforms?.(e,n);Object.assign(n,t)}return n}}function yt(t,e){let n;switch(e){case"vertex":n=t.vs||"";break;case"fragment":n=t.fs||"";break;case"wgsl":n=t.source||"";break;default:G(!1)}if(!t.name)throw new Error("Shader module must have a name");const i=t.name.toUpperCase().replace(/[^0-9a-z]/gi,"_");let s=`// ----- MODULE ${t.name} ---------------\n\n`;return"wgsl"!==e&&(s+=`#define MODULE_${i}\n`),s+=`${n}\n`,s}const wt=/^\s*\#\s*ifdef\s*([a-zA-Z_]+)\s*$/,xt=/^\s*\#\s*endif\s*$/;class Et{static defaultShaderAssembler;_hookFunctions=[];_defaultModules=[];static getDefaultShaderAssembler(){return Et.defaultShaderAssembler=Et.defaultShaderAssembler||new Et,Et.defaultShaderAssembler}addDefaultModule(t){this._defaultModules.find((e=>e.name===("string"==typeof t?t:t.name)))||this._defaultModules.push(t)}removeDefaultModule(t){const e="string"==typeof t?t:t.name;this._defaultModules=this._defaultModules.filter((t=>t.name!==e))}addShaderHook(t,e){e&&(t=Object.assign(e,{hook:t})),this._hookFunctions.push(t)}assembleWGSLShader(t){const e=this._getModuleList(t.modules),n=this._hookFunctions,{source:i,getUniforms:s}=function(t){const e=rt(t.modules||[]);return{source:_t(0,{...t,source:t.source,stage:"vertex",modules:e}),getUniforms:bt(e)}}({...t,source:t.source,modules:e,hookFunctions:n}),r="wgsl"===t.platformInfo.shaderLanguage?function(t){const e=t.split("\n"),n=[];let i=!0,s=null;for(const t of e){const e=t.match(wt),r=t.match(xt);e?(s=e[1],i=Boolean(undefined)):r?i=!0:i&&n.push(t)}return n.join("\n")}(i):i;return{source:r,getUniforms:s,modules:e}}assembleGLSLShaderPair(t){const e=this._getModuleList(t.modules),n=this._hookFunctions,i=function(t){const{vs:e,fs:n}=t,i=rt(t.modules||[]);return{vs:vt(t.platformInfo,{...t,source:e,stage:"vertex",modules:i}),fs:vt(t.platformInfo,{...t,source:n,stage:"fragment",modules:i}),getUniforms:bt(i)}}({...t,vs:t.vs,fs:t.fs,modules:e,hookFunctions:n});return{...i,modules:e}}_getModuleList(t=[]){const e=new Array(this._defaultModules.length+t.length),n={};let i=0;for(let t=0,s=this._defaultModules.length;t<s;++t){const s=this._defaultModules[t],r=s.name;e[i++]=s,n[r]=!0}for(let s=0,r=t.length;s<r;++s){const r=t[s],o=r.name;n[o]||(e[i++]=r,n[o]=!0)}return e.length=i,et(e),e}}function Tt(){const{input:t,inputChannels:e,output:n}={};if(!t)return"#version 300 es\nout vec4 transform_output;\nvoid main() {\n transform_output = vec4(0);\n}";if(!e)throw new Error("inputChannels");return`#version 300 es\nin ${function(t){switch(t){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`invalid channels: ${t}`)}}(e)} ${t};\nout vec4 ${n};\nvoid main() {\n ${n} = ${function(t,e){switch(e){case 1:return`vec4(${t}, 0.0, 0.0, 1.0)`;case 2:return`vec4(${t}, 0.0, 1.0)`;case 3:return`vec4(${t}, 1.0)`;case 4:return t;default:throw new Error(`invalid channels: ${e}`)}}(t,e)};\n}`}function At(){let t;if("undefined"!=typeof window&&window.performance)t=window.performance.now();else if("undefined"!=typeof process&&process.hrtime){const e=process.hrtime();t=1e3*e[0]+e[1]/1e6}else t=Date.now();return t}class St{constructor(t,e){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=t,this.type=e,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(t){return this.sampleSize=t,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(t){return this._count+=t,this._samples++,this._checkSampling(),this}subtractCount(t){return this._count-=t,this._samples++,this._checkSampling(),this}addTime(t){return this._time+=t,this.lastTiming=t,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=At(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(At()-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)}}class Ct{constructor(t){this.stats={},this.id=t.id,this.stats={},this._initializeStats(t.stats),Object.seal(this)}get(t,e="count"){return this._getOrCreate({name:t,type:e})}get size(){return Object.keys(this.stats).length}reset(){for(const t of Object.values(this.stats))t.reset();return this}forEach(t){for(const e of Object.values(this.stats))t(e)}getTable(){const t={};return this.forEach((e=>{t[e.name]={time:e.time||0,count:e.count||0,average:e.getAverageTime()||0,hz:e.getHz()||0}})),t}_initializeStats(t=[]){t.forEach((t=>this._getOrCreate(t)))}_getOrCreate(t){const{name:e,type:n}=t;let i=this.stats[e];return i||(i=t instanceof St?t:new St(e,n),this.stats[e]=i),i}}const Pt=new class{stats=new Map;getStats(t){return this.get(t)}get(t){return this.stats.has(t)||this.stats.set(t,new Ct({id:t})),this.stats.get(t)}},Mt=new D({id:"luma.gl"}),Rt={};function Lt(t="id"){return Rt[t]=Rt[t]||1,`${t}-${Rt[t]++}`}let Ot=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;_attachedResources=new Set;constructor(t,e,n){if(!t)throw new Error("no device");this._device=t,this.props=function(t,e){const n={...e};for(const e in t)void 0!==t[e]&&(n[e]=t[e]);return n}(e,n);const i="undefined"!==this.props.id?this.props.id:Lt(this[Symbol.toStringTag]);this.props.id=i,this.id=i,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(t){this._attachedResources.add(t)}detachResource(t){this._attachedResources.delete(t)}destroyAttachedResource(t){this._attachedResources.delete(t)&&t.destroy()}destroyAttachedResources(){for(const t of Object.values(this._attachedResources))t.destroy();this._attachedResources=new Set}destroyResource(){this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0}removeStats(){const t=this._device.statsManager.getStats("Resource Counts"),e=this[Symbol.toStringTag];t.get(`${e}s Active`).decrementCount()}trackAllocatedMemory(t,e=this[Symbol.toStringTag]){const n=this._device.statsManager.getStats("Resource Counts");n.get("GPU Memory").addCount(t),n.get(`${e} Memory`).addCount(t),this.allocatedBytes=t}trackDeallocatedMemory(t=this[Symbol.toStringTag]){const e=this._device.statsManager.getStats("Resource Counts");e.get("GPU Memory").subtractCount(this.allocatedBytes),e.get(`${t} Memory`).subtractCount(this.allocatedBytes),this.allocatedBytes=0}addStats(){const t=this._device.statsManager.getStats("Resource Counts"),e=this[Symbol.toStringTag];t.get("Resources Created").incrementCount(),t.get(`${e}s Created`).incrementCount(),t.get(`${e}s Active`).incrementCount()}};class It extends Ot{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(t,e){const n={...e};(e.usage||0)&It.INDEX&&!e.indexType&&(e.data instanceof Uint32Array?n.indexType="uint32":e.data instanceof Uint16Array?n.indexType="uint16":e.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(t,n,It.defaultProps),this.usage=n.usage||0,this.indexType=n.indexType,this.updateTimestamp=t.incrementTimestamp()}clone(t){return this.device.createBuffer({...this.props,...t})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(t,e,n){const i=ArrayBuffer.isView(t)?t.buffer:t,s=Math.min(t?t.byteLength:n,It.DEBUG_DATA_MAX_LENGTH);this.debugData=null===i?new ArrayBuffer(s):0===e&&n===i.byteLength?i.slice(0,s):i.slice(e,e+s)}static defaultProps={...Ot.defaultProps,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}function kt(t){const[e,n,i]=Bt[t],s=t.includes("norm");return{signedType:e,primitiveType:n,byteLength:i,normalized:s,integer:!s&&!t.startsWith("float"),signed:t.startsWith("s")}}function Dt(t,e){switch(e){case 1:return t;case 2:return t+t%2;default:return t+(4-t%4)%4}}function Nt(t){const e=ArrayBuffer.isView(t)?t.constructor:t;if(e===Uint8ClampedArray)return"uint8";const n=Object.values(Bt).find((t=>e===t[4]));if(!n)throw new Error(e.name);return n[0]}function Ft(t){const[,,,,e]=Bt[t];return e}const Bt={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 $t(t){let e;t.endsWith("-webgl")&&(t.replace("-webgl",""),e=!0);const[n,i]=t.split("x"),s=n,r=i?parseInt(i):1,o=kt(s),a={type:s,components:r,byteLength:o.byteLength*r,integer:o.integer,signed:o.signed,normalized:o.normalized};return e&&(a.webglOnly=!0),a}function Ut(t,e,n){if(!e||e>4)throw new Error(`size ${e}`);const i=e;return function(t,e,n){const i=n?function(t){const e=t;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}(t):t;switch(i){case"unorm8":return 1===e?"unorm8":3===e?"unorm8x3-webgl":`${i}x${e}`;case"snorm8":case"uint8":case"sint8":case"uint16":case"sint16":case"unorm16":case"snorm16":case"float16":if(1===e||3===e)throw new Error(`size: ${e}`);return`${i}x${e}`;default:return 1===e?i:`${i}x${e}`}}(Nt(t),i,n)}const zt="texture-compression-bc",jt="texture-compression-astc",Gt="texture-compression-etc2",Wt="texture-compression-pvrtc-webgl",Vt="texture-compression-atc-webgl",Ht="float32-renderable-webgl",Xt="float16-renderable-webgl",Zt="snorm8-renderable-webgl",Kt="norm16-renderable-webgl",qt="snorm16-renderable-webgl",Yt="float32-filterable",Jt="float16-filterable-webgl";function Qt(t){const e=te[t];if(!e)throw new Error(`Unsupported texture format ${t}`);return e}const te={r8unorm:{},rg8unorm:{},"rgb8unorm-webgl":{},rgba8unorm:{},"rgba8unorm-srgb":{},r8snorm:{render:Zt},rg8snorm:{render:Zt},"rgb8snorm-webgl":{},rgba8snorm:{render:Zt},r8uint:{},rg8uint:{},rgba8uint:{},r8sint:{},rg8sint:{},rgba8sint:{},bgra8unorm:{},"bgra8unorm-srgb":{},r16unorm:{f:Kt},rg16unorm:{render:Kt},"rgb16unorm-webgl":{f:Kt},rgba16unorm:{render:Kt},r16snorm:{f:qt},rg16snorm:{render:qt},"rgb16snorm-webgl":{f:Kt},rgba16snorm:{render:qt},r16uint:{},rg16uint:{},rgba16uint:{},r16sint:{},rg16sint:{},rgba16sint:{},r16float:{render:Xt,filter:"float16-filterable-webgl"},rg16float:{render:Xt,filter:Jt},rgba16float:{render:Xt,filter:Jt},r32uint:{},rg32uint:{},rgba32uint:{},r32sint:{},rg32sint:{},rgba32sint:{},r32float:{render:Ht,filter:Yt},rg32float:{render:!1,filter:Yt},"rgb32float-webgl":{render:Ht,filter:Yt},rgba32float:{render:Ht,filter:Yt},"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:"rgb9e5ufloat-renderable-webgl"},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Ht},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},"bc1-rgb-unorm-webgl":{f:zt},"bc1-rgb-unorm-srgb-webgl":{f:zt},"bc1-rgba-unorm":{f:zt},"bc1-rgba-unorm-srgb":{f:zt},"bc2-rgba-unorm":{f:zt},"bc2-rgba-unorm-srgb":{f:zt},"bc3-rgba-unorm":{f:zt},"bc3-rgba-unorm-srgb":{f:zt},"bc4-r-unorm":{f:zt},"bc4-r-snorm":{f:zt},"bc5-rg-unorm":{f:zt},"bc5-rg-snorm":{f:zt},"bc6h-rgb-ufloat":{f:zt},"bc6h-rgb-float":{f:zt},"bc7-rgba-unorm":{f:zt},"bc7-rgba-unorm-srgb":{f:zt},"etc2-rgb8unorm":{f:Gt},"etc2-rgb8unorm-srgb":{f:Gt},"etc2-rgb8a1unorm":{f:Gt},"etc2-rgb8a1unorm-srgb":{f:Gt},"etc2-rgba8unorm":{f:Gt},"etc2-rgba8unorm-srgb":{f:Gt},"eac-r11unorm":{f:Gt},"eac-r11snorm":{f:Gt},"eac-rg11unorm":{f:Gt},"eac-rg11snorm":{f:Gt},"astc-4x4-unorm":{f:jt},"astc-4x4-unorm-srgb":{f:jt},"astc-5x4-unorm":{f:jt},"astc-5x4-unorm-srgb":{f:jt},"astc-5x5-unorm":{f:jt},"astc-5x5-unorm-srgb":{f:jt},"astc-6x5-unorm":{f:jt},"astc-6x5-unorm-srgb":{f:jt},"astc-6x6-unorm":{f:jt},"astc-6x6-unorm-srgb":{f:jt},"astc-8x5-unorm":{f:jt},"astc-8x5-unorm-srgb":{f:jt},"astc-8x6-unorm":{f:jt},"astc-8x6-unorm-srgb":{f:jt},"astc-8x8-unorm":{f:jt},"astc-8x8-unorm-srgb":{f:jt},"astc-10x5-unorm":{f:jt},"astc-10x5-unorm-srgb":{f:jt},"astc-10x6-unorm":{f:jt},"astc-10x6-unorm-srgb":{f:jt},"astc-10x8-unorm":{f:jt},"astc-10x8-unorm-srgb":{f:jt},"astc-10x10-unorm":{f:jt},"astc-10x10-unorm-srgb":{f:jt},"astc-12x10-unorm":{f:jt},"astc-12x10-unorm-srgb":{f:jt},"astc-12x12-unorm":{f:jt},"astc-12x12-unorm-srgb":{f:jt},"pvrtc-rgb4unorm-webgl":{f:Wt},"pvrtc-rgba4unorm-webgl":{f:Wt},"pvrtc-rbg2unorm-webgl":{f:Wt},"pvrtc-rgba2unorm-webgl":{f:Wt},"etc1-rbg-unorm-webgl":{f:"texture-compression-etc1-webgl"},"atc-rgb-unorm-webgl":{f:Vt},"atc-rgba-unorm-webgl":{f:Vt},"atc-rgbai-unorm-webgl":{f:Vt}},ee=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],ne=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,ie=new class{getInfo(t){return se(t)}isColor(t){return t.startsWith("rgba")||t.startsWith("bgra")||t.startsWith("rgb")}isDepthStencil(t){return t.startsWith("depth")||t.startsWith("stencil")}isCompressed(t){return ee.some((e=>t.startsWith(e)))}getCapabilities(t){const e=Qt(t),n={format:t,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},i=se(t),s=t.startsWith("depth")||t.startsWith("stencil"),r=i?.signed,o=i?.integer,a=i?.webgl;return n.render&&=!r,n.filter&&=!(s||r||o||a),n}};function se(t){let e=function(t){const e=Qt(t),n=e.bytesPerPixel||1,i=e.bitsPerChannel||[8,8,8,8];delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store;return{...e,format:t,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:n,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}}(t);if(ie.isCompressed(t)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0;const n=function(t){const e=/.*-(\d+)x(\d+)-.*/.exec(t);if(e){const[,t,n]=e;return{blockWidth:Number(t),blockHeight:Number(n)}}return null}(t);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}const n=ne.exec(t);if(n){const[,i,s,r,o,a]=n,c=kt(`${r}${s}`),l=8*c.byteLength,h=i.length;e={format:t,attachment:e.attachment,dataType:c.signedType,components:h,channels:i,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:[l,h>=2?l:0,h>=3?l:0,h>=4?l:0],bytesPerPixel:c.byteLength*i.length,packed:e.packed,srgb:e.srgb},"-webgl"===a&&(e.webgl=!0),"-srgb"===o&&(e.srgb=!0)}return t.endsWith("-webgl")&&(e.webgl=!0),t.endsWith("-srgb")&&(e.srgb=!0),e}class re{}class oe{features;disabledFeatures;constructor(t=[],e){this.features=new Set(t),this.disabledFeatures=e||{}}*[Symbol.iterator](){yield*this.features}has(t){return!this.disabledFeatures?.[t]&&this.features.has(t)}}class ae{static defaultProps={id:null,powerPreference:"high-performance",failIfMajorPerformanceCaveat:!1,createCanvasContext:void 0,webgl:{},onError:()=>{},onResize:t=>{const[e,n]=t.getDevicePixelSize();Mt.log(1,`${t} resized => ${e}x${n}px`)()},onPositionChange:t=>{const[e,n]=t.getPosition();Mt.log(1,`${t} repositioned => ${e},${n}`)()},onVisibilityChange:t=>Mt.log(1,`${t} Visibility changed ${t.isVisible}`)(),onDevicePixelRatioChange:(t,e)=>Mt.log(1,`${t} DPR changed ${e.oldRatio} => ${t.devicePixelRatio}`)(),debug:Mt.get("debug")||void 0,debugShaders:Mt.get("debug-shaders")||void 0,debugFramebuffers:Boolean(Mt.get("debug-framebuffers")),debugFactories:Boolean(Mt.get("debug-factories")),debugWebGL:Boolean(Mt.get("debug-webgl")),debugSpectorJS:void 0,debugSpectorJSUrl:void 0,_reuseDevices:!1,_requestMaxLimits:!0,_cacheShaders:!1,_cachePipelines:!1,_cacheDestroyPolicy:"unused",_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=Pt;timestamp=0;_reused=!1;_lumaData={};_textureCaps={};constructor(t){this.props={...ae.defaultProps,...t},this.id=this.props.id||Lt(this[Symbol.toStringTag].toLowerCase())}getVertexFormatInfo(t){return $t(t)}isVertexFormatSupported(t){return!0}getTextureFormatInfo(t){return ie.getInfo(t)}getTextureFormatCapabilities(t){let e=this._textureCaps[t];if(!e){const n=this._getDeviceTextureFormatCapabilities(t);e=this._getDeviceSpecificTextureFormatCapabilities(n),this._textureCaps[t]=e}return e}getMipLevelCount(t,e,n=1){const i=Math.max(t,e,n);return 1+Math.floor(Math.log2(i))}isExternalImage(t){return function(t){return"undefined"!=typeof ImageData&&t instanceof ImageData||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof VideoFrame&&t instanceof VideoFrame||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}getExternalImageSize(t){return function(t){if("undefined"!=typeof ImageData&&t instanceof ImageData||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas)return{width:t.width,height:t.height};if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)return{width:t.naturalWidth,height:t.naturalHeight};if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)return{width:t.videoWidth,height:t.videoHeight};if("undefined"!=typeof VideoFrame&&t instanceof VideoFrame)return{width:t.displayWidth,height:t.displayHeight};throw new Error("Unknown image type")}(t)}isTextureFormatSupported(t){return this.getTextureFormatCapabilities(t).create}isTextureFormatFilterable(t){return this.getTextureFormatCapabilities(t).filter}isTextureFormatRenderable(t){return this.getTextureFormatCapabilities(t).render}isTextureFormatCompressed(t){return ie.isCompressed(t)}pushDebugGroup(t){this.commandEncoder.pushDebugGroup(t)}popDebugGroup(){this.commandEncoder?.popDebugGroup()}insertDebugMarker(t){this.commandEncoder?.insertDebugMarker(t)}loseDevice(){return!1}incrementTimestamp(){return this.timestamp++}reportError(t,e,...n){return this.props.onError(t,e)?()=>{}:Mt.error(t.message,e,...n)}debug(){this.props.debug||Mt.once(0,"'Type luma.log.set({debug: true}) in console to enable debug breakpoints',\nor 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}beginRenderPass(t){return this.commandEncoder.beginRenderPass(t)}beginComputePass(t){return this.commandEncoder.beginComputePass(t)}getCanvasContext(){return this.getDefaultCanvasContext()}readPixelsToArrayWebGL(t,e){throw new Error("not implemented")}readPixelsToBufferWebGL(t,e){throw new Error("not implemented")}setParametersWebGL(t){throw new Error("not implemented")}getParametersWebGL(t){throw new Error("not implemented")}withParametersWebGL(t,e){throw new Error("not implemented")}clearWebGL(t){throw new Error("not implemented")}resetWebGL(){throw new Error("not implemented")}static _getCanvasContextProps(t){return!0===t.createCanvasContext?{}:t.createCanvasContext}_getDeviceTextureFormatCapabilities(t){const e=ie.getCapabilities(t),n=t=>("string"==typeof t?this.features.has(t):t)??!0,i=n(e.create);return{format:t,create:i,render:i&&n(e.render),filter:i&&n(e.filter),blend:i&&n(e.blend),store:i&&n(e.store)}}_normalizeBufferProps(t){(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e={...t};if((t.usage||0)&It.INDEX&&(t.indexType||(t.data instanceof Uint32Array?e.indexType="uint32":t.data instanceof Uint16Array?e.indexType="uint16":t.data instanceof Uint8Array&&(e.data=new Uint16Array(t.data),e.indexType="uint16")),!e.indexType))throw new Error("indices buffer content must be of type uint16 or uint32");return e}}const ce="No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.";class le{static defaultProps={...ae.defaultProps,type:"best-available",adapters:void 0,waitForPageLoad:!0};stats=Pt;log=Mt;VERSION="9.2.6";spector;preregisteredAdapters=new Map;constructor(){if(globalThis.luma){if(globalThis.luma.VERSION!==this.VERSION)throw Mt.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)(),Mt.error("'yarn why @luma.gl/core' can help identify the source of the conflict")(),new Error("luma.gl - multiple versions detected: see console log");Mt.error("This version of luma.gl has already been initialized")()}Mt.log(1,`${this.VERSION} - set luma.log.level=1 (or higher) to trace rendering`)(),globalThis.luma=this}async createDevice(t={}){const e={...le.defaultProps,...t},n=this.selectAdapter(e.type,e.adapters);if(!n)throw new Error(ce);return e.waitForPageLoad&&await n.pageLoaded,await n.create(e)}async attachDevice(t,e){const n=this._getTypeFromHandle(t,e.adapters),i=n&&this.selectAdapter(n,e.adapters);if(!i)throw new Error(ce);return await(i?.attach?.(t,e))}registerAdapters(t){for(const e of t)this.preregisteredAdapters.set(e.type,e)}getSupportedAdapters(t=[]){const e=this._getAdapterMap(t);return Array.from(e).map((([,t])=>t)).filter((t=>t.isSupported?.())).map((t=>t.type))}getBestAvailableAdapterType(t=[]){const e=["webgpu","webgl","null"],n=this._getAdapterMap(t);for(const t of e)if(n.get(t)?.isSupported?.())return t;return null}selectAdapter(t,e=[]){let n=t;"best-available"===t&&(n=this.getBestAvailableAdapterType(e));const i=this._getAdapterMap(e);return n&&i.get(n)||null}enforceWebGL2(t=!0,e=[]){const n=this._getAdapterMap(e).get("webgl");n||Mt.warn("enforceWebGL2: webgl adapter not found")(),n?.enforceWebGL2?.(t)}setDefaultDeviceProps(t){Object.assign(le.defaultProps,t)}_getAdapterMap(t=[]){const e=new Map(this.preregisteredAdapters);for(const n of t)e.set(n.type,n);return e}_getTypeFromHandle(t,e=[]){return t instanceof WebGL2RenderingContext?"webgl":"undefined"!=typeof GPUDevice&&t instanceof GPUDevice||t?.queue?"webgpu":null===t?"null":(t instanceof WebGLRenderingContext?Mt.warn("WebGL1 is not supported",t)():Mt.warn("Unknown handle type",t)(),null)}}const he=new le;class ue{get pageLoaded(){return pe||(pe=de()||"undefined"==typeof window?Promise.resolve():new Promise((t=>window.addEventListener("load",(()=>t()))))),pe}}const fe=E()&&"undefined"!=typeof document,de=()=>fe&&"complete"===document.readyState;let pe=null;class ge{static isHTMLCanvas(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}static isOffscreenCanvas(t){return"undefined"!=typeof OffscreenCanvas&&t 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=function(){let t,e;return{promise:new Promise(((n,i)=>{t=n,e=i})),resolve:t,reject:e}}();_resizeObserver;_intersectionObserver;_position;destroyed=!1;toString(){return`${this[Symbol.toStringTag]}(${this.id})`}constructor(t){if(this.props={...ge.defaultProps,...t},t=this.props,this.initialized=this._initializedResolvers.promise,this.canvas=E()?t.canvas?"string"==typeof t.canvas?function(t){const e=document.getElementById(t);if(!ge.isHTMLCanvas(e))throw new Error("Object is not a canvas element");return e}(t.canvas):t.canvas:function(t){const{width:e,height:n}=t,i=document.createElement("canvas");i.id=Lt("lumagl-auto-created-canvas"),i.width=e||1,i.height=n||1,i.style.width=Number.isFinite(e)?`${e}px`:"100%",i.style.height=Number.isFinite(n)?`${n}px`:"100%",t?.visible||(i.style.visibility="hidden");const s=function(t){if("string"==typeof t){const e=document.getElementById(t);if(!e)throw new Error(`${t} is not an HTML element`);return e}return t||document.body}(t?.container||null);return s.insertBefore(i,s.firstChild),i}(t):{width:t.width||1,height:t.height||1},ge.isHTMLCanvas(this.canvas)?(this.id=t.id||this.canvas.id,this.type="html-canvas",this.htmlCanvas=this.canvas):ge.isOffscreenCanvas(this.canvas)?(this.id=t.id||"offscreen-canvas",this.type="offscreen-canvas",this.offscreenCanvas=this.canvas):(this.id=t.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],ge.isHTMLCanvas(this.canvas)){this._intersectionObserver=new IntersectionObserver((t=>this._handleIntersection(t))),this._intersectionObserver.observe(this.canvas),this._resizeObserver=new ResizeObserver((t=>this._handleResize(t)));try{this._resizeObserver.observe(this.canvas,{box:"device-pixel-content-box"})}catch{this._resizeObserver.observe(this.canvas,{box:"content-box"})}setTimeout((()=>this._observeDevicePixelRatio()),0),this.props.trackPosition&&this._trackPosition()}}destroy(){this.destroyed=!0}setProps(t){return"useDevicePixels"in t&&(this.props.useDevicePixels=t.useDevicePixels||!1,this._updateDrawingBufferSize()),this}getCSSSize(){return[this.cssWidth,this.cssHeight]}getPosition(){return this._position}getDevicePixelSize(){return[this.devicePixelWidth,this.devicePixelHeight]}getDrawingBufferSize(){return[this.drawingBufferWidth,this.drawingBufferHeight]}getMaxDrawingBufferSize(){const t=this.device.limits.maxTextureDimension2D;return[t,t]}setDrawingBufferSize(t,e){this.canvas.width=t,this.canvas.height=e,this.drawingBufferWidth=t,this.drawingBufferHeight=e}getDevicePixelRatio(){return"undefined"!=typeof window&&window.devicePixelRatio||1}cssToDevicePixels(t,e=!0){const n=this.cssToDeviceRatio(),[i,s]=this.getDrawingBufferSize();return function(t,e,n,i,s){const r=t,o=me(r[0],e,n);let a=_e(r[1],e,i,s),c=me(r[0]+1,e,n);const l=c===n-1?c:c-1;let h;return c=_e(r[1]+1,e,i,s),s?(c=0===c?c:c+1,h=a,a=c):h=c===i-1?c:c-1,{x:o,y:a,width:Math.max(l-o+1,1),height:Math.max(h-a+1,1)}}(t,n,i,s,e)}getPixelSize(){return this.getDevicePixelSize()}getAspect(){const[t,e]=this.getDevicePixelSize();return t/e}cssToDeviceRatio(){try{const[t]=this.getDrawingBufferSize(),[e]=this.getCSSSize();return e?t/e:1}catch{return 1}}resize(t){this.setDrawingBufferSize(t.width,t.height)}_setAutoCreatedCanvasId(t){"lumagl-auto-created-canvas"===this.htmlCanvas?.id&&(this.htmlCanvas.id=t)}_handleIntersection(t){const e=t.find((t=>t.target===this.canvas));if(!e)return;const n=e.isIntersecting;this.isVisible!==n&&(this.isVisible=n,this.device.props.onVisibilityChange(this))}_handleResize(t){const e=t.find((t=>t.target===this.canvas));if(!e)return;this.cssWidth=e.contentBoxSize[0].inlineSize,this.cssHeight=e.contentBoxSize[0].blockSize;const n=this.getDevicePixelSize(),i=e.devicePixelContentBoxSize?.[0].inlineSize||e.contentBoxSize[0].inlineSize*devicePixelRatio,s=e.devicePixelContentBoxSize?.[0].blockSize||e.contentBoxSize[0].blockSize*devicePixelRatio,[r,o]=this.getMaxDrawingBufferSize();this.devicePixelWidth=Math.max(1,Math.min(i,r)),this.devicePixelHeight=Math.max(1,Math.min(s,o)),this._updateDrawingBufferSize(),this.device.props.onResize(this,{oldPixelSize:n})}_updateDrawingBufferSize(){if(this.props.autoResize){if("number"==typeof this.props.useDevicePixels){const t=this.props.useDevicePixels;this.setDrawingBufferSize(this.cssWidth*t,this.cssHeight*t)}else this.props.useDevicePixels?this.setDrawingBufferSize(this.devicePixelWidth,this.devicePixelHeight):this.setDrawingBufferSize(this.cssWidth,this.cssHeight);this._updateDevice()}this._initializedResolvers.resolve(),this.isInitialized=!0,this.updatePosition()}_observeDevicePixelRatio(){const t=this.devicePixelRatio;this.devicePixelRatio=window.devicePixelRatio,this.updatePosition(),this.device.props.onDevicePixelRatioChange(this,{oldRatio:t}),matchMedia(`(resolution: ${this.devicePixelRatio}dppx)`).addEventListener("change",(()=>this._observeDevicePixelRatio()),{once:!0})}_trackPosition(t=100){const e=setInterval((()=>{this.destroyed?clearInterval(e):this.updatePosition()}),t)}updatePosition(){const t=this.htmlCanvas?.getBoundingClientRect();if(t){const e=[t.left,t.top];if(this._position??=e,e[0]!==this._position[0]||e[1]!==this._position[1]){const t=this._position;this._position=e,this.device.props.onPositionChange?.(this,{oldPosition:t})}}}}function me(t,e,n){return Math.min(Math.round(t*e),n-1)}function _e(t,e,n,i){return i?Math.max(0,n-1-Math.round(t*e)):Math.min(Math.round(t*e),n-1)}class ve extends Ot{static defaultProps={...Ot.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(t,e){super(t,e=ve.normalizeProps(t,e),ve.defaultProps)}static normalizeProps(t,e){return e}}const be={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"};class ye extends Ot{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;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(t,e){if(super(t,e=ye.normalizeProps(t,e),ye.defaultProps),this.dimension=this.props.dimension,this.baseDimension=be[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,void 0===this.props.width||void 0===this.props.height)if(t.isExternalImage(e.data)){const n=t.getExternalImageSize(e.data);this.width=n?.width||1,this.height=n?.height||1}else this.width=1,this.height=1,void 0!==this.props.width&&void 0!==this.props.height||Mt.warn(`${this} created with undefined width or height. This is deprecated. Use AsyncTexture instead.`)();this.updateTimestamp=t.incrementTimestamp()}setSampler(t){this.sampler=t instanceof ve?t:this.device.createSampler(t)}clone(t){return this.device.createTexture({...this.props,...t})}static normalizeProps(t,e){const n={...e},{width:i,height:s}=n;return"number"==typeof i&&(n.width=Math.max(1,Math.ceil(i))),"number"==typeof s&&(n.height=Math.max(1,Math.ceil(s))),n}_initializeData(t){this.device.isExternalImage(t)?this.copyExternalImage({image:t,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}):t&&this.copyImageData({data:t,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(t){const{width:e,height:n,depth:i}=this,s={...ye.defaultCopyDataOptions,width:e,height:n,depth:i,...t},r=this.device.getTextureFormatInfo(this.format);if(!t.bytesPerRow&&!r.bytesPerPixel)throw new Error(`bytesPerRow must be provided for texture format ${this.format}`);return s.bytesPerRow=t.bytesPerRow||e*(r.bytesPerPixel||4),s.rowsPerImage=t.rowsPerImage||n,s}_normalizeCopyExternalImageOptions(t){const e=this.device.getExternalImageSize(t.image),n={...ye.defaultCopyExternalImageOptions,...e,...t};return n.width=Math.min(n.width,this.width-n.x),n.height=Math.min(n.height,this.height-n.y),n}static defaultProps={...Ot.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:ye.TEXTURE|ye.RENDER_ATTACHMENT|ye.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,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}}class we extends Ot{get[Symbol.toStringTag](){return"TextureView"}constructor(t,e){super(t,e,we.defaultProps)}static defaultProps={...Ot.defaultProps,format:void 0,dimension:void 0,aspect:"all",baseMipLevel:0,mipLevelCount:void 0,baseArrayLayer:0,arrayLayerCount:void 0}}function xe(t,e,n,i){if(i?.inlineSource){const i=function(t,e){let n="";for(let i=e-2;i<=e;i++){const s=t[i-1];void 0!==s&&(n+=Ee(s,e,undefined))}return n}(e,n);return`\n${i}${t.linePos>0?`${" ".repeat(t.linePos+5)}^^^\n`:""}${t.type.toUpperCase()}: ${t.message}\n\n`}const s="error"===t.type?"red":"#8B4000";return i?.html?`<div class='luma-compiler-log-error' style="color:${s};"><b> ${t.type.toUpperCase()}: ${t.message}</b></div>`:`${t.type.toUpperCase()}: ${t.message}`}function Ee(t,e,n){const i=n?.html?t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'"):t;return`${function(t){let e="";for(let n=t.length;n<4;++n)e+=" ";return e+t}(String(e))}: ${i}${n?.html?"<br/>":"\n"}`}class Te extends Ot{get[Symbol.toStringTag](){return"Shader"}stage;source;compilationStatus="pending";constructor(t,e){super(t,{id:Ae(e={...e,debugShaders:e.debugShaders||t.props.debugShaders||"errors"}),...e},Te.defaultProps),this.stage=this.props.stage,this.source=this.props.source}getCompilationInfoSync(){return null}getTranslatedSource(){return null}async debugShader(){const t=this.props.debugShaders;switch(t){case"never":return;case"errors":if("success"===this.compilationStatus)return}const e=await this.getCompilationInfo();"warnings"===t&&0===e?.length||this._displayShaderLog(e,this.id)}_displayShaderLog(t,e){if("undefined"==typeof document||!document?.createElement)return;const n=`${this.stage} shader "${e}"`;let i=function(t,e,n){let i="";const s=e.split(/\r?\n/),r=t.slice().sort(((t,e)=>t.lineNum-e.lineNum));switch(n?.showSourceCode||"no"){case"all":let e=0;for(let t=1;t<=s.length;t++)for(i+=Ee(s[t-1],t,n);r.length>e&&r[e].lineNum===t;){const t=r[e++];i+=xe(t,s,t.lineNum,{...n,inlineSource:!1})}for(;r.length>e;)i+=xe(r[e++],[],0,{...n,inlineSource:!1});return i;case"issues":case"no":for(const e of t)i+=xe(e,s,e.lineNum,{inlineSource:"no"!==n?.showSourceCode});return i}}(t,this.source,{showSourceCode:"all",html:!0});const s=this.getTranslatedSource();s&&(i+=`<br /><br /><h1>Translated Source</h1><br /><br /><code style="user-select:text;"><pre>${s}</pre></code>`);const r=document.createElement("Button");r.innerHTML=`\n<h1>Compilation error in ${n}</h1><br /><br />\n<code style="user-select:text;"><pre>\n${i}\n</pre></code>`,r.style.top="10px",r.style.left="10px",r.style.position="absolute",r.style.zIndex="9999",r.style.width="100%",r.style.textAlign="left",document.body.appendChild(r);const o=document.getElementsByClassName("luma-compiler-log-error");o[0]?.scrollIntoView(),r.onclick=()=>{const t=`data:text/plain,${encodeURIComponent(this.source)}`;navigator.clipboard.writeText(t)}}static defaultProps={...Ot.defaultProps,language:"auto",stage:void 0,source:"",sourceMap:null,entryPoint:"main",debugShaders:void 0}}function Ae(t){return function(t,e="unnamed"){const n=/#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/.exec(t);return n?n[1]:e}(t.source)||t.id||Lt(`unnamed ${t.stage}-shader`)}class Se extends Ot{get[Symbol.toStringTag](){return"Framebuffer"}width;height;constructor(t,e={}){super(t,e,Se.defaultProps),this.width=this.props.width,this.height=this.props.height}clone(t){const e=this.colorAttachments.map((e=>e.texture.clone(t))),n=this.depthStencilAttachment&&this.depthStencilAttachment.texture.clone(t);return this.device.createFramebuffer({...this.props,colorAttachments:e,depthStencilAttachment:n})}resize(t){let e=!t;if(t){const[n,i]=Array.isArray(t)?t:[t.width,t.height];e=e||i!==this.height||n!==this.width,this.width=n,this.height=i}e&&(Mt.log(2,`Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)(),this.resizeAttachments(this.width,this.height))}autoCreateAttachmentTextures(){if(0===this.props.colorAttachments.length&&!this.props.depthStencilAttachment)throw new Error("Framebuffer has noattachments");this.colorAttachments=this.props.colorAttachments.map(((t,e)=>{if("string"==typeof t){const n=this.createColorTexture(t,e);return this.attachResource(n),n.view}return t instanceof ye?t.view:t}));const t=this.props.depthStencilAttachment;if(t)if("string"==typeof t){const e=this.createDepthStencilTexture(t);this.attachResource(e),this.depthStencilAttachment=e.view}else this.depthStencilAttachment=t instanceof ye?t.view:t}createColorTexture(t,e){return this.device.createTexture({id:`${this.id}-color-attachment-${e}`,usage:ye.RENDER_ATTACHMENT,format:t,width:this.width,height:this.height,sampler:{magFilter:"linear",minFilter:"linear"}})}createDepthStencilTexture(t){return this.device.createTexture({id:`${this.id}-depth-stencil-attachment`,usage:ye.RENDER_ATTACHMENT,format:t,width:this.width,height:this.height})}resizeAttachments(t,e){for(let n=0;n<this.colorAttachments.length;++n)if(this.colorAttachments[n]){const i=this.colorAttachments[n].texture.clone({width:t,height:e});this.destroyAttachedResource(this.colorAttachments[n]),this.colorAttachments[n]=i.view,this.attachResource(i.view)}if(this.depthStencilAttachment){const n=this.depthStencilAttachment.texture.clone({width:t,height:e});this.destroyAttachedResource(this.depthStencilAttachment),this.depthStencilAttachment=n.view,this.attachResource(n)}this.updateAttachments()}static defaultProps={...Ot.defaultProps,width:1,height:1,colorAttachments:[],depthStencilAttachment:null}}class Ce extends Ot{get[Symbol.toStringTag](){return"RenderPipeline"}shaderLayout;bufferLayout;linkStatus="pending";hash="";constructor(t,e){super(t,e,Ce.defaultProps),this.shaderLayout=this.props.shaderLayout,this.bufferLayout=this.props.bufferLayout||[]}static defaultProps={...Ot.defaultProps,vs:null,vertexEntryPoint:"vertexMain",vsConstants:{},fs:null,fragmentEntryPoint:"fragmentMain",fsConstants:{},shaderLayout:null,bufferLayout:[],topology:"triangle-list",colorAttachmentFormats:void 0,depthStencilAttachmentFormat:void 0,parameters:{},bindings:{},uniforms:{}}}class Pe extends Ot{static defaultClearColor=[0,0,0,1];static defaultClearDepth=1;static defaultClearStencil=0;get[Symbol.toStringTag](){return"RenderPass"}constructor(t,e){super(t,e=Pe.normalizeProps(t,e),Pe.defaultProps)}static normalizeProps(t,e){return e}static defaultProps={...Ot.defaultProps,framebuffer:null,parameters:void 0,clearColor:Pe.defaultClearColor,clearColors:void 0,clearDepth:Pe.defaultClearDepth,clearStencil:Pe.defaultClearStencil,depthReadOnly:!1,stencilReadOnly:!1,discard:!1,occlusionQuerySet:void 0,timestampQuerySet:void 0,beginTimestampIndex:void 0,endTimestampIndex:void 0}}class Me extends Ot{get[Symbol.toStringTag](){return"ComputePipeline"}hash="";shaderLayout;constructor(t,e){super(t,e,Me.defaultProps),this.shaderLayout=e.shaderLayout}static defaultProps={...Ot.defaultProps,shader:void 0,entryPoint:void 0,constants:{},shaderLayout:void 0}}class Re extends Ot{get[Symbol.toStringTag](){return"CommandEncoder"}constructor(t,e){super(t,e,Re.defaultProps)}static defaultProps={...Ot.defaultProps,measureExecutionTime:void 0}}class Le extends Ot{get[Symbol.toStringTag](){return"CommandBuffer"}constructor(t,e){super(t,e,Le.defaultProps)}static defaultProps={...Ot.defaultProps}}function Oe(t){return De[t]}const Ie={f32:4,f16:2,i32:4,u32:4},ke={f32:["f32",1],"vec2<f32>":["f32",2],"vec3<f32>":["f32",3],"vec4<f32>":["f32",4],f16:["f16",1],"vec2<f16>":["f16",2],"vec3<f16>":["f16",3],"vec4<f16>":["f16",4],i32:["i32",1],"vec2<i32>":["i32",2],"vec3<i32>":["i32",3],"vec4<i32>":["i32",4],u32:["u32",1],"vec2<u32>":["u32",2],"vec3<u32>":["u32",3],"vec4<u32>":["u32",4]},De={f32:{type:"f32",components:1},f16:{type:"f16",components:1},i32:{type:"i32",components:1},u32:{type:"u32",components:1},"vec2<f32>":{type:"f32",components:2},"vec3<f32>":{type:"f32",components:3},"vec4<f32>":{type:"f32",components:4},"vec2<f16>":{type:"f16",components:2},"vec3<f16>":{type:"f16",components:3},"vec4<f16>":{type:"f16",components:4},"vec2<i32>":{type:"i32",components:2},"vec3<i32>":{type:"i32",components:3},"vec4<i32>":{type:"i32",components:4},"vec2<u32>":{type:"u32",components:2},"vec3<u32>":{type:"u32",components:3},"vec4<u32>":{type:"u32",components:4},"mat2x2<f32>":{type:"f32",components:4},"mat2x3<f32>":{type:"f32",components:6},"mat2x4<f32>":{type:"f32",components:8},"mat3x2<f32>":{type:"f32",components:6},"mat3x3<f32>":{type:"f32",components:9},"mat3x4<f32>":{type:"f32",components:12},"mat4x2<f32>":{type:"f32",components:8},"mat4x3<f32>":{type:"f32",components:12},"mat4x4<f32>":{type:"f32",components:16},"mat2x2<f16>":{type:"f16",components:4},"mat2x3<f16>":{type:"f16",components:6},"mat2x4<f16>":{type:"f16",components:8},"mat3x2<f16>":{type:"f16",components:6},"mat3x3<f16>":{type:"f16",components:9},"mat3x4<f16>":{type:"f16",components:12},"mat4x2<f16>":{type:"f16",components:8},"mat4x3<f16>":{type:"f16",components:12},"mat4x4<f16>":{type:"f16",components:16},"mat2x2<i32>":{type:"i32",components:4},"mat2x3<i32>":{type:"i32",components:6},"mat2x4<i32>":{type:"i32",components:8},"mat3x2<i32>":{type:"i32",components:6},"mat3x3<i32>":{type:"i32",components:9},"mat3x4<i32>":{type:"i32",components:12},"mat4x2<i32>":{type:"i32",components:8},"mat4x3<i32>":{type:"i32",components:12},"mat4x4<i32>":{type:"i32",components:16},"mat2x2<u32>":{type:"u32",components:4},"mat2x3<u32>":{type:"u32",components:6},"mat2x4<u32>":{type:"u32",components:8},"mat3x2<u32>":{type:"u32",components:6},"mat3x3<u32>":{type:"u32",components:9},"mat3x4<u32>":{type:"u32",components:12},"mat4x2<u32>":{type:"u32",components:8},"mat4x3<u32>":{type:"u32",components:12},"mat4x4<u32>":{type:"u32",components:16}};function Ne(t,e){const n={};for(const i of t.attributes){const s=Fe(t,e,i.name);s&&(n[i.name]=s)}return n}function Fe(t,e,n){const i=function(t,e){const n=t.attributes.find((t=>t.name===e));return n||Mt.warn(`shader layout attribute "${e}" not present in shader`),n||null}(t,n),s=function(t,e){Be(t);let n=function(t,e){for(const n of t)if(n.format&&n.name===e)return{attributeName:n.name,bufferName:e,stepMode:n.stepMode,vertexFormat:n.format,byteOffset:0,byteStride:n.byteStride||0};return null}(t,e);return n||(n=function(t,e){for(const n of t){let t=n.byteStride;if("number"!=typeof n.byteStride)for(const e of n.attributes||[])t+=$t(e.format).byteLength;const i=n.attributes?.find((t=>t.attribute===e));if(i)return{attributeName:i.attribute,bufferName:n.name,stepMode:n.stepMode,vertexFormat:i.format,byteOffset:i.byteOffset,byteStride:t}}return null}(t,e),n||(Mt.warn(`layout for attribute "${e}" not present in buffer layout`),null))}(e,n);if(!i)return null;const r=function(t){const[e,n]=ke[t];return{primitiveType:e,components:n,byteLength:Ie[e]*n,integer:"i32"===e||"u32"===e,signed:"u32"!==e}}(i.type),o=function(t){let e;switch(t.primitiveType){case"f32":e="float32";break;case"i32":e="sint32";break;case"u32":e="uint32";break;case"f16":return t.components<=2?"float16x2":"float16x4"}return 1===t.components?e:`${e}x${t.components}`}(r),a=s?.vertexFormat||o,c=$t(a);return{attributeName:s?.attributeName||i.name,bufferName:s?.bufferName||i.name,location:i.location,shaderType:i.type,primitiveType:r.primitiveType,shaderComponents:r.components,vertexFormat:a,bufferDataType:c.type,bufferComponents:c.components,normalized:c.normalized,integer:r.integer,stepMode:s?.stepMode||i.stepMode||"vertex",byteOffset:s?.byteOffset||0,byteStride:s?.byteStride||0}}function Be(t){for(const e of t)(e.attributes&&e.format||!e.attributes&&!e.format)&&Mt.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`)}class $e extends Ot{static defaultProps={...Ot.defaultProps,shaderLayout:void 0,bufferLayout:[]};get[Symbol.toStringTag](){return"VertexArray"}maxVertexAttributes;attributeInfos;indexBuffer=null;attributes;constructor(t,e){super(t,e,$e.defaultProps),this.maxVertexAttributes=t.limits.maxVertexAttributes,this.attributes=new Array(this.maxVertexAttributes).fill(null),this.attributeInfos=function(t,e,n=16){const i=Ne(t,e),s=new Array(n).fill(null);for(const t of Object.values(i))s[t.location]=t;return s}(e.shaderLayout,e.bufferLayout,this.maxVertexAttributes)}setConstantWebGL(t,e){this.device.reportError(new Error("constant attributes not supported"),this)()}}class Ue extends Ot{static defaultProps={...Ot.defaultProps,layout:void 0,buffers:{}};get[Symbol.toStringTag](){return"TransformFeedback"}constructor(t,e){super(t,e,Ue.defaultProps)}}class ze extends Ot{get[Symbol.toStringTag](){return"QuerySet"}constructor(t,e){super(t,e,ze.defaultProps)}static defaultProps={...Ot.defaultProps,type:void 0,count:void 0}}let je;function Ge(t){return(!je||je.byteLength<t)&&(je=new ArrayBuffer(t)),je}function We(t){return Array.isArray(t)?0===t.length||"number"==typeof t[0]:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}(t)}class Ve{layout={};byteLength;constructor(t,e={}){let n=0;for(const[i,s]of Object.entries(t)){const t=Oe(s),{type:r,components:o}=t,a=o*(e?.[i]??1);n=Dt(n,a);const c=n;n+=a,this.layout[i]={type:r,size:a,offset:c}}n+=(4-n%4)%4,this.byteLength=Math.max(4*n,1024)}getData(t){const e=Ge(this.byteLength),n={i32:new Int32Array(e),u32:new Uint32Array(e),f32:new Float32Array(e),f16:new Uint16Array(e)};for(const[e,i]of Object.entries(t)){const t=this.layout[e];if(!t){Mt.warn(`Supplied uniform value ${e} not present in uniform block layout`)();continue}const{type:s,size:r,offset:o}=t,a=n[s];if(1===r){if("number"!=typeof i&&"boolean"!=typeof i){Mt.warn(`Supplied value for single component uniform ${e} is not a number: ${i}`)();continue}a[o]=Number(i)}else{if(!We(i)){Mt.warn(`Supplied value for multi component / array uniform ${e} is not a numeric array: ${i}`)();continue}a.set(i,o)}}return new Uint8Array(e,0,this.byteLength)}has(t){return Boolean(this.layout[t])}get(t){return this.layout[t]}}class He{name;uniforms={};modifiedUniforms={};modified=!0;bindingLayout={};needsRedraw="initialized";constructor(t){if(this.name=t?.name||"unnamed",t?.name&&t?.shaderLayout){const e=t?.shaderLayout.bindings?.find((e=>"uniform"===e.type&&e.name===t?.name));if(!e)throw new Error(t?.name);const n=e;for(const t of n.uniforms||[])this.bindingLayout[t.name]=t}}setUniforms(t){for(const[e,n]of Object.entries(t))this._setUniform(e,n),this.needsRedraw||this.setNeedsRedraw(`${this.name}.${e}=${n}`)}setNeedsRedraw(t){this.needsRedraw=this.needsRedraw||t}getAllUniforms(){return this.modifiedUniforms={},this.needsRedraw=!1,this.uniforms||{}}_setUniform(t,e){(function(t,e){if(t!==e)return!1;const n=t,i=e;if(!We(n))return!1;if(We(i)&&n.length===i.length)for(let t=0;t<n.length;++t)if(i[t]!==n[t])return!1;return!0})(this.uniforms[t],e)||(this.uniforms[t]=function(t){return We(t)?t.slice():t}(e),this.modifiedUniforms[t]=!0,this.modified=!0)}}class Xe{uniformBlocks=new Map;uniformBufferLayouts=new Map;uniformBuffers=new Map;constructor(t){for(const[e,n]of Object.entries(t)){const t=e,i=new Ve(n.uniformTypes??{},n.uniformSizes??{});this.uniformBufferLayouts.set(t,i);const s=new He({name:e});s.setUniforms(n.defaultUniforms||{}),this.uniformBlocks.set(t,s)}}destroy(){for(const t of this.uniformBuffers.values())t.destroy()}setUniforms(t){for(const[e,n]of Object.entries(t))this.uniformBlocks.get(e)?.setUniforms(n);this.updateUniformBuffers()}getUniformBufferByteLength(t){return this.uniformBufferLayouts.get(t)?.byteLength||0}getUniformBufferData(t){const e=this.uniformBlocks.get(t)?.getAllUniforms()||{};return this.uniformBufferLayouts.get(t)?.getData(e)}createUniformBuffer(t,e,n){n&&this.setUniforms(n);const i=this.getUniformBufferByteLength(e),s=t.createBuffer({usage:It.UNIFORM|It.COPY_DST,byteLength:i}),r=this.getUniformBufferData(e);return s.write(r),s}getManagedUniformBuffer(t,e){if(!this.uniformBuffers.get(e)){const n=this.getUniformBufferByteLength(e),i=t.createBuffer({usage:It.UNIFORM|It.COPY_DST,byteLength:n});this.uniformBuffers.set(e,i)}return this.uniformBuffers.get(e)}updateUniformBuffers(){let t=!1;for(const e of this.uniformBlocks.keys()){const n=this.updateUniformBuffer(e);t||=n}return t&&Mt.log(3,`UniformStore.updateUniformBuffers(): ${t}`)(),t}updateUniformBuffer(t){const e=this.uniformBlocks.get(t);let n=this.uniformBuffers.get(t),i=!1;if(n&&e?.needsRedraw){i||=e.needsRedraw;const s=this.getUniformBufferData(t);n=this.uniformBuffers.get(t),n?.write(s);const r=this.uniformBlocks.get(t)?.getAllUniforms();Mt.log(4,`Writing to uniform buffer ${String(t)}`,s,r)()}return i}}class Ze{constructor(t,e){this.name=t,this.attributes=e,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class Ke{constructor(t,e,n){this.name=t,this.type=e,this.attributes=n,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class qe extends Ze{constructor(t,e){super(t,e),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class Ye extends Ze{constructor(t,e){super(t,e),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class Je extends Ze{constructor(t,e,n){super(t,n),this.format=e}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class Qe extends Ze{constructor(t,e,n,i){super(t,n),this.format=e,this.access=i}get isTemplate(){return!0}getTypeName(){let t=this.name;if(null!==this.format){if("vec2"===t||"vec3"===t||"vec4"===t||"mat2x2"===t||"mat2x3"===t||"mat2x4"===t||"mat3x2"===t||"mat3x3"===t||"mat3x4"===t||"mat4x2"===t||"mat4x3"===t||"mat4x4"===t){if("f32"===this.format.name)return t+="f",t;if("i32"===this.format.name)return t+="i",t;if("u32"===this.format.name)return t+="u",t;if("bool"===this.format.name)return t+="b",t;if("f16"===this.format.name)return t+="h",t}t+=`<${this.format.name}>`}else if("vec2"===t||"vec3"===t||"vec4"===t)return t;return t}}var tn;(t=>{t[t.Uniform=0]="Uniform",t[t.Storage=1]="Storage",t[t.Texture=2]="Texture",t[t.Sampler=3]="Sampler",t[t.StorageTexture=4]="StorageTexture"})(tn||(tn={}));class en{constructor(t,e,n,i,s,r,o){this.name=t,this.type=e,this.group=n,this.binding=i,this.attributes=s,this.resourceType=r,this.access=o}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class nn{constructor(t,e){this.name=t,this.type=e}}class sn{constructor(t,e,n,i){this.name=t,this.type=e,this.locationType=n,this.location=i,this.interpolation=null}}class rn{constructor(t,e,n,i){this.name=t,this.type=e,this.locationType=n,this.location=i}}class on{constructor(t,e,n,i){this.name=t,this.type=e,this.attributes=n,this.id=i}}class an{constructor(t,e,n){this.name=t,this.type=e,this.attributes=n}}class cn{constructor(t,e=null,n){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=t,this.stage=e,this.attributes=n}}class ln{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function hn(t){var e=(32768&t)>>15,n=(31744&t)>>10,i=1023&t;return 0==n?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):31==n?i?NaN:1/0*(e?-1:1):(e?-1:1)*Math.pow(2,n-15)*(1+i/Math.pow(2,10))}const un=new Float32Array(1),fn=new Int32Array(un.buffer),dn=new Uint16Array(1);function pn(t){un[0]=t;const e=fn[0],n=e>>31&1;let i=e>>23&255,s=8388607&e;if(255===i)return dn[0]=n<<15|31744|(0!==s?512:0),dn[0];if(0===i){if(0===s)return dn[0]=n<<15,dn[0];s|=8388608;let t=113;for(;!(8388608&s);)s<<=1,t--;return i=127-t,s&=8388607,i>0?(s=(s>>126-i)+(s>>127-i&1),dn[0]=n<<15|i<<10|s>>13,dn[0]):(dn[0]=n<<15,dn[0])}return i=i-127+15,i>=31?(dn[0]=n<<15|31744,dn[0]):i<=0?i<-10?(dn[0]=n<<15,dn[0]):(s=(8388608|s)>>1-i,dn[0]=n<<15|s>>13,dn[0]):(s>>=13,dn[0]=n<<15|i<<10|s,dn[0])}const gn=new Uint32Array(1),mn=new Float32Array(gn.buffer,0,1);function _n(t){return gn[0]=112+(t>>6&31)<<23|(63&t)<<17,mn[0]}function vn(t,e,n,i){const s=[0,0,0,0];for(let r=0;r<i;++r)switch(n){case"8unorm":s[r]=t[e]/255,e++;break;case"8snorm":s[r]=t[e]/255*2-1,e++;break;case"8uint":s[r]=t[e],e++;break;case"8sint":s[r]=t[e]-127,e++;break;case"16uint":s[r]=t[e]|t[e+1]<<8,e+=2;break;case"16sint":s[r]=(t[e]|t[e+1]<<8)-32768,e+=2;break;case"16float":s[r]=hn(t[e]|t[e+1]<<8),e+=2;break;case"32uint":case"32sint":s[r]=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24,e+=4;break;case"32float":s[r]=new Float32Array(t.buffer,e,1)[0],e+=4}return s}function bn(t,e,n,i,s){for(let r=0;r<i;++r)switch(n){case"8unorm":t[e]=255*s[r],e++;break;case"8snorm":t[e]=.5*(s[r]+1)*255,e++;break;case"8uint":t[e]=s[r],e++;break;case"8sint":t[e]=s[r]+127,e++;break;case"16uint":new Uint16Array(t.buffer,e,1)[0]=s[r],e+=2;break;case"16sint":new Int16Array(t.buffer,e,1)[0]=s[r],e+=2;break;case"16float":{const n=pn(s[r]);new Uint16Array(t.buffer,e,1)[0]=n,e+=2;break}case"32uint":new Uint32Array(t.buffer,e,1)[0]=s[r],e+=4;break;case"32sint":new Int32Array(t.buffer,e,1)[0]=s[r],e+=4;break;case"32float":new Float32Array(t.buffer,e,1)[0]=s[r],e+=4}return s}const yn={r8unorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8snorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8uint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8sint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg8unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8snorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"rgba8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8snorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},bgra8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bgra8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r16uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16float:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg16uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba16uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r32uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg32uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba32uint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32sint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32float:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rg11b10ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},stencil8:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!1,hasStencil:!0,channels:1},depth16unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},depth24plus:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,depthOnlyFormat:"depth32float",channels:1},"depth24plus-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,depthOnlyFormat:"depth32float",channels:1},depth32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},"depth32float-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,stencilOnlyFormat:"depth32float",channels:1},rgb9e5ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bc1-rgba-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc1-rgba-unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc4-r-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc4-r-snorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc5-rg-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc5-rg-snorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc6h-rgb-ufloat":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc6h-rgb-float":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"eac-r11unorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-r11snorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-rg11unorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"eac-rg11snorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"astc-4x4-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-4x4-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x5-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-5x5-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x6-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-6x6-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-8x5-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x5-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x6-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x6-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x8-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-8x8-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-10x5-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x5-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x6-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x6-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x8-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x8-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x10-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-10x10-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x12-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4},"astc-12x12-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4}};class wn{constructor(){this.id=wn._id++,this.line=0}get isAstNode(){return!0}get astNodeType(){return""}search(t){t(this)}searchBlock(t,e){if(t){e(xn.instance);for(const n of t)n instanceof Array?this.searchBlock(n,e):n.search(e);e(En.instance)}}constEvaluate(t,e){throw new Error("Cannot evaluate node")}constEvaluateString(t){return this.constEvaluate(t).toString()}}wn._id=0;class xn extends wn{}xn.instance=new xn;class En extends wn{}En.instance=new En;const Tn=new Set(["all","all","any","select","arrayLength","abs","acos","acosh","asin","asinh","atan","atanh","atan2","ceil","clamp","cos","cosh","countLeadingZeros","countOneBits","countTrailingZeros","cross","degrees","determinant","distance","dot","dot4U8Packed","dot4I8Packed","exp","exp2","extractBits","faceForward","firstLeadingBit","firstTrailingBit","floor","fma","fract","frexp","insertBits","inverseSqrt","ldexp","length","log","log2","max","min","mix","modf","normalize","pow","quantizeToF16","radians","reflect","refract","reverseBits","round","saturate","sign","sin","sinh","smoothStep","sqrt","step","tan","tanh","transpose","trunc","dpdx","dpdxCoarse","dpdxFine","dpdy","dpdyCoarse","dpdyFine","fwidth","fwidthCoarse","fwidthFine","textureDimensions","textureGather","textureGatherCompare","textureLoad","textureNumLayers","textureNumLevels","textureNumSamples","textureSample","textureSampleBias","textureSampleCompare","textureSampleCompareLevel","textureSampleGrad","textureSampleLevel","textureSampleBaseClampToEdge","textureStore","atomicLoad","atomicStore","atomicAdd","atomicSub","atomicMax","atomicMin","atomicAnd","atomicOr","atomicXor","atomicExchange","atomicCompareExchangeWeak","pack4x8snorm","pack4x8unorm","pack4xI8","pack4xU8","pack4x8Clamp","pack4xU8Clamp","pack2x16snorm","pack2x16unorm","pack2x16float","unpack4x8snorm","unpack4x8unorm","unpack4xI8","unpack4xU8","unpack2x16snorm","unpack2x16unorm","unpack2x16float","storageBarrier","textureBarrier","workgroupBarrier","workgroupUniformLoad","subgroupAdd","subgroupExclusiveAdd","subgroupInclusiveAdd","subgroupAll","subgroupAnd","subgroupAny","subgroupBallot","subgroupBroadcast","subgroupBroadcastFirst","subgroupElect","subgroupMax","subgroupMin","subgroupMul","subgroupExclusiveMul","subgroupInclusiveMul","subgroupOr","subgroupShuffle","subgroupShuffleDown","subgroupShuffleUp","subgroupShuffleXor","subgroupXor","quadBroadcast","quadSwapDiagonal","quadSwapX","quadSwapY"]);class An extends wn{constructor(){super()}}class Sn extends An{constructor(t,e,n,i,s,r){super(),this.calls=new Set,this.name=t,this.args=e,this.returnType=n,this.body=i,this.startLine=s,this.endLine=r}get astNodeType(){return"function"}search(t){if(this.attributes)for(const e of this.attributes)t(e);t(this);for(const e of this.args)t(e);this.searchBlock(this.body,t)}}class Cn extends An{constructor(t){super(),this.expression=t}get astNodeType(){return"staticAssert"}search(t){this.expression.search(t)}}class Pn extends An{constructor(t,e){super(),this.condition=t,this.body=e}get astNodeType(){return"while"}search(t){this.condition.search(t),this.searchBlock(this.body,t)}}class Mn extends An{constructor(t,e){super(),this.body=t,this.loopId=e}get astNodeType(){return"continuing"}search(t){this.searchBlock(this.body,t)}}class Rn extends An{constructor(t,e,n,i){super(),this.init=t,this.condition=e,this.increment=n,this.body=i}get astNodeType(){return"for"}search(t){var e,n,i;null===(e=this.init)||void 0===e||e.search(t),null===(n=this.condition)||void 0===n||n.search(t),null===(i=this.increment)||void 0===i||i.search(t),this.searchBlock(this.body,t)}}class Ln extends An{constructor(t,e,n,i,s){super(),this.attributes=null,this.name=t,this.type=e,this.storage=n,this.access=i,this.value=s}get astNodeType(){return"var"}search(t){var e;t(this),null===(e=this.value)||void 0===e||e.search(t)}}class On extends An{constructor(t,e,n){super(),this.attributes=null,this.name=t,this.type=e,this.value=n}get astNodeType(){return"override"}search(t){var e;null===(e=this.value)||void 0===e||e.search(t)}}class In extends An{constructor(t,e,n,i,s){super(),this.attributes=null,this.name=t,this.type=e,this.storage=n,this.access=i,this.value=s}get astNodeType(){return"let"}search(t){var e;t(this),null===(e=this.value)||void 0===e||e.search(t)}}class kn extends An{constructor(t,e,n,i,s){super(),this.attributes=null,this.name=t,this.type=e,this.storage=n,this.access=i,this.value=s}get astNodeType(){return"const"}constEvaluate(t,e){return this.value.constEvaluate(t,e)}search(t){var e;t(this),null===(e=this.value)||void 0===e||e.search(t)}}var Dn,Nn,Fn,Bn;(t=>{t.increment="++",t.decrement="--"})(Dn||(Dn={})),(t=>{t.parse=function(e){const n=e;if("parse"==n)throw new Error("Invalid value for IncrementOperator");return t[n]}})(Dn||(Dn={}));class $n extends An{constructor(t,e){super(),this.operator=t,this.variable=e}get astNodeType(){return"increment"}search(t){this.variable.search(t)}}(t=>{t.assign="=",t.addAssign="+=",t.subtractAssin="-=",t.multiplyAssign="*=",t.divideAssign="/=",t.moduloAssign="%=",t.andAssign="&=",t.orAssign="|=",t.xorAssign="^=",t.shiftLeftAssign="<<=",t.shiftRightAssign=">>="})(Nn||(Nn={})),(Nn||(Nn={})).parse=function(t){const e=t;if("parse"==e)throw new Error("Invalid value for AssignOperator");return e};class Un extends An{constructor(t,e,n){super(),this.operator=t,this.variable=e,this.value=n}get astNodeType(){return"assign"}search(t){this.variable.search(t),this.value.search(t)}}class zn extends An{constructor(t,e){super(),this.name=t,this.args=e}get astNodeType(){return"call"}isBuiltin(){return Tn.has(this.name)}search(t){for(const e of this.args)e.search(t);t(this)}}class jn extends An{constructor(t,e){super(),this.body=t,this.continuing=e}get astNodeType(){return"loop"}search(t){var e;this.searchBlock(this.body,t),null===(e=this.continuing)||void 0===e||e.search(t)}}class Gn extends An{constructor(t,e){super(),this.condition=t,this.cases=e}get astNodeType(){return"switch"}search(t){t(this);for(const e of this.cases)e.search(t)}}class Wn extends An{constructor(t,e,n,i){super(),this.condition=t,this.body=e,this.elseif=n,this.else=i}get astNodeType(){return"if"}search(t){this.condition.search(t),this.searchBlock(this.body,t),this.searchBlock(this.elseif,t),this.searchBlock(this.else,t)}}class Vn extends An{constructor(t){super(),this.value=t}get astNodeType(){return"return"}search(t){var e;null===(e=this.value)||void 0===e||e.search(t)}}class Hn extends An{constructor(t){super(),this.name=t}get astNodeType(){return"enable"}}class Xn extends An{constructor(t){super(),this.extensions=t}get astNodeType(){return"requires"}}class Zn extends An{constructor(t,e){super(),this.severity=t,this.rule=e}get astNodeType(){return"diagnostic"}}class Kn extends An{constructor(t,e){super(),this.name=t,this.type=e}get astNodeType(){return"alias"}}class qn extends An{constructor(){super()}get astNodeType(){return"discard"}}class Yn extends An{constructor(){super(),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class Jn extends An{constructor(){super(),this.loopId=-1}get astNodeType(){return"continue"}}class Qn extends An{constructor(t){super(),this.attributes=null,this.name=t}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(t){let e=t[0];if("f32"===e.name)return e;for(let n=1;n<t.length;++n){const i=Qn._priority.get(e.name);Qn._priority.get(t[n].name)<i&&(e=t[n])}return"x32"===e.name?Qn.i32:e}getTypeName(){return this.name}}Qn.x32=new Qn("x32"),Qn.f32=new Qn("f32"),Qn.i32=new Qn("i32"),Qn.u32=new Qn("u32"),Qn.f16=new Qn("f16"),Qn.bool=new Qn("bool"),Qn.void=new Qn("void"),Qn._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class ti extends Qn{constructor(t){super(t)}}class ei extends Qn{constructor(t,e,n,i){super(t),this.members=e,this.startLine=n,this.endLine=i}get astNodeType(){return"struct"}get isStruct(){return!0}getMemberIndex(t){for(let e=0;e<this.members.length;e++)if(this.members[e].name==t)return e;return-1}search(t){for(const e of this.members)t(e)}}class ni extends Qn{constructor(t,e,n){super(t),this.format=e,this.access=n}get astNodeType(){return"template"}getTypeName(){let t=this.name;if(null!==this.format){if("vec2"===t||"vec3"===t||"vec4"===t||"mat2x2"===t||"mat2x3"===t||"mat2x4"===t||"mat3x2"===t||"mat3x3"===t||"mat3x4"===t||"mat4x2"===t||"mat4x3"===t||"mat4x4"===t){if("f32"===this.format.name)return t+="f",t;if("i32"===this.format.name)return t+="i",t;if("u32"===this.format.name)return t+="u",t;if("bool"===this.format.name)return t+="b",t;if("f16"===this.format.name)return t+="h",t}t+=`<${this.format.name}>`}else if("vec2"===t||"vec3"===t||"vec4"===t)return t;return t}}ni.vec2f=new ni("vec2",Qn.f32,null),ni.vec3f=new ni("vec3",Qn.f32,null),ni.vec4f=new ni("vec4",Qn.f32,null),ni.vec2i=new ni("vec2",Qn.i32,null),ni.vec3i=new ni("vec3",Qn.i32,null),ni.vec4i=new ni("vec4",Qn.i32,null),ni.vec2u=new ni("vec2",Qn.u32,null),ni.vec3u=new ni("vec3",Qn.u32,null),ni.vec4u=new ni("vec4",Qn.u32,null),ni.vec2h=new ni("vec2",Qn.f16,null),ni.vec3h=new ni("vec3",Qn.f16,null),ni.vec4h=new ni("vec4",Qn.f16,null),ni.vec2b=new ni("vec2",Qn.bool,null),ni.vec3b=new ni("vec3",Qn.bool,null),ni.vec4b=new ni("vec4",Qn.bool,null),ni.mat2x2f=new ni("mat2x2",Qn.f32,null),ni.mat2x3f=new ni("mat2x3",Qn.f32,null),ni.mat2x4f=new ni("mat2x4",Qn.f32,null),ni.mat3x2f=new ni("mat3x2",Qn.f32,null),ni.mat3x3f=new ni("mat3x3",Qn.f32,null),ni.mat3x4f=new ni("mat3x4",Qn.f32,null),ni.mat4x2f=new ni("mat4x2",Qn.f32,null),ni.mat4x3f=new ni("mat4x3",Qn.f32,null),ni.mat4x4f=new ni("mat4x4",Qn.f32,null),ni.mat2x2h=new ni("mat2x2",Qn.f16,null),ni.mat2x3h=new ni("mat2x3",Qn.f16,null),ni.mat2x4h=new ni("mat2x4",Qn.f16,null),ni.mat3x2h=new ni("mat3x2",Qn.f16,null),ni.mat3x3h=new ni("mat3x3",Qn.f16,null),ni.mat3x4h=new ni("mat3x4",Qn.f16,null),ni.mat4x2h=new ni("mat4x2",Qn.f16,null),ni.mat4x3h=new ni("mat4x3",Qn.f16,null),ni.mat4x4h=new ni("mat4x4",Qn.f16,null),ni.mat2x2i=new ni("mat2x2",Qn.i32,null),ni.mat2x3i=new ni("mat2x3",Qn.i32,null),ni.mat2x4i=new ni("mat2x4",Qn.i32,null),ni.mat3x2i=new ni("mat3x2",Qn.i32,null),ni.mat3x3i=new ni("mat3x3",Qn.i32,null),ni.mat3x4i=new ni("mat3x4",Qn.i32,null),ni.mat4x2i=new ni("mat4x2",Qn.i32,null),ni.mat4x3i=new ni("mat4x3",Qn.i32,null),ni.mat4x4i=new ni("mat4x4",Qn.i32,null),ni.mat2x2u=new ni("mat2x2",Qn.u32,null),ni.mat2x3u=new ni("mat2x3",Qn.u32,null),ni.mat2x4u=new ni("mat2x4",Qn.u32,null),ni.mat3x2u=new ni("mat3x2",Qn.u32,null),ni.mat3x3u=new ni("mat3x3",Qn.u32,null),ni.mat3x4u=new ni("mat3x4",Qn.u32,null),ni.mat4x2u=new ni("mat4x2",Qn.u32,null),ni.mat4x3u=new ni("mat4x3",Qn.u32,null),ni.mat4x4u=new ni("mat4x4",Qn.u32,null);class ii extends Qn{constructor(t,e,n,i){super(t),this.storage=e,this.type=n,this.access=i}get astNodeType(){return"pointer"}}class si extends Qn{constructor(t,e,n,i){super(t),this.attributes=e,this.format=n,this.count=i}get astNodeType(){return"array"}get isArray(){return!0}}class ri extends Qn{constructor(t,e,n){super(t),this.format=e,this.access=n}get astNodeType(){return"sampler"}}class oi extends wn{constructor(){super(),this.postfix=null}}class ai extends oi{constructor(t){super(),this.value=t}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class ci extends oi{constructor(t,e){super(),this.type=t,this.args=e}get astNodeType(){return"createExpr"}search(t){if(t(this),this.args)for(const e of this.args)e.search(t)}constEvaluate(t,e){return e&&(e[0]=this.type),t.evalExpression(this,t.context)}}class li extends oi{constructor(t,e){super(),this.cachedReturnValue=null,this.name=t,this.args=e}get astNodeType(){return"callExpr"}setCachedReturnValue(t){this.cachedReturnValue=t}get isBuiltin(){return Tn.has(this.name)}constEvaluate(t,e){return t.evalExpression(this,t.context)}search(t){for(const e of this.args)e.search(t);t(this)}}class hi extends oi{constructor(t){super(),this.name=t}get astNodeType(){return"varExpr"}search(t){t(this),this.postfix&&this.postfix.search(t)}constEvaluate(t,e){return t.evalExpression(this,t.context)}}class ui extends oi{constructor(t,e){super(),this.name=t,this.initializer=e}get astNodeType(){return"constExpr"}constEvaluate(t,e){if(this.initializer){const e=t.evalExpression(this.initializer,t.context);return null!==e&&this.postfix?e.getSubData(t,this.postfix,t.context):e}return null}search(t){this.initializer.search(t)}}class fi extends oi{constructor(t,e){super(),this.value=t,this.type=e}get astNodeType(){return"literalExpr"}constEvaluate(t,e){return void 0!==e&&(e[0]=this.type),this.value}get isScalar(){return this.value instanceof Mi}get isVector(){return this.value instanceof Li||this.value instanceof Oi}get scalarValue(){return this.value instanceof Mi?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof Li||this.value instanceof Oi?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class di extends oi{constructor(t,e){super(),this.type=t,this.value=e}get astNodeType(){return"bitcastExpr"}search(t){this.value.search(t)}}class pi extends oi{constructor(t){super(),this.index=t}search(t){this.index.search(t)}}class gi extends oi{constructor(){super()}}class mi extends gi{constructor(t,e){super(),this.operator=t,this.right=e}get astNodeType(){return"unaryOp"}constEvaluate(t,e){return t.evalExpression(this,t.context)}search(t){this.right.search(t)}}class _i extends gi{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n}get astNodeType(){return"binaryOp"}_getPromotedType(t,e){return t.name===e.name?t:"f32"===t.name||"f32"===e.name?Qn.f32:"u32"===t.name||"u32"===e.name?Qn.u32:Qn.i32}constEvaluate(t,e){return t.evalExpression(this,t.context)}search(t){this.left.search(t),this.right.search(t)}}class vi extends wn{constructor(t){super(),this.body=t}search(t){t(this),this.searchBlock(this.body,t)}}class bi extends oi{constructor(){super()}get astNodeType(){return"default"}}class yi extends vi{constructor(t,e){super(e),this.selectors=t}get astNodeType(){return"case"}search(t){this.searchBlock(this.body,t)}}class wi extends vi{constructor(t){super(t)}get astNodeType(){return"default"}search(t){this.searchBlock(this.body,t)}}class xi extends wn{constructor(t,e,n){super(),this.name=t,this.type=e,this.attributes=n}get astNodeType(){return"argument"}}class Ei extends wn{constructor(t,e){super(),this.condition=t,this.body=e}get astNodeType(){return"elseif"}search(t){this.condition.search(t),this.searchBlock(this.body,t)}}class Ti extends wn{constructor(t,e,n){super(),this.name=t,this.type=e,this.attributes=n}get astNodeType(){return"member"}}class Ai extends wn{constructor(t,e){super(),this.name=t,this.value=e}get astNodeType(){return"attribute"}}class Si{constructor(t,e){this.parent=null,this.typeInfo=t,this.parent=e,this.id=Si._id++}clone(){throw`Clone: Not implemented for ${this.constructor.name}`}setDataValue(t,e,n,i){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(t,e,n){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}Si._id=0;class Ci extends Si{constructor(){super(new Ze("void",null),null)}toString(){return"void"}}Ci.void=new Ci;class Pi extends Si{constructor(t){super(new Je("pointer",t.typeInfo,null),null),this.reference=t}clone(){return this}setDataValue(t,e,n,i){this.reference.setDataValue(t,e,n,i)}getSubData(t,e,n){return e?this.reference.getSubData(t,e,n):this}toString(){return`&${this.reference.toString()}`}}class Mi extends Si{constructor(t,e,n=null){super(e,n),t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array?this.data=t:"x32"===this.typeInfo.name?this.data=t-Math.floor(t)!=0?new Float32Array([t]):t>=0?new Uint32Array([t]):new Int32Array([t]):"i32"===this.typeInfo.name||"bool"===this.typeInfo.name?this.data=new Int32Array([t]):"u32"===this.typeInfo.name?this.data=new Uint32Array([t]):"f32"===this.typeInfo.name||"f16"===this.typeInfo.name?this.data=new Float32Array([t]):console.error("ScalarData2: Invalid type",e)}clone(){if(this.data instanceof Float32Array)return new Mi(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new Mi(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new Mi(new Uint32Array(this.data),this.typeInfo,null);throw"ScalarData: Invalid data type"}get value(){return this.data[0]}set value(t){this.data[0]=t}setDataValue(t,e,n,i){if(n)return void console.error("SetDataValue: Scalar data does not support postfix",n);if(!(e instanceof Mi))return void console.error("SetDataValue: Invalid value",e);let s=e.data[0];"i32"===this.typeInfo.name||"u32"===this.typeInfo.name?s=Math.floor(s):"bool"===this.typeInfo.name&&(s=s?1:0),this.data[0]=s}getSubData(t,e,n){return e?(console.error("getSubData: Scalar data does not support postfix",e),null):this}toString(){return`${this.value}`}}function Ri(t,e,n){const i=e.length;return 2===i?"f32"===n?new Li(new Float32Array(e),t.getTypeInfo("vec2f")):"i32"===n||"bool"===n?new Li(new Int32Array(e),t.getTypeInfo("vec2i")):"u32"===n?new Li(new Uint32Array(e),t.getTypeInfo("vec2u")):"f16"===n?new Li(new Float32Array(e),t.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${n}`),null):3===i?"f32"===n?new Li(new Float32Array(e),t.getTypeInfo("vec3f")):"i32"===n||"bool"===n?new Li(new Int32Array(e),t.getTypeInfo("vec3i")):"u32"===n?new Li(new Uint32Array(e),t.getTypeInfo("vec3u")):"f16"===n?new Li(new Float32Array(e),t.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${n}`),null):4===i?"f32"===n?new Li(new Float32Array(e),t.getTypeInfo("vec4f")):"i32"===n||"bool"===n?new Li(new Int32Array(e),t.getTypeInfo("vec4i")):"u32"===n?new Li(new Uint32Array(e),t.getTypeInfo("vec4u")):"f16"===n?new Li(new Float32Array(e),t.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${n}`),null):(console.error(`getSubData: Invalid vector size ${e.length}`),null)}class Li extends Si{constructor(t,e,n=null){if(super(e,n),t instanceof Float32Array||t instanceof Uint32Array||t instanceof Int32Array)this.data=t;else{const e=this.typeInfo.name;"vec2f"===e||"vec3f"===e||"vec4f"===e?this.data=new Float32Array(t):"vec2i"===e||"vec3i"===e||"vec4i"===e?this.data=new Int32Array(t):"vec2u"===e||"vec3u"===e||"vec4u"===e?this.data=new Uint32Array(t):"vec2h"===e||"vec3h"===e||"vec4h"===e?this.data=new Float32Array(t):"vec2b"===e||"vec3b"===e||"vec4b"===e?this.data=new Int32Array(t):"vec2"===e||"vec3"===e||"vec4"===e?this.data=new Float32Array(t):console.error(`VectorData: Invalid type ${e}`)}}clone(){if(this.data instanceof Float32Array)return new Li(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new Li(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new Li(new Uint32Array(this.data),this.typeInfo,null);throw"VectorData: Invalid data type"}setDataValue(t,e,n,i){n instanceof ai?console.error("TODO: Set vector postfix"):e instanceof Li?this.data=e.data:console.error("SetDataValue: Invalid value",e)}getSubData(t,e,n){if(null===e)return this;let i=t.getTypeInfo("f32");if(this.typeInfo instanceof Qe)i=this.typeInfo.format||i;else{const e=this.typeInfo.name;"vec2f"===e||"vec3f"===e||"vec4f"===e?i=t.getTypeInfo("f32"):"vec2i"===e||"vec3i"===e||"vec4i"===e?i=t.getTypeInfo("i32"):"vec2b"===e||"vec3b"===e||"vec4b"===e?i=t.getTypeInfo("bool"):"vec2u"===e||"vec3u"===e||"vec4u"===e?i=t.getTypeInfo("u32"):"vec2h"===e||"vec3h"===e||"vec4h"===e?i=t.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${e}`)}let s=this;for(;null!==e&&null!==s;){if(e instanceof pi){const r=e.index;let o=-1;if(r instanceof fi){if(!(r.value instanceof Mi))return console.error(`GetSubData: Invalid array index ${r.value}`),null;o=r.value.value}else{const e=t.evalExpression(r,n);if(!(e instanceof Mi))return console.error("GetSubData: Unknown index type",r),null;o=e.value}if(o<0||o>=s.data.length)return console.error("GetSubData: Index out of range",o),null;if(s.data instanceof Float32Array){const t=new Float32Array(s.data.buffer,s.data.byteOffset+4*o,1);return new Mi(t,i)}if(s.data instanceof Int32Array){const t=new Int32Array(s.data.buffer,s.data.byteOffset+4*o,1);return new Mi(t,i)}if(s.data instanceof Uint32Array){const t=new Uint32Array(s.data.buffer,s.data.byteOffset+4*o,1);return new Mi(t,i)}throw"GetSubData: Invalid data type"}if(!(e instanceof ai))return console.error("GetSubData: Unknown postfix",e),null;{const n=e.value.toLowerCase();if(1===n.length){let t=0;if("x"===n||"r"===n)t=0;else if("y"===n||"g"===n)t=1;else if("z"===n||"b"===n)t=2;else{if("w"!==n&&"a"!==n)return console.error(`GetSubData: Unknown member ${n}`),null;t=3}if(this.data instanceof Float32Array){let e=new Float32Array(this.data.buffer,this.data.byteOffset+4*t,1);return new Mi(e,i,this)}if(this.data instanceof Int32Array){let e=new Int32Array(this.data.buffer,this.data.byteOffset+4*t,1);return new Mi(e,i,this)}if(this.data instanceof Uint32Array){let e=new Uint32Array(this.data.buffer,this.data.byteOffset+4*t,1);return new Mi(e,i,this)}}const r=[];for(const t of n)"x"===t||"r"===t?r.push(this.data[0]):"y"===t||"g"===t?r.push(this.data[1]):"z"===t||"b"===t?r.push(this.data[2]):"w"===t||"a"===t?r.push(this.data[3]):console.error(`GetDataValue: Unknown member ${t}`);s=Ri(t,r,i.name)}e=e.postfix}return s}toString(){let t=`${this.data[0]}`;for(let e=1;e<this.data.length;++e)t+=`, ${this.data[e]}`;return t}}class Oi extends Si{constructor(t,e,n=null){super(e,n),this.data=t instanceof Float32Array?t:new Float32Array(t)}clone(){return new Oi(new Float32Array(this.data),this.typeInfo,null)}setDataValue(t,e,n,i){n instanceof ai?console.error("TODO: Set matrix postfix"):e instanceof Oi?this.data=e.data:console.error("SetDataValue: Invalid value",e)}getSubData(t,e,n){if(null===e)return this;const i=this.typeInfo.name;if(t.getTypeInfo("f32"),this.typeInfo instanceof Qe);else if(i.endsWith("f"))t.getTypeInfo("f32");else if(i.endsWith("i"))t.getTypeInfo("i32");else if(i.endsWith("u"))t.getTypeInfo("u32");else{if(!i.endsWith("h"))return console.error(`GetDataValue: Unknown type ${i}`),null;t.getTypeInfo("f16")}if(e instanceof pi){const s=e.index;let r=-1;if(s instanceof fi){if(!(s.value instanceof Mi))return console.error(`GetDataValue: Invalid array index ${s.value}`),null;r=s.value.value}else{const e=t.evalExpression(s,n);if(!(e instanceof Mi))return console.error("GetDataValue: Unknown index type",s),null;r=e.value}if(r<0||r>=this.data.length)return console.error("GetDataValue: Index out of range",r),null;const o=i.endsWith("h")?"h":"f";let a;if("mat2x2"===i||"mat2x2f"===i||"mat2x2h"===i||"mat3x2"===i||"mat3x2f"===i||"mat3x2h"===i||"mat4x2"===i||"mat4x2f"===i||"mat4x2h"===i)a=new Li(new Float32Array(this.data.buffer,this.data.byteOffset+2*r*4,2),t.getTypeInfo(`vec2${o}`));else if("mat2x3"===i||"mat2x3f"===i||"mat2x3h"===i||"mat3x3"===i||"mat3x3f"===i||"mat3x3h"===i||"mat4x3"===i||"mat4x3f"===i||"mat4x3h"===i)a=new Li(new Float32Array(this.data.buffer,this.data.byteOffset+3*r*4,3),t.getTypeInfo(`vec3${o}`));else{if("mat2x4"!==i&&"mat2x4f"!==i&&"mat2x4h"!==i&&"mat3x4"!==i&&"mat3x4f"!==i&&"mat3x4h"!==i&&"mat4x4"!==i&&"mat4x4f"!==i&&"mat4x4h"!==i)return console.error(`GetDataValue: Unknown type ${i}`),null;a=new Li(new Float32Array(this.data.buffer,this.data.byteOffset+4*r*4,4),t.getTypeInfo(`vec4${o}`))}return e.postfix?a.getSubData(t,e.postfix,n):a}return console.error("GetDataValue: Invalid postfix",e),null}toString(){let t=`${this.data[0]}`;for(let e=1;e<this.data.length;++e)t+=`, ${this.data[e]}`;return t}}class Ii extends Si{constructor(t,e,n=0,i=null){super(e,i),this.buffer=t instanceof ArrayBuffer?t:t.buffer,this.offset=n}clone(){const t=new Uint8Array(new Uint8Array(this.buffer,this.offset,this.typeInfo.size));return new Ii(t.buffer,this.typeInfo,0,null)}setDataValue(t,e,n,i){if(null===e)return void console.log("setDataValue: NULL data.");let s=this.offset,r=this.typeInfo;for(;n;){if(n instanceof pi)if(r instanceof Ye){const e=n.index;if(e instanceof fi){if(!(e.value instanceof Mi))return void console.error(`SetDataValue: Invalid index type ${e.value}`);s+=e.value.value*r.stride}else{const n=t.evalExpression(e,i);if(!(n instanceof Mi))return void console.error("SetDataValue: Unknown index type",e);s+=n.value*r.stride}r=r.format}else console.error(`SetDataValue: Type ${r.getTypeName()} is not an array`);else{if(!(n instanceof ai))return void console.error("SetDataValue: Unknown postfix type",n);{const t=n.value;if(r instanceof qe){let e=!1;for(const n of r.members)if(n.name===t){s+=n.offset,r=n.type,e=!0;break}if(!e)return void console.error(`SetDataValue: Member ${t} not found`)}else if(r instanceof Ze){const n=r.getTypeName();let i=0;if("x"===t||"r"===t)i=0;else if("y"===t||"g"===t)i=1;else if("z"===t||"b"===t)i=2;else{if("w"!==t&&"a"!==t)return void console.error(`SetDataValue: Unknown member ${t}`);i=3}if(!(e instanceof Mi))return void console.error("SetDataValue: Invalid value",e);const o=e.value;return"vec2f"===n?void(new Float32Array(this.buffer,s,2)[i]=o):"vec3f"===n?void(new Float32Array(this.buffer,s,3)[i]=o):"vec4f"===n?void(new Float32Array(this.buffer,s,4)[i]=o):"vec2i"===n?void(new Int32Array(this.buffer,s,2)[i]=o):"vec3i"===n?void(new Int32Array(this.buffer,s,3)[i]=o):"vec4i"===n?void(new Int32Array(this.buffer,s,4)[i]=o):"vec2u"===n?void(new Uint32Array(this.buffer,s,2)[i]=o):"vec3u"===n?void(new Uint32Array(this.buffer,s,3)[i]=o):"vec4u"===n?void(new Uint32Array(this.buffer,s,4)[i]=o):void console.error(`SetDataValue: Type ${n} is not a struct`)}}}n=n.postfix}this.setData(t,e,r,s,i)}setData(t,e,n,i,s){const r=n.getTypeName();if("f32"!==r&&"f16"!==r)if("i32"!==r&&"atomic<i32>"!==r&&"x32"!==r)if("u32"!==r&&"atomic<u32>"!==r)if("bool"!==r){if("vec2f"===r||"vec2h"===r){const t=new Float32Array(this.buffer,i,2);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1]):(t[0]=e[0],t[1]=e[1]))}if("vec3f"===r||"vec3h"===r){const t=new Float32Array(this.buffer,i,3);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2]):(t[0]=e[0],t[1]=e[1],t[2]=e[2]))}if("vec4f"===r||"vec4h"===r){const t=new Float32Array(this.buffer,i,4);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3]))}if("vec2i"===r){const t=new Int32Array(this.buffer,i,2);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1]):(t[0]=e[0],t[1]=e[1]))}if("vec3i"===r){const t=new Int32Array(this.buffer,i,3);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2]):(t[0]=e[0],t[1]=e[1],t[2]=e[2]))}if("vec4i"===r){const t=new Int32Array(this.buffer,i,4);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3]))}if("vec2u"===r){const t=new Uint32Array(this.buffer,i,2);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1]):(t[0]=e[0],t[1]=e[1]))}if("vec3u"===r){const t=new Uint32Array(this.buffer,i,3);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2]):(t[0]=e[0],t[1]=e[1],t[2]=e[2]))}if("vec4u"===r){const t=new Uint32Array(this.buffer,i,4);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3]))}if("vec2b"===r){const t=new Uint32Array(this.buffer,i,2);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1]):(t[0]=e[0],t[1]=e[1]))}if("vec3b"===r){const t=new Uint32Array(this.buffer,i,3);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2]):(t[0]=e[0],t[1]=e[1],t[2]=e[2]))}if("vec4b"===r){const t=new Uint32Array(this.buffer,i,4);return void(e instanceof Li?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3]))}if("mat2x2f"===r||"mat2x2h"===r){const t=new Float32Array(this.buffer,i,4);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3]))}if("mat2x3f"===r||"mat2x3h"===r){const t=new Float32Array(this.buffer,i,6);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]))}if("mat2x4f"===r||"mat2x4h"===r){const t=new Float32Array(this.buffer,i,8);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5],t[6]=e.data[6],t[7]=e.data[7]):(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]))}if("mat3x2f"===r||"mat3x2h"===r){const t=new Float32Array(this.buffer,i,6);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5]):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5]))}if("mat3x3f"===r||"mat3x3h"===r){const t=new Float32Array(this.buffer,i,9);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5],t[6]=e.data[6],t[7]=e.data[7],t[8]=e.data[8]):(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]))}if("mat3x4f"===r||"mat3x4h"===r){const t=new Float32Array(this.buffer,i,12);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5],t[6]=e.data[6],t[7]=e.data[7],t[8]=e.data[8],t[9]=e.data[9],t[10]=e.data[10],t[11]=e.data[11]):(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]))}if("mat4x2f"===r||"mat4x2h"===r){const t=new Float32Array(this.buffer,i,8);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5],t[6]=e.data[6],t[7]=e.data[7]):(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]))}if("mat4x3f"===r||"mat4x3h"===r){const t=new Float32Array(this.buffer,i,12);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5],t[6]=e.data[6],t[7]=e.data[7],t[8]=e.data[8],t[9]=e.data[9],t[10]=e.data[10],t[11]=e.data[11]):(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]))}if("mat4x4f"===r||"mat4x4h"===r){const t=new Float32Array(this.buffer,i,16);return void(e instanceof Oi?(t[0]=e.data[0],t[1]=e.data[1],t[2]=e.data[2],t[3]=e.data[3],t[4]=e.data[4],t[5]=e.data[5],t[6]=e.data[6],t[7]=e.data[7],t[8]=e.data[8],t[9]=e.data[9],t[10]=e.data[10],t[11]=e.data[11],t[12]=e.data[12],t[13]=e.data[13],t[14]=e.data[14],t[15]=e.data[15]):(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]))}if(e instanceof Ii){if(n===e.typeInfo)return void new Uint8Array(this.buffer,i,e.buffer.byteLength).set(new Uint8Array(e.buffer));console.error("SetDataValue: Type mismatch",r,e.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${r}`)}else e instanceof Mi&&(new Int32Array(this.buffer,i,1)[0]=e.value);else e instanceof Mi&&(new Uint32Array(this.buffer,i,1)[0]=e.value);else e instanceof Mi&&(new Int32Array(this.buffer,i,1)[0]=e.value);else e instanceof Mi&&(new Float32Array(this.buffer,i,1)[0]=e.value)}getSubData(t,e,n){var i,s,r;if(null===e)return this;let o=this.offset,a=this.typeInfo;for(;e;){if(e instanceof pi){const i=e.index,s=i instanceof oi?t.evalExpression(i,n):i;let r=0;if(s instanceof Mi?r=s.value:"number"==typeof s?r=s:console.error("GetDataValue: Invalid index type",i),a instanceof Ye)o+=r*a.stride,a=a.format;else{const e=a.getTypeName();"mat4x4"===e||"mat4x4f"===e||"mat4x4h"===e?(o+=16*r,a=t.getTypeInfo("vec4f")):console.error(`getDataValue: Type ${a.getTypeName()} is not an array`)}}else{if(!(e instanceof ai))return console.error("GetDataValue: Unknown postfix type",e),null;{const n=e.value;if(a instanceof qe){let t=!1;for(const e of a.members)if(e.name===n){o+=e.offset,a=e.type,t=!0;break}if(!t)return console.error(`GetDataValue: Member ${n} not found`),null}else if(a instanceof Ze){const e=a.getTypeName();if("vec2f"===e||"vec3f"===e||"vec4f"===e||"vec2i"===e||"vec3i"===e||"vec4i"===e||"vec2u"===e||"vec3u"===e||"vec4u"===e||"vec2b"===e||"vec3b"===e||"vec4b"===e||"vec2h"===e||"vec3h"===e||"vec4h"===e||"vec2"===e||"vec3"===e||"vec4"===e){if(n.length>0&&n.length<5){let i="f";const s=[];for(let r=0;r<n.length;++r){const a=n[r].toLowerCase();let c=0;if("x"===a||"r"===a)c=0;else if("y"===a||"g"===a)c=1;else if("z"===a||"b"===a)c=2;else{if("w"!==a&&"a"!==a)return console.error(`Unknown member ${n}`),null;c=3}if(1===n.length){if(e.endsWith("f"))return this.buffer.byteLength<o+4*c+4?(console.log("Insufficient buffer data"),null):new Mi(new Float32Array(this.buffer,o+4*c,1),t.getTypeInfo("f32"),this);if(e.endsWith("h"))return new Mi(new Float32Array(this.buffer,o+4*c,1),t.getTypeInfo("f16"),this);if(e.endsWith("i"))return new Mi(new Int32Array(this.buffer,o+4*c,1),t.getTypeInfo("i32"),this);if(e.endsWith("b"))return new Mi(new Int32Array(this.buffer,o+4*c,1),t.getTypeInfo("bool"),this);if(e.endsWith("u"))return new Mi(new Uint32Array(this.buffer,o+4*c,1),t.getTypeInfo("i32"),this)}if("vec2f"===e)s.push(new Float32Array(this.buffer,o,2)[c]);else if("vec3f"===e){if(o+12>=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const t=new Float32Array(this.buffer,o,3);s.push(t[c])}else if("vec4f"===e)s.push(new Float32Array(this.buffer,o,4)[c]);else if("vec2i"===e)i="i",s.push(new Int32Array(this.buffer,o,2)[c]);else if("vec3i"===e)i="i",s.push(new Int32Array(this.buffer,o,3)[c]);else if("vec4i"===e)i="i",s.push(new Int32Array(this.buffer,o,4)[c]);else if("vec2u"===e){i="u";const t=new Uint32Array(this.buffer,o,2);s.push(t[c])}else"vec3u"===e?(i="u",s.push(new Uint32Array(this.buffer,o,3)[c])):"vec4u"===e&&(i="u",s.push(new Uint32Array(this.buffer,o,4)[c]))}return 2===s.length?a=t.getTypeInfo(`vec2${i}`):3===s.length?a=t.getTypeInfo(`vec3${i}`):4===s.length?a=t.getTypeInfo(`vec4${i}`):console.error(`GetDataValue: Invalid vector length ${s.length}`),new Li(s,a,null)}return console.error(`GetDataValue: Unknown member ${n}`),null}return console.error(`GetDataValue: Type ${e} is not a struct`),null}}}e=e.postfix}const c=a.getTypeName();return"f32"===c?new Mi(new Float32Array(this.buffer,o,1),a,this):"i32"===c?new Mi(new Int32Array(this.buffer,o,1),a,this):"u32"===c?new Mi(new Uint32Array(this.buffer,o,1),a,this):"vec2f"===c?new Li(new Float32Array(this.buffer,o,2),a,this):"vec3f"===c?new Li(new Float32Array(this.buffer,o,3),a,this):"vec4f"===c?new Li(new Float32Array(this.buffer,o,4),a,this):"vec2i"===c?new Li(new Int32Array(this.buffer,o,2),a,this):"vec3i"===c?new Li(new Int32Array(this.buffer,o,3),a,this):"vec4i"===c?new Li(new Int32Array(this.buffer,o,4),a,this):"vec2u"===c?new Li(new Uint32Array(this.buffer,o,2),a,this):"vec3u"===c?new Li(new Uint32Array(this.buffer,o,3),a,this):"vec4u"===c?new Li(new Uint32Array(this.buffer,o,4),a,this):a instanceof Qe&&"atomic"===a.name?"u32"===(null===(i=a.format)||void 0===i?void 0:i.name)?new Mi(new Uint32Array(this.buffer,o,1)[0],a.format,this):"i32"===(null===(s=a.format)||void 0===s?void 0:s.name)?new Mi(new Int32Array(this.buffer,o,1)[0],a.format,this):(console.error(`GetDataValue: Invalid atomic format ${null===(r=a.format)||void 0===r?void 0:r.name}`),null):new Ii(this.buffer,a,o,this)}toString(){let t="";if(this.typeInfo instanceof Ye)if("f32"===this.typeInfo.format.name){const e=new Float32Array(this.buffer,this.offset);t=`[${e[0]}`;for(let n=1;n<e.length;++n)t+=`, ${e[n]}`}else if("i32"===this.typeInfo.format.name){const e=new Int32Array(this.buffer,this.offset);t=`[${e[0]}`;for(let n=1;n<e.length;++n)t+=`, ${e[n]}`}else if("u32"===this.typeInfo.format.name){const e=new Uint32Array(this.buffer,this.offset);t=`[${e[0]}`;for(let n=1;n<e.length;++n)t+=`, ${e[n]}`}else if("vec2f"===this.typeInfo.format.name){const e=new Float32Array(this.buffer,this.offset);t=`[${e[0]}, ${e[1]}]`;for(let n=1;n<e.length/2;++n)t+=`, [${e[2*n]}, ${e[2*n+1]}]`}else if("vec3f"===this.typeInfo.format.name){const e=new Float32Array(this.buffer,this.offset);t=`[${e[0]}, ${e[1]}, ${e[2]}]`;for(let n=4;n<e.length;n+=4)t+=`, [${e[n]}, ${e[n+1]}, ${e[n+2]}]`}else if("vec4f"===this.typeInfo.format.name){const e=new Float32Array(this.buffer,this.offset);t=`[${e[0]}, ${e[1]}, ${e[2]}, ${e[3]}]`;for(let n=4;n<e.length;n+=4)t+=`, [${e[n]}, ${e[n+1]}, ${e[n+2]}, ${e[n+3]}]`}else t="[...]";else this.typeInfo instanceof qe?t+="{...}":t="[...]";return t}}class ki extends Si{constructor(t,e,n,i){super(e,null),this.data=t,this.descriptor=n,this.view=i}clone(){return new ki(this.data,this.typeInfo,this.descriptor,this.view)}get width(){var t,e;const n=this.descriptor.size;return n instanceof Array&&n.length>0?null!==(t=n[0])&&void 0!==t?t:0:n instanceof Object&&null!==(e=n.width)&&void 0!==e?e:0}get height(){var t,e;const n=this.descriptor.size;return n instanceof Array&&n.length>1?null!==(t=n[1])&&void 0!==t?t:0:n instanceof Object&&null!==(e=n.height)&&void 0!==e?e:0}get depthOrArrayLayers(){var t,e;const n=this.descriptor.size;return n instanceof Array&&n.length>2?null!==(t=n[2])&&void 0!==t?t:0:n instanceof Object&&null!==(e=n.depthOrArrayLayers)&&void 0!==e?e:0}get format(){var t;return this.descriptor&&null!==(t=this.descriptor.format)&&void 0!==t?t:"rgba8unorm"}get sampleCount(){var t;return this.descriptor&&null!==(t=this.descriptor.sampleCount)&&void 0!==t?t:1}get mipLevelCount(){var t;return this.descriptor&&null!==(t=this.descriptor.mipLevelCount)&&void 0!==t?t:1}get dimension(){var t;return this.descriptor&&null!==(t=this.descriptor.dimension)&&void 0!==t?t:"2d"}getMipLevelSize(t){if(t>=this.mipLevelCount)return[0,0,0];const e=[this.width,this.height,this.depthOrArrayLayers];for(let n=0;n<e.length;++n)e[n]=Math.max(1,e[n]>>t);return e}get texelByteSize(){const t=yn[this.format];return t?t.isDepthStencil?4:t.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const t=yn[this.format];return!!t&&t.isDepthStencil}getGpuSize(){const t=this.format,e=yn[t],n=this.width;return!t||n<=0||!e?-1:n/e.blockWidth*("1d"===this.dimension?1:this.height/e.blockHeight)*e.bytesPerBlock*this.depthOrArrayLayers}getPixel(t,e,n=0,i=0){const s=this.texelByteSize,r=this.bytesPerRow,o=this.height;return function(t,e,n,i,s,r,o,a,c){const l=i*(o>>=s)*(r>>=s)+n*o+e*a;switch(c){case"r8unorm":return[vn(t,l,"8unorm",1)[0]];case"r8snorm":return[vn(t,l,"8snorm",1)[0]];case"r8uint":return[vn(t,l,"8uint",1)[0]];case"r8sint":return[vn(t,l,"8sint",1)[0]];case"rg8unorm":{const e=vn(t,l,"8unorm",2);return[e[0],e[1]]}case"rg8snorm":{const e=vn(t,l,"8snorm",2);return[e[0],e[1]]}case"rg8uint":{const e=vn(t,l,"8uint",2);return[e[0],e[1]]}case"rg8sint":{const e=vn(t,l,"8sint",2);return[e[0],e[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const e=vn(t,l,"8unorm",4);return[e[0],e[1],e[2],e[3]]}case"rgba8snorm":{const e=vn(t,l,"8snorm",4);return[e[0],e[1],e[2],e[3]]}case"rgba8uint":{const e=vn(t,l,"8uint",4);return[e[0],e[1],e[2],e[3]]}case"rgba8sint":{const e=vn(t,l,"8sint",4);return[e[0],e[1],e[2],e[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const e=vn(t,l,"8unorm",4);return[e[2],e[1],e[0],e[3]]}case"r16uint":return[vn(t,l,"16uint",1)[0]];case"r16sint":return[vn(t,l,"16sint",1)[0]];case"r16float":return[vn(t,l,"16float",1)[0]];case"rg16uint":{const e=vn(t,l,"16uint",2);return[e[0],e[1]]}case"rg16sint":{const e=vn(t,l,"16sint",2);return[e[0],e[1]]}case"rg16float":{const e=vn(t,l,"16float",2);return[e[0],e[1]]}case"rgba16uint":{const e=vn(t,l,"16uint",4);return[e[0],e[1],e[2],e[3]]}case"rgba16sint":{const e=vn(t,l,"16sint",4);return[e[0],e[1],e[2],e[3]]}case"rgba16float":{const e=vn(t,l,"16float",4);return[e[0],e[1],e[2],e[3]]}case"r32uint":return[vn(t,l,"32uint",1)[0]];case"r32sint":return[vn(t,l,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[vn(t,l,"32float",1)[0]];case"rg32uint":{const e=vn(t,l,"32uint",2);return[e[0],e[1]]}case"rg32sint":{const e=vn(t,l,"32sint",2);return[e[0],e[1]]}case"rg32float":{const e=vn(t,l,"32float",2);return[e[0],e[1]]}case"rgba32uint":{const e=vn(t,l,"32uint",4);return[e[0],e[1],e[2],e[3]]}case"rgba32sint":{const e=vn(t,l,"32sint",4);return[e[0],e[1],e[2],e[3]]}case"rgba32float":{const e=vn(t,l,"32float",4);return[e[0],e[1],e[2],e[3]]}case"rg11b10ufloat":{const e=new Uint32Array(t.buffer,l,1)[0],n=(4192256&e)>>11,i=(4290772992&e)>>22;return[_n(2047&e),_n(n),function(t){return gn[0]=112+(t>>5&31)<<23|(31&t)<<18,mn[0]}(i),1]}}return null}(new Uint8Array(this.data[i]),t,e,n,i,o,r,s,this.format)}setPixel(t,e,n,i,s){const r=this.texelByteSize,o=this.bytesPerRow,a=this.height;!function(t,e,n,i,s,r,o,a,c,l){const h=i*(o>>=s)*(r>>=s)+n*o+e*a;switch(c){case"r8unorm":return void bn(t,h,"8unorm",1,l);case"r8snorm":return void bn(t,h,"8snorm",1,l);case"r8uint":return void bn(t,h,"8uint",1,l);case"r8sint":return void bn(t,h,"8sint",1,l);case"rg8unorm":return void bn(t,h,"8unorm",2,l);case"rg8snorm":return void bn(t,h,"8snorm",2,l);case"rg8uint":return void bn(t,h,"8uint",2,l);case"rg8sint":return void bn(t,h,"8sint",2,l);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void bn(t,h,"8unorm",4,l);case"rgba8snorm":return void bn(t,h,"8snorm",4,l);case"rgba8uint":return void bn(t,h,"8uint",4,l);case"rgba8sint":return void bn(t,h,"8sint",4,l);case"r16uint":return void bn(t,h,"16uint",1,l);case"r16sint":return void bn(t,h,"16sint",1,l);case"r16float":return void bn(t,h,"16float",1,l);case"rg16uint":return void bn(t,h,"16uint",2,l);case"rg16sint":return void bn(t,h,"16sint",2,l);case"rg16float":return void bn(t,h,"16float",2,l);case"rgba16uint":return void bn(t,h,"16uint",4,l);case"rgba16sint":return void bn(t,h,"16sint",4,l);case"rgba16float":return void bn(t,h,"16float",4,l);case"r32uint":return void bn(t,h,"32uint",1,l);case"r32sint":return void bn(t,h,"32sint",1,l);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void bn(t,h,"32float",1,l);case"rg32uint":return void bn(t,h,"32uint",2,l);case"rg32sint":return void bn(t,h,"32sint",2,l);case"rg32float":return void bn(t,h,"32float",2,l);case"rgba32uint":return void bn(t,h,"32uint",4,l);case"rgba32sint":return void bn(t,h,"32sint",4,l);case"rgba32float":return void bn(t,h,"32float",4,l);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}}(new Uint8Array(this.data[i]),t,e,n,i,a,o,r,this.format,s)}}(t=>{t[t.token=0]="token",t[t.keyword=1]="keyword",t[t.reserved=2]="reserved"})(Bn||(Bn={}));class Di{constructor(t,e,n){this.name=t,this.type=e,this.rule=n}toString(){return this.name}}class Ni{}Fn=Ni,Ni.none=new Di("",Bn.reserved,""),Ni.eof=new Di("EOF",Bn.token,""),Ni.reserved={asm:new Di("asm",Bn.reserved,"asm"),bf16:new Di("bf16",Bn.reserved,"bf16"),do:new Di("do",Bn.reserved,"do"),enum:new Di("enum",Bn.reserved,"enum"),f16:new Di("f16",Bn.reserved,"f16"),f64:new Di("f64",Bn.reserved,"f64"),handle:new Di("handle",Bn.reserved,"handle"),i8:new Di("i8",Bn.reserved,"i8"),i16:new Di("i16",Bn.reserved,"i16"),i64:new Di("i64",Bn.reserved,"i64"),mat:new Di("mat",Bn.reserved,"mat"),premerge:new Di("premerge",Bn.reserved,"premerge"),regardless:new Di("regardless",Bn.reserved,"regardless"),typedef:new Di("typedef",Bn.reserved,"typedef"),u8:new Di("u8",Bn.reserved,"u8"),u16:new Di("u16",Bn.reserved,"u16"),u64:new Di("u64",Bn.reserved,"u64"),unless:new Di("unless",Bn.reserved,"unless"),using:new Di("using",Bn.reserved,"using"),vec:new Di("vec",Bn.reserved,"vec"),void:new Di("void",Bn.reserved,"void")},Ni.keywords={array:new Di("array",Bn.keyword,"array"),atomic:new Di("atomic",Bn.keyword,"atomic"),bool:new Di("bool",Bn.keyword,"bool"),f32:new Di("f32",Bn.keyword,"f32"),i32:new Di("i32",Bn.keyword,"i32"),mat2x2:new Di("mat2x2",Bn.keyword,"mat2x2"),mat2x3:new Di("mat2x3",Bn.keyword,"mat2x3"),mat2x4:new Di("mat2x4",Bn.keyword,"mat2x4"),mat3x2:new Di("mat3x2",Bn.keyword,"mat3x2"),mat3x3:new Di("mat3x3",Bn.keyword,"mat3x3"),mat3x4:new Di("mat3x4",Bn.keyword,"mat3x4"),mat4x2:new Di("mat4x2",Bn.keyword,"mat4x2"),mat4x3:new Di("mat4x3",Bn.keyword,"mat4x3"),mat4x4:new Di("mat4x4",Bn.keyword,"mat4x4"),ptr:new Di("ptr",Bn.keyword,"ptr"),sampler:new Di("sampler",Bn.keyword,"sampler"),sampler_comparison:new Di("sampler_comparison",Bn.keyword,"sampler_comparison"),struct:new Di("struct",Bn.keyword,"struct"),texture_1d:new Di("texture_1d",Bn.keyword,"texture_1d"),texture_2d:new Di("texture_2d",Bn.keyword,"texture_2d"),texture_2d_array:new Di("texture_2d_array",Bn.keyword,"texture_2d_array"),texture_3d:new Di("texture_3d",Bn.keyword,"texture_3d"),texture_cube:new Di("texture_cube",Bn.keyword,"texture_cube"),texture_cube_array:new Di("texture_cube_array",Bn.keyword,"texture_cube_array"),texture_multisampled_2d:new Di("texture_multisampled_2d",Bn.keyword,"texture_multisampled_2d"),texture_storage_1d:new Di("texture_storage_1d",Bn.keyword,"texture_storage_1d"),texture_storage_2d:new Di("texture_storage_2d",Bn.keyword,"texture_storage_2d"),texture_storage_2d_array:new Di("texture_storage_2d_array",Bn.keyword,"texture_storage_2d_array"),texture_storage_3d:new Di("texture_storage_3d",Bn.keyword,"texture_storage_3d"),texture_depth_2d:new Di("texture_depth_2d",Bn.keyword,"texture_depth_2d"),texture_depth_2d_array:new Di("texture_depth_2d_array",Bn.keyword,"texture_depth_2d_array"),texture_depth_cube:new Di("texture_depth_cube",Bn.keyword,"texture_depth_cube"),texture_depth_cube_array:new Di("texture_depth_cube_array",Bn.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new Di("texture_depth_multisampled_2d",Bn.keyword,"texture_depth_multisampled_2d"),texture_external:new Di("texture_external",Bn.keyword,"texture_external"),u32:new Di("u32",Bn.keyword,"u32"),vec2:new Di("vec2",Bn.keyword,"vec2"),vec3:new Di("vec3",Bn.keyword,"vec3"),vec4:new Di("vec4",Bn.keyword,"vec4"),bitcast:new Di("bitcast",Bn.keyword,"bitcast"),block:new Di("block",Bn.keyword,"block"),break:new Di("break",Bn.keyword,"break"),case:new Di("case",Bn.keyword,"case"),continue:new Di("continue",Bn.keyword,"continue"),continuing:new Di("continuing",Bn.keyword,"continuing"),default:new Di("default",Bn.keyword,"default"),diagnostic:new Di("diagnostic",Bn.keyword,"diagnostic"),discard:new Di("discard",Bn.keyword,"discard"),else:new Di("else",Bn.keyword,"else"),enable:new Di("enable",Bn.keyword,"enable"),fallthrough:new Di("fallthrough",Bn.keyword,"fallthrough"),false:new Di("false",Bn.keyword,"false"),fn:new Di("fn",Bn.keyword,"fn"),for:new Di("for",Bn.keyword,"for"),function:new Di("function",Bn.keyword,"function"),if:new Di("if",Bn.keyword,"if"),let:new Di("let",Bn.keyword,"let"),const:new Di("const",Bn.keyword,"const"),loop:new Di("loop",Bn.keyword,"loop"),while:new Di("while",Bn.keyword,"while"),private:new Di("private",Bn.keyword,"private"),read:new Di("read",Bn.keyword,"read"),read_write:new Di("read_write",Bn.keyword,"read_write"),return:new Di("return",Bn.keyword,"return"),requires:new Di("requires",Bn.keyword,"requires"),storage:new Di("storage",Bn.keyword,"storage"),switch:new Di("switch",Bn.keyword,"switch"),true:new Di("true",Bn.keyword,"true"),alias:new Di("alias",Bn.keyword,"alias"),type:new Di("type",Bn.keyword,"type"),uniform:new Di("uniform",Bn.keyword,"uniform"),var:new Di("var",Bn.keyword,"var"),override:new Di("override",Bn.keyword,"override"),workgroup:new Di("workgroup",Bn.keyword,"workgroup"),write:new Di("write",Bn.keyword,"write"),r8unorm:new Di("r8unorm",Bn.keyword,"r8unorm"),r8snorm:new Di("r8snorm",Bn.keyword,"r8snorm"),r8uint:new Di("r8uint",Bn.keyword,"r8uint"),r8sint:new Di("r8sint",Bn.keyword,"r8sint"),r16uint:new Di("r16uint",Bn.keyword,"r16uint"),r16sint:new Di("r16sint",Bn.keyword,"r16sint"),r16float:new Di("r16float",Bn.keyword,"r16float"),rg8unorm:new Di("rg8unorm",Bn.keyword,"rg8unorm"),rg8snorm:new Di("rg8snorm",Bn.keyword,"rg8snorm"),rg8uint:new Di("rg8uint",Bn.keyword,"rg8uint"),rg8sint:new Di("rg8sint",Bn.keyword,"rg8sint"),r32uint:new Di("r32uint",Bn.keyword,"r32uint"),r32sint:new Di("r32sint",Bn.keyword,"r32sint"),r32float:new Di("r32float",Bn.keyword,"r32float"),rg16uint:new Di("rg16uint",Bn.keyword,"rg16uint"),rg16sint:new Di("rg16sint",Bn.keyword,"rg16sint"),rg16float:new Di("rg16float",Bn.keyword,"rg16float"),rgba8unorm:new Di("rgba8unorm",Bn.keyword,"rgba8unorm"),rgba8unorm_srgb:new Di("rgba8unorm_srgb",Bn.keyword,"rgba8unorm_srgb"),rgba8snorm:new Di("rgba8snorm",Bn.keyword,"rgba8snorm"),rgba8uint:new Di("rgba8uint",Bn.keyword,"rgba8uint"),rgba8sint:new Di("rgba8sint",Bn.keyword,"rgba8sint"),bgra8unorm:new Di("bgra8unorm",Bn.keyword,"bgra8unorm"),bgra8unorm_srgb:new Di("bgra8unorm_srgb",Bn.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new Di("rgb10a2unorm",Bn.keyword,"rgb10a2unorm"),rg11b10float:new Di("rg11b10float",Bn.keyword,"rg11b10float"),rg32uint:new Di("rg32uint",Bn.keyword,"rg32uint"),rg32sint:new Di("rg32sint",Bn.keyword,"rg32sint"),rg32float:new Di("rg32float",Bn.keyword,"rg32float"),rgba16uint:new Di("rgba16uint",Bn.keyword,"rgba16uint"),rgba16sint:new Di("rgba16sint",Bn.keyword,"rgba16sint"),rgba16float:new Di("rgba16float",Bn.keyword,"rgba16float"),rgba32uint:new Di("rgba32uint",Bn.keyword,"rgba32uint"),rgba32sint:new Di("rgba32sint",Bn.keyword,"rgba32sint"),rgba32float:new Di("rgba32float",Bn.keyword,"rgba32float"),static_assert:new Di("static_assert",Bn.keyword,"static_assert")},Ni.tokens={decimal_float_literal:new Di("decimal_float_literal",Bn.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new Di("hex_float_literal",Bn.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new Di("int_literal",Bn.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new Di("uint_literal",Bn.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new Di("name",Bn.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new Di("ident",Bn.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new Di("and",Bn.token,"&"),and_and:new Di("and_and",Bn.token,"&&"),arrow:new Di("arrow ",Bn.token,"->"),attr:new Di("attr",Bn.token,"@"),forward_slash:new Di("forward_slash",Bn.token,"/"),bang:new Di("bang",Bn.token,"!"),bracket_left:new Di("bracket_left",Bn.token,"["),bracket_right:new Di("bracket_right",Bn.token,"]"),brace_left:new Di("brace_left",Bn.token,"{"),brace_right:new Di("brace_right",Bn.token,"}"),colon:new Di("colon",Bn.token,":"),comma:new Di("comma",Bn.token,","),equal:new Di("equal",Bn.token,"="),equal_equal:new Di("equal_equal",Bn.token,"=="),not_equal:new Di("not_equal",Bn.token,"!="),greater_than:new Di("greater_than",Bn.token,">"),greater_than_equal:new Di("greater_than_equal",Bn.token,">="),shift_right:new Di("shift_right",Bn.token,">>"),less_than:new Di("less_than",Bn.token,"<"),less_than_equal:new Di("less_than_equal",Bn.token,"<="),shift_left:new Di("shift_left",Bn.token,"<<"),modulo:new Di("modulo",Bn.token,"%"),minus:new Di("minus",Bn.token,"-"),minus_minus:new Di("minus_minus",Bn.token,"--"),period:new Di("period",Bn.token,"."),plus:new Di("plus",Bn.token,"+"),plus_plus:new Di("plus_plus",Bn.token,"++"),or:new Di("or",Bn.token,"|"),or_or:new Di("or_or",Bn.token,"||"),paren_left:new Di("paren_left",Bn.token,"("),paren_right:new Di("paren_right",Bn.token,")"),semicolon:new Di("semicolon",Bn.token,";"),star:new Di("star",Bn.token,"*"),tilde:new Di("tilde",Bn.token,"~"),underscore:new Di("underscore",Bn.token,"_"),xor:new Di("xor",Bn.token,"^"),plus_equal:new Di("plus_equal",Bn.token,"+="),minus_equal:new Di("minus_equal",Bn.token,"-="),times_equal:new Di("times_equal",Bn.token,"*="),division_equal:new Di("division_equal",Bn.token,"/="),modulo_equal:new Di("modulo_equal",Bn.token,"%="),and_equal:new Di("and_equal",Bn.token,"&="),or_equal:new Di("or_equal",Bn.token,"|="),xor_equal:new Di("xor_equal",Bn.token,"^="),shift_right_equal:new Di("shift_right_equal",Bn.token,">>="),shift_left_equal:new Di("shift_left_equal",Bn.token,"<<=")},Ni.simpleTokens={"@":Fn.tokens.attr,"{":Fn.tokens.brace_left,"}":Fn.tokens.brace_right,":":Fn.tokens.colon,",":Fn.tokens.comma,"(":Fn.tokens.paren_left,")":Fn.tokens.paren_right,";":Fn.tokens.semicolon},Ni.literalTokens={"&":Fn.tokens.and,"&&":Fn.tokens.and_and,"->":Fn.tokens.arrow,"/":Fn.tokens.forward_slash,"!":Fn.tokens.bang,"[":Fn.tokens.bracket_left,"]":Fn.tokens.bracket_right,"=":Fn.tokens.equal,"==":Fn.tokens.equal_equal,"!=":Fn.tokens.not_equal,">":Fn.tokens.greater_than,">=":Fn.tokens.greater_than_equal,">>":Fn.tokens.shift_right,"<":Fn.tokens.less_than,"<=":Fn.tokens.less_than_equal,"<<":Fn.tokens.shift_left,"%":Fn.tokens.modulo,"-":Fn.tokens.minus,"--":Fn.tokens.minus_minus,".":Fn.tokens.period,"+":Fn.tokens.plus,"++":Fn.tokens.plus_plus,"|":Fn.tokens.or,"||":Fn.tokens.or_or,"*":Fn.tokens.star,"~":Fn.tokens.tilde,_:Fn.tokens.underscore,"^":Fn.tokens.xor,"+=":Fn.tokens.plus_equal,"-=":Fn.tokens.minus_equal,"*=":Fn.tokens.times_equal,"/=":Fn.tokens.division_equal,"%=":Fn.tokens.modulo_equal,"&=":Fn.tokens.and_equal,"|=":Fn.tokens.or_equal,"^=":Fn.tokens.xor_equal,">>=":Fn.tokens.shift_right_equal,"<<=":Fn.tokens.shift_left_equal},Ni.regexTokens={decimal_float_literal:Fn.tokens.decimal_float_literal,hex_float_literal:Fn.tokens.hex_float_literal,int_literal:Fn.tokens.int_literal,uint_literal:Fn.tokens.uint_literal,ident:Fn.tokens.ident},Ni.storage_class=[Fn.keywords.function,Fn.keywords.private,Fn.keywords.workgroup,Fn.keywords.uniform,Fn.keywords.storage],Ni.access_mode=[Fn.keywords.read,Fn.keywords.write,Fn.keywords.read_write],Ni.sampler_type=[Fn.keywords.sampler,Fn.keywords.sampler_comparison],Ni.sampled_texture_type=[Fn.keywords.texture_1d,Fn.keywords.texture_2d,Fn.keywords.texture_2d_array,Fn.keywords.texture_3d,Fn.keywords.texture_cube,Fn.keywords.texture_cube_array],Ni.multisampled_texture_type=[Fn.keywords.texture_multisampled_2d],Ni.storage_texture_type=[Fn.keywords.texture_storage_1d,Fn.keywords.texture_storage_2d,Fn.keywords.texture_storage_2d_array,Fn.keywords.texture_storage_3d],Ni.depth_texture_type=[Fn.keywords.texture_depth_2d,Fn.keywords.texture_depth_2d_array,Fn.keywords.texture_depth_cube,Fn.keywords.texture_depth_cube_array,Fn.keywords.texture_depth_multisampled_2d],Ni.texture_external_type=[Fn.keywords.texture_external],Ni.any_texture_type=[...Fn.sampled_texture_type,...Fn.multisampled_texture_type,...Fn.storage_texture_type,...Fn.depth_texture_type,...Fn.texture_external_type],Ni.texel_format=[Fn.keywords.r8unorm,Fn.keywords.r8snorm,Fn.keywords.r8uint,Fn.keywords.r8sint,Fn.keywords.r16uint,Fn.keywords.r16sint,Fn.keywords.r16float,Fn.keywords.rg8unorm,Fn.keywords.rg8snorm,Fn.keywords.rg8uint,Fn.keywords.rg8sint,Fn.keywords.r32uint,Fn.keywords.r32sint,Fn.keywords.r32float,Fn.keywords.rg16uint,Fn.keywords.rg16sint,Fn.keywords.rg16float,Fn.keywords.rgba8unorm,Fn.keywords.rgba8unorm_srgb,Fn.keywords.rgba8snorm,Fn.keywords.rgba8uint,Fn.keywords.rgba8sint,Fn.keywords.bgra8unorm,Fn.keywords.bgra8unorm_srgb,Fn.keywords.rgb10a2unorm,Fn.keywords.rg11b10float,Fn.keywords.rg32uint,Fn.keywords.rg32sint,Fn.keywords.rg32float,Fn.keywords.rgba16uint,Fn.keywords.rgba16sint,Fn.keywords.rgba16float,Fn.keywords.rgba32uint,Fn.keywords.rgba32sint,Fn.keywords.rgba32float],Ni.const_literal=[Fn.tokens.int_literal,Fn.tokens.uint_literal,Fn.tokens.decimal_float_literal,Fn.tokens.hex_float_literal,Fn.keywords.true,Fn.keywords.false],Ni.literal_or_ident=[Fn.tokens.ident,Fn.tokens.int_literal,Fn.tokens.uint_literal,Fn.tokens.decimal_float_literal,Fn.tokens.hex_float_literal,Fn.tokens.name],Ni.element_count_expression=[Fn.tokens.int_literal,Fn.tokens.uint_literal,Fn.tokens.ident],Ni.template_types=[Fn.keywords.vec2,Fn.keywords.vec3,Fn.keywords.vec4,Fn.keywords.mat2x2,Fn.keywords.mat2x3,Fn.keywords.mat2x4,Fn.keywords.mat3x2,Fn.keywords.mat3x3,Fn.keywords.mat3x4,Fn.keywords.mat4x2,Fn.keywords.mat4x3,Fn.keywords.mat4x4,Fn.keywords.atomic,Fn.keywords.bitcast,...Fn.any_texture_type],Ni.attribute_name=[Fn.tokens.ident,Fn.keywords.block,Fn.keywords.diagnostic],Ni.assignment_operators=[Fn.tokens.equal,Fn.tokens.plus_equal,Fn.tokens.minus_equal,Fn.tokens.times_equal,Fn.tokens.division_equal,Fn.tokens.modulo_equal,Fn.tokens.and_equal,Fn.tokens.or_equal,Fn.tokens.xor_equal,Fn.tokens.shift_right_equal,Fn.tokens.shift_left_equal],Ni.increment_operators=[Fn.tokens.plus_plus,Fn.tokens.minus_minus];class Fi{constructor(t,e,n,i,s){this.type=t,this.lexeme=e,this.line=n,this.start=i,this.end=s}toString(){return this.lexeme}isTemplateType(){return-1!=Ni.template_types.indexOf(this.type)}isArrayType(){return this.type==Ni.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class Bi{constructor(t){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=null!=t?t:""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new Fi(Ni.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let t=this._advance();if("\n"==t)return this._line++,!0;if(this._isWhitespace(t))return!0;if("/"==t){if("/"==this._peekAhead()){for(;"\n"!=t;){if(this._isAtEnd())return!0;t=this._advance()}return this._line++,!0}if("*"==this._peekAhead()){this._advance();let e=1;for(;e>0;){if(this._isAtEnd())return!0;if(t=this._advance(),"\n"==t)this._line++;else if("*"==t){if("/"==this._peekAhead()&&(this._advance(),e--,0==e))return!0}else"/"==t&&"*"==this._peekAhead()&&(this._advance(),e++)}return!0}}const e=Ni.simpleTokens[t];if(e)return this._addToken(e),!0;let n=Ni.none;const i=this._isAlpha(t),s="_"===t;if(this._isAlphaNumeric(t)){let e=this._peekAhead();for(;this._isAlphaNumeric(e);)t+=this._advance(),e=this._peekAhead()}if(i){const e=Ni.keywords[t];if(e)return this._addToken(e),!0}if(i||s)return this._addToken(Ni.tokens.ident),!0;for(;;){let e=this._findType(t);const i=this._peekAhead();if("-"==t&&this._tokens.length>0){if("="==i)return this._current++,t+=i,this._addToken(Ni.tokens.minus_equal),!0;if("-"==i)return this._current++,t+=i,this._addToken(Ni.tokens.minus_minus),!0;const n=this._tokens.length-1;if((-1!=Ni.literal_or_ident.indexOf(this._tokens[n].type)||this._tokens[n].type==Ni.tokens.paren_right)&&">"!=i)return this._addToken(e),!0}if(">"==t&&(">"==i||"="==i)){let t=!1,n=this._tokens.length-1;for(let e=0;e<5&&n>=0&&-1===Ni.assignment_operators.indexOf(this._tokens[n].type);++e,--n)if(this._tokens[n].type===Ni.tokens.less_than){n>0&&this._tokens[n-1].isArrayOrTemplateType()&&(t=!0);break}if(t)return this._addToken(e),!0}if(e===Ni.none){let i=t,s=0;const r=2;for(let t=0;t<r;++t)if(i+=this._peekAhead(t),e=this._findType(i),e!==Ni.none){s=t;break}if(e===Ni.none)return n!==Ni.none&&(this._current--,this._addToken(n),!0);t=i,this._current+=s+1}if(n=e,this._isAtEnd())break;t+=this._advance()}return n!==Ni.none&&(this._addToken(n),!0)}_findType(t){for(const e in Ni.regexTokens){const n=Ni.regexTokens[e];if(this._match(t,n.rule))return n}return Ni.literalTokens[t]||Ni.none}_match(t,e){const n=e.exec(t);return n&&0==n.index&&n[0]==t}_isAtEnd(){return this._current>=this._source.length}_isAlpha(t){return!this._isNumeric(t)&&!this._isWhitespace(t)&&"_"!==t&&"."!==t&&"("!==t&&")"!==t&&"["!==t&&"]"!==t&&"{"!==t&&"}"!==t&&","!==t&&";"!==t&&":"!==t&&"="!==t&&"!"!==t&&"<"!==t&&">"!==t&&"+"!==t&&"-"!==t&&"*"!==t&&"/"!==t&&"%"!==t&&"&"!==t&&"|"!==t&&"^"!==t&&"~"!==t&&"@"!==t&&"#"!==t&&"?"!==t&&"'"!==t&&"`"!==t&&'"'!==t&&"\\"!==t&&"\n"!==t&&"\r"!==t&&"\t"!==t&&"\0"!==t}_isNumeric(t){return t>="0"&&t<="9"}_isAlphaNumeric(t){return this._isAlpha(t)||this._isNumeric(t)||"_"===t}_isWhitespace(t){return" "==t||"\t"==t||"\r"==t}_advance(t=0){let e=this._source[this._current];return t=t||0,t++,this._current+=t,e}_peekAhead(t=0){return this._current+(t=t||0)>=this._source.length?"\0":this._source[this._current+t]}_addToken(t){const e=this._source.substring(this._start,this._current);this._tokens.push(new Fi(t,e,this._line,this._start,this._current))}}function $i(t){return Array.isArray(t)||(null==t?void 0:t.buffer)instanceof ArrayBuffer}const Ui=new Float32Array(1),zi=new Uint32Array(Ui.buffer),ji=new Uint32Array(Ui.buffer),Gi=new Int32Array(1),Wi=new Float32Array(Gi.buffer),Vi=new Uint32Array(Gi.buffer),Hi=new Uint32Array(1),Xi=new Float32Array(Hi.buffer),Zi=new Int32Array(Hi.buffer);function Ki(t,e,n){if(e===n)return t;if("f32"===e){if("i32"===n||"x32"===n)return Ui[0]=t,zi[0];if("u32"===n)return Ui[0]=t,ji[0]}else if("i32"===e||"x32"===e){if("f32"===n)return Gi[0]=t,Wi[0];if("u32"===n)return Gi[0]=t,Vi[0]}else if("u32"===e){if("f32"===n)return Hi[0]=t,Xi[0];if("i32"===n||"x32"===n)return Hi[0]=t,Zi[0]}return console.error(`Unsupported cast from ${e} to ${n}`),t}class qi{constructor(t){this.resources=null,this.inUse=!1,this.info=null,this.node=t}}class Yi{constructor(t,e){this.align=t,this.size=e}}class Ji{constructor(){this.uniforms=[],this.storage=[],this.textures=[],this.samplers=[],this.aliases=[],this.overrides=[],this.structs=[],this.entry=new ln,this.functions=[],this._types=new Map,this._functions=new Map}_isStorageTexture(t){return"texture_storage_1d"==t.name||"texture_storage_2d"==t.name||"texture_storage_2d_array"==t.name||"texture_storage_3d"==t.name}updateAST(t){for(const e of t)e instanceof Sn&&this._functions.set(e.name,new qi(e));for(const e of t)if(e instanceof ei){const t=this.getTypeInfo(e,null);t instanceof qe&&this.structs.push(t)}for(const e of t)if(e instanceof Kn)this.aliases.push(this._getAliasInfo(e));else{if(e instanceof On){const t=e,n=this._getAttributeNum(t.attributes,"id",0),i=null!=t.type?this.getTypeInfo(t.type,t.attributes):null;this.overrides.push(new on(t.name,i,t.attributes,n));continue}if(this._isUniformVar(e)){const t=e,n=this._getAttributeNum(t.attributes,"group",0),i=this._getAttributeNum(t.attributes,"binding",0),s=this.getTypeInfo(t.type,t.attributes),r=new en(t.name,s,n,i,t.attributes,tn.Uniform,t.access);r.access||(r.access="read"),this.uniforms.push(r);continue}if(this._isStorageVar(e)){const t=e,n=this._getAttributeNum(t.attributes,"group",0),i=this._getAttributeNum(t.attributes,"binding",0),s=this.getTypeInfo(t.type,t.attributes),r=this._isStorageTexture(s),o=new en(t.name,s,n,i,t.attributes,r?tn.StorageTexture:tn.Storage,t.access);o.access||(o.access="read"),this.storage.push(o);continue}if(this._isTextureVar(e)){const t=e,n=this._getAttributeNum(t.attributes,"group",0),i=this._getAttributeNum(t.attributes,"binding",0),s=this.getTypeInfo(t.type,t.attributes),r=this._isStorageTexture(s),o=new en(t.name,s,n,i,t.attributes,r?tn.StorageTexture:tn.Texture,t.access);o.access||(o.access="read"),r?this.storage.push(o):this.textures.push(o);continue}if(this._isSamplerVar(e)){const t=e,n=this._getAttributeNum(t.attributes,"group",0),i=this._getAttributeNum(t.attributes,"binding",0),s=this.getTypeInfo(t.type,t.attributes),r=new en(t.name,s,n,i,t.attributes,tn.Sampler,t.access);this.samplers.push(r);continue}}for(const e of t)if(e instanceof Sn){const t=this._getAttribute(e,"vertex"),n=this._getAttribute(e,"fragment"),i=this._getAttribute(e,"compute"),s=t||n||i,r=new cn(e.name,null==s?void 0:s.name,e.attributes);r.attributes=e.attributes,r.startLine=e.startLine,r.endLine=e.endLine,this.functions.push(r),this._functions.get(e.name).info=r,s&&(this._functions.get(e.name).inUse=!0,r.inUse=!0,r.resources=this._findResources(e,!!s),r.inputs=this._getInputs(e.args),r.outputs=this._getOutputs(e.returnType),this.entry[s.name].push(r)),r.arguments=e.args.map((t=>new an(t.name,this.getTypeInfo(t.type,t.attributes),t.attributes))),r.returnType=e.returnType?this.getTypeInfo(e.returnType,e.attributes):null;continue}for(const t of this._functions.values())t.info&&(t.info.inUse=t.inUse,this._addCalls(t.node,t.info.calls));for(const t of this._functions.values())t.node.search((e=>{var n,i,s;if(e instanceof Ai){if(e.value)if($i(e.value))for(const i of e.value)for(const e of this.overrides)i===e.name&&(null===(n=t.info)||void 0===n||n.overrides.push(e));else for(const n of this.overrides)e.value===n.name&&(null===(i=t.info)||void 0===i||i.overrides.push(n))}else if(e instanceof hi)for(const n of this.overrides)e.name===n.name&&(null===(s=t.info)||void 0===s||s.overrides.push(n))}));for(const t of this.uniforms)this._markStructsInUse(t.type);for(const t of this.storage)this._markStructsInUse(t.type)}getFunctionInfo(t){for(const e of this.functions)if(e.name==t)return e;return null}getStructInfo(t){for(const e of this.structs)if(e.name==t)return e;return null}getOverrideInfo(t){for(const e of this.overrides)if(e.name==t)return e;return null}_markStructsInUse(t){if(t)if(t.isStruct){if(t.inUse=!0,t.members)for(const e of t.members)this._markStructsInUse(e.type)}else if(t.isArray)this._markStructsInUse(t.format);else if(t.isTemplate)t.format&&this._markStructsInUse(t.format);else{const e=this._getAlias(t.name);e&&this._markStructsInUse(e)}}_addCalls(t,e){var n;for(const i of t.calls){const t=null===(n=this._functions.get(i.name))||void 0===n?void 0:n.info;t&&e.add(t)}}findResource(t,e,n){if(n){for(const i of this.entry.compute)if(i.name===n)for(const n of i.resources)if(n.group==t&&n.binding==e)return n;for(const i of this.entry.vertex)if(i.name===n)for(const n of i.resources)if(n.group==t&&n.binding==e)return n;for(const i of this.entry.fragment)if(i.name===n)for(const n of i.resources)if(n.group==t&&n.binding==e)return n}for(const n of this.uniforms)if(n.group==t&&n.binding==e)return n;for(const n of this.storage)if(n.group==t&&n.binding==e)return n;for(const n of this.textures)if(n.group==t&&n.binding==e)return n;for(const n of this.samplers)if(n.group==t&&n.binding==e)return n;return null}_findResource(t){for(const e of this.uniforms)if(e.name==t)return e;for(const e of this.storage)if(e.name==t)return e;for(const e of this.textures)if(e.name==t)return e;for(const e of this.samplers)if(e.name==t)return e;return null}_markStructsFromAST(t){const e=this.getTypeInfo(t,null);this._markStructsInUse(e)}_findResources(t,e){const n=[],i=this,s=[];return t.search((r=>{if(r instanceof xn)s.push({});else if(r instanceof En)s.pop();else if(r instanceof Ln){const t=r;e&&null!==t.type&&this._markStructsFromAST(t.type),s.length>0&&(s[s.length-1][t.name]=t)}else if(r instanceof ci)e&&null!==r.type&&this._markStructsFromAST(r.type);else if(r instanceof In){const t=r;e&&null!==t.type&&this._markStructsFromAST(t.type),s.length>0&&(s[s.length-1][t.name]=t)}else if(r instanceof hi){if(s.length>0&&s[s.length-1][r.name])return;const t=i._findResource(r.name);t&&n.push(t)}else if(r instanceof li){const s=i._functions.get(r.name);s&&(e&&(s.inUse=!0),t.calls.add(s.node),null===s.resources&&(s.resources=i._findResources(s.node,e)),n.push(...s.resources))}else if(r instanceof zn){const s=i._functions.get(r.name);s&&(e&&(s.inUse=!0),t.calls.add(s.node),null===s.resources&&(s.resources=i._findResources(s.node,e)),n.push(...s.resources))}})),[...new Map(n.map((t=>[t.name,t]))).values()]}getBindGroups(){const t=[];function e(e,n){e>=t.length&&(t.length=e+1),void 0===t[e]&&(t[e]=[]),n>=t[e].length&&(t[e].length=n+1)}for(const n of this.uniforms)e(n.group,n.binding),t[n.group][n.binding]=n;for(const n of this.storage)e(n.group,n.binding),t[n.group][n.binding]=n;for(const n of this.textures)e(n.group,n.binding),t[n.group][n.binding]=n;for(const n of this.samplers)e(n.group,n.binding),t[n.group][n.binding]=n;return t}_getOutputs(t,e){if(void 0===e&&(e=[]),t instanceof ei)this._getStructOutputs(t,e);else{const n=this._getOutputInfo(t);null!==n&&e.push(n)}return e}_getStructOutputs(t,e){for(const n of t.members)if(n.type instanceof ei)this._getStructOutputs(n.type,e);else{const t=this._getAttribute(n,"location")||this._getAttribute(n,"builtin");if(null!==t){const i=this.getTypeInfo(n.type,n.type.attributes),s=this._parseInt(t.value),r=new rn(n.name,i,t.name,s);e.push(r)}}}_getOutputInfo(t){const e=this._getAttribute(t,"location")||this._getAttribute(t,"builtin");if(null!==e){const n=this.getTypeInfo(t,t.attributes),i=this._parseInt(e.value);return new rn("",n,e.name,i)}return null}_getInputs(t,e){void 0===e&&(e=[]);for(const n of t)if(n.type instanceof ei)this._getStructInputs(n.type,e);else{const t=this._getInputInfo(n);null!==t&&e.push(t)}return e}_getStructInputs(t,e){for(const n of t.members)if(n.type instanceof ei)this._getStructInputs(n.type,e);else{const t=this._getInputInfo(n);null!==t&&e.push(t)}}_getInputInfo(t){const e=this._getAttribute(t,"location")||this._getAttribute(t,"builtin");if(null!==e){const n=this._getAttribute(t,"interpolation"),i=this.getTypeInfo(t.type,t.attributes),s=this._parseInt(e.value),r=new sn(t.name,i,e.name,s);return null!==n&&(r.interpolation=this._parseString(n.value)),r}return null}_parseString(t){return t instanceof Array&&(t=t[0]),t}_parseInt(t){t instanceof Array&&(t=t[0]);const e=parseInt(t);return isNaN(e)?t:e}_getAlias(t){for(const e of this.aliases)if(e.name==t)return e.type;return null}_getAliasInfo(t){return new nn(t.name,this.getTypeInfo(t.type,null))}getTypeInfoByName(t){for(const e of this.structs)if(e.name==t)return e;for(const e of this.aliases)if(e.name==t)return e.type;return null}getTypeInfo(t,e=null){if(this._types.has(t))return this._types.get(t);if(t instanceof ii){const n=t.type?this.getTypeInfo(t.type,t.attributes):null,i=new Je(t.name,n,e);return this._types.set(t,i),this._updateTypeInfo(i),i}if(t instanceof si){const n=t,i=n.format?this.getTypeInfo(n.format,n.attributes):null,s=new Ye(n.name,e);return s.format=i,s.count=n.count,this._types.set(t,s),this._updateTypeInfo(s),s}if(t instanceof ei){const n=t,i=new qe(n.name,e);i.startLine=n.startLine,i.endLine=n.endLine;for(const t of n.members){const e=this.getTypeInfo(t.type,t.attributes);i.members.push(new Ke(t.name,e,t.attributes))}return this._types.set(t,i),this._updateTypeInfo(i),i}if(t instanceof ri){const n=t,i=n.format?n.format instanceof Qn?this.getTypeInfo(n.format,null):new Ze(n.format,null):null,s=new Qe(n.name,i,e,n.access);return this._types.set(t,s),this._updateTypeInfo(s),s}if(t instanceof ni){const n=t,i=n.format?this.getTypeInfo(n.format,null):null,s=new Qe(n.name,i,e,n.access);return this._types.set(t,s),this._updateTypeInfo(s),s}const n=new Ze(t.name,e);return this._types.set(t,n),this._updateTypeInfo(n),n}_updateTypeInfo(t){var e,n,i;const s=this._getTypeSize(t);if(t.size=null!==(e=null==s?void 0:s.size)&&void 0!==e?e:0,t instanceof Ye&&t.format){const e=this._getTypeSize(t.format);t.stride=Math.max(null!==(n=null==e?void 0:e.size)&&void 0!==n?n:0,null!==(i=null==e?void 0:e.align)&&void 0!==i?i:0),this._updateTypeInfo(t.format)}t instanceof Je&&this._updateTypeInfo(t.format),t instanceof qe&&this._updateStructInfo(t)}_updateStructInfo(t){let e=0,n=0,i=0,s=0;for(let r=0,o=t.members.length;r<o;++r){const o=t.members[r],a=this._getTypeSize(o);if(!a)continue;this._getAlias(o.type.name);const c=a.align,l=a.size;e=this._roundUp(c,e+n),n=l,i=e,s=Math.max(s,c),o.offset=e,o.size=l,this._updateTypeInfo(o.type)}t.size=this._roundUp(s,i+n),t.align=s}_getTypeSize(t){var e,n;if(null==t)return null;const i=this._getAttributeNum(t.attributes,"size",0),s=this._getAttributeNum(t.attributes,"align",0);if(t instanceof Ke&&(t=t.type),t instanceof Ze){const e=this._getAlias(t.name);null!==e&&(t=e)}{const n=Ji._typeInfo[t.name];if(void 0!==n){const r="f16"===(null===(e=t.format)||void 0===e?void 0:e.name)?2:1;return new Yi(Math.max(s,n.align/r),Math.max(i,n.size/r))}}{const e=Ji._typeInfo[t.name.substring(0,t.name.length-1)];if(e){const n="h"===t.name[t.name.length-1]?2:1;return new Yi(Math.max(s,e.align/n),Math.max(i,e.size/n))}}if(t instanceof Ye){let e=t,r=8,o=8;const a=this._getTypeSize(e.format);return null!==a&&(o=a.size,r=a.align),o=e.count*this._getAttributeNum(null!==(n=null==t?void 0:t.attributes)&&void 0!==n?n:null,"stride",this._roundUp(r,o)),i&&(o=i),new Yi(Math.max(s,r),Math.max(i,o))}if(t instanceof qe){let e=0,n=0,r=0,o=0,a=0;for(const n of t.members){const t=this._getTypeSize(n.type);null!==t&&(e=Math.max(t.align,e),r=this._roundUp(t.align,r+o),o=t.size,a=r)}return n=this._roundUp(e,a+o),new Yi(Math.max(s,e),Math.max(i,n))}return null}_isUniformVar(t){return t instanceof Ln&&"uniform"==t.storage}_isStorageVar(t){return t instanceof Ln&&"storage"==t.storage}_isTextureVar(t){return t instanceof Ln&&null!==t.type&&-1!=Ji._textureTypes.indexOf(t.type.name)}_isSamplerVar(t){return t instanceof Ln&&null!==t.type&&-1!=Ji._samplerTypes.indexOf(t.type.name)}_getAttribute(t,e){if(!t||!t.attributes)return null;const n=t.attributes;for(let t of n)if(t.name==e)return t;return null}_getAttributeNum(t,e,n){if(null===t)return n;for(let i of t)if(i.name==e){let t=null!==i&&null!==i.value?i.value:n;return t instanceof Array&&(t=t[0]),"number"==typeof t?t:"string"==typeof t?parseInt(t):n}return n}_roundUp(t,e){return Math.ceil(e/t)*t}}Ji._typeInfo={f16:{align:2,size:2},i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},atomic:{align:4,size:4},vec2:{align:8,size:8},vec3:{align:16,size:12},vec4:{align:16,size:16},mat2x2:{align:8,size:16},mat3x2:{align:8,size:24},mat4x2:{align:8,size:32},mat2x3:{align:16,size:32},mat3x3:{align:16,size:48},mat4x3:{align:16,size:64},mat2x4:{align:16,size:32},mat3x4:{align:16,size:48},mat4x4:{align:16,size:64}},Ji._textureTypes=Ni.any_texture_type.map((t=>t.name)),Ji._samplerTypes=Ni.sampler_type.map((t=>t.name));let Qi=0;class ts{constructor(t,e,n){this.id=Qi++,this.name=t,this.value=e,this.node=n}clone(){return new ts(this.name,this.value,this.node)}}class es{constructor(t){this.id=Qi++,this.name=t.name,this.node=t}clone(){return new es(this.node)}}class ns{constructor(t){this.parent=null,this.variables=new Map,this.functions=new Map,this.currentFunctionName="",this.id=Qi++,t&&(this.parent=t,this.currentFunctionName=t.currentFunctionName)}getVariable(t){var e;return this.variables.has(t)?null!==(e=this.variables.get(t))&&void 0!==e?e:null:this.parent?this.parent.getVariable(t):null}getFunction(t){var e;return this.functions.has(t)?null!==(e=this.functions.get(t))&&void 0!==e?e:null:this.parent?this.parent.getFunction(t):null}createVariable(t,e,n){this.variables.set(t,new ts(t,e,null!=n?n:null))}setVariable(t,e,n){const i=this.getVariable(t);null!==i?i.value=e:this.createVariable(t,e,n)}getVariableValue(t){var e;const n=this.getVariable(t);return null!==(e=null==n?void 0:n.value)&&void 0!==e?e:null}clone(){return new ns(this)}}class is{evalExpression(t,e){return null}getTypeInfo(t){return null}getVariableName(t,e){return""}}class ss{constructor(t){this.exec=t}getTypeInfo(t){return this.exec.getTypeInfo(t)}All(t,e){const n=this.exec.evalExpression(t.args[0],e);let i=!0;if(n instanceof Li)return n.data.forEach((t=>{t||(i=!1)})),new Mi(i?1:0,this.getTypeInfo("bool"));throw new Error(`All() expects a vector argument. Line ${t.line}`)}Any(t,e){const n=this.exec.evalExpression(t.args[0],e);if(n instanceof Li){const t=n.data.some((t=>t));return new Mi(t?1:0,this.getTypeInfo("bool"))}throw new Error(`Any() expects a vector argument. Line ${t.line}`)}Select(t,e){const n=this.exec.evalExpression(t.args[2],e);if(!(n instanceof Mi))throw new Error(`Select() expects a bool condition. Line ${t.line}`);return this.exec.evalExpression(n.value?t.args[1]:t.args[0],e)}ArrayLength(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.evalExpression(n,e);return new Mi(i instanceof Ii&&0===i.typeInfo.size?i.buffer.byteLength/i.typeInfo.stride:i.typeInfo.size,this.getTypeInfo("u32"))}Abs(t,e){const n=this.exec.evalExpression(t.args[0],e);if(n instanceof Li)return new Li(n.data.map((t=>Math.abs(t))),n.typeInfo);const i=n;return new Mi(Math.abs(i.value),i.typeInfo)}Acos(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.acos(t))),n.typeInfo):new Mi(Math.acos(n.value),n.typeInfo)}Acosh(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.acosh(t))),n.typeInfo):new Mi(Math.acosh(n.value),n.typeInfo)}Asin(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.asin(t))),n.typeInfo):new Mi(Math.asin(n.value),n.typeInfo)}Asinh(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.asinh(t))),n.typeInfo):new Mi(Math.asinh(n.value),n.typeInfo)}Atan(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.atan(t))),n.typeInfo):new Mi(Math.atan(n.value),n.typeInfo)}Atanh(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.atanh(t))),n.typeInfo):new Mi(Math.atanh(n.value),n.typeInfo)}Atan2(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return n instanceof Li&&i instanceof Li?new Li(n.data.map(((t,e)=>Math.atan2(t,i.data[e]))),n.typeInfo):new Mi(Math.atan2(n.value,i.value),n.typeInfo)}Ceil(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.ceil(t))),n.typeInfo):new Mi(Math.ceil(n.value),n.typeInfo)}_clamp(t,e,n){return Math.min(Math.max(t,e),n)}Clamp(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);return n instanceof Li&&i instanceof Li&&s instanceof Li?new Li(n.data.map(((t,e)=>this._clamp(t,i.data[e],s.data[e]))),n.typeInfo):new Mi(this._clamp(n.value,i.value,s.value),n.typeInfo)}Cos(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.cos(t))),n.typeInfo):new Mi(Math.cos(n.value),n.typeInfo)}Cosh(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.cosh(t))),n.typeInfo):new Mi(Math.cos(n.value),n.typeInfo)}CountLeadingZeros(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.clz32(t))),n.typeInfo):new Mi(Math.clz32(n.value),n.typeInfo)}_countOneBits(t){let e=0;for(;0!==t;)1&t&&e++,t>>=1;return e}CountOneBits(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>this._countOneBits(t))),n.typeInfo):new Mi(this._countOneBits(n.value),n.typeInfo)}_countTrailingZeros(t){if(0===t)return 32;let e=0;for(;!(1&t);)t>>=1,e++;return e}CountTrailingZeros(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>this._countTrailingZeros(t))),n.typeInfo):new Mi(this._countTrailingZeros(n.value),n.typeInfo)}Cross(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);if(n instanceof Li&&i instanceof Li){if(3!==n.data.length||3!==i.data.length)return console.error(`Cross() expects 3D vectors. Line ${t.line}`),null;const e=n.data,s=i.data;return new Li([e[1]*s[2]-s[1]*e[2],e[2]*s[0]-s[2]*e[0],e[0]*s[1]-s[0]*e[1]],n.typeInfo)}return console.error(`Cross() expects vector arguments. Line ${t.line}`),null}Degrees(t,e){const n=this.exec.evalExpression(t.args[0],e),i=180/Math.PI;return n instanceof Li?new Li(n.data.map((t=>t*i)),n.typeInfo):new Mi(n.value*i,this.getTypeInfo("f32"))}Determinant(t,e){const n=this.exec.evalExpression(t.args[0],e);if(n instanceof Oi){const t=n.data,e=n.typeInfo.getTypeName(),i=e.endsWith("h")?this.getTypeInfo("f16"):this.getTypeInfo("f32");if("mat2x2"===e||"mat2x2f"===e||"mat2x2h"===e)return new Mi(t[0]*t[3]-t[1]*t[2],i);if("mat2x3"===e||"mat2x3f"===e||"mat2x3h"===e)return new Mi(t[0]*(t[4]*t[8]-t[5]*t[7])-t[1]*(t[3]*t[8]-t[5]*t[6])+t[2]*(t[3]*t[7]-t[4]*t[6]),i);if("mat2x4"===e||"mat2x4f"===e||"mat2x4h"===e)console.error(`TODO: Determinant for ${e}`);else if("mat3x2"===e||"mat3x2f"===e||"mat3x2h"===e)console.error(`TODO: Determinant for ${e}`);else{if("mat3x3"===e||"mat3x3f"===e||"mat3x3h"===e)return new Mi(t[0]*(t[4]*t[8]-t[5]*t[7])-t[1]*(t[3]*t[8]-t[5]*t[6])+t[2]*(t[3]*t[7]-t[4]*t[6]),i);"mat3x4"===e||"mat3x4f"===e||"mat3x4h"===e||"mat4x2"===e||"mat4x2f"===e||"mat4x2h"===e||"mat4x3"===e||"mat4x3f"===e||"mat4x3h"===e?console.error(`TODO: Determinant for ${e}`):"mat4x4"!==e&&"mat4x4f"!==e&&"mat4x4h"!==e||console.error(`TODO: Determinant for ${e}`)}}return console.error(`Determinant expects a matrix argument. Line ${t.line}`),null}Distance(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);if(n instanceof Li&&i instanceof Li){let t=0;for(let e=0;e<n.data.length;++e)t+=(n.data[e]-i.data[e])*(n.data[e]-i.data[e]);return new Mi(Math.sqrt(t),this.getTypeInfo("f32"))}return new Mi(Math.abs(n.value-i.value),n.typeInfo)}_dot(t,e){let n=0;for(let i=0;i<t.length;++i)n+=e[i]*t[i];return n}Dot(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return n instanceof Li&&i instanceof Li?new Mi(this._dot(n.data,i.data),this.getTypeInfo("f32")):(console.error(`Dot() expects vector arguments. Line ${t.line}`),null)}Dot4U8Packed(t,e){return console.error(`TODO: dot4U8Packed. Line ${t.line}`),null}Dot4I8Packed(t,e){return console.error(`TODO: dot4I8Packed. Line ${t.line}`),null}Exp(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.exp(t))),n.typeInfo):new Mi(Math.exp(n.value),n.typeInfo)}Exp2(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.pow(2,t))),n.typeInfo):new Mi(Math.pow(2,n.value),n.typeInfo)}ExtractBits(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);if("u32"!==i.typeInfo.name&&"x32"!==i.typeInfo.name)return console.error(`ExtractBits() expects an i32 offset argument. Line ${t.line}`),null;if("u32"!==s.typeInfo.name&&"x32"!==s.typeInfo.name)return console.error(`ExtractBits() expects an i32 count argument. Line ${t.line}`),null;const r=i.value,o=s.value;return n instanceof Li?new Li(n.data.map((t=>t>>r&(1<<o)-1)),n.typeInfo):"i32"!==n.typeInfo.name&&"x32"!==n.typeInfo.name?(console.error(`ExtractBits() expects an i32 argument. Line ${t.line}`),null):new Mi(n.value>>r&(1<<o)-1,this.getTypeInfo("i32"))}FaceForward(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);if(n instanceof Li&&i instanceof Li&&s instanceof Li){const t=this._dot(i.data,s.data);return new Li(t<0?Array.from(n.data):n.data.map((t=>-t)),n.typeInfo)}return console.error(`FaceForward() expects vector arguments. Line ${t.line}`),null}_firstLeadingBit(t){return 0===t?-1:31-Math.clz32(t)}FirstLeadingBit(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>this._firstLeadingBit(t))),n.typeInfo):new Mi(this._firstLeadingBit(n.value),n.typeInfo)}_firstTrailingBit(t){return 0===t?-1:Math.log2(t&-t)}FirstTrailingBit(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>this._firstTrailingBit(t))),n.typeInfo):new Mi(this._firstTrailingBit(n.value),n.typeInfo)}Floor(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.floor(t))),n.typeInfo):new Mi(Math.floor(n.value),n.typeInfo)}Fma(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);return n instanceof Li&&i instanceof Li&&s instanceof Li?n.data.length!==i.data.length||n.data.length!==s.data.length?(console.error(`Fma() expects vectors of the same length. Line ${t.line}`),null):new Li(n.data.map(((t,e)=>t*i.data[e]+s.data[e])),n.typeInfo):new Mi(n.value*i.value+s.value,n.typeInfo)}Fract(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>t-Math.floor(t))),n.typeInfo):new Mi(n.value-Math.floor(n.value),n.typeInfo)}Frexp(t,e){return console.error(`TODO: frexp. Line ${t.line}`),null}InsertBits(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e),r=this.exec.evalExpression(t.args[3],e);if("u32"!==s.typeInfo.name&&"x32"!==s.typeInfo.name)return console.error(`InsertBits() expects an i32 offset argument. Line ${t.line}`),null;const o=s.value,a=(1<<r.value)-1<<o,c=~a;return n instanceof Li&&i instanceof Li?new Li(n.data.map(((t,e)=>t&c|i.data[e]<<o&a)),n.typeInfo):new Mi(n.value&c|i.value<<o&a,n.typeInfo)}InverseSqrt(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>1/Math.sqrt(t))),n.typeInfo):new Mi(1/Math.sqrt(n.value),n.typeInfo)}Ldexp(t,e){return console.error(`TODO: ldexp. Line ${t.line}`),null}Length(t,e){const n=this.exec.evalExpression(t.args[0],e);if(n instanceof Li){let t=0;return n.data.forEach((e=>{t+=e*e})),new Mi(Math.sqrt(t),this.getTypeInfo("f32"))}return new Mi(Math.abs(n.value),n.typeInfo)}Log(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.log(t))),n.typeInfo):new Mi(Math.log(n.value),n.typeInfo)}Log2(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.log2(t))),n.typeInfo):new Mi(Math.log2(n.value),n.typeInfo)}Max(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return n instanceof Li&&i instanceof Li?new Li(n.data.map(((t,e)=>Math.max(t,i.data[e]))),n.typeInfo):new Mi(Math.max(n.value,i.value),n.typeInfo)}Min(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return n instanceof Li&&i instanceof Li?new Li(n.data.map(((t,e)=>Math.min(t,i.data[e]))),n.typeInfo):new Mi(Math.min(n.value,i.value),n.typeInfo)}Mix(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);return n instanceof Li&&i instanceof Li&&s instanceof Li?new Li(n.data.map(((t,e)=>n.data[e]*(1-s.data[e])+i.data[e]*s.data[e])),n.typeInfo):new Mi(n.value*(1-s.value)+i.value*s.value,n.typeInfo)}Modf(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return n instanceof Li&&i instanceof Li?new Li(n.data.map(((t,e)=>t%i.data[e])),n.typeInfo):new Mi(n.value%i.value,n.typeInfo)}Normalize(t,e){const n=this.exec.evalExpression(t.args[0],e);if(n instanceof Li){const i=this.Length(t,e).value;return new Li(n.data.map((t=>t/i)),n.typeInfo)}return console.error(`Normalize() expects a vector argument. Line ${t.line}`),null}Pow(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return n instanceof Li&&i instanceof Li?new Li(n.data.map(((t,e)=>Math.pow(t,i.data[e]))),n.typeInfo):new Mi(Math.pow(n.value,i.value),n.typeInfo)}QuantizeToF16(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>t)),n.typeInfo):new Mi(n.value,n.typeInfo)}Radians(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>t*Math.PI/180)),n.typeInfo):new Mi(n.value*Math.PI/180,this.getTypeInfo("f32"))}Reflect(t,e){let n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);if(n instanceof Li&&i instanceof Li){const t=this._dot(n.data,i.data);return new Li(n.data.map(((e,n)=>e-2*t*i.data[n])),n.typeInfo)}return console.error(`Reflect() expects vector arguments. Line ${t.line}`),null}Refract(t,e){let n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);if(n instanceof Li&&i instanceof Li&&s instanceof Mi){const t=this._dot(i.data,n.data);return new Li(n.data.map(((e,n)=>{const r=1-s.value*s.value*(1-t*t);if(r<0)return 0;const o=Math.sqrt(r);return s.value*e-(s.value*t+o)*i.data[n]})),n.typeInfo)}return console.error(`Refract() expects vector arguments and a scalar argument. Line ${t.line}`),null}ReverseBits(t,e){return console.error(`TODO: reverseBits. Line ${t.line}`),null}Round(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.round(t))),n.typeInfo):new Mi(Math.round(n.value),n.typeInfo)}Saturate(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.min(Math.max(t,0),1))),n.typeInfo):new Mi(Math.min(Math.max(n.value,0),1),n.typeInfo)}Sign(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.sign(t))),n.typeInfo):new Mi(Math.sign(n.value),n.typeInfo)}Sin(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.sin(t))),n.typeInfo):new Mi(Math.sin(n.value),n.typeInfo)}Sinh(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.sinh(t))),n.typeInfo):new Mi(Math.sinh(n.value),n.typeInfo)}_smoothstep(t,e,n){const i=Math.min(Math.max((n-t)/(e-t),0),1);return i*i*(3-2*i)}SmoothStep(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e),s=this.exec.evalExpression(t.args[2],e);return s instanceof Li&&n instanceof Li&&i instanceof Li?new Li(s.data.map(((t,e)=>this._smoothstep(n.data[e],i.data[e],t))),s.typeInfo):new Mi(this._smoothstep(n.value,i.value,s.value),s.typeInfo)}Sqrt(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.sqrt(t))),n.typeInfo):new Mi(Math.sqrt(n.value),n.typeInfo)}Step(t,e){const n=this.exec.evalExpression(t.args[0],e),i=this.exec.evalExpression(t.args[1],e);return i instanceof Li&&n instanceof Li?new Li(i.data.map(((t,e)=>t<n.data[e]?0:1)),i.typeInfo):new Mi(i.value<n.value?0:1,n.typeInfo)}Tan(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.tan(t))),n.typeInfo):new Mi(Math.tan(n.value),n.typeInfo)}Tanh(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.tanh(t))),n.typeInfo):new Mi(Math.tanh(n.value),n.typeInfo)}_getTransposeType(t){const e=t.getTypeName();return"mat2x2f"===e||"mat2x2h"===e?t:"mat2x3f"===e?this.getTypeInfo("mat3x2f"):"mat2x3h"===e?this.getTypeInfo("mat3x2h"):"mat2x4f"===e?this.getTypeInfo("mat4x2f"):"mat2x4h"===e?this.getTypeInfo("mat4x2h"):"mat3x2f"===e?this.getTypeInfo("mat2x3f"):"mat3x2h"===e?this.getTypeInfo("mat2x3h"):"mat3x3f"===e||"mat3x3h"===e?t:"mat3x4f"===e?this.getTypeInfo("mat4x3f"):"mat3x4h"===e?this.getTypeInfo("mat4x3h"):"mat4x2f"===e?this.getTypeInfo("mat2x4f"):"mat4x2h"===e?this.getTypeInfo("mat2x4h"):"mat4x3f"===e?this.getTypeInfo("mat3x4f"):"mat4x3h"===e?this.getTypeInfo("mat3x4h"):("mat4x4f"===e||"mat4x4h"===e||console.error(`Invalid matrix type ${e}`),t)}Transpose(t,e){const n=this.exec.evalExpression(t.args[0],e);if(!(n instanceof Oi))return console.error(`Transpose() expects a matrix argument. Line ${t.line}`),null;const i=this._getTransposeType(n.typeInfo);if("mat2x2"===n.typeInfo.name||"mat2x2f"===n.typeInfo.name||"mat2x2h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[2],t[1],t[3]],i)}if("mat2x3"===n.typeInfo.name||"mat2x3f"===n.typeInfo.name||"mat2x3h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[3],t[6],t[1],t[4],t[7]],i)}if("mat2x4"===n.typeInfo.name||"mat2x4f"===n.typeInfo.name||"mat2x4h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13]],i)}if("mat3x2"===n.typeInfo.name||"mat3x2f"===n.typeInfo.name||"mat3x2h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[3],t[1],t[4],t[2],t[5]],i)}if("mat3x3"===n.typeInfo.name||"mat3x3f"===n.typeInfo.name||"mat3x3h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[3],t[6],t[1],t[4],t[7],t[2],t[5],t[8]],i)}if("mat3x4"===n.typeInfo.name||"mat3x4f"===n.typeInfo.name||"mat3x4h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14]],i)}if("mat4x2"===n.typeInfo.name||"mat4x2f"===n.typeInfo.name||"mat4x2h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[4],t[1],t[5],t[2],t[6]],i)}if("mat4x3"===n.typeInfo.name||"mat4x3f"===n.typeInfo.name||"mat4x3h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]],i)}if("mat4x4"===n.typeInfo.name||"mat4x4f"===n.typeInfo.name||"mat4x4h"===n.typeInfo.name){const t=n.data;return new Oi([t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15]],i)}return console.error(`Invalid matrix type ${n.typeInfo.name}`),null}Trunc(t,e){const n=this.exec.evalExpression(t.args[0],e);return n instanceof Li?new Li(n.data.map((t=>Math.trunc(t))),n.typeInfo):new Mi(Math.trunc(n.value),n.typeInfo)}Dpdx(t,e){return console.error(`TODO: dpdx. Line ${t.line}`),null}DpdxCoarse(t,e){return console.error(`TODO: dpdxCoarse. Line ${t.line}`),null}DpdxFine(t,e){return console.error("TODO: dpdxFine"),null}Dpdy(t,e){return console.error("TODO: dpdy"),null}DpdyCoarse(t,e){return console.error("TODO: dpdyCoarse"),null}DpdyFine(t,e){return console.error("TODO: dpdyFine"),null}Fwidth(t,e){return console.error("TODO: fwidth"),null}FwidthCoarse(t,e){return console.error("TODO: fwidthCoarse"),null}FwidthFine(t,e){return console.error("TODO: fwidthFine"),null}TextureDimensions(t,e){const n=t.args[0],i=t.args.length>1?this.exec.evalExpression(t.args[1],e).value:0;if(n instanceof hi){const s=n.name,r=e.getVariableValue(s);if(r instanceof ki){if(i<0||i>=r.mipLevelCount)return console.error(`Invalid mip level for textureDimensions. Line ${t.line}`),null;const e=r.getMipLevelSize(i),n=r.dimension;return"1d"===n?new Mi(e[0],this.getTypeInfo("u32")):"3d"===n?new Li(e,this.getTypeInfo("vec3u")):"2d"===n?new Li(e.slice(0,2),this.getTypeInfo("vec2u")):(console.error(`Invalid texture dimension ${n} not found. Line ${t.line}`),null)}return console.error(`Texture ${s} not found. Line ${t.line}`),null}return console.error(`Invalid texture argument for textureDimensions. Line ${t.line}`),null}TextureGather(t,e){return console.error("TODO: textureGather"),null}TextureGatherCompare(t,e){return console.error("TODO: textureGatherCompare"),null}TextureLoad(t,e){const n=t.args[0],i=this.exec.evalExpression(t.args[1],e),s=t.args.length>2?this.exec.evalExpression(t.args[2],e).value:0;if(!(i instanceof Li)||2!==i.data.length)return console.error(`Invalid UV argument for textureLoad. Line ${t.line}`),null;if(n instanceof hi){const r=n.name,o=e.getVariableValue(r);if(o instanceof ki){const e=Math.floor(i.data[0]),n=Math.floor(i.data[1]);if(e<0||e>=o.width||n<0||n>=o.height)return console.error(`Texture ${r} out of bounds. Line ${t.line}`),null;const a=o.getPixel(e,n,0,s);return null===a?(console.error(`Invalid texture format for textureLoad. Line ${t.line}`),null):new Li(a,this.getTypeInfo("vec4f"))}return console.error(`Texture ${r} not found. Line ${t.line}`),null}return console.error(`Invalid texture argument for textureLoad. Line ${t.line}`),null}TextureNumLayers(t,e){const n=t.args[0];if(n instanceof hi){const i=n.name,s=e.getVariableValue(i);return s instanceof ki?new Mi(s.depthOrArrayLayers,this.getTypeInfo("u32")):(console.error(`Texture ${i} not found. Line ${t.line}`),null)}return console.error(`Invalid texture argument for textureNumLayers. Line ${t.line}`),null}TextureNumLevels(t,e){const n=t.args[0];if(n instanceof hi){const i=n.name,s=e.getVariableValue(i);return s instanceof ki?new Mi(s.mipLevelCount,this.getTypeInfo("u32")):(console.error(`Texture ${i} not found. Line ${t.line}`),null)}return console.error(`Invalid texture argument for textureNumLevels. Line ${t.line}`),null}TextureNumSamples(t,e){const n=t.args[0];if(n instanceof hi){const i=n.name,s=e.getVariableValue(i);return s instanceof ki?new Mi(s.sampleCount,this.getTypeInfo("u32")):(console.error(`Texture ${i} not found. Line ${t.line}`),null)}return console.error(`Invalid texture argument for textureNumSamples. Line ${t.line}`),null}TextureSample(t,e){return console.error("TODO: textureSample"),null}TextureSampleBias(t,e){return console.error("TODO: textureSampleBias"),null}TextureSampleCompare(t,e){return console.error("TODO: textureSampleCompare"),null}TextureSampleCompareLevel(t,e){return console.error("TODO: textureSampleCompareLevel"),null}TextureSampleGrad(t,e){return console.error("TODO: textureSampleGrad"),null}TextureSampleLevel(t,e){return console.error("TODO: textureSampleLevel"),null}TextureSampleBaseClampToEdge(t,e){return console.error("TODO: textureSampleBaseClampToEdge"),null}TextureStore(t,e){const n=t.args[0],i=this.exec.evalExpression(t.args[1],e),s=4===t.args.length?this.exec.evalExpression(t.args[2],e).value:0,r=4===t.args.length?this.exec.evalExpression(t.args[3],e).data:this.exec.evalExpression(t.args[2],e).data;if(4!==r.length)return console.error(`Invalid value argument for textureStore. Line ${t.line}`),null;if(!(i instanceof Li)||2!==i.data.length)return console.error(`Invalid UV argument for textureStore. Line ${t.line}`),null;if(n instanceof hi){const o=n.name,a=e.getVariableValue(o);if(a instanceof ki){const e=a.getMipLevelSize(0),n=Math.floor(i.data[0]),c=Math.floor(i.data[1]);return n<0||n>=e[0]||c<0||c>=e[1]?(console.error(`Texture ${o} out of bounds. Line ${t.line}`),null):(a.setPixel(n,c,0,s,Array.from(r)),null)}return console.error(`Texture ${o} not found. Line ${t.line}`),null}return console.error(`Invalid texture argument for textureStore. Line ${t.line}`),null}AtomicLoad(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e);return e.getVariable(i).value.getSubData(this.exec,n.postfix,e)}AtomicStore(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e);return o instanceof Mi&&r instanceof Mi&&(o.value=r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),null}AtomicAdd(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value+=r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicSub(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value-=r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicMax(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value=Math.max(o.value,r.value)),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicMin(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value=Math.min(o.value,r.value)),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicAnd(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value=o.value&r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicOr(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value=o.value|r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicXor(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value=o.value^r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicExchange(t,e){let n=t.args[0];n instanceof mi&&(n=n.right);const i=this.exec.getVariableName(n,e),s=e.getVariable(i),r=this.exec.evalExpression(t.args[1],e),o=s.value.getSubData(this.exec,n.postfix,e),a=new Mi(o.value,o.typeInfo);return o instanceof Mi&&r instanceof Mi&&(o.value=r.value),s.value instanceof Ii&&s.value.setDataValue(this.exec,o,n.postfix,e),a}AtomicCompareExchangeWeak(t,e){return console.error("TODO: atomicCompareExchangeWeak"),null}Pack4x8snorm(t,e){return console.error("TODO: pack4x8snorm"),null}Pack4x8unorm(t,e){return console.error("TODO: pack4x8unorm"),null}Pack4xI8(t,e){return console.error("TODO: pack4xI8"),null}Pack4xU8(t,e){return console.error("TODO: pack4xU8"),null}Pack4x8Clamp(t,e){return console.error("TODO: pack4x8Clamp"),null}Pack4xU8Clamp(t,e){return console.error("TODO: pack4xU8Clamp"),null}Pack2x16snorm(t,e){return console.error("TODO: pack2x16snorm"),null}Pack2x16unorm(t,e){return console.error("TODO: pack2x16unorm"),null}Pack2x16float(t,e){return console.error("TODO: pack2x16float"),null}Unpack4x8snorm(t,e){return console.error("TODO: unpack4x8snorm"),null}Unpack4x8unorm(t,e){return console.error("TODO: unpack4x8unorm"),null}Unpack4xI8(t,e){return console.error("TODO: unpack4xI8"),null}Unpack4xU8(t,e){return console.error("TODO: unpack4xU8"),null}Unpack2x16snorm(t,e){return console.error("TODO: unpack2x16snorm"),null}Unpack2x16unorm(t,e){return console.error("TODO: unpack2x16unorm"),null}Unpack2x16float(t,e){return console.error("TODO: unpack2x16float"),null}StorageBarrier(t,e){return null}TextureBarrier(t,e){return null}WorkgroupBarrier(t,e){return null}WorkgroupUniformLoad(t,e){return null}SubgroupAdd(t,e){return console.error("TODO: subgroupAdd"),null}SubgroupExclusiveAdd(t,e){return console.error("TODO: subgroupExclusiveAdd"),null}SubgroupInclusiveAdd(t,e){return console.error("TODO: subgroupInclusiveAdd"),null}SubgroupAll(t,e){return console.error("TODO: subgroupAll"),null}SubgroupAnd(t,e){return console.error("TODO: subgroupAnd"),null}SubgroupAny(t,e){return console.error("TODO: subgroupAny"),null}SubgroupBallot(t,e){return console.error("TODO: subgroupBallot"),null}SubgroupBroadcast(t,e){return console.error("TODO: subgroupBroadcast"),null}SubgroupBroadcastFirst(t,e){return console.error("TODO: subgroupBroadcastFirst"),null}SubgroupElect(t,e){return console.error("TODO: subgroupElect"),null}SubgroupMax(t,e){return console.error("TODO: subgroupMax"),null}SubgroupMin(t,e){return console.error("TODO: subgroupMin"),null}SubgroupMul(t,e){return console.error("TODO: subgroupMul"),null}SubgroupExclusiveMul(t,e){return console.error("TODO: subgroupExclusiveMul"),null}SubgroupInclusiveMul(t,e){return console.error("TODO: subgroupInclusiveMul"),null}SubgroupOr(t,e){return console.error("TODO: subgroupOr"),null}SubgroupShuffle(t,e){return console.error("TODO: subgroupShuffle"),null}SubgroupShuffleDown(t,e){return console.error("TODO: subgroupShuffleDown"),null}SubgroupShuffleUp(t,e){return console.error("TODO: subgroupShuffleUp"),null}SubgroupShuffleXor(t,e){return console.error("TODO: subgroupShuffleXor"),null}SubgroupXor(t,e){return console.error("TODO: subgroupXor"),null}QuadBroadcast(t,e){return console.error("TODO: quadBroadcast"),null}QuadSwapDiagonal(t,e){return console.error("TODO: quadSwapDiagonal"),null}QuadSwapX(t,e){return console.error("TODO: quadSwapX"),null}QuadSwapY(t,e){return console.error("TODO: quadSwapY"),null}}const rs={vec2:2,vec2f:2,vec2i:2,vec2u:2,vec2b:2,vec2h:2,vec3:3,vec3f:3,vec3i:3,vec3u:3,vec3b:3,vec3h:3,vec4:4,vec4f:4,vec4i:4,vec4u:4,vec4b:4,vec4h:4},os={mat2x2:[2,2,4],mat2x2f:[2,2,4],mat2x2h:[2,2,4],mat2x3:[2,3,6],mat2x3f:[2,3,6],mat2x3h:[2,3,6],mat2x4:[2,4,8],mat2x4f:[2,4,8],mat2x4h:[2,4,8],mat3x2:[3,2,6],mat3x2f:[3,2,6],mat3x2h:[3,2,6],mat3x3:[3,3,9],mat3x3f:[3,3,9],mat3x3h:[3,3,9],mat3x4:[3,4,12],mat3x4f:[3,4,12],mat3x4h:[3,4,12],mat4x2:[4,2,8],mat4x2f:[4,2,8],mat4x2h:[4,2,8],mat4x3:[4,3,12],mat4x3f:[4,3,12],mat4x3h:[4,3,12],mat4x4:[4,4,16],mat4x4f:[4,4,16],mat4x4h:[4,4,16]};class as extends is{constructor(t,e){var n;super(),this.ast=null!=t?t:[],this.reflection=new Ji,this.reflection.updateAST(this.ast),this.context=null!==(n=null==e?void 0:e.clone())&&void 0!==n?n:new ns,this.builtins=new ss(this),this.typeInfo={bool:this.getTypeInfo(Qn.bool),i32:this.getTypeInfo(Qn.i32),u32:this.getTypeInfo(Qn.u32),f32:this.getTypeInfo(Qn.f32),f16:this.getTypeInfo(Qn.f16),vec2f:this.getTypeInfo(ni.vec2f),vec2u:this.getTypeInfo(ni.vec2u),vec2i:this.getTypeInfo(ni.vec2i),vec2h:this.getTypeInfo(ni.vec2h),vec3f:this.getTypeInfo(ni.vec3f),vec3u:this.getTypeInfo(ni.vec3u),vec3i:this.getTypeInfo(ni.vec3i),vec3h:this.getTypeInfo(ni.vec3h),vec4f:this.getTypeInfo(ni.vec4f),vec4u:this.getTypeInfo(ni.vec4u),vec4i:this.getTypeInfo(ni.vec4i),vec4h:this.getTypeInfo(ni.vec4h),mat2x2f:this.getTypeInfo(ni.mat2x2f),mat2x3f:this.getTypeInfo(ni.mat2x3f),mat2x4f:this.getTypeInfo(ni.mat2x4f),mat3x2f:this.getTypeInfo(ni.mat3x2f),mat3x3f:this.getTypeInfo(ni.mat3x3f),mat3x4f:this.getTypeInfo(ni.mat3x4f),mat4x2f:this.getTypeInfo(ni.mat4x2f),mat4x3f:this.getTypeInfo(ni.mat4x3f),mat4x4f:this.getTypeInfo(ni.mat4x4f)}}getVariableValue(t){var e,n;const i=null!==(n=null===(e=this.context.getVariable(t))||void 0===e?void 0:e.value)&&void 0!==n?n:null;if(null===i)return null;if(i instanceof Mi)return i.value;if(i instanceof Li)return Array.from(i.data);if(i instanceof Oi)return Array.from(i.data);if(i instanceof Ii&&i.typeInfo instanceof Ye){if("u32"===i.typeInfo.format.name)return Array.from(new Uint32Array(i.buffer,i.offset,i.typeInfo.count));if("i32"===i.typeInfo.format.name)return Array.from(new Int32Array(i.buffer,i.offset,i.typeInfo.count));if("f32"===i.typeInfo.format.name)return Array.from(new Float32Array(i.buffer,i.offset,i.typeInfo.count))}return console.error(`Unsupported return variable type ${i.typeInfo.name}`),null}execute(t){(t=null!=t?t:{}).constants&&this._setOverrides(t.constants,this.context),this._execStatements(this.ast,this.context)}dispatchWorkgroups(t,e,n,i){const s=this.context.clone();(i=null!=i?i:{}).constants&&this._setOverrides(i.constants,s),this._execStatements(this.ast,s);const r=s.getFunction(t);if(!r)return void console.error(`Function ${t} not found`);if("number"==typeof e)e=[e,1,1];else{if(0===e.length)return void console.error("Invalid dispatch count");1===e.length?e=[e[0],1,1]:2===e.length?e=[e[0],e[1],1]:e.length>3&&(e=[e[0],e[1],e[2]])}const o=e[0],a=e[1],c=e[2],l=this.getTypeInfo("vec3u");s.setVariable("@num_workgroups",new Li(e,l));const h=this.reflection.getFunctionInfo(t);null===h&&console.error(`Function ${t} not found in reflection data`);for(const t in n)for(const e in n[t]){const i=n[t][e];s.variables.forEach((n=>{var s;const r=n.node;if(null==r?void 0:r.attributes){let o=null,a=null;for(const t of r.attributes)"binding"===t.name?o=t.value:"group"===t.name&&(a=t.value);if(e==o&&t==a){let o=!1;for(const i of h.resources)if(i.name===n.name&&i.group===parseInt(t)&&i.binding===parseInt(e)){o=!0;break}if(o)if(void 0!==i.texture&&void 0!==i.descriptor){const t=new ki(i.texture,this.getTypeInfo(r.type),i.descriptor,null!==(s=i.texture.view)&&void 0!==s?s:null);n.value=t}else n.value=new Ii(void 0!==i.uniform?i.uniform:i,this.getTypeInfo(r.type))}}}))}for(let t=0;t<c;++t)for(let e=0;e<a;++e)for(let n=0;n<o;++n)s.setVariable("@workgroup_id",new Li([n,e,t],this.getTypeInfo("vec3u"))),this._dispatchWorkgroup(r,[n,e,t],s)}execStatement(t,e){if(t instanceof Vn)return this.evalExpression(t.value,e);if(t instanceof Yn){if(t.condition){const n=this.evalExpression(t.condition,e);if(!(n instanceof Mi))throw new Error("Invalid break-if condition");if(!n.value)return null}return as._breakObj}if(t instanceof Jn)return as._continueObj;if(t instanceof In)this._let(t,e);else if(t instanceof Ln)this._var(t,e);else if(t instanceof kn)this._const(t,e);else if(t instanceof Sn)this._function(t,e);else{if(t instanceof Wn)return this._if(t,e);if(t instanceof Gn)return this._switch(t,e);if(t instanceof Rn)return this._for(t,e);if(t instanceof Pn)return this._while(t,e);if(t instanceof jn)return this._loop(t,e);if(t instanceof Mn){const n=e.clone();return n.currentFunctionName=e.currentFunctionName,this._execStatements(t.body,n)}if(t instanceof Un)this._assign(t,e);else if(t instanceof $n)this._increment(t,e);else{if(t instanceof ei)return null;if(t instanceof On){const n=t.name;null===e.getVariable(n)&&e.setVariable(n,new Mi(0,this.getTypeInfo("u32")))}else if(t instanceof zn)this._call(t,e);else{if(t instanceof Zn)return null;if(t instanceof Kn)return null;console.error("Invalid statement type.",t,`Line ${t.line}`)}}}return null}evalExpression(t,e){return t instanceof _i?this._evalBinaryOp(t,e):t instanceof fi?this._evalLiteral(t,e):t instanceof hi?this._evalVariable(t,e):t instanceof li?this._evalCall(t,e):t instanceof ci?this._evalCreate(t,e):t instanceof ui?this._evalConst(t,e):t instanceof di?this._evalBitcast(t,e):t instanceof mi?this._evalUnaryOp(t,e):(console.error("Invalid expression type",t,`Line ${t.line}`),null)}getTypeInfo(t){var e;if(t instanceof Qn){const e=this.reflection.getTypeInfo(t);if(null!==e)return e}let n=null!==(e=this.typeInfo[t])&&void 0!==e?e:null;return null!==n||(n=this.reflection.getTypeInfoByName(t)),n}_setOverrides(t,e){for(const n in t){const i=t[n],s=this.reflection.getOverrideInfo(n);null!==s?(null===s.type&&(s.type=this.getTypeInfo("u32")),"u32"===s.type.name||"i32"===s.type.name||"f32"===s.type.name||"f16"===s.type.name?e.setVariable(n,new Mi(i,s.type)):"bool"===s.type.name?e.setVariable(n,new Mi(i?1:0,s.type)):"vec2"===s.type.name||"vec3"===s.type.name||"vec4"===s.type.name||"vec2f"===s.type.name||"vec3f"===s.type.name||"vec4f"===s.type.name||"vec2i"===s.type.name||"vec3i"===s.type.name||"vec4i"===s.type.name||"vec2u"===s.type.name||"vec3u"===s.type.name||"vec4u"===s.type.name||"vec2h"===s.type.name||"vec3h"===s.type.name||"vec4h"===s.type.name?e.setVariable(n,new Li(i,s.type)):console.error(`Invalid constant type for ${n}`)):console.error(`Override ${n} does not exist in the shader.`)}}_dispatchWorkgroup(t,e,n){const i=[1,1,1];for(const e of t.node.attributes)if("workgroup_size"===e.name){if(e.value.length>0){const t=n.getVariableValue(e.value[0]);i[0]=t instanceof Mi?t.value:parseInt(e.value[0])}if(e.value.length>1){const t=n.getVariableValue(e.value[1]);i[1]=t instanceof Mi?t.value:parseInt(e.value[1])}if(e.value.length>2){const t=n.getVariableValue(e.value[2]);i[2]=t instanceof Mi?t.value:parseInt(e.value[2])}}const s=this.getTypeInfo("vec3u"),r=this.getTypeInfo("u32");n.setVariable("@workgroup_size",new Li(i,s));const o=i[0],a=i[1],c=i[2];for(let l=0,h=0;l<c;++l)for(let c=0;c<a;++c)for(let a=0;a<o;++a,++h){const o=[a+e[0]*i[0],c+e[1]*i[1],l+e[2]*i[2]];n.setVariable("@local_invocation_id",new Li([a,c,l],s)),n.setVariable("@global_invocation_id",new Li(o,s)),n.setVariable("@local_invocation_index",new Mi(h,r)),this._dispatchExec(t,n)}}_dispatchExec(t,e){for(const n of t.node.args)for(const t of n.attributes)if("builtin"===t.name){const i=e.getVariable(`@${t.value}`);void 0!==i&&e.variables.set(n.name,i)}this._execStatements(t.node.body,e)}getVariableName(t,e){for(;t instanceof mi;)t=t.right;return t instanceof hi?t.name:(console.error("Unknown variable type",t,"Line",t.line),null)}_execStatements(t,e){for(const n of t){if(n instanceof Array){const t=e.clone(),i=this._execStatements(n,t);if(i)return i;continue}const t=this.execStatement(n,e);if(t)return t}return null}_call(t,e){const n=e.clone();n.currentFunctionName=t.name;const i=e.getFunction(t.name);if(i){for(let e=0;e<i.node.args.length;++e){const s=i.node.args[e],r=this.evalExpression(t.args[e],n);n.setVariable(s.name,r,s)}this._execStatements(i.node.body,n)}else t.isBuiltin?this._callBuiltinFunction(t,n):this.getTypeInfo(t.name)&&this._evalCreate(t,e)}_increment(t,e){const n=this.getVariableName(t.variable,e),i=e.getVariable(n);i?"++"===t.operator?i.value instanceof Mi?i.value.value++:console.error(`Variable ${n} is not a scalar. Line ${t.line}`):"--"===t.operator?i.value instanceof Mi?i.value.value--:console.error(`Variable ${n} is not a scalar. Line ${t.line}`):console.error(`Unknown increment operator ${t.operator}. Line ${t.line}`):console.error(`Variable ${n} not found. Line ${t.line}`)}_getVariableData(t,e){if(t instanceof hi){const n=this.getVariableName(t,e),i=e.getVariable(n);return null===i?(console.error(`Variable ${n} not found. Line ${t.line}`),null):i.value.getSubData(this,t.postfix,e)}if(t instanceof mi){if("*"===t.operator){const n=this._getVariableData(t.right,e);return n instanceof Pi?n.reference.getSubData(this,t.postfix,e):(console.error(`Variable ${t.right} is not a pointer. Line ${t.line}`),null)}if("&"===t.operator){const n=this._getVariableData(t.right,e);return new Pi(n)}}return null}_assign(t,e){let n=null,i="<var>",s=null;if(t.variable instanceof mi){const n=this._getVariableData(t.variable,e),i=this.evalExpression(t.value,e),s=t.operator;if("="===s){if(n instanceof Mi||n instanceof Li||n instanceof Oi){if(i instanceof Mi||i instanceof Li||i instanceof Oi&&n.data.length===i.data.length)return void n.data.set(i.data);console.error(`Invalid assignment. Line ${t.line}`)}else if(n instanceof Ii&&i instanceof Ii&&n.buffer.byteLength-n.offset>=i.buffer.byteLength-i.offset)return void(n.buffer.byteLength%4==0?new Uint32Array(n.buffer,n.offset,n.typeInfo.size/4).set(new Uint32Array(i.buffer,i.offset,i.typeInfo.size/4)):new Uint8Array(n.buffer,n.offset,n.typeInfo.size).set(new Uint8Array(i.buffer,i.offset,i.typeInfo.size)));return console.error(`Invalid assignment. Line ${t.line}`),null}if("+="===s)return n instanceof Mi||n instanceof Li||n instanceof Oi?i instanceof Mi||i instanceof Li||i instanceof Oi?void n.data.set(i.data.map(((t,e)=>n.data[e]+t))):void console.error(`Invalid assignment . Line ${t.line}`):void console.error(`Invalid assignment. Line ${t.line}`);if("-="===s)return(n instanceof Mi||n instanceof Li||n instanceof Oi)&&(i instanceof Mi||i instanceof Li||i instanceof Oi)?void n.data.set(i.data.map(((t,e)=>n.data[e]-t))):void console.error(`Invalid assignment. Line ${t.line}`)}if(t.variable instanceof mi){if("*"===t.variable.operator){i=this.getVariableName(t.variable.right,e);const s=e.getVariable(i);if(!(s&&s.value instanceof Pi))return void console.error(`Variable ${i} is not a pointer. Line ${t.line}`);n=s.value.reference;let r=t.variable.postfix;if(!r){let e=t.variable.right;for(;e instanceof mi;){if(e.postfix){r=e.postfix;break}e=e.right}}r&&(n=n.getSubData(this,r,e))}}else{s=t.variable.postfix,i=this.getVariableName(t.variable,e);const r=e.getVariable(i);if(null===r)return void console.error(`Variable ${i} not found. Line ${t.line}`);n=r.value}if(n instanceof Pi&&(n=n.reference),null===n)return void console.error(`Variable ${i} not found. Line ${t.line}`);const r=this.evalExpression(t.value,e),o=t.operator;if("="===o)if(n instanceof Ii)n.setDataValue(this,r,s,e);else if(s){if(!(n instanceof Li||n instanceof Oi))return void console.error(`Variable ${i} is not a vector or matrix. Line ${t.line}`);if(s instanceof pi){const o=this.evalExpression(s.index,e).value;if(n instanceof Li){if(!(r instanceof Mi))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[o]=r.value}else{if(!(n instanceof Oi))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);{const o=this.evalExpression(s.index,e).value;if(o<0)return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);if(!(r instanceof Li))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);{const e=n.typeInfo.getTypeName();if("mat2x2"===e||"mat2x2f"===e||"mat2x2h"===e){if(!(o<2&&2===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[2*o]=r.data[0],n.data[2*o+1]=r.data[1]}else if("mat2x3"===e||"mat2x3f"===e||"mat2x3h"===e){if(!(o<2&&3===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[3*o]=r.data[0],n.data[3*o+1]=r.data[1],n.data[3*o+2]=r.data[2]}else if("mat2x4"===e||"mat2x4f"===e||"mat2x4h"===e){if(!(o<2&&4===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[4*o]=r.data[0],n.data[4*o+1]=r.data[1],n.data[4*o+2]=r.data[2],n.data[4*o+3]=r.data[3]}else if("mat3x2"===e||"mat3x2f"===e||"mat3x2h"===e){if(!(o<3&&2===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[2*o]=r.data[0],n.data[2*o+1]=r.data[1]}else if("mat3x3"===e||"mat3x3f"===e||"mat3x3h"===e){if(!(o<3&&3===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[3*o]=r.data[0],n.data[3*o+1]=r.data[1],n.data[3*o+2]=r.data[2]}else if("mat3x4"===e||"mat3x4f"===e||"mat3x4h"===e){if(!(o<3&&4===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[4*o]=r.data[0],n.data[4*o+1]=r.data[1],n.data[4*o+2]=r.data[2],n.data[4*o+3]=r.data[3]}else if("mat4x2"===e||"mat4x2f"===e||"mat4x2h"===e){if(!(o<4&&2===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[2*o]=r.data[0],n.data[2*o+1]=r.data[1]}else if("mat4x3"===e||"mat4x3f"===e||"mat4x3h"===e){if(!(o<4&&3===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[3*o]=r.data[0],n.data[3*o+1]=r.data[1],n.data[3*o+2]=r.data[2]}else{if("mat4x4"!==e&&"mat4x4f"!==e&&"mat4x4h"!==e)return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);if(!(o<4&&4===r.data.length))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);n.data[4*o]=r.data[0],n.data[4*o+1]=r.data[1],n.data[4*o+2]=r.data[2],n.data[4*o+3]=r.data[3]}}}}}else if(s instanceof ai){const e=s.value;if(!(n instanceof Li))return void console.error(`Invalid assignment to ${e}. Variable ${i} is not a vector. Line ${t.line}`);if(r instanceof Mi){if(e.length>1)return void console.error(`Invalid assignment to ${e} for variable ${i}. Line ${t.line}`);if("x"===e)n.data[0]=r.value;else if("y"===e){if(n.data.length<2)return void console.error(`Invalid assignment to ${e} for variable ${i}. Line ${t.line}`);n.data[1]=r.value}else if("z"===e){if(n.data.length<3)return void console.error(`Invalid assignment to ${e} for variable ${i}. Line ${t.line}`);n.data[2]=r.value}else if("w"===e){if(n.data.length<4)return void console.error(`Invalid assignment to ${e} for variable ${i}. Line ${t.line}`);n.data[3]=r.value}}else{if(!(r instanceof Li))return void console.error(`Invalid assignment to ${i}. Line ${t.line}`);if(e.length!==r.data.length)return void console.error(`Invalid assignment to ${e} for variable ${i}. Line ${t.line}`);for(let s=0;s<e.length;++s){const o=e[s];if("x"===o||"r"===o)n.data[0]=r.data[s];else if("y"===o||"g"===o){if(r.data.length<2)return void console.error(`Invalid assignment to ${o} for variable ${i}. Line ${t.line}`);n.data[1]=r.data[s]}else if("z"===o||"b"===o){if(r.data.length<3)return void console.error(`Invalid assignment to ${o} for variable ${i}. Line ${t.line}`);n.data[2]=r.data[s]}else{if("w"!==o&&"a"!==o)return void console.error(`Invalid assignment to ${o} for variable ${i}. Line ${t.line}`);if(r.data.length<4)return void console.error(`Invalid assignment to ${o} for variable ${i}. Line ${t.line}`);n.data[3]=r.data[s]}}}}}else n instanceof Mi&&r instanceof Mi?n.value=r.value:n instanceof Li&&r instanceof Li||n instanceof Oi&&r instanceof Oi?n.data.set(r.data):console.error(`Invalid assignment to ${i}. Line ${t.line}`);else{const i=n.getSubData(this,s,e);if(i instanceof Li&&r instanceof Mi){const e=i.data,n=r.value;if("+="===o)for(let t=0;t<e.length;++t)e[t]+=n;else if("-="===o)for(let t=0;t<e.length;++t)e[t]-=n;else if("*="===o)for(let t=0;t<e.length;++t)e[t]*=n;else if("/="===o)for(let t=0;t<e.length;++t)e[t]/=n;else if("%="===o)for(let t=0;t<e.length;++t)e[t]%=n;else if("&="===o)for(let t=0;t<e.length;++t)e[t]&=n;else if("|="===o)for(let t=0;t<e.length;++t)e[t]|=n;else if("^="===o)for(let t=0;t<e.length;++t)e[t]^=n;else if("<<="===o)for(let t=0;t<e.length;++t)e[t]<<=n;else if(">>="===o)for(let t=0;t<e.length;++t)e[t]>>=n;else console.error(`Invalid operator ${o}. Line ${t.line}`)}else if(i instanceof Li&&r instanceof Li){const e=i.data,n=r.data;if(e.length!==n.length)return void console.error(`Vector length mismatch. Line ${t.line}`);if("+="===o)for(let t=0;t<e.length;++t)e[t]+=n[t];else if("-="===o)for(let t=0;t<e.length;++t)e[t]-=n[t];else if("*="===o)for(let t=0;t<e.length;++t)e[t]*=n[t];else if("/="===o)for(let t=0;t<e.length;++t)e[t]/=n[t];else if("%="===o)for(let t=0;t<e.length;++t)e[t]%=n[t];else if("&="===o)for(let t=0;t<e.length;++t)e[t]&=n[t];else if("|="===o)for(let t=0;t<e.length;++t)e[t]|=n[t];else if("^="===o)for(let t=0;t<e.length;++t)e[t]^=n[t];else if("<<="===o)for(let t=0;t<e.length;++t)e[t]<<=n[t];else if(">>="===o)for(let t=0;t<e.length;++t)e[t]>>=n[t];else console.error(`Invalid operator ${o}. Line ${t.line}`)}else{if(!(i instanceof Mi&&r instanceof Mi))return void console.error(`Invalid type for ${t.operator} operator. Line ${t.line}`);"+="===o?i.value+=r.value:"-="===o?i.value-=r.value:"*="===o?i.value*=r.value:"/="===o?i.value/=r.value:"%="===o?i.value%=r.value:"&="===o?i.value&=r.value:"|="===o?i.value|=r.value:"^="===o?i.value^=r.value:"<<="===o?i.value<<=r.value:">>="===o?i.value>>=r.value:console.error(`Invalid operator ${o}. Line ${t.line}`)}n instanceof Ii&&n.setDataValue(this,i,s,e)}}_function(t,e){const n=new es(t);e.functions.set(t.name,n)}_const(t,e){let n=null;null!==t.value&&(n=this.evalExpression(t.value,e)),e.createVariable(t.name,n,t)}_let(t,e){let n=null;if(null!==t.value){if(n=this.evalExpression(t.value,e),null===n)return void console.error(`Invalid value for variable ${t.name}. Line ${t.line}`);t.value instanceof mi||(n=n.clone())}else{const i=t.type.name;if("f32"===i||"i32"===i||"u32"===i||"bool"===i||"f16"===i||"vec2"===i||"vec3"===i||"vec4"===i||"vec2f"===i||"vec3f"===i||"vec4f"===i||"vec2i"===i||"vec3i"===i||"vec4i"===i||"vec2u"===i||"vec3u"===i||"vec4u"===i||"vec2h"===i||"vec3h"===i||"vec4h"===i||"vec2b"===i||"vec3b"===i||"vec4b"===i||"mat2x2"===i||"mat2x3"===i||"mat2x4"===i||"mat3x2"===i||"mat3x3"===i||"mat3x4"===i||"mat4x2"===i||"mat4x3"===i||"mat4x4"===i||"mat2x2f"===i||"mat2x3f"===i||"mat2x4f"===i||"mat3x2f"===i||"mat3x3f"===i||"mat3x4f"===i||"mat4x2f"===i||"mat4x3f"===i||"mat4x4f"===i||"mat2x2h"===i||"mat2x3h"===i||"mat2x4h"===i||"mat3x2h"===i||"mat3x3h"===i||"mat3x4h"===i||"mat4x2h"===i||"mat4x3h"===i||"mat4x4h"===i||"array"===i){const i=new ci(t.type,[]);n=this._evalCreate(i,e)}}e.createVariable(t.name,n,t)}_var(t,e){let n=null;if(null!==t.value){if(n=this.evalExpression(t.value,e),null===n)return void console.error(`Invalid value for variable ${t.name}. Line ${t.line}`);t.value instanceof mi||(n=n.clone())}else{if(null===t.type)return void console.error(`Variable ${t.name} has no type. Line ${t.line}`);const i=t.type.name;if("f32"===i||"i32"===i||"u32"===i||"bool"===i||"f16"===i||"vec2"===i||"vec3"===i||"vec4"===i||"vec2f"===i||"vec3f"===i||"vec4f"===i||"vec2i"===i||"vec3i"===i||"vec4i"===i||"vec2u"===i||"vec3u"===i||"vec4u"===i||"vec2h"===i||"vec3h"===i||"vec4h"===i||"vec2b"===i||"vec3b"===i||"vec4b"===i||"mat2x2"===i||"mat2x3"===i||"mat2x4"===i||"mat3x2"===i||"mat3x3"===i||"mat3x4"===i||"mat4x2"===i||"mat4x3"===i||"mat4x4"===i||"mat2x2f"===i||"mat2x3f"===i||"mat2x4f"===i||"mat3x2f"===i||"mat3x3f"===i||"mat3x4f"===i||"mat4x2f"===i||"mat4x3f"===i||"mat4x4f"===i||"mat2x2h"===i||"mat2x3h"===i||"mat2x4h"===i||"mat3x2h"===i||"mat3x3h"===i||"mat3x4h"===i||"mat4x2h"===i||"mat4x3h"===i||"mat4x4h"===i||t.type instanceof si||t.type instanceof ei||t.type instanceof ni){const i=new ci(t.type,[]);n=this._evalCreate(i,e)}}e.createVariable(t.name,n,t)}_switch(t,e){e=e.clone();const n=this.evalExpression(t.condition,e);if(!(n instanceof Mi))return console.error(`Invalid if condition. Line ${t.line}`),null;let i=null;for(const s of t.cases)if(s instanceof yi)for(const r of s.selectors){if(r instanceof bi){i=s;continue}const o=this.evalExpression(r,e);if(!(o instanceof Mi))return console.error(`Invalid case selector. Line ${t.line}`),null;if(o.value===n.value)return this._execStatements(s.body,e)}else s instanceof wi&&(i=s);return i?this._execStatements(i.body,e):null}_if(t,e){e=e.clone();const n=this.evalExpression(t.condition,e);if(!(n instanceof Mi))return console.error(`Invalid if condition. Line ${t.line}`),null;if(n.value)return this._execStatements(t.body,e);for(const n of t.elseif){const i=this.evalExpression(n.condition,e);if(!(i instanceof Mi))return console.error(`Invalid if condition. Line ${t.line}`),null;if(i.value)return this._execStatements(n.body,e)}return t.else?this._execStatements(t.else,e):null}_getScalarValue(t){return t instanceof Mi?t.value:(console.error("Expected scalar value.",t),0)}_for(t,e){for(e=e.clone(),this.execStatement(t.init,e);this._getScalarValue(this.evalExpression(t.condition,e));){const n=this._execStatements(t.body,e);if(n===as._breakObj)break;if(null!==n&&n!==as._continueObj)return n;this.execStatement(t.increment,e)}return null}_loop(t,e){for(e=e.clone();;){const n=this._execStatements(t.body,e);if(n===as._breakObj)break;if(n===as._continueObj){if(t.continuing&&this._execStatements(t.continuing.body,e)===as._breakObj)break}else if(null!==n)return n}return null}_while(t,e){for(e=e.clone();this._getScalarValue(this.evalExpression(t.condition,e));){const n=this._execStatements(t.body,e);if(n===as._breakObj)break;if(n!==as._continueObj&&null!==n)return n}return null}_evalBitcast(t,e){const n=this.evalExpression(t.value,e),i=t.type;if(n instanceof Mi){const t=Ki(n.value,n.typeInfo.name,i.name);return new Mi(t,this.getTypeInfo(i))}if(n instanceof Li){const e=n.typeInfo.getTypeName();let s="";if(e.endsWith("f"))s="f32";else if(e.endsWith("i"))s="i32";else if(e.endsWith("u"))s="u32";else if(e.endsWith("b"))s="bool";else{if(!e.endsWith("h"))return console.error(`Unknown vector type ${e}. Line ${t.line}`),null;s="f16"}const r=i.getTypeName();let o="";if(r.endsWith("f"))o="f32";else if(r.endsWith("i"))o="i32";else if(r.endsWith("u"))o="u32";else if(r.endsWith("b"))o="bool";else{if(!r.endsWith("h"))return console.error(`Unknown vector type ${o}. Line ${t.line}`),null;o="f16"}const a=function(t,e,n){if(e===n)return t;const i=new Array(t.length);for(let s=0;s<t.length;s++)i[s]=Ki(t[s],e,n);return i}(Array.from(n.data),s,o);return new Li(a,this.getTypeInfo(i))}return console.error(`TODO: bitcast for ${n.typeInfo.name}. Line ${t.line}`),null}_evalConst(t,e){return e.getVariableValue(t.name).clone().getSubData(this,t.postfix,e)}_evalCreate(t,e){var n;if(t instanceof ci){if(null===t.type)return Ci.void;switch(t.type.getTypeName()){case"bool":case"i32":case"u32":case"f32":case"f16":return this._callConstructorValue(t,e);case"vec2":case"vec3":case"vec4":case"vec2f":case"vec3f":case"vec4f":case"vec2h":case"vec3h":case"vec4h":case"vec2i":case"vec3i":case"vec4i":case"vec2u":case"vec3u":case"vec4u":case"vec2b":case"vec3b":case"vec4b":return this._callConstructorVec(t,e);case"mat2x2":case"mat2x2f":case"mat2x2h":case"mat2x3":case"mat2x3f":case"mat2x3h":case"mat2x4":case"mat2x4f":case"mat2x4h":case"mat3x2":case"mat3x2f":case"mat3x2h":case"mat3x3":case"mat3x3f":case"mat3x3h":case"mat3x4":case"mat3x4f":case"mat3x4h":case"mat4x2":case"mat4x2f":case"mat4x2h":case"mat4x3":case"mat4x3f":case"mat4x3h":case"mat4x4":case"mat4x4f":case"mat4x4h":return this._callConstructorMatrix(t,e)}}const i=t instanceof ci?t.type.name:t.name,s=this.getTypeInfo(t instanceof ci?t.type:t.name);if(null===s)return console.error(`Unknown type ${i}. Line ${t.line}`),null;if(0===s.size)return null;const r=new Ii(new ArrayBuffer(s.size),s,0);if(s instanceof qe){if(t.args)for(let n=0;n<t.args.length;++n){const i=s.members[n],o=this.evalExpression(t.args[n],e);r.setData(this,o,i.type,i.offset,e)}}else if(s instanceof Ye){let i=0;if(t.args)for(let o=0;o<t.args.length;++o){const a=this.evalExpression(t.args[o],e);null===s.format&&(s.format="x32"===(null===(n=a.typeInfo)||void 0===n?void 0:n.name)?this.getTypeInfo("i32"):a.typeInfo),r.setData(this,a,s.format,i,e),i+=s.stride}}else console.error(`Unknown type "${i}". Line ${t.line}`);return t instanceof ci?r.getSubData(this,t.postfix,e):r}_evalLiteral(t,e){const n=this.getTypeInfo(t.type),i=n.name;return"x32"===i||"u32"===i||"f32"===i||"f16"===i||"i32"===i||"bool"===i?new Mi(t.scalarValue,n):"vec2"===i||"vec3"===i||"vec4"===i||"vec2f"===i||"vec3f"===i||"vec4f"===i||"vec2h"===i||"vec3h"===i||"vec4h"===i||"vec2i"===i||"vec3i"===i||"vec4i"===i||"vec2u"===i||"vec3u"===i||"vec4u"===i?this._callConstructorVec(t,e):"mat2x2"===i||"mat2x3"===i||"mat2x4"===i||"mat3x2"===i||"mat3x3"===i||"mat3x4"===i||"mat4x2"===i||"mat4x3"===i||"mat4x4"===i||"mat2x2f"===i||"mat2x3f"===i||"mat2x4f"===i||"mat3x2f"===i||"mat3x3f"===i||"mat3x4f"===i||"mat4x2f"===i||"mat4x3f"===i||"mat4x4f"===i||"mat2x2h"===i||"mat2x3h"===i||"mat2x4h"===i||"mat3x2h"===i||"mat3x3h"===i||"mat3x4h"===i||"mat4x2h"===i||"mat4x3h"===i||"mat4x4h"===i?this._callConstructorMatrix(t,e):t.value}_evalVariable(t,e){const n=e.getVariableValue(t.name);return null===n?n:n.getSubData(this,t.postfix,e)}_maxFormatTypeInfo(t){let e=t[0];if("f32"===e.name)return e;for(let n=1;n<t.length;++n){const i=as._priority.get(e.name);as._priority.get(t[n].name)<i&&(e=t[n])}return"x32"===e.name?this.getTypeInfo("i32"):e}_evalUnaryOp(t,e){const n=this.evalExpression(t.right,e);if("&"===t.operator)return new Pi(n);if("*"===t.operator)return n instanceof Pi?n.reference.getSubData(this,t.postfix,e):(console.error(`Invalid dereference. Line ${t.line}`),null);const i=n instanceof Mi?n.value:n instanceof Li?Array.from(n.data):null;switch(t.operator){case"+":{if($i(i)){const t=i.map((t=>+t));return new Li(t,n.typeInfo)}const t=i,e=this._maxFormatTypeInfo([n.typeInfo,n.typeInfo]);return new Mi(+t,e)}case"-":{if($i(i)){const t=i.map((t=>-t));return new Li(t,n.typeInfo)}const t=i,e=this._maxFormatTypeInfo([n.typeInfo,n.typeInfo]);return new Mi(-t,e)}case"!":{if($i(i)){const t=i.map((t=>t?0:1));return new Li(t,n.typeInfo)}const t=i,e=this._maxFormatTypeInfo([n.typeInfo,n.typeInfo]);return new Mi(t?0:1,e)}case"~":{if($i(i)){const t=i.map((t=>~t));return new Li(t,n.typeInfo)}const t=i,e=this._maxFormatTypeInfo([n.typeInfo,n.typeInfo]);return new Mi(~t,e)}}return console.error(`Invalid unary operator ${t.operator}. Line ${t.line}`),null}_evalBinaryOp(t,e){const n=this.evalExpression(t.left,e),i=this.evalExpression(t.right,e),s=n instanceof Mi?n.value:n instanceof Li||n instanceof Oi?Array.from(n.data):null,r=i instanceof Mi?i.value:i instanceof Li||i instanceof Oi?Array.from(i.data):null;switch(t.operator){case"+":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t+i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e+t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t+e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e+o,a)}case"-":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t-i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e-t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t-e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e-o,a)}case"*":{if($i(s)&&$i(r)){const e=s,o=r;if(n instanceof Oi&&i instanceof Oi){const s=function(t,e,n,i){if(void 0===os[e.name]||void 0===os[i.name])return null;const s=os[e.name][0],r=os[e.name][1],o=os[i.name][0];if(s!==os[i.name][1])return null;const a=new Array(o*r);for(let e=0;e<r;e++)for(let i=0;i<o;i++){let c=0;for(let o=0;o<s;o++)c+=t[o*r+e]*n[i*s+o];a[e*o+i]=c}return a}(e,n.typeInfo,o,i.typeInfo);if(null===s)return console.error(`Matrix multiplication failed. Line ${t.line}.`),null;const r=this.getTypeInfo(`mat${os[i.typeInfo.name][0]}x${os[n.typeInfo.name][1]}f`);return new Oi(s,r)}if(n instanceof Oi&&i instanceof Li){const s=function(t,e,n,i){if(void 0===os[e.name]||void 0===rs[i.name])return null;const s=os[e.name][0],r=os[e.name][1];if(s!==n.length)return null;const o=new Array(r);for(let e=0;e<r;e++){let i=0;for(let o=0;o<s;o++)i+=t[o*r+e]*n[o];o[e]=i}return o}(e,n.typeInfo,o,i.typeInfo);return null===s?(console.error(`Matrix vector multiplication failed. Line ${t.line}.`),null):new Li(s,i.typeInfo)}if(n instanceof Li&&i instanceof Oi){const s=function(t,e,n,i){if(void 0===rs[e.name]||void 0===os[i.name])return null;const s=os[i.name][0],r=os[i.name][1];if(r!==t.length)return null;const o=[];for(let e=0;e<s;e++){let i=0;for(let o=0;o<r;o++)i+=t[o]*n[o*s+e];o[e]=i}return o}(e,n.typeInfo,o,i.typeInfo);return null===s?(console.error(`Matrix vector multiplication failed. Line ${t.line}.`),null):new Li(s,n.typeInfo)}{if(e.length!==o.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const i=e.map(((t,e)=>t*o[e]));return new Li(i,n.typeInfo)}}if($i(s)){const t=r,e=s.map((e=>e*t));return n instanceof Oi?new Oi(e,n.typeInfo):new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t*e));return i instanceof Oi?new Oi(e,i.typeInfo):new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e*o,a)}case"%":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t%i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e%t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t%e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e%o,a)}case"/":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t/i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e/t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t/e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e/o,a)}case"&":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t&i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e&t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t&e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e&o,a)}case"|":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t|i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e|t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t|e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e|o,a)}case"^":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t^i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e^t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t^e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e^o,a)}case"<<":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t<<i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e<<t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t<<e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e<<o,a)}case">>":{if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t>>i[e]));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e>>t));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t>>e));return new Li(e,i.typeInfo)}const e=s,o=r,a=this._maxFormatTypeInfo([n.typeInfo,i.typeInfo]);return new Mi(e>>o,a)}case">":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t>i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e>t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t>e?1:0));return new Li(e,i.typeInfo)}return new Mi(s>r?1:0,this.getTypeInfo("bool"));case"<":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t<i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e<t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t<e?1:0));return new Li(e,i.typeInfo)}return new Mi(s<r?1:0,this.getTypeInfo("bool"));case"==":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t===i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e==t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t==e?1:0));return new Li(e,i.typeInfo)}return new Mi(s===r?1:0,this.getTypeInfo("bool"));case"!=":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t!==i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e!==t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t!==e?1:0));return new Li(e,i.typeInfo)}return new Mi(s!==r?1:0,this.getTypeInfo("bool"));case">=":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t>=i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e>=t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t>=e?1:0));return new Li(e,i.typeInfo)}return new Mi(s>=r?1:0,this.getTypeInfo("bool"));case"<=":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t<=i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e<=t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t<=e?1:0));return new Li(e,i.typeInfo)}return new Mi(s<=r?1:0,this.getTypeInfo("bool"));case"&&":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t&&i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e&&t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t&&e?1:0));return new Li(e,i.typeInfo)}return new Mi(s&&r?1:0,this.getTypeInfo("bool"));case"||":if($i(s)&&$i(r)){const e=s,i=r;if(e.length!==i.length)return console.error(`Vector length mismatch. Line ${t.line}.`),null;const o=e.map(((t,e)=>t||i[e]?1:0));return new Li(o,n.typeInfo)}if($i(s)){const t=r,e=s.map((e=>e||t?1:0));return new Li(e,n.typeInfo)}if($i(r)){const t=s,e=r.map((e=>t||e?1:0));return new Li(e,i.typeInfo)}return new Mi(s||r?1:0,this.getTypeInfo("bool"))}return console.error(`Unknown operator ${t.operator}. Line ${t.line}`),null}_evalCall(t,e){if(null!==t.cachedReturnValue)return t.cachedReturnValue;const n=e.clone();n.currentFunctionName=t.name;const i=e.getFunction(t.name);if(!i)return t.isBuiltin?this._callBuiltinFunction(t,n):this.getTypeInfo(t.name)?this._evalCreate(t,e):(console.error(`Unknown function "${t.name}". Line ${t.line}`),null);for(let e=0;e<i.node.args.length;++e){const s=i.node.args[e],r=this.evalExpression(t.args[e],n);n.createVariable(s.name,r,s)}return this._execStatements(i.node.body,n)}_callBuiltinFunction(t,e){switch(t.name){case"all":return this.builtins.All(t,e);case"any":return this.builtins.Any(t,e);case"select":return this.builtins.Select(t,e);case"arrayLength":return this.builtins.ArrayLength(t,e);case"abs":return this.builtins.Abs(t,e);case"acos":return this.builtins.Acos(t,e);case"acosh":return this.builtins.Acosh(t,e);case"asin":return this.builtins.Asin(t,e);case"asinh":return this.builtins.Asinh(t,e);case"atan":return this.builtins.Atan(t,e);case"atanh":return this.builtins.Atanh(t,e);case"atan2":return this.builtins.Atan2(t,e);case"ceil":return this.builtins.Ceil(t,e);case"clamp":return this.builtins.Clamp(t,e);case"cos":return this.builtins.Cos(t,e);case"cosh":return this.builtins.Cosh(t,e);case"countLeadingZeros":return this.builtins.CountLeadingZeros(t,e);case"countOneBits":return this.builtins.CountOneBits(t,e);case"countTrailingZeros":return this.builtins.CountTrailingZeros(t,e);case"cross":return this.builtins.Cross(t,e);case"degrees":return this.builtins.Degrees(t,e);case"determinant":return this.builtins.Determinant(t,e);case"distance":return this.builtins.Distance(t,e);case"dot":return this.builtins.Dot(t,e);case"dot4U8Packed":return this.builtins.Dot4U8Packed(t,e);case"dot4I8Packed":return this.builtins.Dot4I8Packed(t,e);case"exp":return this.builtins.Exp(t,e);case"exp2":return this.builtins.Exp2(t,e);case"extractBits":return this.builtins.ExtractBits(t,e);case"faceForward":return this.builtins.FaceForward(t,e);case"firstLeadingBit":return this.builtins.FirstLeadingBit(t,e);case"firstTrailingBit":return this.builtins.FirstTrailingBit(t,e);case"floor":return this.builtins.Floor(t,e);case"fma":return this.builtins.Fma(t,e);case"fract":return this.builtins.Fract(t,e);case"frexp":return this.builtins.Frexp(t,e);case"insertBits":return this.builtins.InsertBits(t,e);case"inverseSqrt":return this.builtins.InverseSqrt(t,e);case"ldexp":return this.builtins.Ldexp(t,e);case"length":return this.builtins.Length(t,e);case"log":return this.builtins.Log(t,e);case"log2":return this.builtins.Log2(t,e);case"max":return this.builtins.Max(t,e);case"min":return this.builtins.Min(t,e);case"mix":return this.builtins.Mix(t,e);case"modf":return this.builtins.Modf(t,e);case"normalize":return this.builtins.Normalize(t,e);case"pow":return this.builtins.Pow(t,e);case"quantizeToF16":return this.builtins.QuantizeToF16(t,e);case"radians":return this.builtins.Radians(t,e);case"reflect":return this.builtins.Reflect(t,e);case"refract":return this.builtins.Refract(t,e);case"reverseBits":return this.builtins.ReverseBits(t,e);case"round":return this.builtins.Round(t,e);case"saturate":return this.builtins.Saturate(t,e);case"sign":return this.builtins.Sign(t,e);case"sin":return this.builtins.Sin(t,e);case"sinh":return this.builtins.Sinh(t,e);case"smoothstep":return this.builtins.SmoothStep(t,e);case"sqrt":return this.builtins.Sqrt(t,e);case"step":return this.builtins.Step(t,e);case"tan":return this.builtins.Tan(t,e);case"tanh":return this.builtins.Tanh(t,e);case"transpose":return this.builtins.Transpose(t,e);case"trunc":return this.builtins.Trunc(t,e);case"dpdx":return this.builtins.Dpdx(t,e);case"dpdxCoarse":return this.builtins.DpdxCoarse(t,e);case"dpdxFine":return this.builtins.DpdxFine(t,e);case"dpdy":return this.builtins.Dpdy(t,e);case"dpdyCoarse":return this.builtins.DpdyCoarse(t,e);case"dpdyFine":return this.builtins.DpdyFine(t,e);case"fwidth":return this.builtins.Fwidth(t,e);case"fwidthCoarse":return this.builtins.FwidthCoarse(t,e);case"fwidthFine":return this.builtins.FwidthFine(t,e);case"textureDimensions":return this.builtins.TextureDimensions(t,e);case"textureGather":return this.builtins.TextureGather(t,e);case"textureGatherCompare":return this.builtins.TextureGatherCompare(t,e);case"textureLoad":return this.builtins.TextureLoad(t,e);case"textureNumLayers":return this.builtins.TextureNumLayers(t,e);case"textureNumLevels":return this.builtins.TextureNumLevels(t,e);case"textureNumSamples":return this.builtins.TextureNumSamples(t,e);case"textureSample":return this.builtins.TextureSample(t,e);case"textureSampleBias":return this.builtins.TextureSampleBias(t,e);case"textureSampleCompare":return this.builtins.TextureSampleCompare(t,e);case"textureSampleCompareLevel":return this.builtins.TextureSampleCompareLevel(t,e);case"textureSampleGrad":return this.builtins.TextureSampleGrad(t,e);case"textureSampleLevel":return this.builtins.TextureSampleLevel(t,e);case"textureSampleBaseClampToEdge":return this.builtins.TextureSampleBaseClampToEdge(t,e);case"textureStore":return this.builtins.TextureStore(t,e);case"atomicLoad":return this.builtins.AtomicLoad(t,e);case"atomicStore":return this.builtins.AtomicStore(t,e);case"atomicAdd":return this.builtins.AtomicAdd(t,e);case"atomicSub":return this.builtins.AtomicSub(t,e);case"atomicMax":return this.builtins.AtomicMax(t,e);case"atomicMin":return this.builtins.AtomicMin(t,e);case"atomicAnd":return this.builtins.AtomicAnd(t,e);case"atomicOr":return this.builtins.AtomicOr(t,e);case"atomicXor":return this.builtins.AtomicXor(t,e);case"atomicExchange":return this.builtins.AtomicExchange(t,e);case"atomicCompareExchangeWeak":return this.builtins.AtomicCompareExchangeWeak(t,e);case"pack4x8snorm":return this.builtins.Pack4x8snorm(t,e);case"pack4x8unorm":return this.builtins.Pack4x8unorm(t,e);case"pack4xI8":return this.builtins.Pack4xI8(t,e);case"pack4xU8":return this.builtins.Pack4xU8(t,e);case"pack4x8Clamp":return this.builtins.Pack4x8Clamp(t,e);case"pack4xU8Clamp":return this.builtins.Pack4xU8Clamp(t,e);case"pack2x16snorm":return this.builtins.Pack2x16snorm(t,e);case"pack2x16unorm":return this.builtins.Pack2x16unorm(t,e);case"pack2x16float":return this.builtins.Pack2x16float(t,e);case"unpack4x8snorm":return this.builtins.Unpack4x8snorm(t,e);case"unpack4x8unorm":return this.builtins.Unpack4x8unorm(t,e);case"unpack4xI8":return this.builtins.Unpack4xI8(t,e);case"unpack4xU8":return this.builtins.Unpack4xU8(t,e);case"unpack2x16snorm":return this.builtins.Unpack2x16snorm(t,e);case"unpack2x16unorm":return this.builtins.Unpack2x16unorm(t,e);case"unpack2x16float":return this.builtins.Unpack2x16float(t,e);case"storageBarrier":return this.builtins.StorageBarrier(t,e);case"textureBarrier":return this.builtins.TextureBarrier(t,e);case"workgroupBarrier":return this.builtins.WorkgroupBarrier(t,e);case"workgroupUniformLoad":return this.builtins.WorkgroupUniformLoad(t,e);case"subgroupAdd":return this.builtins.SubgroupAdd(t,e);case"subgroupExclusiveAdd":return this.builtins.SubgroupExclusiveAdd(t,e);case"subgroupInclusiveAdd":return this.builtins.SubgroupInclusiveAdd(t,e);case"subgroupAll":return this.builtins.SubgroupAll(t,e);case"subgroupAnd":return this.builtins.SubgroupAnd(t,e);case"subgroupAny":return this.builtins.SubgroupAny(t,e);case"subgroupBallot":return this.builtins.SubgroupBallot(t,e);case"subgroupBroadcast":return this.builtins.SubgroupBroadcast(t,e);case"subgroupBroadcastFirst":return this.builtins.SubgroupBroadcastFirst(t,e);case"subgroupElect":return this.builtins.SubgroupElect(t,e);case"subgroupMax":return this.builtins.SubgroupMax(t,e);case"subgroupMin":return this.builtins.SubgroupMin(t,e);case"subgroupMul":return this.builtins.SubgroupMul(t,e);case"subgroupExclusiveMul":return this.builtins.SubgroupExclusiveMul(t,e);case"subgroupInclusiveMul":return this.builtins.SubgroupInclusiveMul(t,e);case"subgroupOr":return this.builtins.SubgroupOr(t,e);case"subgroupShuffle":return this.builtins.SubgroupShuffle(t,e);case"subgroupShuffleDown":return this.builtins.SubgroupShuffleDown(t,e);case"subgroupShuffleUp":return this.builtins.SubgroupShuffleUp(t,e);case"subgroupShuffleXor":return this.builtins.SubgroupShuffleXor(t,e);case"subgroupXor":return this.builtins.SubgroupXor(t,e);case"quadBroadcast":return this.builtins.QuadBroadcast(t,e);case"quadSwapDiagonal":return this.builtins.QuadSwapDiagonal(t,e);case"quadSwapX":return this.builtins.QuadSwapX(t,e);case"quadSwapY":return this.builtins.QuadSwapY(t,e)}const n=e.getFunction(t.name);if(n){const i=e.clone();for(let e=0;e<n.node.args.length;++e){const s=n.node.args[e],r=this.evalExpression(t.args[e],i);i.setVariable(s.name,r,s)}return this._execStatements(n.node.body,i)}return null}_callConstructorValue(t,e){if(!t.args||0===t.args.length)return new Mi(0,this.getTypeInfo(t.type));const n=this.evalExpression(t.args[0],e);return n.typeInfo=this.getTypeInfo(t.type),n.getSubData(this,t.postfix,e).clone()}_callConstructorVec(t,e){const n=this.getTypeInfo(t.type),i=t.type.getTypeName(),s=rs[i];if(void 0===s)return console.error(`Invalid vec constructor ${i}. Line ${t.line}`),null;const r=[];if(t instanceof fi)if(t.isVector){const e=t.vectorValue;for(const t of e)r.push(t)}else r.push(t.scalarValue);else if(t.args)for(const n of t.args){const t=this.evalExpression(n,e);if(t instanceof Li){const e=t.data;for(let t=0;t<e.length;++t)r.push(e[t])}else t instanceof Mi&&r.push(t.value)}if(t.type instanceof ni&&null===t.type.format&&(t.type.format=ni.f32),0===r.length){const i=new Array(s).fill(0);return new Li(i,n).getSubData(this,t.postfix,e)}if(1===r.length)for(;r.length<s;)r.push(r[0]);return r.length<s?(console.error(`Invalid vec constructor. Line ${t.line}`),null):new Li(r.length>s?r.slice(0,s):r,n).getSubData(this,t.postfix,e)}_callConstructorMatrix(t,e){const n=this.getTypeInfo(t.type),i=t.type.getTypeName(),s=os[i];if(void 0===s)return console.error(`Invalid matrix constructor ${i}. Line ${t.line}`),null;const r=[];if(t instanceof fi)if(t.isVector){const e=t.vectorValue;for(const t of e)r.push(t)}else r.push(t.scalarValue);else if(t.args)for(const n of t.args){const t=this.evalExpression(n,e);t instanceof Li?r.push(...t.data):t instanceof Mi?r.push(t.value):t instanceof Oi&&r.push(...t.data)}if(n instanceof Qe&&null===n.format&&(n.format=this.getTypeInfo("f32")),0===r.length){const i=new Array(s[2]).fill(0);return new Oi(i,n).getSubData(this,t.postfix,e)}return r.length!==s[2]?(console.error(`Invalid matrix constructor. Line ${t.line}`),null):new Oi(r,n).getSubData(this,t.postfix,e)}}as._breakObj=new Si(new Ze("BREAK",null),null),as._continueObj=new Si(new Ze("CONTINUE",null),null),as._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class cs{constructor(){this.constants=new Map,this.aliases=new Map,this.structs=new Map}}class ls{constructor(){this._tokens=[],this._current=0,this._currentLine=1,this._deferArrayCountEval=[],this._currentLoop=[],this._context=new cs,this._exec=new as,this._forwardTypeCount=0}parse(t){this._initialize(t),this._deferArrayCountEval.length=0;const e=[];for(;!this._isAtEnd();){const t=this._global_decl_or_directive();if(!t)break;e.push(t)}if(this._deferArrayCountEval.length>0){for(const e of this._deferArrayCountEval){const n=e.arrayType,i=e.countNode;if(i instanceof hi){const e=this._context.constants.get(i.name);if(e)try{const t=e.constEvaluate(this._exec);n.count=t}catch(t){}}}this._deferArrayCountEval.length=0}if(this._forwardTypeCount>0)for(const t of e)t.search((t=>{t instanceof Ti||t instanceof ii?t.type=this._forwardType(t.type):t instanceof si?t.format=this._forwardType(t.format):t instanceof Ln||t instanceof In||t instanceof kn?t.type=this._forwardType(t.type):t instanceof Sn?t.returnType=this._forwardType(t.returnType):t instanceof xi&&(t.type=this._forwardType(t.type))}));return e}_forwardType(t){if(t instanceof ti){const e=this._getType(t.name);if(e)return e}else t instanceof ii?t.type=this._forwardType(t.type):t instanceof si&&(t.format=this._forwardType(t.format));return t}_initialize(t){if(t)if("string"==typeof t){const e=new Bi(t);this._tokens=e.scanTokens()}else this._tokens=t;else this._tokens=[];this._current=0}_updateNode(t,e){return t.line=null!=e?e:this._currentLine,t}_error(t,e){return{token:t,message:e,toString:()=>`${e}`}}_isAtEnd(){return this._current>=this._tokens.length||this._peek().type==Ni.eof}_match(t){if(t instanceof Di)return!!this._check(t)&&(this._advance(),!0);for(let e=0,n=t.length;e<n;++e)if(this._check(t[e]))return this._advance(),!0;return!1}_consume(t,e){if(this._check(t))return this._advance();throw this._error(this._peek(),`${e}. Line:${this._currentLine}`)}_check(t){if(this._isAtEnd())return!1;const e=this._peek();if(t instanceof Array){const n=e.type;let i=!1;for(const e of t){if(n===e)return!0;e===Ni.tokens.name&&(i=!0)}if(i){const t=Ni.tokens.name.rule.exec(e.lexeme);if(t&&0==t.index&&t[0]==e.lexeme)return!0}return!1}if(e.type===t)return!0;if(t===Ni.tokens.name){const t=Ni.tokens.name.rule.exec(e.lexeme);return t&&0==t.index&&t[0]==e.lexeme}return!1}_advance(){var t,e;return this._currentLine=null!==(e=null===(t=this._peek())||void 0===t?void 0:t.line)&&void 0!==e?e:-1,this._isAtEnd()||this._current++,this._previous()}_peek(){return this._tokens[this._current]}_previous(){return this._tokens[this._current-1]}_global_decl_or_directive(){for(;this._match(Ni.tokens.semicolon)&&!this._isAtEnd(););if(this._match(Ni.keywords.alias)){const t=this._type_alias();return this._consume(Ni.tokens.semicolon,"Expected ';'"),this._exec.reflection.updateAST([t]),t}if(this._match(Ni.keywords.diagnostic)){const t=this._diagnostic();return this._consume(Ni.tokens.semicolon,"Expected ';'"),this._exec.reflection.updateAST([t]),t}if(this._match(Ni.keywords.requires)){const t=this._requires_directive();return this._consume(Ni.tokens.semicolon,"Expected ';'"),this._exec.reflection.updateAST([t]),t}if(this._match(Ni.keywords.enable)){const t=this._enable_directive();return this._consume(Ni.tokens.semicolon,"Expected ';'"),this._exec.reflection.updateAST([t]),t}const t=this._attribute();if(this._check(Ni.keywords.var)){const e=this._global_variable_decl();return null!=e&&(e.attributes=t),this._consume(Ni.tokens.semicolon,"Expected ';'."),this._exec.reflection.updateAST([e]),e}if(this._check(Ni.keywords.override)){const e=this._override_variable_decl();return null!=e&&(e.attributes=t),this._consume(Ni.tokens.semicolon,"Expected ';'."),this._exec.reflection.updateAST([e]),e}if(this._check(Ni.keywords.let)){const e=this._global_let_decl();return null!=e&&(e.attributes=t),this._consume(Ni.tokens.semicolon,"Expected ';'."),this._exec.reflection.updateAST([e]),e}if(this._check(Ni.keywords.const)){const e=this._global_const_decl();return null!=e&&(e.attributes=t),this._consume(Ni.tokens.semicolon,"Expected ';'."),this._exec.reflection.updateAST([e]),e}if(this._check(Ni.keywords.struct)){const e=this._struct_decl();return null!=e&&(e.attributes=t),this._exec.reflection.updateAST([e]),e}if(this._check(Ni.keywords.fn)){const e=this._function_decl();return null!=e&&(e.attributes=t),this._exec.reflection.updateAST([e]),e}return null}_function_decl(){if(!this._match(Ni.keywords.fn))return null;const t=this._currentLine,e=this._consume(Ni.tokens.ident,"Expected function name.").toString();this._consume(Ni.tokens.paren_left,"Expected '(' for function arguments.");const n=[];if(!this._check(Ni.tokens.paren_right))do{if(this._check(Ni.tokens.paren_right))break;const t=this._attribute(),e=this._consume(Ni.tokens.name,"Expected argument name.").toString();this._consume(Ni.tokens.colon,"Expected ':' for argument type.");const i=this._attribute(),s=this._type_decl();null!=s&&(s.attributes=i,n.push(this._updateNode(new xi(e,s,t))))}while(this._match(Ni.tokens.comma));this._consume(Ni.tokens.paren_right,"Expected ')' after function arguments.");let i=null;if(this._match(Ni.tokens.arrow)){const t=this._attribute();i=this._type_decl(),null!=i&&(i.attributes=t)}const s=this._compound_statement();return this._updateNode(new Sn(e,n,i,s,t,this._currentLine),t)}_compound_statement(){const t=[];for(this._consume(Ni.tokens.brace_left,"Expected '{' for block.");!this._check(Ni.tokens.brace_right);){const e=this._statement();null!==e&&t.push(e)}return this._consume(Ni.tokens.brace_right,"Expected '}' for block."),t}_statement(){for(;this._match(Ni.tokens.semicolon)&&!this._isAtEnd(););if(this._check(Ni.tokens.attr)&&this._attribute(),this._check(Ni.keywords.if))return this._if_statement();if(this._check(Ni.keywords.switch))return this._switch_statement();if(this._check(Ni.keywords.loop))return this._loop_statement();if(this._check(Ni.keywords.for))return this._for_statement();if(this._check(Ni.keywords.while))return this._while_statement();if(this._check(Ni.keywords.continuing))return this._continuing_statement();if(this._check(Ni.keywords.static_assert))return this._static_assert_statement();if(this._check(Ni.tokens.brace_left))return this._compound_statement();let t=null;if(this._check(Ni.keywords.return))t=this._return_statement();else if(this._check([Ni.keywords.var,Ni.keywords.let,Ni.keywords.const]))t=this._variable_statement();else if(this._match(Ni.keywords.discard))t=this._updateNode(new qn);else if(this._match(Ni.keywords.break)){const e=this._updateNode(new Yn);this._currentLoop.length>0&&(e.loopId=this._currentLoop[this._currentLoop.length-1].id),t=e,this._check(Ni.keywords.if)&&(this._advance(),e.condition=this._optional_paren_expression())}else if(this._match(Ni.keywords.continue)){const e=this._updateNode(new Jn);if(!(this._currentLoop.length>0))throw this._error(this._peek(),`Continue statement must be inside a loop. Line: ${e.line}`);e.loopId=this._currentLoop[this._currentLoop.length-1].id,t=e}else t=this._increment_decrement_statement()||this._func_call_statement()||this._assignment_statement();return null!=t&&this._consume(Ni.tokens.semicolon,"Expected ';' after statement."),t}_static_assert_statement(){if(!this._match(Ni.keywords.static_assert))return null;const t=this._currentLine,e=this._optional_paren_expression();return this._updateNode(new Cn(e),t)}_while_statement(){if(!this._match(Ni.keywords.while))return null;const t=this._updateNode(new Pn(null,null));return this._currentLoop.push(t),t.condition=this._optional_paren_expression(),this._check(Ni.tokens.attr)&&this._attribute(),t.body=this._compound_statement(),this._currentLoop.pop(),t}_continuing_statement(){const t=this._currentLoop.length>0?this._currentLoop[this._currentLoop.length-1].id:-1;if(!this._match(Ni.keywords.continuing))return null;const e=this._currentLine,n=this._compound_statement();return this._updateNode(new Mn(n,t),e)}_for_statement(){if(!this._match(Ni.keywords.for))return null;this._consume(Ni.tokens.paren_left,"Expected '('.");const t=this._updateNode(new Rn(null,null,null,null));return this._currentLoop.push(t),t.init=this._check(Ni.tokens.semicolon)?null:this._for_init(),this._consume(Ni.tokens.semicolon,"Expected ';'."),t.condition=this._check(Ni.tokens.semicolon)?null:this._short_circuit_or_expression(),this._consume(Ni.tokens.semicolon,"Expected ';'."),t.increment=this._check(Ni.tokens.paren_right)?null:this._for_increment(),this._consume(Ni.tokens.paren_right,"Expected ')'."),this._check(Ni.tokens.attr)&&this._attribute(),t.body=this._compound_statement(),this._currentLoop.pop(),t}_for_init(){return this._variable_statement()||this._func_call_statement()||this._assignment_statement()}_for_increment(){return this._func_call_statement()||this._increment_decrement_statement()||this._assignment_statement()}_variable_statement(){if(this._check(Ni.keywords.var)){const t=this._variable_decl();if(null===t)throw this._error(this._peek(),"Variable declaration expected.");let e=null;return this._match(Ni.tokens.equal)&&(e=this._short_circuit_or_expression()),this._updateNode(new Ln(t.name,t.type,t.storage,t.access,e),t.line)}if(this._match(Ni.keywords.let)){const t=this._currentLine,e=this._consume(Ni.tokens.name,"Expected name for let.").toString();let n=null;if(this._match(Ni.tokens.colon)){const t=this._attribute();n=this._type_decl(),null!=n&&(n.attributes=t)}this._consume(Ni.tokens.equal,"Expected '=' for let.");const i=this._short_circuit_or_expression();return this._updateNode(new In(e,n,null,null,i),t)}if(this._match(Ni.keywords.const)){const t=this._currentLine,e=this._consume(Ni.tokens.name,"Expected name for const.").toString();let n=null;if(this._match(Ni.tokens.colon)){const t=this._attribute();n=this._type_decl(),null!=n&&(n.attributes=t)}this._consume(Ni.tokens.equal,"Expected '=' for const.");const i=this._short_circuit_or_expression();return null===n&&i instanceof fi&&(n=i.type),this._updateNode(new kn(e,n,null,null,i),t)}return null}_increment_decrement_statement(){const t=this._current,e=this._unary_expression();if(null==e)return null;if(!this._check(Ni.increment_operators))return this._current=t,null;const n=this._consume(Ni.increment_operators,"Expected increment operator");return this._updateNode(new $n(n.type===Ni.tokens.plus_plus?Dn.increment:Dn.decrement,e))}_assignment_statement(){let t=null;const e=this._currentLine;if(this._check(Ni.tokens.brace_right))return null;let n=this._match(Ni.tokens.underscore);if(n||(t=this._unary_expression()),!n&&null==t)return null;const i=this._consume(Ni.assignment_operators,"Expected assignment operator."),s=this._short_circuit_or_expression();return this._updateNode(new Un(Nn.parse(i.lexeme),t,s),e)}_func_call_statement(){if(!this._check(Ni.tokens.ident))return null;const t=this._currentLine,e=this._current,n=this._consume(Ni.tokens.ident,"Expected function name."),i=this._argument_expression_list();return null===i?(this._current=e,null):this._updateNode(new zn(n.lexeme,i),t)}_loop_statement(){if(!this._match(Ni.keywords.loop))return null;this._check(Ni.tokens.attr)&&this._attribute(),this._consume(Ni.tokens.brace_left,"Expected '{' for loop.");const t=this._updateNode(new jn([],null));this._currentLoop.push(t);let e=this._statement();for(;null!==e;){if(Array.isArray(e))for(let n of e)t.body.push(n);else t.body.push(e);if(e instanceof Mn){t.continuing=e;break}e=this._statement()}return this._currentLoop.pop(),this._consume(Ni.tokens.brace_right,"Expected '}' for loop."),t}_switch_statement(){if(!this._match(Ni.keywords.switch))return null;const t=this._updateNode(new Gn(null,[]));if(this._currentLoop.push(t),t.condition=this._optional_paren_expression(),this._check(Ni.tokens.attr)&&this._attribute(),this._consume(Ni.tokens.brace_left,"Expected '{' for switch."),t.cases=this._switch_body(),null==t.cases||0==t.cases.length)throw this._error(this._previous(),"Expected 'case' or 'default'.");return this._consume(Ni.tokens.brace_right,"Expected '}' for switch."),this._currentLoop.pop(),t}_switch_body(){const t=[];let e=!1;for(;this._check([Ni.keywords.default,Ni.keywords.case]);){if(this._match(Ni.keywords.case)){const n=this._case_selectors();for(const t of n)if(t instanceof bi){if(e)throw this._error(this._previous(),"Multiple default cases in switch statement.");e=!0;break}this._match(Ni.tokens.colon),this._check(Ni.tokens.attr)&&this._attribute(),this._consume(Ni.tokens.brace_left,"Exected '{' for switch case.");const i=this._case_body();this._consume(Ni.tokens.brace_right,"Exected '}' for switch case."),t.push(this._updateNode(new yi(n,i)))}if(this._match(Ni.keywords.default)){if(e)throw this._error(this._previous(),"Multiple default cases in switch statement.");this._match(Ni.tokens.colon),this._check(Ni.tokens.attr)&&this._attribute(),this._consume(Ni.tokens.brace_left,"Exected '{' for switch default.");const n=this._case_body();this._consume(Ni.tokens.brace_right,"Exected '}' for switch default."),t.push(this._updateNode(new wi(n)))}}return t}_case_selectors(){const t=[];for(this._match(Ni.keywords.default)?t.push(this._updateNode(new bi)):t.push(this._shift_expression());this._match(Ni.tokens.comma);)this._match(Ni.keywords.default)?t.push(this._updateNode(new bi)):t.push(this._shift_expression());return t}_case_body(){if(this._match(Ni.keywords.fallthrough))return this._consume(Ni.tokens.semicolon,"Expected ';'"),[];let t=this._statement();if(null==t)return[];t instanceof Array||(t=[t]);const e=this._case_body();return 0==e.length?t:[...t,e[0]]}_if_statement(){if(!this._match(Ni.keywords.if))return null;const t=this._currentLine,e=this._optional_paren_expression();this._check(Ni.tokens.attr)&&this._attribute();const n=this._compound_statement();let i=[];this._match_elseif()&&(this._check(Ni.tokens.attr)&&this._attribute(),i=this._elseif_statement(i));let s=null;return this._match(Ni.keywords.else)&&(this._check(Ni.tokens.attr)&&this._attribute(),s=this._compound_statement()),this._updateNode(new Wn(e,n,i,s),t)}_match_elseif(){return this._tokens[this._current].type===Ni.keywords.else&&this._tokens[this._current+1].type===Ni.keywords.if&&(this._advance(),this._advance(),!0)}_elseif_statement(t=[]){const e=this._optional_paren_expression(),n=this._compound_statement();return t.push(this._updateNode(new Ei(e,n))),this._match_elseif()&&(this._check(Ni.tokens.attr)&&this._attribute(),this._elseif_statement(t)),t}_return_statement(){if(!this._match(Ni.keywords.return))return null;const t=this._short_circuit_or_expression();return this._updateNode(new Vn(t))}_short_circuit_or_expression(){let t=this._short_circuit_and_expr();for(;this._match(Ni.tokens.or_or);)t=this._updateNode(new _i(this._previous().toString(),t,this._short_circuit_and_expr()));return t}_short_circuit_and_expr(){let t=this._inclusive_or_expression();for(;this._match(Ni.tokens.and_and);)t=this._updateNode(new _i(this._previous().toString(),t,this._inclusive_or_expression()));return t}_inclusive_or_expression(){let t=this._exclusive_or_expression();for(;this._match(Ni.tokens.or);)t=this._updateNode(new _i(this._previous().toString(),t,this._exclusive_or_expression()));return t}_exclusive_or_expression(){let t=this._and_expression();for(;this._match(Ni.tokens.xor);)t=this._updateNode(new _i(this._previous().toString(),t,this._and_expression()));return t}_and_expression(){let t=this._equality_expression();for(;this._match(Ni.tokens.and);)t=this._updateNode(new _i(this._previous().toString(),t,this._equality_expression()));return t}_equality_expression(){const t=this._relational_expression();return this._match([Ni.tokens.equal_equal,Ni.tokens.not_equal])?this._updateNode(new _i(this._previous().toString(),t,this._relational_expression())):t}_relational_expression(){let t=this._shift_expression();for(;this._match([Ni.tokens.less_than,Ni.tokens.greater_than,Ni.tokens.less_than_equal,Ni.tokens.greater_than_equal]);)t=this._updateNode(new _i(this._previous().toString(),t,this._shift_expression()));return t}_shift_expression(){let t=this._additive_expression();for(;this._match([Ni.tokens.shift_left,Ni.tokens.shift_right]);)t=this._updateNode(new _i(this._previous().toString(),t,this._additive_expression()));return t}_additive_expression(){let t=this._multiplicative_expression();for(;this._match([Ni.tokens.plus,Ni.tokens.minus]);)t=this._updateNode(new _i(this._previous().toString(),t,this._multiplicative_expression()));return t}_multiplicative_expression(){let t=this._unary_expression();for(;this._match([Ni.tokens.star,Ni.tokens.forward_slash,Ni.tokens.modulo]);)t=this._updateNode(new _i(this._previous().toString(),t,this._unary_expression()));return t}_unary_expression(){return this._match([Ni.tokens.minus,Ni.tokens.bang,Ni.tokens.tilde,Ni.tokens.star,Ni.tokens.and])?this._updateNode(new mi(this._previous().toString(),this._unary_expression())):this._singular_expression()}_singular_expression(){const t=this._primary_expression(),e=this._postfix_expression();return e&&(t.postfix=e),t}_postfix_expression(){if(this._match(Ni.tokens.bracket_left)){const t=this._short_circuit_or_expression();this._consume(Ni.tokens.bracket_right,"Expected ']'.");const e=this._updateNode(new pi(t)),n=this._postfix_expression();return n&&(e.postfix=n),e}if(this._match(Ni.tokens.period)){const t=this._consume(Ni.tokens.name,"Expected member name."),e=this._postfix_expression(),n=this._updateNode(new ai(t.lexeme));return e&&(n.postfix=e),n}return null}_getStruct(t){return this._context.aliases.has(t)?this._context.aliases.get(t).type:this._context.structs.has(t)?this._context.structs.get(t):null}_getType(t){const e=this._getStruct(t);if(null!==e)return e;switch(t){case"void":return Qn.void;case"bool":return Qn.bool;case"i32":return Qn.i32;case"u32":return Qn.u32;case"f32":return Qn.f32;case"f16":return Qn.f16;case"vec2f":return ni.vec2f;case"vec3f":return ni.vec3f;case"vec4f":return ni.vec4f;case"vec2i":return ni.vec2i;case"vec3i":return ni.vec3i;case"vec4i":return ni.vec4i;case"vec2u":return ni.vec2u;case"vec3u":return ni.vec3u;case"vec4u":return ni.vec4u;case"vec2h":return ni.vec2h;case"vec3h":return ni.vec3h;case"vec4h":return ni.vec4h;case"mat2x2f":return ni.mat2x2f;case"mat2x3f":return ni.mat2x3f;case"mat2x4f":return ni.mat2x4f;case"mat3x2f":return ni.mat3x2f;case"mat3x3f":return ni.mat3x3f;case"mat3x4f":return ni.mat3x4f;case"mat4x2f":return ni.mat4x2f;case"mat4x3f":return ni.mat4x3f;case"mat4x4f":return ni.mat4x4f;case"mat2x2h":return ni.mat2x2h;case"mat2x3h":return ni.mat2x3h;case"mat2x4h":return ni.mat2x4h;case"mat3x2h":return ni.mat3x2h;case"mat3x3h":return ni.mat3x3h;case"mat3x4h":return ni.mat3x4h;case"mat4x2h":return ni.mat4x2h;case"mat4x3h":return ni.mat4x3h;case"mat4x4h":return ni.mat4x4h;case"mat2x2i":return ni.mat2x2i;case"mat2x3i":return ni.mat2x3i;case"mat2x4i":return ni.mat2x4i;case"mat3x2i":return ni.mat3x2i;case"mat3x3i":return ni.mat3x3i;case"mat3x4i":return ni.mat3x4i;case"mat4x2i":return ni.mat4x2i;case"mat4x3i":return ni.mat4x3i;case"mat4x4i":return ni.mat4x4i;case"mat2x2u":return ni.mat2x2u;case"mat2x3u":return ni.mat2x3u;case"mat2x4u":return ni.mat2x4u;case"mat3x2u":return ni.mat3x2u;case"mat3x3u":return ni.mat3x3u;case"mat3x4u":return ni.mat3x4u;case"mat4x2u":return ni.mat4x2u;case"mat4x3u":return ni.mat4x3u;case"mat4x4u":return ni.mat4x4u}return null}_validateTypeRange(t,e){if("i32"===e.name){if(t<-2147483648||t>2147483647)throw this._error(this._previous(),`Value out of range for i32: ${t}. Line: ${this._currentLine}.`)}else if("u32"===e.name&&(t<0||t>4294967295))throw this._error(this._previous(),`Value out of range for u32: ${t}. Line: ${this._currentLine}.`)}_primary_expression(){if(this._match(Ni.tokens.ident)){const t=this._previous().toString();if(this._check(Ni.tokens.paren_left)){const e=this._argument_expression_list(),n=this._getType(t);return this._updateNode(null!==n?new ci(n,e):new li(t,e))}if(this._context.constants.has(t)){const e=this._context.constants.get(t);return this._updateNode(new ui(t,e.value))}return this._updateNode(new hi(t))}if(this._match(Ni.tokens.int_literal)){const t=this._previous().toString();let e=t.endsWith("i")||t.endsWith("i")?Qn.i32:t.endsWith("u")||t.endsWith("U")?Qn.u32:Qn.x32;const n=parseInt(t);return this._validateTypeRange(n,e),this._updateNode(new fi(new Mi(n,this._exec.getTypeInfo(e)),e))}if(this._match(Ni.tokens.uint_literal)){const t=parseInt(this._previous().toString());return this._validateTypeRange(t,Qn.u32),this._updateNode(new fi(new Mi(t,this._exec.getTypeInfo(Qn.u32)),Qn.u32))}if(this._match([Ni.tokens.decimal_float_literal,Ni.tokens.hex_float_literal])){let t=this._previous().toString(),e=t.endsWith("h");e&&(t=t.substring(0,t.length-1));const n=parseFloat(t);this._validateTypeRange(n,e?Qn.f16:Qn.f32);const i=e?Qn.f16:Qn.f32;return this._updateNode(new fi(new Mi(n,this._exec.getTypeInfo(i)),i))}if(this._match([Ni.keywords.true,Ni.keywords.false])){let t=this._previous().toString()===Ni.keywords.true.rule;return this._updateNode(new fi(new Mi(t?1:0,this._exec.getTypeInfo(Qn.bool)),Qn.bool))}if(this._check(Ni.tokens.paren_left))return this._paren_expression();if(this._match(Ni.keywords.bitcast)){this._consume(Ni.tokens.less_than,"Expected '<'.");const t=this._type_decl();this._consume(Ni.tokens.greater_than,"Expected '>'.");const e=this._paren_expression();return this._updateNode(new di(t,e))}const t=this._type_decl(),e=this._argument_expression_list();return this._updateNode(new ci(t,e))}_argument_expression_list(){if(!this._match(Ni.tokens.paren_left))return null;const t=[];do{if(this._check(Ni.tokens.paren_right))break;const e=this._short_circuit_or_expression();t.push(e)}while(this._match(Ni.tokens.comma));return this._consume(Ni.tokens.paren_right,"Expected ')' for agument list"),t}_optional_paren_expression(){this._match(Ni.tokens.paren_left);const t=this._short_circuit_or_expression();return this._match(Ni.tokens.paren_right),t}_paren_expression(){this._consume(Ni.tokens.paren_left,"Expected '('.");const t=this._short_circuit_or_expression();return this._consume(Ni.tokens.paren_right,"Expected ')'."),t}_struct_decl(){if(!this._match(Ni.keywords.struct))return null;const t=this._currentLine,e=this._consume(Ni.tokens.ident,"Expected name for struct.").toString();this._consume(Ni.tokens.brace_left,"Expected '{' for struct body.");const n=[];for(;!this._check(Ni.tokens.brace_right);){const t=this._attribute(),e=this._consume(Ni.tokens.name,"Expected variable name.").toString();this._consume(Ni.tokens.colon,"Expected ':' for struct member type.");const i=this._attribute(),s=this._type_decl();null!=s&&(s.attributes=i),this._check(Ni.tokens.brace_right)?this._match(Ni.tokens.comma):this._consume(Ni.tokens.comma,"Expected ',' for struct member."),n.push(this._updateNode(new Ti(e,s,t)))}this._consume(Ni.tokens.brace_right,"Expected '}' after struct body.");const i=this._updateNode(new ei(e,n,t,this._currentLine),t);return this._context.structs.set(e,i),i}_global_variable_decl(){const t=this._variable_decl();if(!t)return null;if(this._match(Ni.tokens.equal)){const e=this._const_expression();t.value=e}if(null!==t.type&&t.value instanceof fi){if("x32"!==t.value.type.name&&t.type.getTypeName()!==t.value.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${t.value.type.name} to ${t.type.name}. Line:${this._currentLine}`);t.value.isScalar&&this._validateTypeRange(t.value.scalarValue,t.type),t.value.type=t.type}else null===t.type&&t.value instanceof fi&&(t.type="x32"===t.value.type.name?Qn.i32:t.value.type,t.value.isScalar&&this._validateTypeRange(t.value.scalarValue,t.type));return t}_override_variable_decl(){const t=this._override_decl();return t&&this._match(Ni.tokens.equal)&&(t.value=this._const_expression()),t}_global_const_decl(){var t;if(!this._match(Ni.keywords.const))return null;const e=this._consume(Ni.tokens.name,"Expected variable name"),n=this._currentLine;let i=null;if(this._match(Ni.tokens.colon)){const t=this._attribute();i=this._type_decl(),null!=i&&(i.attributes=t)}let s=null;this._consume(Ni.tokens.equal,"const declarations require an assignment");const r=this._short_circuit_or_expression();try{let t=[Qn.f32],n=r.constEvaluate(this._exec,t);n instanceof Mi&&this._validateTypeRange(n.value,t[0]),t[0]instanceof ni&&null===t[0].format&&n.typeInfo instanceof Qe&&null!==n.typeInfo.format&&("f16"===n.typeInfo.format.name?t[0].format=Qn.f16:"f32"===n.typeInfo.format.name?t[0].format=Qn.f32:"i32"===n.typeInfo.format.name?t[0].format=Qn.i32:"u32"===n.typeInfo.format.name?t[0].format=Qn.u32:"bool"===n.typeInfo.format.name?t[0].format=Qn.bool:console.error(`TODO: impelement template format type ${n.typeInfo.format.name}`)),s=this._updateNode(new fi(n,t[0])),this._exec.context.setVariable(e.toString(),n)}catch(t){s=r}if(null!==i&&s instanceof fi){if("x32"!==s.type.name&&i.getTypeName()!==s.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${s.type.name} to ${i.name}. Line:${this._currentLine}`);s.type=i,s.isScalar&&this._validateTypeRange(s.scalarValue,s.type)}else null===i&&s instanceof fi&&(i=null!==(t=null==s?void 0:s.type)&&void 0!==t?t:Qn.f32,i===Qn.x32&&(i=Qn.i32));const o=this._updateNode(new kn(e.toString(),i,"","",s),n);return this._context.constants.set(o.name,o),o}_global_let_decl(){if(!this._match(Ni.keywords.let))return null;const t=this._currentLine,e=this._consume(Ni.tokens.name,"Expected variable name");let n=null;if(this._match(Ni.tokens.colon)){const t=this._attribute();n=this._type_decl(),null!=n&&(n.attributes=t)}let i=null;if(this._match(Ni.tokens.equal)&&(i=this._const_expression()),null!==n&&i instanceof fi){if("x32"!==i.type.name&&n.getTypeName()!==i.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${i.type.name} to ${n.name}. Line:${this._currentLine}`);i.type=n}else null===n&&i instanceof fi&&(n="x32"===i.type.name?Qn.i32:i.type);return i instanceof fi&&i.isScalar&&this._validateTypeRange(i.scalarValue,n),this._updateNode(new In(e.toString(),n,"","",i),t)}_const_expression(){return this._short_circuit_or_expression()}_variable_decl(){if(!this._match(Ni.keywords.var))return null;const t=this._currentLine;let e="",n="";this._match(Ni.tokens.less_than)&&(e=this._consume(Ni.storage_class,"Expected storage_class.").toString(),this._match(Ni.tokens.comma)&&(n=this._consume(Ni.access_mode,"Expected access_mode.").toString()),this._consume(Ni.tokens.greater_than,"Expected '>'."));const i=this._consume(Ni.tokens.name,"Expected variable name");let s=null;if(this._match(Ni.tokens.colon)){const t=this._attribute();s=this._type_decl(),null!=s&&(s.attributes=t)}return this._updateNode(new Ln(i.toString(),s,e,n,null),t)}_override_decl(){if(!this._match(Ni.keywords.override))return null;const t=this._consume(Ni.tokens.name,"Expected variable name");let e=null;if(this._match(Ni.tokens.colon)){const t=this._attribute();e=this._type_decl(),null!=e&&(e.attributes=t)}return this._updateNode(new On(t.toString(),e,null))}_diagnostic(){this._consume(Ni.tokens.paren_left,"Expected '('");const t=this._consume(Ni.tokens.ident,"Expected severity control name.");this._consume(Ni.tokens.comma,"Expected ','");let e=this._consume(Ni.tokens.ident,"Expected diagnostic rule name.").toString();return this._match(Ni.tokens.period)&&(e+=`.${this._consume(Ni.tokens.ident,"Expected diagnostic message.").toString()}`),this._consume(Ni.tokens.paren_right,"Expected ')'"),this._updateNode(new Zn(t.toString(),e))}_enable_directive(){const t=this._consume(Ni.tokens.ident,"identity expected.");return this._updateNode(new Hn(t.toString()))}_requires_directive(){const t=[this._consume(Ni.tokens.ident,"identity expected.").toString()];for(;this._match(Ni.tokens.comma);){const e=this._consume(Ni.tokens.ident,"identity expected.");t.push(e.toString())}return this._updateNode(new Xn(t))}_type_alias(){const t=this._consume(Ni.tokens.ident,"identity expected.");this._consume(Ni.tokens.equal,"Expected '=' for type alias.");let e=this._type_decl();if(null===e)throw this._error(this._peek(),"Expected Type for Alias.");this._context.aliases.has(e.name)&&(e=this._context.aliases.get(e.name).type);const n=this._updateNode(new Kn(t.toString(),e));return this._context.aliases.set(n.name,n),n}_type_decl(){if(this._check([Ni.tokens.ident,...Ni.texel_format,Ni.keywords.bool,Ni.keywords.f32,Ni.keywords.i32,Ni.keywords.u32])){const t=this._advance().toString();if(this._context.structs.has(t))return this._context.structs.get(t);if(this._context.aliases.has(t))return this._context.aliases.get(t).type;if(!this._getType(t)){const e=this._updateNode(new ti(t));return this._forwardTypeCount++,e}return this._updateNode(new Qn(t))}let t=this._texture_sampler_types();if(t)return t;if(this._check(Ni.template_types)){let t=this._advance().toString(),e=null,n=null;return this._match(Ni.tokens.less_than)&&(e=this._type_decl(),n=null,this._match(Ni.tokens.comma)&&(n=this._consume(Ni.access_mode,"Expected access_mode for pointer").toString()),this._consume(Ni.tokens.greater_than,"Expected '>' for type.")),this._updateNode(new ni(t,e,n))}if(this._match(Ni.keywords.ptr)){let t=this._previous().toString();this._consume(Ni.tokens.less_than,"Expected '<' for pointer.");const e=this._consume(Ni.storage_class,"Expected storage_class for pointer");this._consume(Ni.tokens.comma,"Expected ',' for pointer.");const n=this._type_decl();let i=null;return this._match(Ni.tokens.comma)&&(i=this._consume(Ni.access_mode,"Expected access_mode for pointer").toString()),this._consume(Ni.tokens.greater_than,"Expected '>' for pointer."),this._updateNode(new ii(t,e.toString(),n,i))}const e=this._attribute();if(this._match(Ni.keywords.array)){let n=null,i=-1;const s=this._previous();let r=null;if(this._match(Ni.tokens.less_than)){n=this._type_decl(),this._context.aliases.has(n.name)&&(n=this._context.aliases.get(n.name).type);let e="";if(this._match(Ni.tokens.comma)){r=this._shift_expression();try{e=r.constEvaluate(this._exec).toString(),r=null}catch(t){e="1"}}this._consume(Ni.tokens.greater_than,"Expected '>' for array."),i=e?parseInt(e):0}const o=this._updateNode(new si(s.toString(),e,n,i));return r&&this._deferArrayCountEval.push({arrayType:o,countNode:r}),o}return null}_texture_sampler_types(){if(this._match(Ni.sampler_type))return this._updateNode(new ri(this._previous().toString(),null,null));if(this._match(Ni.depth_texture_type))return this._updateNode(new ri(this._previous().toString(),null,null));if(this._match(Ni.sampled_texture_type)||this._match(Ni.multisampled_texture_type)){const t=this._previous();this._consume(Ni.tokens.less_than,"Expected '<' for sampler type.");const e=this._type_decl();return this._consume(Ni.tokens.greater_than,"Expected '>' for sampler type."),this._updateNode(new ri(t.toString(),e,null))}if(this._match(Ni.storage_texture_type)){const t=this._previous();this._consume(Ni.tokens.less_than,"Expected '<' for sampler type.");const e=this._consume(Ni.texel_format,"Invalid texel format.").toString();this._consume(Ni.tokens.comma,"Expected ',' after texel format.");const n=this._consume(Ni.access_mode,"Expected access mode for storage texture type.").toString();return this._consume(Ni.tokens.greater_than,"Expected '>' for sampler type."),this._updateNode(new ri(t.toString(),e,n))}return null}_attribute(){let t=[];for(;this._match(Ni.tokens.attr);){const e=this._consume(Ni.attribute_name,"Expected attribute name"),n=this._updateNode(new Ai(e.toString(),null));if(this._match(Ni.tokens.paren_left)){if(n.value=this._consume(Ni.literal_or_ident,"Expected attribute value").toString(),this._check(Ni.tokens.comma)){this._advance();do{const t=this._consume(Ni.literal_or_ident,"Expected attribute value").toString();n.value instanceof Array||(n.value=[n.value]),n.value.push(t)}while(this._match(Ni.tokens.comma))}this._consume(Ni.tokens.paren_right,"Expected ')'")}t.push(n)}return 0==t.length?null:t}}class hs extends Ji{constructor(t){super(),t&&this.update(t)}update(t){const e=(new ls).parse(t);this.updateAST(e)}}function us(t){return t?.format?`${t.name}<${t.format.name}>`:t.name}const fs=1/Math.PI*180,ds=1/180*Math.PI;globalThis.mathgl=globalThis.mathgl||{config:{EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1}};const ps=globalThis.mathgl.config;function gs(t,{precision:e=ps.precision}={}){return t=function(t){return Math.round(t/ps.EPSILON)*ps.EPSILON}(t),`${parseFloat(t.toPrecision(e))}`}function ms(t){return Array.isArray(t)||ArrayBuffer.isView(t)&&!(t instanceof DataView)}function _s(t,e){return xs(t,(t=>t*ds),e)}function vs(t,e){return xs(t,(t=>t*fs),e)}function bs(t,e,n){return xs(t,(t=>Math.max(e,Math.min(n,t))))}function ys(t,e,n){return ms(t)?t.map(((t,i)=>ys(t,e[i],n))):n*e+(1-n)*t}function ws(t,e){const n=ps.EPSILON;try{if(t===e)return!0;if(ms(t)&&ms(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;++n)if(!ws(t[n],e[n]))return!1;return!0}return t&&t.equals?t.equals(e):e&&e.equals?e.equals(t):"number"==typeof t&&"number"==typeof e&&Math.abs(t-e)<=ps.EPSILON*Math.max(1,Math.abs(t),Math.abs(e))}finally{ps.EPSILON=n}}function xs(t,e,n){if(ms(t)){const i=t;n=n||function(t){return t.clone?t.clone():new Array(t.length)}(i);for(let s=0;s<n.length&&s<i.length;++s)n[s]=e("number"==typeof t?t:t[s],s,n);return n}return e(t)}class Es extends Array{clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=t[n+e];return this.check()}toArray(t=[],e=0){for(let n=0;n<this.ELEMENTS;++n)t[e+n]=this[n];return t}toObject(t){return t}from(t){return Array.isArray(t)?this.copy(t):this.fromObject(t)}to(t){return t===this?this:ms(t)?this.toArray(t):this.toObject(t)}toTarget(t){return t?this.to(t):this}toFloat32Array(){return new Float32Array(this)}toString(){return this.formatString(ps)}formatString(t){let e="";for(let n=0;n<this.ELEMENTS;++n)e+=(n>0?", ":"")+gs(this[n],t);return`${t.printTypes?this.constructor.name:""}[${e}]`}equals(t){if(!t||this.length!==t.length)return!1;for(let e=0;e<this.ELEMENTS;++e)if(!ws(this[e],t[e]))return!1;return!0}exactEquals(t){if(!t||this.length!==t.length)return!1;for(let e=0;e<this.ELEMENTS;++e)if(this[e]!==t[e])return!1;return!0}negate(){for(let t=0;t<this.ELEMENTS;++t)this[t]=-this[t];return this.check()}lerp(t,e,n){if(void 0===n)return this.lerp(this,t,e);for(let i=0;i<this.ELEMENTS;++i){const s=t[i];this[i]=s+n*(("number"==typeof e?e:e[i])-s)}return this.check()}min(t){for(let e=0;e<this.ELEMENTS;++e)this[e]=Math.min(t[e],this[e]);return this.check()}max(t){for(let e=0;e<this.ELEMENTS;++e)this[e]=Math.max(t[e],this[e]);return this.check()}clamp(t,e){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],t[n]),e[n]);return this.check()}add(...t){for(const e of t)for(let t=0;t<this.ELEMENTS;++t)this[t]+=e[t];return this.check()}subtract(...t){for(const e of t)for(let t=0;t<this.ELEMENTS;++t)this[t]-=e[t];return this.check()}scale(t){if("number"==typeof t)for(let e=0;e<this.ELEMENTS;++e)this[e]*=t;else for(let e=0;e<this.ELEMENTS&&e<t.length;++e)this[e]*=t[e];return this.check()}multiplyByScalar(t){for(let e=0;e<this.ELEMENTS;++e)this[e]*=t;return this.check()}check(){if(ps.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let t=this.length===this.ELEMENTS;for(let e=0;e<this.ELEMENTS;++e)t=t&&Number.isFinite(this[e]);return t}sub(t){return this.subtract(t)}setScalar(t){for(let e=0;e<this.ELEMENTS;++e)this[e]=t;return this.check()}addScalar(t){for(let e=0;e<this.ELEMENTS;++e)this[e]+=t;return this.check()}subScalar(t){return this.addScalar(-t)}multiplyScalar(t){for(let e=0;e<this.ELEMENTS;++e)this[e]*=t;return this.check()}divideScalar(t){return this.multiplyByScalar(1/t)}clampScalar(t,e){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],t),e);return this.check()}get elements(){return this}}function Ts(t){if(!Number.isFinite(t))throw new Error(`Invalid number ${JSON.stringify(t)}`);return t}function As(t,e,n=""){if(ps.debug&&!function(t,e){if(t.length!==e)return!1;for(let e=0;e<t.length;++e)if(!Number.isFinite(t[e]))return!1;return!0}(t,e))throw new Error(`math.gl: ${n} some fields set to invalid numbers'`);return t}function Ss(t,e){if(!t)throw new Error(`math.gl assertion ${e}`)}class Cs extends Es{get x(){return this[0]}set x(t){this[0]=Ts(t)}get y(){return this[1]}set y(t){this[1]=Ts(t)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let t=0;for(let e=0;e<this.ELEMENTS;++e)t+=this[e]*this[e];return t}magnitudeSquared(){return this.lengthSquared()}distance(t){return Math.sqrt(this.distanceSquared(t))}distanceSquared(t){let e=0;for(let n=0;n<this.ELEMENTS;++n){const i=this[n]-t[n];e+=i*i}return Ts(e)}dot(t){let e=0;for(let n=0;n<this.ELEMENTS;++n)e+=this[n]*t[n];return Ts(e)}normalize(){const t=this.magnitude();if(0!==t)for(let e=0;e<this.ELEMENTS;++e)this[e]/=t;return this.check()}multiply(...t){for(const e of t)for(let t=0;t<this.ELEMENTS;++t)this[t]*=e[t];return this.check()}divide(...t){for(const e of t)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e[t];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(t){return this.distance(t)}distanceToSquared(t){return this.distanceSquared(t)}getComponent(t){return Ss(t>=0&&t<this.ELEMENTS,"index is out of range"),Ts(this[t])}setComponent(t,e){return Ss(t>=0&&t<this.ELEMENTS,"index is out of range"),this[t]=e,this.check()}addVectors(t,e){return this.copy(t).add(e)}subVectors(t,e){return this.copy(t).subtract(e)}multiplyVectors(t,e){return this.copy(t).multiply(e)}addScaledVector(t,e){return this.add(new this.constructor(t).multiplyScalar(e))}}const Ps=1e-6;let Ms="undefined"!=typeof Float32Array?Float32Array:Array;function Rs(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function Ls(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function Os(t){const e=t[0],n=t[1];return Math.sqrt(e*e+n*n)}function Is(t,e){return t[0]=-e[0],t[1]=-e[1],t}function ks(t,e,n,i){const s=e[0],r=e[1];return t[0]=s+i*(n[0]-s),t[1]=r+i*(n[1]-r),t}const Ds=function(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t};function Ns(t,e,n){const i=e[0],s=e[1],r=e[2],o=n[3]*i+n[7]*s+n[11]*r||1;return t[0]=(n[0]*i+n[4]*s+n[8]*r)/o,t[1]=(n[1]*i+n[5]*s+n[9]*r)/o,t[2]=(n[2]*i+n[6]*s+n[10]*r)/o,t}function Fs(t,e,n){const i=e[0],s=e[1],r=e[2];return t[0]=n[0]*i+n[3]*s+n[6]*r,t[1]=n[1]*i+n[4]*s+n[7]*r,t[2]=n[2]*i+n[5]*s+n[8]*r,t[3]=e[3],t}function Bs(){const t=new Ms(3);return Ms!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function $s(t){const e=t[0],n=t[1],i=t[2];return Math.sqrt(e*e+n*n+i*i)}function Us(t,e,n){const i=new Ms(3);return i[0]=t,i[1]=e,i[2]=n,i}function zs(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function js(t,e,n){const i=e[0],s=e[1],r=e[2],o=n[0],a=n[1],c=n[2];return t[0]=s*c-r*a,t[1]=r*o-i*c,t[2]=i*a-s*o,t}function Gs(t,e,n){const i=e[0],s=e[1],r=e[2];let o=n[3]*i+n[7]*s+n[11]*r+n[15];return o=o||1,t[0]=(n[0]*i+n[4]*s+n[8]*r+n[12])/o,t[1]=(n[1]*i+n[5]*s+n[9]*r+n[13])/o,t[2]=(n[2]*i+n[6]*s+n[10]*r+n[14])/o,t}function Ws(t,e,n){const i=e[0],s=e[1],r=e[2];return t[0]=i*n[0]+s*n[3]+r*n[6],t[1]=i*n[1]+s*n[4]+r*n[7],t[2]=i*n[2]+s*n[5]+r*n[8],t}function Vs(t,e,n){const i=n[0],s=n[1],r=n[2],o=e[0],a=e[1],c=e[2];let l=s*c-r*a,h=r*o-i*c,u=i*a-s*o,f=s*u-r*h,d=r*l-i*u,p=i*h-s*l;const g=2*n[3];return l*=g,h*=g,u*=g,f*=2,d*=2,p*=2,t[0]=o+l+f,t[1]=a+h+d,t[2]=c+u+p,t}!function(){const t=new Ms(2);Ms!=Float32Array&&(t[0]=0,t[1]=0)}();const Hs=function(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t[2]=e[2]-n[2],t},Xs=$s,Zs=function(t){const e=t[0],n=t[1],i=t[2];return e*e+n*n+i*i};Bs();const Ks=[0,0,0];let qs,Ys;class Js extends Cs{static get ZERO(){return qs||(qs=new Js(0,0,0),Object.freeze(qs)),qs}constructor(t=0,e=0,n=0){super(-0,-0,-0),1===arguments.length&&ms(t)?this.copy(t):(ps.debug&&(Ts(t),Ts(e),Ts(n)),this[0]=t,this[1]=e,this[2]=n)}set(t,e,n){return this[0]=t,this[1]=e,this[2]=n,this.check()}copy(t){return this[0]=t[0],this[1]=t[1],this[2]=t[2],this.check()}fromObject(t){return ps.debug&&(Ts(t.x),Ts(t.y),Ts(t.z)),this[0]=t.x,this[1]=t.y,this[2]=t.z,this.check()}toObject(t){return t.x=this[0],t.y=this[1],t.z=this[2],t}get ELEMENTS(){return 3}get z(){return this[2]}set z(t){this[2]=Ts(t)}angle(t){return function(t,e){const n=t[0],i=t[1],s=t[2],r=e[0],o=e[1],a=e[2],c=Math.sqrt((n*n+i*i+s*s)*(r*r+o*o+a*a)),l=c&&zs(t,e)/c;return Math.acos(Math.min(Math.max(l,-1),1))}(this,t)}cross(t){return js(this,this,t),this.check()}rotateX({radians:t,origin:e=Ks}){return function(t,e,n,i){const s=[],r=[];s[0]=e[0]-n[0],s[1]=e[1]-n[1],s[2]=e[2]-n[2],r[0]=s[0],r[1]=s[1]*Math.cos(i)-s[2]*Math.sin(i),r[2]=s[1]*Math.sin(i)+s[2]*Math.cos(i),t[0]=r[0]+n[0],t[1]=r[1]+n[1],t[2]=r[2]+n[2]}(this,this,e,t),this.check()}rotateY({radians:t,origin:e=Ks}){return function(t,e,n,i){const s=[],r=[];s[0]=e[0]-n[0],s[1]=e[1]-n[1],s[2]=e[2]-n[2],r[0]=s[2]*Math.sin(i)+s[0]*Math.cos(i),r[1]=s[1],r[2]=s[2]*Math.cos(i)-s[0]*Math.sin(i),t[0]=r[0]+n[0],t[1]=r[1]+n[1],t[2]=r[2]+n[2]}(this,this,e,t),this.check()}rotateZ({radians:t,origin:e=Ks}){return function(t,e,n,i){const s=[],r=[];s[0]=e[0]-n[0],s[1]=e[1]-n[1],s[2]=e[2]-n[2],r[0]=s[0]*Math.cos(i)-s[1]*Math.sin(i),r[1]=s[0]*Math.sin(i)+s[1]*Math.cos(i),r[2]=s[2],t[0]=r[0]+n[0],t[1]=r[1]+n[1],t[2]=r[2]+n[2]}(this,this,e,t),this.check()}transform(t){return this.transformAsPoint(t)}transformAsPoint(t){return Gs(this,this,t),this.check()}transformAsVector(t){return Ns(this,this,t),this.check()}transformByMatrix3(t){return Ws(this,this,t),this.check()}transformByMatrix2(t){return function(t,e,n){const i=e[0],s=e[1];t[0]=n[0]*i+n[2]*s,t[1]=n[1]*i+n[3]*s,t[2]=e[2]}(this,this,t),this.check()}transformByQuaternion(t){return Vs(this,this,t),this.check()}}class Qs extends Cs{static get ZERO(){return Ys||(Ys=new Qs(0,0,0,0),Object.freeze(Ys)),Ys}constructor(t=0,e=0,n=0,i=0){super(-0,-0,-0,-0),ms(t)&&1===arguments.length?this.copy(t):(ps.debug&&(Ts(t),Ts(e),Ts(n),Ts(i)),this[0]=t,this[1]=e,this[2]=n,this[3]=i)}set(t,e,n,i){return this[0]=t,this[1]=e,this[2]=n,this[3]=i,this.check()}copy(t){return this[0]=t[0],this[1]=t[1],this[2]=t[2],this[3]=t[3],this.check()}fromObject(t){return ps.debug&&(Ts(t.x),Ts(t.y),Ts(t.z),Ts(t.w)),this[0]=t.x,this[1]=t.y,this[2]=t.z,this[3]=t.w,this}toObject(t){return t.x=this[0],t.y=this[1],t.z=this[2],t.w=this[3],t}get ELEMENTS(){return 4}get z(){return this[2]}set z(t){this[2]=Ts(t)}get w(){return this[3]}set w(t){this[3]=Ts(t)}transform(t){return Gs(this,this,t),this.check()}transformByMatrix3(t){return Fs(this,this,t),this.check()}transformByMatrix2(t){return function(t,e,n){const i=e[0],s=e[1];t[0]=n[0]*i+n[2]*s,t[1]=n[1]*i+n[3]*s,t[2]=e[2],t[3]=e[3]}(this,this,t),this.check()}transformByQuaternion(t){return Vs(this,this,t),this.check()}applyMatrix4(t){return t.transform(this,this),this}}class tr extends Es{toString(){let t="[";if(ps.printRowMajor){t+="row-major:";for(let e=0;e<this.RANK;++e)for(let n=0;n<this.RANK;++n)t+=` ${this[n*this.RANK+e]}`}else{t+="column-major:";for(let e=0;e<this.ELEMENTS;++e)t+=` ${this[e]}`}return t+="]",t}getElementIndex(t,e){return e*this.RANK+t}getElement(t,e){return this[e*this.RANK+t]}setElement(t,e,n){return this[e*this.RANK+t]=Ts(n),this}getColumn(t,e=new Array(this.RANK).fill(-0)){const n=t*this.RANK;for(let t=0;t<this.RANK;++t)e[t]=this[n+t];return e}setColumn(t,e){const n=t*this.RANK;for(let t=0;t<this.RANK;++t)this[n+t]=e[t];return this}}function er(t,e,n){const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],f=n[0],d=n[1],p=n[2],g=n[3],m=n[4],_=n[5],v=n[6],b=n[7],y=n[8];return t[0]=f*i+d*o+p*l,t[1]=f*s+d*a+p*h,t[2]=f*r+d*c+p*u,t[3]=g*i+m*o+_*l,t[4]=g*s+m*a+_*h,t[5]=g*r+m*c+_*u,t[6]=v*i+b*o+y*l,t[7]=v*s+b*a+y*h,t[8]=v*r+b*c+y*u,t}function nr(t,e,n){const i=n[0],s=n[1];return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=s*e[3],t[4]=s*e[4],t[5]=s*e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}var ir;!function(t){t[t.COL0ROW0=0]="COL0ROW0",t[t.COL0ROW1=1]="COL0ROW1",t[t.COL0ROW2=2]="COL0ROW2",t[t.COL1ROW0=3]="COL1ROW0",t[t.COL1ROW1=4]="COL1ROW1",t[t.COL1ROW2=5]="COL1ROW2",t[t.COL2ROW0=6]="COL2ROW0",t[t.COL2ROW1=7]="COL2ROW1",t[t.COL2ROW2=8]="COL2ROW2"}(ir||(ir={}));const sr=Object.freeze([1,0,0,0,1,0,0,0,1]);class rr extends tr{static get IDENTITY(){return ar||(ar=new rr,Object.freeze(ar)),ar}static get ZERO(){return or||(or=new rr([0,0,0,0,0,0,0,0,0]),Object.freeze(or)),or}get ELEMENTS(){return 9}get RANK(){return 3}get INDICES(){return ir}constructor(t,...e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0),1===arguments.length&&Array.isArray(t)?this.copy(t):e.length>0?this.copy([t,...e]):this.identity()}copy(t){return this[0]=t[0],this[1]=t[1],this[2]=t[2],this[3]=t[3],this[4]=t[4],this[5]=t[5],this[6]=t[6],this[7]=t[7],this[8]=t[8],this.check()}identity(){return this.copy(sr)}fromObject(t){return this.check()}fromQuaternion(t){return function(t,e){const n=e[0],i=e[1],s=e[2],r=e[3],o=n+n,a=i+i,c=s+s,l=n*o,h=i*o,u=i*a,f=s*o,d=s*a,p=s*c,g=r*o,m=r*a,_=r*c;t[0]=1-u-p,t[3]=h-_,t[6]=f+m,t[1]=h+_,t[4]=1-l-p,t[7]=d-g,t[2]=f-m,t[5]=d+g,t[8]=1-l-u}(this,t),this.check()}set(t,e,n,i,s,r,o,a,c){return this[0]=t,this[1]=e,this[2]=n,this[3]=i,this[4]=s,this[5]=r,this[6]=o,this[7]=a,this[8]=c,this.check()}setRowMajor(t,e,n,i,s,r,o,a,c){return this[0]=t,this[1]=i,this[2]=o,this[3]=e,this[4]=s,this[5]=a,this[6]=n,this[7]=r,this[8]=c,this.check()}determinant(){return function(t){const e=t[3],n=t[4],i=t[5],s=t[6],r=t[7],o=t[8];return t[0]*(o*n-i*r)+t[1]*(-o*e+i*s)+t[2]*(r*e-n*s)}(this)}transpose(){return function(t,e){if(t===e){const n=e[1],i=e[2],s=e[5];t[1]=e[3],t[2]=e[6],t[3]=n,t[5]=e[7],t[6]=i,t[7]=s}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8]}(this,this),this.check()}invert(){return function(t,e){const n=e[0],i=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=h*o-a*l,f=-h*r+a*c,d=l*r-o*c;let p=n*u+i*f+s*d;p&&(p=1/p,t[0]=u*p,t[1]=(-h*i+s*l)*p,t[2]=(a*i-s*o)*p,t[3]=f*p,t[4]=(h*n-s*c)*p,t[5]=(-a*n+s*r)*p,t[6]=d*p,t[7]=(-l*n+i*c)*p,t[8]=(o*n-i*r)*p)}(this,this),this.check()}multiplyLeft(t){return er(this,t,this),this.check()}multiplyRight(t){return er(this,this,t),this.check()}rotate(t){return function(t,e,n){const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],f=Math.sin(n),d=Math.cos(n);t[0]=d*i+f*o,t[1]=d*s+f*a,t[2]=d*r+f*c,t[3]=d*o-f*i,t[4]=d*a-f*s,t[5]=d*c-f*r,t[6]=l,t[7]=h,t[8]=u}(this,this,t),this.check()}scale(t){return Array.isArray(t)?nr(this,this,t):nr(this,this,[t,t]),this.check()}translate(t){return function(t,e,n){const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],f=n[0],d=n[1];t[0]=i,t[1]=s,t[2]=r,t[3]=o,t[4]=a,t[5]=c,t[6]=f*i+d*o+l,t[7]=f*s+d*a+h,t[8]=f*r+d*c+u}(this,this,t),this.check()}transform(t,e){let n;switch(t.length){case 2:n=function(t,e,n){const i=e[0],s=e[1];return t[0]=n[0]*i+n[3]*s+n[6],t[1]=n[1]*i+n[4]*s+n[7],t}(e||[-0,-0],t,this);break;case 3:n=Ws(e||[-0,-0,-0],t,this);break;case 4:n=Fs(e||[-0,-0,-0,-0],t,this);break;default:throw new Error("Illegal vector")}return As(n,t.length),n}transformVector(t,e){return this.transform(t,e)}transformVector2(t,e){return this.transform(t,e)}transformVector3(t,e){return this.transform(t,e)}}let or,ar=null;function cr(t,e){const n=e[0],i=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=e[9],f=e[10],d=e[11],p=e[12],g=e[13],m=e[14],_=e[15],v=n*a-i*o,b=n*c-s*o,y=n*l-r*o,w=i*c-s*a,x=i*l-r*a,E=s*l-r*c,T=h*g-u*p,A=h*m-f*p,S=h*_-d*p,C=u*m-f*g,P=u*_-d*g,M=f*_-d*m;let R=v*M-b*P+y*C+w*S-x*A+E*T;return R?(R=1/R,t[0]=(a*M-c*P+l*C)*R,t[1]=(s*P-i*M-r*C)*R,t[2]=(g*E-m*x+_*w)*R,t[3]=(f*x-u*E-d*w)*R,t[4]=(c*S-o*M-l*A)*R,t[5]=(n*M-s*S+r*A)*R,t[6]=(m*y-p*E-_*b)*R,t[7]=(h*E-f*y+d*b)*R,t[8]=(o*P-a*S+l*T)*R,t[9]=(i*S-n*P-r*T)*R,t[10]=(p*x-g*y+_*v)*R,t[11]=(u*y-h*x-d*v)*R,t[12]=(a*A-o*C-c*T)*R,t[13]=(n*C-i*A+s*T)*R,t[14]=(g*b-p*w-m*v)*R,t[15]=(h*w-u*b+f*v)*R,t):null}function lr(t,e,n){const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],f=e[9],d=e[10],p=e[11],g=e[12],m=e[13],_=e[14],v=e[15];let b=n[0],y=n[1],w=n[2],x=n[3];return t[0]=b*i+y*a+w*u+x*g,t[1]=b*s+y*c+w*f+x*m,t[2]=b*r+y*l+w*d+x*_,t[3]=b*o+y*h+w*p+x*v,b=n[4],y=n[5],w=n[6],x=n[7],t[4]=b*i+y*a+w*u+x*g,t[5]=b*s+y*c+w*f+x*m,t[6]=b*r+y*l+w*d+x*_,t[7]=b*o+y*h+w*p+x*v,b=n[8],y=n[9],w=n[10],x=n[11],t[8]=b*i+y*a+w*u+x*g,t[9]=b*s+y*c+w*f+x*m,t[10]=b*r+y*l+w*d+x*_,t[11]=b*o+y*h+w*p+x*v,b=n[12],y=n[13],w=n[14],x=n[15],t[12]=b*i+y*a+w*u+x*g,t[13]=b*s+y*c+w*f+x*m,t[14]=b*r+y*l+w*d+x*_,t[15]=b*o+y*h+w*p+x*v,t}function hr(t,e,n){const i=n[0],s=n[1],r=n[2];let o,a,c,l,h,u,f,d,p,g,m,_;return e===t?(t[12]=e[0]*i+e[4]*s+e[8]*r+e[12],t[13]=e[1]*i+e[5]*s+e[9]*r+e[13],t[14]=e[2]*i+e[6]*s+e[10]*r+e[14],t[15]=e[3]*i+e[7]*s+e[11]*r+e[15]):(o=e[0],a=e[1],c=e[2],l=e[3],h=e[4],u=e[5],f=e[6],d=e[7],p=e[8],g=e[9],m=e[10],_=e[11],t[0]=o,t[1]=a,t[2]=c,t[3]=l,t[4]=h,t[5]=u,t[6]=f,t[7]=d,t[8]=p,t[9]=g,t[10]=m,t[11]=_,t[12]=o*i+h*s+p*r+e[12],t[13]=a*i+u*s+g*r+e[13],t[14]=c*i+f*s+m*r+e[14],t[15]=l*i+d*s+_*r+e[15]),t}function ur(t,e,n){const i=n[0],s=n[1],r=n[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]*s,t[5]=e[5]*s,t[6]=e[6]*s,t[7]=e[7]*s,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function fr(t,e,n){const i=Math.sin(n),s=Math.cos(n),r=e[4],o=e[5],a=e[6],c=e[7],l=e[8],h=e[9],u=e[10],f=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]=r*s+l*i,t[5]=o*s+h*i,t[6]=a*s+u*i,t[7]=c*s+f*i,t[8]=l*s-r*i,t[9]=h*s-o*i,t[10]=u*s-a*i,t[11]=f*s-c*i,t}function dr(t,e,n){const i=Math.sin(n),s=Math.cos(n),r=e[0],o=e[1],a=e[2],c=e[3],l=e[4],h=e[5],u=e[6],f=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]=r*s+l*i,t[1]=o*s+h*i,t[2]=a*s+u*i,t[3]=c*s+f*i,t[4]=l*s-r*i,t[5]=h*s-o*i,t[6]=u*s-a*i,t[7]=f*s-c*i,t}function pr(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t}function gr(t,e,n){const i=e[0],s=e[1],r=e[2],o=e[3];return t[0]=n[0]*i+n[4]*s+n[8]*r+n[12]*o,t[1]=n[1]*i+n[5]*s+n[9]*r+n[13]*o,t[2]=n[2]*i+n[6]*s+n[10]*r+n[14]*o,t[3]=n[3]*i+n[7]*s+n[11]*r+n[15]*o,t}var mr;!function(){const t=new Ms(4);Ms!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0)}(),function(t){t[t.COL0ROW0=0]="COL0ROW0",t[t.COL0ROW1=1]="COL0ROW1",t[t.COL0ROW2=2]="COL0ROW2",t[t.COL0ROW3=3]="COL0ROW3",t[t.COL1ROW0=4]="COL1ROW0",t[t.COL1ROW1=5]="COL1ROW1",t[t.COL1ROW2=6]="COL1ROW2",t[t.COL1ROW3=7]="COL1ROW3",t[t.COL2ROW0=8]="COL2ROW0",t[t.COL2ROW1=9]="COL2ROW1",t[t.COL2ROW2=10]="COL2ROW2",t[t.COL2ROW3=11]="COL2ROW3",t[t.COL3ROW0=12]="COL3ROW0",t[t.COL3ROW1=13]="COL3ROW1",t[t.COL3ROW2=14]="COL3ROW2",t[t.COL3ROW3=15]="COL3ROW3"}(mr||(mr={}));const _r=45*Math.PI/180,vr=1,br=.1,yr=500,wr=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class xr extends tr{static get IDENTITY(){return Tr||(Tr=new xr,Object.freeze(Tr)),Tr}static get ZERO(){return Er||(Er=new xr([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Er)),Er}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return mr}constructor(t){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),1===arguments.length&&Array.isArray(t)?this.copy(t):this.identity()}copy(t){return this[0]=t[0],this[1]=t[1],this[2]=t[2],this[3]=t[3],this[4]=t[4],this[5]=t[5],this[6]=t[6],this[7]=t[7],this[8]=t[8],this[9]=t[9],this[10]=t[10],this[11]=t[11],this[12]=t[12],this[13]=t[13],this[14]=t[14],this[15]=t[15],this.check()}set(t,e,n,i,s,r,o,a,c,l,h,u,f,d,p,g){return this[0]=t,this[1]=e,this[2]=n,this[3]=i,this[4]=s,this[5]=r,this[6]=o,this[7]=a,this[8]=c,this[9]=l,this[10]=h,this[11]=u,this[12]=f,this[13]=d,this[14]=p,this[15]=g,this.check()}setRowMajor(t,e,n,i,s,r,o,a,c,l,h,u,f,d,p,g){return this[0]=t,this[1]=s,this[2]=c,this[3]=f,this[4]=e,this[5]=r,this[6]=l,this[7]=d,this[8]=n,this[9]=o,this[10]=h,this[11]=p,this[12]=i,this[13]=a,this[14]=u,this[15]=g,this.check()}toRowMajor(t){return t[0]=this[0],t[1]=this[4],t[2]=this[8],t[3]=this[12],t[4]=this[1],t[5]=this[5],t[6]=this[9],t[7]=this[13],t[8]=this[2],t[9]=this[6],t[10]=this[10],t[11]=this[14],t[12]=this[3],t[13]=this[7],t[14]=this[11],t[15]=this[15],t}identity(){return this.copy(wr)}fromObject(t){return this.check()}fromQuaternion(t){return function(t,e){const n=e[0],i=e[1],s=e[2],r=e[3],o=n+n,a=i+i,c=s+s,l=n*o,h=i*o,u=i*a,f=s*o,d=s*a,p=s*c,g=r*o,m=r*a,_=r*c;t[0]=1-u-p,t[1]=h+_,t[2]=f-m,t[3]=0,t[4]=h-_,t[5]=1-l-p,t[6]=d+g,t[7]=0,t[8]=f+m,t[9]=d-g,t[10]=1-l-u,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1}(this,t),this.check()}frustum(t){const{left:e,right:n,bottom:i,top:s,near:r=br,far:o=yr}=t;return o===1/0?function(t,e,n,i,s,r){const o=2*r/(s-i),a=(n+e)/(n-e),c=(s+i)/(s-i),l=-2*r;t[0]=2*r/(n-e),t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=a,t[9]=c,t[10]=-1,t[11]=-1,t[12]=0,t[13]=0,t[14]=l,t[15]=0}(this,e,n,i,s,r):function(t,e,n,i,s,r,o){const a=1/(n-e),c=1/(s-i),l=1/(r-o);t[0]=2*r*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*r*c,t[6]=0,t[7]=0,t[8]=(n+e)*a,t[9]=(s+i)*c,t[10]=(o+r)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=o*r*2*l,t[15]=0}(this,e,n,i,s,r,o),this.check()}lookAt(t){const{eye:e,center:n=[0,0,0],up:i=[0,1,0]}=t;return function(t,e,n,i){let s,r,o,a,c,l,h,u,f,d;const p=e[0],g=e[1],m=e[2],_=i[0],v=i[1],b=i[2],y=n[0],w=n[1],x=n[2];Math.abs(p-y)<Ps&&Math.abs(g-w)<Ps&&Math.abs(m-x)<Ps?function(t){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):(u=p-y,f=g-w,d=m-x,s=1/Math.sqrt(u*u+f*f+d*d),u*=s,f*=s,d*=s,r=v*d-b*f,o=b*u-_*d,a=_*f-v*u,s=Math.sqrt(r*r+o*o+a*a),s?(s=1/s,r*=s,o*=s,a*=s):(r=0,o=0,a=0),c=f*a-d*o,l=d*r-u*a,h=u*o-f*r,s=Math.sqrt(c*c+l*l+h*h),s?(s=1/s,c*=s,l*=s,h*=s):(c=0,l=0,h=0),t[0]=r,t[1]=c,t[2]=u,t[3]=0,t[4]=o,t[5]=l,t[6]=f,t[7]=0,t[8]=a,t[9]=h,t[10]=d,t[11]=0,t[12]=-(r*p+o*g+a*m),t[13]=-(c*p+l*g+h*m),t[14]=-(u*p+f*g+d*m),t[15]=1)}(this,e,n,i),this.check()}ortho(t){const{left:e,right:n,bottom:i,top:s,near:r=br,far:o=yr}=t;return function(t,e,n,i,s,r,o){const a=1/(e-n),c=1/(i-s),l=1/(r-o);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+n)*a,t[13]=(s+i)*c,t[14]=(o+r)*l,t[15]=1}(this,e,n,i,s,r,o),this.check()}orthographic(t){const{fovy:e=_r,aspect:n=vr,focalDistance:i=1,near:s=br,far:r=yr}=t;Ar(e);const o=i*Math.tan(e/2),a=o*n;return this.ortho({left:-a,right:a,bottom:-o,top:o,near:s,far:r})}perspective(t){const{fovy:e=45*Math.PI/180,aspect:n=1,near:i=.1,far:s=500}=t;return Ar(e),function(t,e,n,i,s){const r=1/Math.tan(e/2);if(t[0]=r/n,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=r,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=s&&s!==1/0){const e=1/(i-s);t[10]=(s+i)*e,t[14]=2*s*i*e}else t[10]=-1,t[14]=-2*i}(this,e,n,i,s),this.check()}determinant(){return function(t){const e=t[0],n=t[1],i=t[2],s=t[4],r=t[5],o=t[6],a=t[8],c=t[9],l=t[10],h=t[12],u=t[13],f=t[14],d=e*r-n*s,p=e*o-i*s,g=n*o-i*r,m=a*u-c*h,_=a*f-l*h,v=c*f-l*u;return t[7]*(e*v-n*_+i*m)-t[3]*(s*v-r*_+o*m)+t[15]*(a*g-c*p+l*d)-t[11]*(h*g-u*p+f*d)}(this)}getScale(t=[-0,-0,-0]){return t[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),t[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),t[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),t}getTranslation(t=[-0,-0,-0]){return t[0]=this[12],t[1]=this[13],t[2]=this[14],t}getRotation(t,e){t=t||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0];const n=this.getScale(e=e||[-0,-0,-0]),i=1/n[0],s=1/n[1],r=1/n[2];return t[0]=this[0]*i,t[1]=this[1]*s,t[2]=this[2]*r,t[3]=0,t[4]=this[4]*i,t[5]=this[5]*s,t[6]=this[6]*r,t[7]=0,t[8]=this[8]*i,t[9]=this[9]*s,t[10]=this[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}getRotationMatrix3(t,e){t=t||[-0,-0,-0,-0,-0,-0,-0,-0,-0];const n=this.getScale(e=e||[-0,-0,-0]),i=1/n[0],s=1/n[1],r=1/n[2];return t[0]=this[0]*i,t[1]=this[1]*s,t[2]=this[2]*r,t[3]=this[4]*i,t[4]=this[5]*s,t[5]=this[6]*r,t[6]=this[8]*i,t[7]=this[9]*s,t[8]=this[10]*r,t}transpose(){return function(t,e){if(t===e){const n=e[1],i=e[2],s=e[3],r=e[6],o=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=n,t[6]=e[9],t[7]=e[13],t[8]=i,t[9]=r,t[11]=e[14],t[12]=s,t[13]=o,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]}(this,this),this.check()}invert(){return cr(this,this),this.check()}multiplyLeft(t){return lr(this,t,this),this.check()}multiplyRight(t){return lr(this,this,t),this.check()}rotateX(t){return fr(this,this,t),this.check()}rotateY(t){return function(t,e,n){const i=Math.sin(n),s=Math.cos(n),r=e[0],o=e[1],a=e[2],c=e[3],l=e[8],h=e[9],u=e[10],f=e[11];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]=r*s-l*i,t[1]=o*s-h*i,t[2]=a*s-u*i,t[3]=c*s-f*i,t[8]=r*i+l*s,t[9]=o*i+h*s,t[10]=a*i+u*s,t[11]=c*i+f*s}(this,this,t),this.check()}rotateZ(t){return dr(this,this,t),this.check()}rotateXYZ(t){return this.rotateX(t[0]).rotateY(t[1]).rotateZ(t[2])}rotateAxis(t,e){return function(t,e,n,i){let s,r,o,a,c,l,h,u,f,d,p,g,m,_,v,b,y,w,x,E,T,A,S,C,P=i[0],M=i[1],R=i[2],L=Math.sqrt(P*P+M*M+R*R);L<Ps||(L=1/L,P*=L,M*=L,R*=L,r=Math.sin(n),s=Math.cos(n),o=1-s,a=e[0],c=e[1],l=e[2],h=e[3],u=e[4],f=e[5],d=e[6],p=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=P*P*o+s,y=M*P*o+R*r,w=R*P*o-M*r,x=P*M*o-R*r,E=M*M*o+s,T=R*M*o+P*r,A=P*R*o+M*r,S=M*R*o-P*r,C=R*R*o+s,t[0]=a*b+u*y+g*w,t[1]=c*b+f*y+m*w,t[2]=l*b+d*y+_*w,t[3]=h*b+p*y+v*w,t[4]=a*x+u*E+g*T,t[5]=c*x+f*E+m*T,t[6]=l*x+d*E+_*T,t[7]=h*x+p*E+v*T,t[8]=a*A+u*S+g*C,t[9]=c*A+f*S+m*C,t[10]=l*A+d*S+_*C,t[11]=h*A+p*S+v*C,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]))}(this,this,t,e),this.check()}scale(t){return ur(this,this,Array.isArray(t)?t:[t,t,t]),this.check()}translate(t){return hr(this,this,t),this.check()}transform(t,e){return 4===t.length?(As(e=gr(e||[-0,-0,-0,-0],t,this),4),e):this.transformAsPoint(t,e)}transformAsPoint(t,e){const{length:n}=t;let i;switch(n){case 2:i=function(t,e,n){const i=e[0],s=e[1];return t[0]=n[0]*i+n[4]*s+n[12],t[1]=n[1]*i+n[5]*s+n[13],t}(e||[-0,-0],t,this);break;case 3:i=Gs(e||[-0,-0,-0],t,this);break;default:throw new Error("Illegal vector")}return As(i,t.length),i}transformAsVector(t,e){let n;switch(t.length){case 2:n=function(t,e,n){const i=e[0],s=e[1],r=n[3]*i+n[7]*s||1;return t[0]=(n[0]*i+n[4]*s)/r,t[1]=(n[1]*i+n[5]*s)/r,t}(e||[-0,-0],t,this);break;case 3:n=Ns(e||[-0,-0,-0],t,this);break;default:throw new Error("Illegal vector")}return As(n,t.length),n}transformPoint(t,e){return this.transformAsPoint(t,e)}transformVector(t,e){return this.transformAsPoint(t,e)}transformDirection(t,e){return this.transformAsVector(t,e)}makeRotationX(t){return this.identity().rotateX(t)}makeTranslation(t,e,n){return this.identity().translate([t,e,n])}}let Er,Tr;function Ar(t){if(t>2*Math.PI)throw Error("expected radians")}function Sr(){const t=new Ms(4);return Ms!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Cr(t,e,n){n*=.5;const i=Math.sin(n);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(n),t}function Pr(t,e,n){const i=e[0],s=e[1],r=e[2],o=e[3],a=n[0],c=n[1],l=n[2],h=n[3];return t[0]=i*h+o*a+s*l-r*c,t[1]=s*h+o*c+r*a-i*l,t[2]=r*h+o*l+i*c-s*a,t[3]=o*h-i*a-s*c-r*l,t}const Mr=pr,Rr=function(){const t=Bs(),e=Us(1,0,0),n=Us(0,1,0);return function(i,s,r){const o=zs(s,r);return o<-.999999?(js(t,e,s),Xs(t)<1e-6&&js(t,n,s),function(t,e){const n=e[0],i=e[1],s=e[2];let r=n*n+i*i+s*s;r>0&&(r=1/Math.sqrt(r)),t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r}(t,t),Cr(i,t,Math.PI),i):o>.999999?(i[0]=0,i[1]=0,i[2]=0,i[3]=1,i):(js(t,s,r),i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=1+o,function(t,e){const n=e[0],i=e[1],s=e[2],r=e[3];let o=n*n+i*i+s*s+r*r;return o>0&&(o=1/Math.sqrt(o)),t[0]=n*o,t[1]=i*o,t[2]=s*o,t[3]=r*o,t}(i,i))}}();Sr(),Sr(),function(){const t=new Ms(9);Ms!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1}();const Lr=[0,0,0,1];class Or extends Es{constructor(t=0,e=0,n=0,i=1){super(-0,-0,-0,-0),Array.isArray(t)&&1===arguments.length?this.copy(t):this.set(t,e,n,i)}copy(t){return this[0]=t[0],this[1]=t[1],this[2]=t[2],this[3]=t[3],this.check()}set(t,e,n,i){return this[0]=t,this[1]=e,this[2]=n,this[3]=i,this.check()}fromObject(t){return this[0]=t.x,this[1]=t.y,this[2]=t.z,this[3]=t.w,this.check()}fromMatrix3(t){return function(t,e){const n=e[0]+e[4]+e[8];let i;if(n>0)i=Math.sqrt(n+1),t[3]=.5*i,i=.5/i,t[0]=(e[5]-e[7])*i,t[1]=(e[6]-e[2])*i,t[2]=(e[1]-e[3])*i;else{let n=0;e[4]>e[0]&&(n=1),e[8]>e[3*n+n]&&(n=2);const s=(n+1)%3,r=(n+2)%3;i=Math.sqrt(e[3*n+n]-e[3*s+s]-e[3*r+r]+1),t[n]=.5*i,i=.5/i,t[3]=(e[3*s+r]-e[3*r+s])*i,t[s]=(e[3*s+n]+e[3*n+s])*i,t[r]=(e[3*r+n]+e[3*n+r])*i}}(this,t),this.check()}fromAxisRotation(t,e){return Cr(this,t,e),this.check()}identity(){var t;return(t=this)[0]=0,t[1]=0,t[2]=0,t[3]=1,this.check()}setAxisAngle(t,e){return this.fromAxisRotation(t,e)}get ELEMENTS(){return 4}get x(){return this[0]}set x(t){this[0]=Ts(t)}get y(){return this[1]}set y(t){this[1]=Ts(t)}get z(){return this[2]}set z(t){this[2]=Ts(t)}get w(){return this[3]}set w(t){this[3]=Ts(t)}len(){return function(t){const e=t[0],n=t[1],i=t[2],s=t[3];return Math.sqrt(e*e+n*n+i*i+s*s)}(this)}lengthSquared(){return function(t){const e=t[0],n=t[1],i=t[2],s=t[3];return e*e+n*n+i*i+s*s}(this)}dot(t){return function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}(this,t)}rotationTo(t,e){return Rr(this,t,e),this.check()}add(t){return function(t,e,n){t[0]=e[0]+n[0],t[1]=e[1]+n[1],t[2]=e[2]+n[2],t[3]=e[3]+n[3]}(this,this,t),this.check()}calculateW(){return function(t,e){const n=e[0],i=e[1],s=e[2];t[0]=n,t[1]=i,t[2]=s,t[3]=Math.sqrt(Math.abs(1-n*n-i*i-s*s))}(this,this),this.check()}conjugate(){return function(t,e){t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3]}(this,this),this.check()}invert(){return function(t,e){const n=e[0],i=e[1],s=e[2],r=e[3],o=n*n+i*i+s*s+r*r,a=o?1/o:0;t[0]=-n*a,t[1]=-i*a,t[2]=-s*a,t[3]=r*a}(this,this),this.check()}lerp(t,e,n){return void 0===n?this.lerp(this,t,e):(function(t,e,n,i){const s=e[0],r=e[1],o=e[2],a=e[3];t[0]=s+i*(n[0]-s),t[1]=r+i*(n[1]-r),t[2]=o+i*(n[2]-o),t[3]=a+i*(n[3]-a)}(this,t,e,n),this.check())}multiplyRight(t){return Pr(this,this,t),this.check()}multiplyLeft(t){return Pr(this,t,this),this.check()}normalize(){const t=this.len(),e=t>0?1/t:0;return this[0]=this[0]*e,this[1]=this[1]*e,this[2]=this[2]*e,this[3]=this[3]*e,0===t&&(this[3]=1),this.check()}rotateX(t){return function(t,e,n){n*=.5;const i=e[0],s=e[1],r=e[2],o=e[3],a=Math.sin(n),c=Math.cos(n);t[0]=i*c+o*a,t[1]=s*c+r*a,t[2]=r*c-s*a,t[3]=o*c-i*a}(this,this,t),this.check()}rotateY(t){return function(t,e,n){n*=.5;const i=e[0],s=e[1],r=e[2],o=e[3],a=Math.sin(n),c=Math.cos(n);t[0]=i*c-r*a,t[1]=s*c+o*a,t[2]=r*c+i*a,t[3]=o*c-s*a}(this,this,t),this.check()}rotateZ(t){return function(t,e,n){n*=.5;const i=e[0],s=e[1],r=e[2],o=e[3],a=Math.sin(n),c=Math.cos(n);t[0]=i*c+s*a,t[1]=s*c-i*a,t[2]=r*c+o*a,t[3]=o*c-r*a}(this,this,t),this.check()}scale(t){return Mr(this,this,t),this.check()}slerp(t,e,n){let i,s,r;switch(arguments.length){case 1:({start:i=Lr,target:s,ratio:r}=t);break;case 2:i=this,s=t,r=e;break;default:i=t,s=e,r=n}return function(t,e,n,i){const s=e[0],r=e[1],o=e[2],a=e[3];let c,l,h,u,f,d=n[0],p=n[1],g=n[2],m=n[3];c=s*d+r*p+o*g+a*m,c<0&&(c=-c,d=-d,p=-p,g=-g,m=-m),1-c>Ps?(l=Math.acos(c),f=Math.sin(l),h=Math.sin((1-i)*l)/f,u=Math.sin(i*l)/f):(h=1-i,u=i),t[0]=h*s+u*d,t[1]=h*r+u*p,t[2]=h*o+u*g,t[3]=h*a+u*m}(this,i,s,r),this.check()}transformVector4(t,e=new Qs){return function(t,e,n){const i=e[0],s=e[1],r=e[2],o=n[0],a=n[1],c=n[2],l=n[3],h=l*i+a*r-c*s,u=l*s+c*i-o*r,f=l*r+o*s-a*i,d=-o*i-a*s-c*r;t[0]=h*l+d*-o+u*-c-f*-a,t[1]=u*l+d*-a+f*-o-h*-c,t[2]=f*l+d*-c+h*-a-u*-o,t[3]=e[3]}(e,t,this),As(e,4)}lengthSq(){return this.lengthSquared()}setFromAxisAngle(t,e){return this.setAxisAngle(t,e)}premultiply(t){return this.multiplyLeft(t)}multiply(t){return this.multiplyRight(t)}}function Ir(t,e=[],n=0){const i=Math.fround(t),s=t-i;return e[n]=i,e[n+1]=s,e}const kr={name:"fp64arithmetic",vs:"\nuniform fp64arithmeticUniforms {\n uniform float ONE;\n} fp64;\n\n/*\nAbout LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n\nThe purpose of this workaround is to prevent shader compilers from\noptimizing away necessary arithmetic operations by swapping their sequences\nor transform the equation to some 'equivalent' form.\n\nThe method is to multiply an artifical variable, ONE, which will be known to\nthe compiler to be 1 only at runtime. The whole expression is then represented\nas a polynomial with respective to ONE. In the coefficients of all terms, only one a\nand one b should appear\n\nerr = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE\n*/\n\n// Divide float number to high and low floats to extend fraction bits\nvec2 split(float a) {\n const float SPLIT = 4097.0;\n float t = a * SPLIT;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float a_hi = t * fp64.ONE - (t - a);\n float a_lo = a * fp64.ONE - a_hi;\n#else\n float a_hi = t - (t - a);\n float a_lo = a - a_hi;\n#endif\n return vec2(a_hi, a_lo);\n}\n\n// Divide float number again when high float uses too many fraction bits\nvec2 split2(vec2 a) {\n vec2 b = split(a.x);\n b.y += a.y;\n return b;\n}\n\n// Special sum operation when a > b\nvec2 quickTwoSum(float a, float b) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float sum = (a + b) * fp64.ONE;\n float err = b - (sum - a) * fp64.ONE;\n#else\n float sum = a + b;\n float err = b - (sum - a);\n#endif\n return vec2(sum, err);\n}\n\n// General sum operation\nvec2 twoSum(float a, float b) {\n float s = (a + b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v);\n#else\n float v = s - a;\n float err = (a - (s - v)) + (b - v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSub(float a, float b) {\n float s = (a - b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v);\n#else\n float v = s - a;\n float err = (a - (s - v)) - (b + v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSqr(float a) {\n float prod = a * a;\n vec2 a_fp64 = split(a);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x *\n a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y;\n#endif\n return vec2(prod, err);\n}\n\nvec2 twoProd(float a, float b) {\n float prod = a * b;\n vec2 a_fp64 = split(a);\n vec2 b_fp64 = split(b);\n float err = ((a_fp64.x * b_fp64.x - prod) + a_fp64.x * b_fp64.y +\n a_fp64.y * b_fp64.x) + a_fp64.y * b_fp64.y;\n return vec2(prod, err);\n}\n\nvec2 sum_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSum(a.x, b.x);\n t = twoSum(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 sub_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSub(a.x, b.x);\n t = twoSub(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 mul_fp64(vec2 a, vec2 b) {\n vec2 prod = twoProd(a.x, b.x);\n // y component is for the error\n prod.y += a.x * b.y;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n prod.y += a.y * b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nvec2 div_fp64(vec2 a, vec2 b) {\n float xn = 1.0 / b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n vec2 yn = mul_fp64(a, vec2(xn, 0));\n#else\n vec2 yn = a * xn;\n#endif\n float diff = (sub_fp64(a, mul_fp64(b, yn))).x;\n vec2 prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nvec2 sqrt_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n\n float x = 1.0 / sqrt(a.x);\n float yn = a.x * x;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n vec2 yn_sqr = twoSqr(yn) * fp64.ONE;\n#else\n vec2 yn_sqr = twoSqr(yn);\n#endif\n float diff = sub_fp64(a, yn_sqr).x;\n vec2 prod = twoProd(x * 0.5, diff);\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2(yn, 0.0), prod);\n#endif\n}\n",defaultUniforms:{ONE:1},uniformTypes:{ONE:"f32"},fp64ify:Ir,fp64LowPart:function(t){return t-Math.fround(t)},fp64ifyMatrix4:function(t){const e=new Float32Array(32);for(let n=0;n<4;++n)for(let i=0;i<4;++i)Ir(t[4*i+n],e,2*(4*n+i));return e}},Dr={props:{},uniforms:{},name:"picking",uniformTypes:{isActive:"f32",isAttribute:"f32",isHighlightActive:"f32",useFloatColors:"f32",highlightedObjectColor:"vec3<f32>",highlightColor:"vec4<f32>"},defaultUniforms:{isActive:!1,isAttribute:!1,isHighlightActive:!1,useFloatColors:!0,highlightedObjectColor:[0,0,0],highlightColor:[0,1,1,1]},vs:"uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useFloatColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nout vec4 picking_vRGBcolor_Avalid;\n\n// Normalize unsigned byte color to 0-1 range\nvec3 picking_normalizeColor(vec3 color) {\n return picking.useFloatColors > 0.5 ? color : color / 255.0;\n}\n\n// Normalize unsigned byte color to 0-1 range\nvec4 picking_normalizeColor(vec4 color) {\n return picking.useFloatColors > 0.5 ? color : color / 255.0;\n}\n\nbool picking_isColorZero(vec3 color) {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nbool picking_isColorValid(vec3 color) {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n\n// Check if this vertex is highlighted \nbool isVertexHighlighted(vec3 vertexColor) {\n vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n return\n bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor));\n}\n\n// Set the current picking color\nvoid picking_setPickingColor(vec3 pickingColor) {\n pickingColor = picking_normalizeColor(pickingColor);\n\n if (bool(picking.isActive)) {\n // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable\n picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor));\n\n if (!bool(picking.isAttribute)) {\n // Stores the picking color so that the fragment shader can render it during picking\n picking_vRGBcolor_Avalid.rgb = pickingColor;\n }\n } else {\n // Do the comparison with selected item color in vertex shader as it should mean fewer compares\n picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor));\n }\n}\n\nvoid picking_setPickingAttribute(float value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.r = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec2 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rg = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec3 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rgb = value;\n }\n}\n",fs:"uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useFloatColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nin vec4 picking_vRGBcolor_Avalid;\n\n/*\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (picking.isActive > 0.5) {\n return color;\n }\n\n bool selected = bool(picking_vRGBcolor_Avalid.a);\n\n if (selected) {\n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n } else {\n return color;\n }\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_vRGBcolor_Avalid.a == 0.0) {\n discard;\n }\n return picking_vRGBcolor_Avalid;\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 highlightColor = picking_filterHighlightColor(color);\n return picking_filterPickingColor(highlightColor);\n}\n",getUniforms:function(t={}){const e={};if(void 0===t.highlightedObjectColor);else if(null===t.highlightedObjectColor)e.isHighlightActive=!1;else{e.isHighlightActive=!0;const n=t.highlightedObjectColor.slice(0,3);e.highlightedObjectColor=n}if(t.highlightColor){const n=Array.from(t.highlightColor,(t=>t/255));Number.isFinite(n[3])||(n[3]=1),e.highlightColor=n}return void 0!==t.isActive&&(e.isActive=Boolean(t.isActive),e.isAttribute=Boolean(t.isAttribute)),void 0!==t.useFloatColors&&(e.useFloatColors=Boolean(t.useFloatColors)),e}},Nr="precision highp int;\n\n// #if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\nstruct AmbientLight {\n vec3 color;\n};\n\nstruct PointLight {\n vec3 color;\n vec3 position;\n vec3 attenuation; // 2nd order x:Constant-y:Linear-z:Exponential\n};\n\nstruct DirectionalLight {\n vec3 color;\n vec3 direction;\n};\n\nuniform lightingUniforms {\n int enabled;\n int lightType;\n\n int directionalLightCount;\n int pointLightCount;\n\n vec3 ambientColor;\n\n vec3 lightColor0;\n vec3 lightPosition0;\n vec3 lightDirection0;\n vec3 lightAttenuation0;\n\n vec3 lightColor1;\n vec3 lightPosition1;\n vec3 lightDirection1;\n vec3 lightAttenuation1;\n\n vec3 lightColor2;\n vec3 lightPosition2;\n vec3 lightDirection2;\n vec3 lightAttenuation2;\n} lighting;\n\nPointLight lighting_getPointLight(int index) {\n switch (index) {\n case 0:\n return PointLight(lighting.lightColor0, lighting.lightPosition0, lighting.lightAttenuation0);\n case 1:\n return PointLight(lighting.lightColor1, lighting.lightPosition1, lighting.lightAttenuation1);\n case 2:\n default: \n return PointLight(lighting.lightColor2, lighting.lightPosition2, lighting.lightAttenuation2);\n }\n}\n\nDirectionalLight lighting_getDirectionalLight(int index) {\n switch (index) {\n case 0:\n return DirectionalLight(lighting.lightColor0, lighting.lightDirection0);\n case 1:\n return DirectionalLight(lighting.lightColor1, lighting.lightDirection1);\n case 2:\n default: \n return DirectionalLight(lighting.lightColor2, lighting.lightDirection2);\n }\n} \n\nfloat getPointLightAttenuation(PointLight pointLight, float distance) {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n\n// #endif\n";var Fr;!function(t){t[t.POINT=0]="POINT",t[t.DIRECTIONAL=1]="DIRECTIONAL"}(Fr||(Fr={}));const Br={props:{},uniforms:{},name:"lighting",defines:{},uniformTypes:{enabled:"i32",lightType:"i32",directionalLightCount:"i32",pointLightCount:"i32",ambientColor:"vec3<f32>",lightColor0:"vec3<f32>",lightPosition0:"vec3<f32>",lightDirection0:"vec3<f32>",lightAttenuation0:"vec3<f32>",lightColor1:"vec3<f32>",lightPosition1:"vec3<f32>",lightDirection1:"vec3<f32>",lightAttenuation1:"vec3<f32>",lightColor2:"vec3<f32>",lightPosition2:"vec3<f32>",lightDirection2:"vec3<f32>",lightAttenuation2:"vec3<f32>"},defaultUniforms:{enabled:1,lightType:Fr.POINT,directionalLightCount:0,pointLightCount:0,ambientColor:[.1,.1,.1],lightColor0:[1,1,1],lightPosition0:[1,1,2],lightDirection0:[1,1,1],lightAttenuation0:[1,0,0],lightColor1:[1,1,1],lightPosition1:[1,1,2],lightDirection1:[1,1,1],lightAttenuation1:[1,0,0],lightColor2:[1,1,1],lightPosition2:[1,1,2],lightDirection2:[1,1,1],lightAttenuation2:[1,0,0]},source:"// #if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\nstruct AmbientLight {\n color: vec3<f32>,\n};\n\nstruct PointLight {\n color: vec3<f32>,\n position: vec3<f32>,\n attenuation: vec3<f32>, // 2nd order x:Constant-y:Linear-z:Exponential\n};\n\nstruct DirectionalLight {\n color: vec3<f32>,\n direction: vec3<f32>,\n};\n\nstruct lightingUniforms {\n enabled: i32,\n pointLightCount: i32,\n directionalLightCount: i32,\n\n ambientColor: vec3<f32>,\n\n // TODO - support multiple lights by uncommenting arrays below\n lightType: i32,\n lightColor: vec3<f32>,\n lightDirection: vec3<f32>,\n lightPosition: vec3<f32>,\n lightAttenuation: vec3<f32>,\n\n // AmbientLight ambientLight;\n // PointLight pointLight[MAX_LIGHTS];\n // DirectionalLight directionalLight[MAX_LIGHTS];\n};\n\n// Binding 0:1 is reserved for lighting (Note: could go into separate bind group as it is stable across draw calls)\n@binding(1) @group(0) var<uniform> lighting : lightingUniforms;\n\nfn lighting_getPointLight(index: i32) -> PointLight {\n return PointLight(lighting.lightColor, lighting.lightPosition, lighting.lightAttenuation);\n}\n\nfn lighting_getDirectionalLight(index: i32) -> DirectionalLight {\n return DirectionalLight(lighting.lightColor, lighting.lightDirection);\n} \n\nfn getPointLightAttenuation(pointLight: PointLight, distance: f32) -> f32 {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n",vs:Nr,fs:Nr,getUniforms:function(t,e={}){if(!(t=t?{...t}:t))return{...Br.defaultUniforms};t.lights&&(t={...t,...Ur(t.lights),lights:void 0});const{ambientLight:n,pointLights:i,directionalLights:s}=t||{};if(!(n||i&&i.length>0||s&&s.length>0))return{...Br.defaultUniforms,enabled:0};const r={...Br.defaultUniforms,...e,...$r({ambientLight:n,pointLights:i,directionalLights:s})};return void 0!==t.enabled&&(r.enabled=t.enabled?1:0),r}};function $r({ambientLight:t,pointLights:e=[],directionalLights:n=[]}){const i={};i.ambientColor=zr(t);let s=0;for(const t of e){i.lightType=Fr.POINT;const e=s;i[`lightColor${e}`]=zr(t),i[`lightPosition${e}`]=t.position,i[`lightAttenuation${e}`]=t.attenuation||[1,0,0],s++}for(const t of n){i.lightType=Fr.DIRECTIONAL;const e=s;i[`lightColor${e}`]=zr(t),i[`lightDirection${e}`]=t.direction,s++}return s>5&&Mt.warn("MAX_LIGHTS exceeded")(),i.directionalLightCount=n.length,i.pointLightCount=e.length,i}function Ur(t){const e={pointLights:[],directionalLights:[]};for(const n of t||[])switch(n.type){case"ambient":e.ambientLight=n;break;case"directional":e.directionalLights?.push(n);break;case"point":e.pointLights?.push(n)}return e}function zr(t={}){const{color:e=[0,0,0],intensity:n=1}=t;return e.map((t=>t*n/255))}const jr="uniform phongMaterialUniforms {\n uniform float ambient;\n uniform float diffuse;\n uniform float shininess;\n uniform vec3 specularColor;\n} material;\n",Gr="#define MAX_LIGHTS 3\n\nuniform phongMaterialUniforms {\n uniform float ambient;\n uniform float diffuse;\n uniform float shininess;\n uniform vec3 specularColor;\n} material;\n\nvec3 lighting_getLightColor(vec3 surfaceColor, vec3 light_direction, vec3 view_direction, vec3 normal_worldspace, vec3 color) {\n vec3 halfway_direction = normalize(light_direction + view_direction);\n float lambertian = dot(light_direction, normal_worldspace);\n float specular = 0.0;\n if (lambertian > 0.0) {\n float specular_angle = max(dot(normal_worldspace, halfway_direction), 0.0);\n specular = pow(specular_angle, material.shininess);\n }\n lambertian = max(lambertian, 0.0);\n return (lambertian * material.diffuse * surfaceColor + specular * material.specularColor) * color;\n}\n\nvec3 lighting_getLightColor(vec3 surfaceColor, vec3 cameraPosition, vec3 position_worldspace, vec3 normal_worldspace) {\n vec3 lightColor = surfaceColor;\n\n if (lighting.enabled == 0) {\n return lightColor;\n }\n\n vec3 view_direction = normalize(cameraPosition - position_worldspace);\n lightColor = material.ambient * surfaceColor * lighting.ambientColor;\n\n for (int i = 0; i < lighting.pointLightCount; i++) {\n PointLight pointLight = lighting_getPointLight(i);\n vec3 light_position_worldspace = pointLight.position;\n vec3 light_direction = normalize(light_position_worldspace - position_worldspace);\n float light_attenuation = getPointLightAttenuation(pointLight, distance(light_position_worldspace, position_worldspace));\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, pointLight.color / light_attenuation);\n }\n\n int totalLights = min(MAX_LIGHTS, lighting.pointLightCount + lighting.directionalLightCount);\n for (int i = lighting.pointLightCount; i < totalLights; i++) {\n DirectionalLight directionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n \n return lightColor;\n}\n",Wr="struct phongMaterialUniforms {\n ambient: f32,\n diffuse: f32,\n shininess: f32,\n specularColor: vec3<f32>,\n};\n\n@binding(2) @group(0) var<uniform> phongMaterial : phongMaterialUniforms;\n\nfn lighting_getLightColor(surfaceColor: vec3<f32>, light_direction: vec3<f32>, view_direction: vec3<f32>, normal_worldspace: vec3<f32>, color: vec3<f32>) -> vec3<f32> {\n let halfway_direction: vec3<f32> = normalize(light_direction + view_direction);\n var lambertian: f32 = dot(light_direction, normal_worldspace);\n var specular: f32 = 0.0;\n if (lambertian > 0.0) {\n let specular_angle = max(dot(normal_worldspace, halfway_direction), 0.0);\n specular = pow(specular_angle, phongMaterial.shininess);\n }\n lambertian = max(lambertian, 0.0);\n return (lambertian * phongMaterial.diffuse * surfaceColor + specular * phongMaterial.specularColor) * color;\n}\n\nfn lighting_getLightColor2(surfaceColor: vec3<f32>, cameraPosition: vec3<f32>, position_worldspace: vec3<f32>, normal_worldspace: vec3<f32>) -> vec3<f32> {\n var lightColor: vec3<f32> = surfaceColor;\n\n if (lighting.enabled == 0) {\n return lightColor;\n }\n\n let view_direction: vec3<f32> = normalize(cameraPosition - position_worldspace);\n lightColor = phongMaterial.ambient * surfaceColor * lighting.ambientColor;\n\n if (lighting.lightType == 0) {\n let pointLight: PointLight = lighting_getPointLight(0);\n let light_position_worldspace: vec3<f32> = pointLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, pointLight.color);\n } else if (lighting.lightType == 1) {\n var directionalLight: DirectionalLight = lighting_getDirectionalLight(0);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n \n return lightColor;\n /*\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= lighting.pointLightCount) {\n break;\n }\n PointLight pointLight = lighting.pointLight[i];\n vec3 light_position_worldspace = pointLight.position;\n vec3 light_direction = normalize(light_position_worldspace - position_worldspace);\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, pointLight.color);\n }\n\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= lighting.directionalLightCount) {\n break;\n }\n DirectionalLight directionalLight = lighting.directionalLight[i];\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n */\n}\n\nfn lighting_getSpecularLightColor(cameraPosition: vec3<f32>, position_worldspace: vec3<f32>, normal_worldspace: vec3<f32>) -> vec3<f32>{\n var lightColor = vec3<f32>(0, 0, 0);\n let surfaceColor = vec3<f32>(0, 0, 0);\n\n if (lighting.enabled == 0) {\n let view_direction = normalize(cameraPosition - position_worldspace);\n\n switch (lighting.lightType) {\n case 0, default: {\n let pointLight: PointLight = lighting_getPointLight(0);\n let light_position_worldspace: vec3<f32> = pointLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, pointLight.color);\n }\n case 1: {\n let directionalLight: DirectionalLight = lighting_getDirectionalLight(0);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n }\n }\n return lightColor;\n}\n",Vr={props:{},name:"gouraudMaterial",vs:Gr.replace("phongMaterial","gouraudMaterial"),fs:jr.replace("phongMaterial","gouraudMaterial"),source:Wr.replaceAll("phongMaterial","gouraudMaterial"),defines:{LIGHTING_VERTEX:!0},dependencies:[Br],uniformTypes:{ambient:"f32",diffuse:"f32",shininess:"f32",specularColor:"vec3<f32>"},defaultUniforms:{ambient:.35,diffuse:.6,shininess:32,specularColor:[.15,.15,.15]},getUniforms(t){const e={...t};return e.specularColor&&(e.specularColor=e.specularColor.map((t=>t/255))),{...Vr.defaultUniforms,...e}}},Hr={name:"phongMaterial",dependencies:[Br],source:Wr,vs:jr,fs:Gr,defines:{LIGHTING_FRAGMENT:!0},uniformTypes:{ambient:"f32",diffuse:"f32",shininess:"f32",specularColor:"vec3<f32>"},defaultUniforms:{ambient:.35,diffuse:.6,shininess:32,specularColor:[.15,.15,.15]},getUniforms(t){const e={...t};return e.specularColor&&(e.specularColor=e.specularColor.map((t=>t/255))),{...Hr.defaultUniforms,...e}}},Xr="uniform layerUniforms {\n uniform float opacity;\n} layer;\n",Zr={name:"layer",vs:Xr,fs:Xr,getUniforms:t=>({opacity:Math.pow(t.opacity,1/2.2)}),uniformTypes:{opacity:"f32"}};var Kr={name:"color",dependencies:[],source:"\n\nstruct ColorUniforms {\n opacity: f32,\n};\n\nvar<private> color: ColorUniforms = ColorUniforms(1.0);\n// TODO (kaapp) avoiding binding index collisions to handle layer opacity \n// requires some thought.\n// @group(0) @binding(0) var<uniform> color: ColorUniforms;\n\n@must_use\nfn deckgl_premultiplied_alpha(fragColor: vec4<f32>) -> vec4<f32> {\n return vec4(fragColor.rgb * fragColor.a, fragColor.a); \n};\n",getUniforms:()=>({}),uniformTypes:{opacity:"f32"}};const qr="#define SMOOTH_EDGE_RADIUS 0.5";var Yr,Jr,Qr,to={name:"geometry",source:"const SMOOTH_EDGE_RADIUS: f32 = 0.5;\n\nstruct VertexGeometry {\n position: vec4<f32>,\n worldPosition: vec3<f32>,\n worldPositionAlt: vec3<f32>,\n normal: vec3<f32>,\n uv: vec2<f32>,\n pickingColor: vec3<f32>,\n};\n\nvar<private> geometry_: VertexGeometry = VertexGeometry(\n vec4<f32>(0.0, 0.0, 1.0, 0.0),\n vec3<f32>(0.0, 0.0, 0.0),\n vec3<f32>(0.0, 0.0, 0.0),\n vec3<f32>(0.0, 0.0, 0.0),\n vec2<f32>(0.0, 0.0),\n vec3<f32>(0.0, 0.0, 0.0)\n);\n\nstruct FragmentGeometry {\n uv: vec2<f32>,\n};\n\nvar<private> fragmentGeometry: FragmentGeometry;\n\nfn smoothedge(edge: f32, x: f32) -> f32 {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n",vs:`${qr}\n\nstruct VertexGeometry {\n vec4 position;\n vec3 worldPosition;\n vec3 worldPositionAlt;\n vec3 normal;\n vec2 uv;\n vec3 pickingColor;\n} geometry = VertexGeometry(\n vec4(0.0, 0.0, 1.0, 0.0),\n vec3(0.0),\n vec3(0.0),\n vec3(0.0),\n vec2(0.0),\n vec3(0.0)\n);\n`,fs:`${qr}\n\nstruct FragmentGeometry {\n vec2 uv;\n} geometry;\n\nfloat smoothedge(float edge, float x) {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n`};!function(t){t[t.Start=1]="Start",t[t.Move=2]="Move",t[t.End=4]="End",t[t.Cancel=8]="Cancel"}(Yr||(Yr={})),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"}(Jr||(Jr={})),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"}(Qr||(Qr={}));const eo="manipulation",no="none",io="pan-x",so="pan-y";class ro{constructor(t,e){this.actions="",this.manager=t,this.set(e)}set(t){"compute"===t&&(t=this.compute()),this.manager.element&&(this.manager.element.style.touchAction=t,this.actions=t)}update(){this.set(this.manager.options.touchAction)}compute(){let t=[];for(const e of this.manager.recognizers)e.options.enable&&(t=t.concat(e.getTouchAction()));return function(t){if(t.includes(no))return no;const e=t.includes(io),n=t.includes(so);return e&&n?no:e||n?e?io:so:t.includes(eo)?eo:"auto"}(t.join(" "))}}function oo(t){return t.trim().split(/\s+/g)}function ao(t,e,n){if(t)for(const i of oo(e))t.addEventListener(i,n,!1)}function co(t,e,n){if(t)for(const i of oo(e))t.removeEventListener(i,n,!1)}function lo(t){return(t.ownerDocument||t).defaultView}function ho(t){const e=t.length;if(1===e)return{x:Math.round(t[0].clientX),y:Math.round(t[0].clientY)};let n=0,i=0,s=0;for(;s<e;)n+=t[s].clientX,i+=t[s].clientY,s++;return{x:Math.round(n/e),y:Math.round(i/e)}}function uo(t){const e=[];let n=0;for(;n<t.pointers.length;)e[n]={clientX:Math.round(t.pointers[n].clientX),clientY:Math.round(t.pointers[n].clientY)},n++;return{timeStamp:Date.now(),pointers:e,center:ho(e),deltaX:t.deltaX,deltaY:t.deltaY}}function fo(t,e){const n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function po(t,e){const n=e.clientX-t.clientX,i=e.clientY-t.clientY;return Math.sqrt(n*n+i*i)}function go(t,e){return 180*Math.atan2(e.clientY-t.clientY,e.clientX-t.clientX)/Math.PI}function mo(t,e){return t===e?Jr.None:Math.abs(t)>=Math.abs(e)?t<0?Jr.Left:Jr.Right:e<0?Jr.Up:Jr.Down}function _o(t,e,n){return{x:e/t||0,y:n/t||0}}let vo=class{constructor(t){this.evEl="",this.evWin="",this.evTarget="",this.domHandler=t=>{this.manager.options.enable&&this.handler(t)},this.manager=t,this.element=t.element,this.target=t.options.inputTarget||t.element}callback(t,e){!function(t,e,n){const i=n.pointers.length,s=n.changedPointers.length,r=e&Yr.Start&&i-s==0,o=e&(Yr.End|Yr.Cancel)&&i-s==0;n.isFirst=Boolean(r),n.isFinal=Boolean(o),r&&(t.session={}),n.eventType=e;const a=function(t,e){const{session:n}=t,{pointers:i}=e,{length:s}=i;n.firstInput||(n.firstInput=uo(e)),s>1&&!n.firstMultiple?n.firstMultiple=uo(e):1===s&&(n.firstMultiple=!1);const{firstInput:r,firstMultiple:o}=n,a=o?o.center:r.center,c=e.center=ho(i);var l,h;e.timeStamp=Date.now(),e.deltaTime=e.timeStamp-r.timeStamp,e.angle=(l=a,h=c,180*Math.atan2(h.y-l.y,h.x-l.x)/Math.PI),e.distance=fo(a,c);const{deltaX:u,deltaY:f}=function(t,e){const n=e.center;let i=t.offsetDelta,s=t.prevDelta;const r=t.prevInput;return e.eventType!==Yr.Start&&r?.eventType!==Yr.End||(s=t.prevDelta={x:r?.deltaX||0,y:r?.deltaY||0},i=t.offsetDelta={x:n.x,y:n.y}),{deltaX:s.x+(n.x-i.x),deltaY:s.y+(n.y-i.y)}}(n,e);e.deltaX=u,e.deltaY=f,e.offsetDirection=mo(e.deltaX,e.deltaY);const d=_o(e.deltaTime,e.deltaX,e.deltaY);var p,g;e.overallVelocityX=d.x,e.overallVelocityY=d.y,e.overallVelocity=Math.abs(d.x)>Math.abs(d.y)?d.x:d.y,e.scale=o?(p=o.pointers,po((g=i)[0],g[1])/po(p[0],p[1])):1,e.rotation=o?function(t,e){return go(e[1],e[0])-go(t[1],t[0])}(o.pointers,i):0,e.maxPointers=n.prevInput?e.pointers.length>n.prevInput.maxPointers?e.pointers.length:n.prevInput.maxPointers:e.pointers.length;let m=t.element;return function(t,e){let n=t;for(;n;){if(n===e)return!0;n=n.parentNode}return!1}(e.srcEvent.target,m)&&(m=e.srcEvent.target),e.target=m,function(t,e){const n=t.lastInterval||e,i=e.timeStamp-n.timeStamp;let s,r,o,a;if(e.eventType!==Yr.Cancel&&(i>25||void 0===n.velocity)){const c=e.deltaX-n.deltaX,l=e.deltaY-n.deltaY,h=_o(i,c,l);r=h.x,o=h.y,s=Math.abs(h.x)>Math.abs(h.y)?h.x:h.y,a=mo(c,l),t.lastInterval=e}else s=n.velocity,r=n.velocityX,o=n.velocityY,a=n.direction;e.velocity=s,e.velocityX=r,e.velocityY=o,e.direction=a}(n,e),e}(t,n);t.emit("hammer.input",a),t.recognize(a),t.session.prevInput=a}(this.manager,t,e)}init(){ao(this.element,this.evEl,this.domHandler),ao(this.target,this.evTarget,this.domHandler),ao(lo(this.element),this.evWin,this.domHandler)}destroy(){co(this.element,this.evEl,this.domHandler),co(this.target,this.evTarget,this.domHandler),co(lo(this.element),this.evWin,this.domHandler)}};const bo={pointerdown:Yr.Start,pointermove:Yr.Move,pointerup:Yr.End,pointercancel:Yr.Cancel,pointerout:Yr.Cancel};class yo extends vo{constructor(t){super(t),this.evEl="pointerdown",this.evWin="pointermove pointerup pointercancel",this.store=this.manager.session.pointerEvents=[],this.init()}handler(t){const{store:e}=this;let n=!1;const i=bo[t.type],s=t.pointerType,r="touch"===s;let o=e.findIndex((e=>e.pointerId===t.pointerId));i&Yr.Start&&(t.buttons||r)?o<0&&(e.push(t),o=e.length-1):i&(Yr.End|Yr.Cancel)&&(n=!0),o<0||(e[o]=t,this.callback(i,{pointers:e,changedPointers:[t],eventType:i,pointerType:s,srcEvent:t}),n&&e.splice(o,1))}}const wo=["","webkit","Moz","MS","ms","o"];function xo(t,e){const n=e[0].toUpperCase()+e.slice(1);for(const i of wo){const s=i?i+n:e;if(s in t)return s}}const Eo={touchAction:"compute",enable:!0,inputTarget:null,cssProps:{userSelect:"none",userDrag:"none",touchCallout:"none",tapHighlightColor:"rgba(0,0,0,0)"}};class To{constructor(t,e){this.options={...Eo,...e,cssProps:{...Eo.cssProps,...e.cssProps},inputTarget:e.inputTarget||t},this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=t,this.input=new yo(this),this.touchAction=new ro(this,this.options.touchAction),this.toggleCssProps(!0)}set(t){return Object.assign(this.options,t),t.touchAction&&this.touchAction.update(),t.inputTarget&&(this.input.destroy(),this.input.target=t.inputTarget,this.input.init()),this}stop(t){this.session.stopped=t?2:1}recognize(t){const{session:e}=this;if(e.stopped)return;let n;this.session.prevented&&t.srcEvent.preventDefault();const{recognizers:i}=this;let{curRecognizer:s}=e;(!s||s&&s.state&Qr.Recognized)&&(s=e.curRecognizer=null);let r=0;for(;r<i.length;)n=i[r],2===e.stopped||s&&n!==s&&!n.canRecognizeWith(s)?n.reset():n.recognize(t),!s&&n.state&(Qr.Began|Qr.Changed|Qr.Ended)&&(s=e.curRecognizer=n),r++}get(t){const{recognizers:e}=this;for(let n=0;n<e.length;n++)if(e[n].options.event===t)return e[n];return null}add(t){if(Array.isArray(t)){for(const e of t)this.add(e);return this}const e=this.get(t.options.event);return e&&this.remove(e),this.recognizers.push(t),t.manager=this,this.touchAction.update(),t}remove(t){if(Array.isArray(t)){for(const e of t)this.remove(e);return this}const e="string"==typeof t?this.get(t):t;if(e){const{recognizers:t}=this,n=t.indexOf(e);-1!==n&&(t.splice(n,1),this.touchAction.update())}return this}on(t,e){if(!t||!e)return;const{handlers:n}=this;for(const i of oo(t))n[i]=n[i]||[],n[i].push(e)}off(t,e){if(!t)return;const{handlers:n}=this;for(const i of oo(t))e?n[i]&&n[i].splice(n[i].indexOf(e),1):delete n[i]}emit(t,e){const n=this.handlers[t]&&this.handlers[t].slice();if(!n||!n.length)return;const i=e;i.type=t,i.preventDefault=function(){e.srcEvent.preventDefault()};let s=0;for(;s<n.length;)n[s](i),s++}destroy(){this.toggleCssProps(!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}toggleCssProps(t){const{element:e}=this;if(e){for(const[n,i]of Object.entries(this.options.cssProps)){const s=xo(e.style,n);t?(this.oldCssProps[s]=e.style[s],e.style[s]=i):e.style[s]=this.oldCssProps[s]||""}t||(this.oldCssProps={})}}}let Ao=1;function So(t){return t&Qr.Cancelled?"cancel":t&Qr.Ended?"end":t&Qr.Changed?"move":t&Qr.Began?"start":""}class Co{constructor(t){this.options=t,this.id=Ao++,this.state=Qr.Possible,this.simultaneous={},this.requireFail=[]}set(t){return Object.assign(this.options,t),this.manager.touchAction.update(),this}recognizeWith(t){if(Array.isArray(t)){for(const e of t)this.recognizeWith(e);return this}let e;if("string"==typeof t){if(e=this.manager.get(t),!e)throw new Error(`Cannot find recognizer ${t}`)}else e=t;const{simultaneous:n}=this;return n[e.id]||(n[e.id]=e,e.recognizeWith(this)),this}dropRecognizeWith(t){if(Array.isArray(t)){for(const e of t)this.dropRecognizeWith(e);return this}let e;return e="string"==typeof t?this.manager.get(t):t,e&&delete this.simultaneous[e.id],this}requireFailure(t){if(Array.isArray(t)){for(const e of t)this.requireFailure(e);return this}let e;if("string"==typeof t){if(e=this.manager.get(t),!e)throw new Error(`Cannot find recognizer ${t}`)}else e=t;const{requireFail:n}=this;return-1===n.indexOf(e)&&(n.push(e),e.requireFailure(this)),this}dropRequireFailure(t){if(Array.isArray(t)){for(const e of t)this.dropRequireFailure(e);return this}let e;if(e="string"==typeof t?this.manager.get(t):t,e){const t=this.requireFail.indexOf(e);t>-1&&this.requireFail.splice(t,1)}return this}hasRequireFailures(){return Boolean(this.requireFail.find((t=>t.options.enable)))}canRecognizeWith(t){return Boolean(this.simultaneous[t.id])}emit(t){if(!t)return;const{state:e}=this;e<Qr.Ended&&this.manager.emit(this.options.event+So(e),t),this.manager.emit(this.options.event,t),t.additionalEvent&&this.manager.emit(t.additionalEvent,t),e>=Qr.Ended&&this.manager.emit(this.options.event+So(e),t)}tryEmit(t){this.canEmit()?this.emit(t):this.state=Qr.Failed}canEmit(){let t=0;for(;t<this.requireFail.length;){if(!(this.requireFail[t].state&(Qr.Failed|Qr.Possible)))return!1;t++}return!0}recognize(t){const e={...t};if(!this.options.enable)return this.reset(),void(this.state=Qr.Failed);this.state&(Qr.Recognized|Qr.Cancelled|Qr.Failed)&&(this.state=Qr.Possible),this.state=this.process(e),this.state&(Qr.Began|Qr.Changed|Qr.Ended|Qr.Cancelled)&&this.tryEmit(e)}getEventNames(){return[this.options.event]}reset(){}}class Po extends Co{attrTest(t){const e=this.options.pointers;return 0===e||t.pointers.length===e}process(t){const{state:e}=this,{eventType:n}=t,i=e&(Qr.Began|Qr.Changed),s=this.attrTest(t);return i&&(n&Yr.Cancel||!s)?e|Qr.Cancelled:i||s?n&Yr.End?e|Qr.Ended:e&Qr.Began?e|Qr.Changed:Qr.Began:Qr.Failed}}class Mo extends Co{constructor(t={}){super({enable:!0,event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10,...t}),this.pTime=null,this.pCenter=null,this._timer=null,this._input=null,this.count=0}getTouchAction(){return[eo]}process(t){const{options:e}=this,n=t.pointers.length===e.pointers,i=t.distance<e.threshold,s=t.deltaTime<e.time;if(this.reset(),t.eventType&Yr.Start&&0===this.count)return this.failTimeout();if(i&&s&&n){if(t.eventType!==Yr.End)return this.failTimeout();const n=!this.pTime||t.timeStamp-this.pTime<e.interval,i=!this.pCenter||fo(this.pCenter,t.center)<e.posThreshold;if(this.pTime=t.timeStamp,this.pCenter=t.center,i&&n?this.count+=1:this.count=1,this._input=t,0==this.count%e.taps)return this.hasRequireFailures()?(this._timer=setTimeout((()=>{this.state=Qr.Recognized,this.tryEmit(this._input)}),e.interval),Qr.Began):Qr.Recognized}return Qr.Failed}failTimeout(){return this._timer=setTimeout((()=>{this.state=Qr.Failed}),this.options.interval),Qr.Failed}reset(){clearTimeout(this._timer)}emit(t){this.state===Qr.Recognized&&(t.tapCount=this.count,this.manager.emit(this.options.event,t))}}const Ro=["","start","move","end","cancel","up","down","left","right"];class Lo extends Po{constructor(t={}){super({enable:!0,pointers:1,event:"pan",threshold:10,direction:Jr.All,...t}),this.pX=null,this.pY=null}getTouchAction(){const{options:{direction:t}}=this,e=[];return t&Jr.Horizontal&&e.push(so),t&Jr.Vertical&&e.push(io),e}getEventNames(){return Ro.map((t=>this.options.event+t))}directionTest(t){const{options:e}=this;let n=!0,{distance:i}=t,{direction:s}=t;const r=t.deltaX,o=t.deltaY;return s&e.direction||(e.direction&Jr.Horizontal?(s=0===r?Jr.None:r<0?Jr.Left:Jr.Right,n=r!==this.pX,i=Math.abs(t.deltaX)):(s=0===o?Jr.None:o<0?Jr.Up:Jr.Down,n=o!==this.pY,i=Math.abs(t.deltaY))),t.direction=s,n&&i>e.threshold&&Boolean(s&e.direction)}attrTest(t){return super.attrTest(t)&&(Boolean(this.state&Qr.Began)||!(this.state&Qr.Began)&&this.directionTest(t))}emit(t){this.pX=t.deltaX,this.pY=t.deltaY;const e=Jr[t.direction].toLowerCase();e&&(t.additionalEvent=this.options.event+e),super.emit(t)}}const Oo=["","start","move","end","cancel","in","out"];class Io{constructor(t,e,n){this.element=t,this.callback=e,this.options=n}}const ko=-1!==("undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"").indexOf("firefox"),Do=4.000244140625;class No extends Io{constructor(t,e,n){super(t,e,{enable:!0,...n}),this.handleEvent=t=>{if(!this.options.enable)return;let e=t.deltaY;globalThis.WheelEvent&&(ko&&t.deltaMode===globalThis.WheelEvent.DOM_DELTA_PIXEL&&(e/=globalThis.devicePixelRatio),t.deltaMode===globalThis.WheelEvent.DOM_DELTA_LINE&&(e*=40)),0!==e&&e%Do==0&&(e=Math.floor(e/Do)),t.shiftKey&&e&&(e*=.25),this.callback({type:"wheel",center:{x:t.clientX,y:t.clientY},delta:-e,srcEvent:t,pointerType:"mouse",target:t.target})},t.addEventListener("wheel",this.handleEvent,{passive:!1})}destroy(){this.element.removeEventListener("wheel",this.handleEvent)}enableEventType(t,e){"wheel"===t&&(this.options.enable=e)}}const Fo=["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"];class Bo extends Io{constructor(t,e,n){super(t,e,{enable:!0,...n}),this.handleEvent=t=>{this.handleOverEvent(t),this.handleOutEvent(t),this.handleEnterEvent(t),this.handleLeaveEvent(t),this.handleMoveEvent(t)},this.pressed=!1;const{enable:i}=this.options;this.enableMoveEvent=i,this.enableLeaveEvent=i,this.enableEnterEvent=i,this.enableOutEvent=i,this.enableOverEvent=i,Fo.forEach((e=>t.addEventListener(e,this.handleEvent)))}destroy(){Fo.forEach((t=>this.element.removeEventListener(t,this.handleEvent)))}enableEventType(t,e){switch(t){case"pointermove":this.enableMoveEvent=e;break;case"pointerover":this.enableOverEvent=e;break;case"pointerout":this.enableOutEvent=e;break;case"pointerenter":this.enableEnterEvent=e;break;case"pointerleave":this.enableLeaveEvent=e}}handleOverEvent(t){this.enableOverEvent&&"mouseover"===t.type&&this._emit("pointerover",t)}handleOutEvent(t){this.enableOutEvent&&"mouseout"===t.type&&this._emit("pointerout",t)}handleEnterEvent(t){this.enableEnterEvent&&"mouseenter"===t.type&&this._emit("pointerenter",t)}handleLeaveEvent(t){this.enableLeaveEvent&&"mouseleave"===t.type&&this._emit("pointerleave",t)}handleMoveEvent(t){if(this.enableMoveEvent)switch(t.type){case"mousedown":t.button>=0&&(this.pressed=!0);break;case"mousemove":0===t.buttons&&(this.pressed=!1),this.pressed||this._emit("pointermove",t);break;case"mouseup":this.pressed=!1}}_emit(t,e){this.callback({type:t,center:{x:e.clientX,y:e.clientY},srcEvent:e,pointerType:"mouse",target:e.target})}}const $o=["keydown","keyup"];class Uo extends Io{constructor(t,e,n){super(t,e,{enable:!0,tabIndex:0,...n}),this.handleEvent=t=>{const e=t.target||t.srcElement;"INPUT"===e.tagName&&"text"===e.type||"TEXTAREA"===e.tagName||(this.enableDownEvent&&"keydown"===t.type&&this.callback({type:"keydown",srcEvent:t,key:t.key,target:t.target}),this.enableUpEvent&&"keyup"===t.type&&this.callback({type:"keyup",srcEvent:t,key:t.key,target:t.target}))},this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,t.tabIndex=this.options.tabIndex,t.style.outline="none",$o.forEach((e=>t.addEventListener(e,this.handleEvent)))}destroy(){$o.forEach((t=>this.element.removeEventListener(t,this.handleEvent)))}enableEventType(t,e){"keydown"===t&&(this.enableDownEvent=e),"keyup"===t&&(this.enableUpEvent=e)}}class zo extends Io{constructor(t,e,n){super(t,e,n),this.handleEvent=t=>{this.options.enable&&this.callback({type:"contextmenu",center:{x:t.clientX,y:t.clientY},srcEvent:t,pointerType:"mouse",target:t.target})},t.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(t,e){"contextmenu"===t&&(this.options.enable=e)}}const jo={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4};function Go(t){const e=jo[t.srcEvent.type];if(!e)return null;const{buttons:n,button:i}=t.srcEvent;let s=!1,r=!1,o=!1;return 2===e?(s=Boolean(1&n),r=Boolean(4&n),o=Boolean(2&n)):(s=0===i,r=1===i,o=2===i),{leftButton:s,middleButton:r,rightButton:o}}function Wo(t,e){const n=t.center;if(!n)return null;const i=e.getBoundingClientRect();return{center:n,offsetCenter:{x:(n.x-i.left-e.clientLeft)/(i.width/e.offsetWidth||1),y:(n.y-i.top-e.clientTop)/(i.height/e.offsetHeight||1)}}}const Vo={srcElement:"root",priority:0};class Ho{constructor(t,e){this.handleEvent=t=>{if(this.isEmpty())return;const e=this._normalizeEvent(t);let n=t.srcEvent.target;for(;n&&n!==e.rootElement;){if(this._emit(e,n),e.handled)return;n=n.parentNode}this._emit(e,"root")},this.eventManager=t,this.recognizerName=e,this.handlers=[],this.handlersByElement=new Map,this._active=!1}isEmpty(){return!this._active}add(t,e,n,i=!1,s=!1){const{handlers:r,handlersByElement:o}=this,a={...Vo,...n};let c=o.get(a.srcElement);c||(c=[],o.set(a.srcElement,c));const l={type:t,handler:e,srcElement:a.srcElement,priority:a.priority};i&&(l.once=!0),s&&(l.passive=!0),r.push(l),this._active=this._active||!l.passive;let h=c.length-1;for(;h>=0&&!(c[h].priority>=l.priority);)h--;c.splice(h+1,0,l)}remove(t,e){const{handlers:n,handlersByElement:i}=this;for(let s=n.length-1;s>=0;s--){const r=n[s];if(r.type===t&&r.handler===e){n.splice(s,1);const t=i.get(r.srcElement);t.splice(t.indexOf(r),1),0===t.length&&i.delete(r.srcElement)}}this._active=n.some((t=>!t.passive))}_emit(t,e){const n=this.handlersByElement.get(e);if(n){let e=!1;const i=()=>{t.handled=!0},s=()=>{t.handled=!0,e=!0},r=[];for(let o=0;o<n.length;o++){const{type:a,handler:c,once:l}=n[o];if(c({...t,type:a,stopPropagation:i,stopImmediatePropagation:s}),l&&r.push(n[o]),e)break}for(let t=0;t<r.length;t++){const{type:e,handler:n}=r[t];this.remove(e,n)}}}_normalizeEvent(t){const e=this.eventManager.getElement();return{...t,...Go(t),...Wo(t,e),preventDefault:()=>{t.srcEvent.preventDefault()},stopImmediatePropagation:null,stopPropagation:null,handled:!1,rootElement:e}}}function Xo(t){if("recognizer"in t)return t;let e;const n=Array.isArray(t)?[...t]:[t];return e="function"==typeof n[0]?new(n.shift())(n.shift()||{}):n.shift(),{recognizer:e,recognizeWith:"string"==typeof n[0]?[n[0]]:n[0],requireFailure:"string"==typeof n[1]?[n[1]]:n[1]}}class Zo{constructor(t=null,e={}){if(this._onBasicInput=t=>{this.manager.emit(t.srcEvent.type,t)},this._onOtherEvent=t=>{this.manager.emit(t.type,t)},this.options={recognizers:[],events:{},touchAction:"compute",tabIndex:0,cssProps:{},...e},this.events=new Map,this.element=t,t){this.manager=new To(t,this.options);for(const t of this.options.recognizers){const{recognizer:e,recognizeWith:n,requireFailure:i}=Xo(t);this.manager.add(e),n&&e.recognizeWith(n),i&&e.requireFailure(i)}this.manager.on("hammer.input",this._onBasicInput),this.wheelInput=new No(t,this._onOtherEvent,{enable:!1}),this.moveInput=new Bo(t,this._onOtherEvent,{enable:!1}),this.keyInput=new Uo(t,this._onOtherEvent,{enable:!1,tabIndex:e.tabIndex}),this.contextmenuInput=new zo(t,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(t,e,n){this._addEventHandler(t,e,n,!1)}once(t,e,n){this._addEventHandler(t,e,n,!0)}watch(t,e,n){this._addEventHandler(t,e,n,!1,!0)}off(t,e){this._removeEventHandler(t,e)}_toggleRecognizer(t,e){const{manager:n}=this;if(!n)return;const i=n.get(t);i&&(i.set({enable:e}),n.touchAction.update()),this.wheelInput?.enableEventType(t,e),this.moveInput?.enableEventType(t,e),this.keyInput?.enableEventType(t,e),this.contextmenuInput?.enableEventType(t,e)}_addEventHandler(t,e,n,i,s){if("string"!=typeof t){n=e;for(const[e,r]of Object.entries(t))this._addEventHandler(e,r,n,i,s);return}const{manager:r,events:o}=this;if(!r)return;let a=o.get(t);if(!a){const e=this._getRecognizerName(t)||t;a=new Ho(this,e),o.set(t,a),r&&r.on(t,a.handleEvent)}a.add(t,e,n,i,s),a.isEmpty()||this._toggleRecognizer(a.recognizerName,!0)}_removeEventHandler(t,e){if("string"!=typeof t){for(const[e,n]of Object.entries(t))this._removeEventHandler(e,n);return}const{events:n}=this,i=n.get(t);if(i&&(i.remove(t,e),i.isEmpty())){const{recognizerName:t}=i;let e=!1;for(const i of n.values())if(i.recognizerName===t&&!i.isEmpty()){e=!0;break}e||this._toggleRecognizer(t,!1)}}_getRecognizerName(t){return this.manager.recognizers.find((e=>e.getEventNames().includes(t)))?.options.event}}const Ko={DEFAULT:-1,LNGLAT:1,METER_OFFSETS:2,LNGLAT_OFFSETS:3,CARTESIAN:0};Object.defineProperty(Ko,"IDENTITY",{get:()=>(F.deprecated("COORDINATE_SYSTEM.IDENTITY","COORDINATE_SYSTEM.CARTESIAN")(),0)});const qo={WEB_MERCATOR:1,GLOBE:2,WEB_MERCATOR_AUTO_OFFSET:4,IDENTITY:0},Yo={common:0,meters:1,pixels:2},Jo={click:"onClick",dblclick:"onClick",panstart:"onDragStart",panmove:"onDrag",panend:"onDragEnd"},Qo={multipan:[Lo,{threshold:10,direction:Jr.Vertical,pointers:2}],pinch:[class extends Po{constructor(t={}){super({enable:!0,event:"pinch",threshold:0,pointers:2,...t})}getTouchAction(){return[no]}getEventNames(){return Oo.map((t=>this.options.event+t))}attrTest(t){return super.attrTest(t)&&(Math.abs(t.scale-1)>this.options.threshold||Boolean(this.state&Qr.Began))}emit(t){1!==t.scale&&(t.additionalEvent=this.options.event+(t.scale<1?"in":"out")),super.emit(t)}},{},null,["multipan"]],pan:[Lo,{threshold:1},["pinch"],["multipan"]],dblclick:[Mo,{event:"dblclick",taps:2}],click:[Mo,{event:"click"},null,["dblclick"]]},ta={DRAW:"draw",MASK:"mask",TERRAIN:"terrain"};function ea(t,e){if(t===e)return!0;if(Array.isArray(t)){const n=t.length;if(!e||e.length!==n)return!1;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}return!1}function na(t){let e,n={};return i=>{for(const s in i)if(!ea(i[s],n[s])){e=t(i),n=i;break}return e}}const ia=[0,0,0,0],sa=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0],ra=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],oa=[0,0,0],aa=[0,0,0],ca=na((function({viewport:t,devicePixelRatio:e,coordinateSystem:n,coordinateOrigin:i}){const{projectionCenter:s,viewProjectionMatrix:r,originCommon:o,cameraPosCommon:a,shaderCoordinateOrigin:c,geospatialOrigin:l}=function(t,e,n){const{viewMatrixUncentered:i,projectionMatrix:s}=t;let{viewMatrix:r,viewProjectionMatrix:o}=t,a=ia,c=ia,l=t.cameraPosition;const{geospatialOrigin:h,shaderCoordinateOrigin:u,offsetMode:f}=la(t,e,n);return f&&(c=t.projectPosition(h||u),l=[l[0]-c[0],l[1]-c[1],l[2]-c[2]],c[3]=1,a=gr([],c,o),r=i||r,o=lr([],s,r),o=lr([],o,sa)),{viewMatrix:r,viewProjectionMatrix:o,projectionCenter:a,originCommon:c,cameraPosCommon:l,shaderCoordinateOrigin:u,geospatialOrigin:h}}(t,n,i),h=t.getDistanceScales(),u=[t.width*e,t.height*e],f=gr([],[0,0,-t.focalDistance,1],t.projectionMatrix)[3]||1,d={coordinateSystem:n,projectionMode:t.projectionMode,coordinateOrigin:c,commonOrigin:o.slice(0,3),center:s,pseudoMeters:Boolean(t._pseudoMeters),viewportSize:u,devicePixelRatio:e,focalDistance:f,commonUnitsPerMeter:h.unitsPerMeter,commonUnitsPerWorldUnit:h.unitsPerMeter,commonUnitsPerWorldUnit2:oa,scale:t.scale,wrapLongitude:!1,viewProjectionMatrix:r,modelMatrix:ra,cameraPosition:a};if(l){const e=t.getDistanceScales(l);switch(n){case Ko.METER_OFFSETS:d.commonUnitsPerWorldUnit=e.unitsPerMeter,d.commonUnitsPerWorldUnit2=e.unitsPerMeter2;break;case Ko.LNGLAT:case Ko.LNGLAT_OFFSETS:t._pseudoMeters||(d.commonUnitsPerMeter=e.unitsPerMeter),d.commonUnitsPerWorldUnit=e.unitsPerDegree,d.commonUnitsPerWorldUnit2=e.unitsPerDegree2;break;case Ko.CARTESIAN:d.commonUnitsPerWorldUnit=[1,1,e.unitsPerMeter[2]],d.commonUnitsPerWorldUnit2=[0,0,e.unitsPerMeter2[2]]}}return d}));function la(t,e,n=aa){n.length<3&&(n=[n[0],n[1],0]);let i,s=n,r=!0;switch(i=e===Ko.LNGLAT_OFFSETS||e===Ko.METER_OFFSETS?n:t.isGeospatial?[Math.fround(t.longitude),Math.fround(t.latitude),0]:null,t.projectionMode){case qo.WEB_MERCATOR:e!==Ko.LNGLAT&&e!==Ko.CARTESIAN||(i=[0,0,0],r=!1);break;case qo.WEB_MERCATOR_AUTO_OFFSET:e===Ko.LNGLAT?s=i:e===Ko.CARTESIAN&&(s=[Math.fround(t.center[0]),Math.fround(t.center[1]),0],i=t.unprojectPosition(s),s[0]-=n[0],s[1]-=n[1],s[2]-=n[2]);break;case qo.IDENTITY:s=t.position.map(Math.fround),s[2]=s[2]||0;break;case qo.GLOBE:r=!1,i=null;break;default:r=!1}return{geospatialOrigin:i,shaderCoordinateOrigin:s,offsetMode:r}}function ha({viewport:t,devicePixelRatio:e=1,modelMatrix:n=null,coordinateSystem:i=Ko.DEFAULT,coordinateOrigin:s=aa,autoWrapLongitude:r=!1}){i===Ko.DEFAULT&&(i=t.isGeospatial?Ko.LNGLAT:Ko.CARTESIAN);const o=ca({viewport:t,devicePixelRatio:e,coordinateSystem:i,coordinateOrigin:s});return o.wrapLongitude=r,o.modelMatrix=n||ra,o}const ua=`${Object.keys(Ko).map((t=>`const COORDINATE_SYSTEM_${t}: i32 = ${Ko[t]};`)).join("")}\n${Object.keys(qo).map((t=>`const PROJECTION_MODE_${t}: i32 = ${qo[t]};`)).join("")}\n${Object.keys(Yo).map((t=>`const UNIT_${t.toUpperCase()}: i32 = ${Yo[t]};`)).join("")}\n\nconst TILE_SIZE: f32 = 512.0;\nconst PI: f32 = 3.1415926536;\nconst WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0);\nconst ZERO_64_LOW: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);\nconst EARTH_RADIUS: f32 = 6370972.0; // meters\nconst GLOBE_RADIUS: f32 = 256.0;\n\n// -----------------------------------------------------------------------------\n// Uniform block (converted from GLSL uniform block)\n// -----------------------------------------------------------------------------\nstruct ProjectUniforms {\n wrapLongitude: i32,\n coordinateSystem: i32,\n commonUnitsPerMeter: vec3<f32>,\n projectionMode: i32,\n scale: f32,\n commonUnitsPerWorldUnit: vec3<f32>,\n commonUnitsPerWorldUnit2: vec3<f32>,\n center: vec4<f32>,\n modelMatrix: mat4x4<f32>,\n viewProjectionMatrix: mat4x4<f32>,\n viewportSize: vec2<f32>,\n devicePixelRatio: f32,\n focalDistance: f32,\n cameraPosition: vec3<f32>,\n coordinateOrigin: vec3<f32>,\n commonOrigin: vec3<f32>,\n pseudoMeters: i32,\n};\n\n@group(0) @binding(0)\nvar<uniform> project: ProjectUniforms;\n\n// -----------------------------------------------------------------------------\n// Geometry data\n// (In your GLSL code, "geometry" was assumed to be available globally. In WGSL,\n// you might supply this via vertex attributes or a uniform. Here we define a\n// uniform struct for demonstration.)\n// -----------------------------------------------------------------------------\n\n// Structure to carry additional geometry data used by deck.gl filters.\nstruct Geometry {\n worldPosition: vec3<f32>,\n worldPositionAlt: vec3<f32>,\n position: vec4<f32>,\n normal: vec3<f32>,\n uv: vec2<f32>,\n pickingColor: vec3<f32>,\n};\n\n// @group(0) @binding(1)\nvar<private> geometry: Geometry;\n\n\n// -----------------------------------------------------------------------------\n// Functions\n// -----------------------------------------------------------------------------\n\n// Returns an adjustment factor for commonUnitsPerMeter\nfn _project_size_at_latitude(lat: f32) -> f32 {\n let y = clamp(lat, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n}\n\n// Overloaded version: scales a value in meters at a given latitude.\nfn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 {\n return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat);\n}\n\n// Computes a non-linear scale factor based on geometry.\n// (Note: This function relies on "geometry" being provided.)\nfn project_size() -> f32 {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project.pseudoMeters == 0) {\n if (geometry.position.w == 0.0) {\n return _project_size_at_latitude(geometry.worldPosition.y);\n }\n let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n let y2 = y * y;\n let y4 = y2 * y2;\n let y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\n\n// Overloads to scale offsets (meters to world units)\nfn project_size_float(meters: f32) -> f32 {\n return meters * project.commonUnitsPerMeter.z * project_size();\n}\n\nfn project_size_vec2(meters: vec2<f32>) -> vec2<f32> {\n return meters * project.commonUnitsPerMeter.xy * project_size();\n}\n\nfn project_size_vec3(meters: vec3<f32>) -> vec3<f32> {\n return meters * project.commonUnitsPerMeter * project_size();\n}\n\nfn project_size_vec4(meters: vec4<f32>) -> vec4<f32> {\n return vec4<f32>(meters.xyz * project.commonUnitsPerMeter, meters.w);\n}\n\n// Returns a rotation matrix aligning the z‑axis with the given up vector.\nfn project_get_orientation_matrix(up: vec3<f32>) -> mat3x3<f32> {\n let uz = normalize(up);\n let ux = select(\n vec3<f32>(1.0, 0.0, 0.0),\n normalize(vec3<f32>(uz.y, -uz.x, 0.0)),\n abs(uz.z) == 1.0\n );\n let uy = cross(uz, ux);\n return mat3x3<f32>(ux, uy, uz);\n}\n\n// Since WGSL does not support "out" parameters, we return a struct.\nstruct RotationResult {\n needsRotation: bool,\n transform: mat3x3<f32>,\n};\n\nfn project_needs_rotation(commonPosition: vec3<f32>) -> RotationResult {\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n return RotationResult(true, project_get_orientation_matrix(commonPosition));\n } else {\n return RotationResult(false, mat3x3<f32>()); // identity alternative if needed\n };\n}\n\n// Projects a normal vector from the current coordinate system to world space.\nfn project_normal(vector: vec3<f32>) -> vec3<f32> {\n let normal_modelspace = project.modelMatrix * vec4<f32>(vector, 0.0);\n var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter);\n let rotResult = project_needs_rotation(geometry.position.xyz);\n if (rotResult.needsRotation) {\n n = rotResult.transform * n;\n }\n return n;\n}\n\n// Applies a scale offset based on y-offset (dy)\nfn project_offset_(offset: vec4<f32>) -> vec4<f32> {\n let dy: f32 = offset.y;\n let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy;\n return vec4<f32>(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\n\n// Projects lng/lat coordinates to a unit tile [0,1]\nfn project_mercator_(lnglat: vec2<f32>) -> vec2<f32> {\n var x = lnglat.x;\n if (project.wrapLongitude != 0) {\n x = ((x + 180.0) % 360.0) - 180.0;\n }\n let y = clamp(lnglat.y, -89.9, 89.9);\n return vec2<f32>(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// Projects lng/lat/z coordinates for a globe projection.\nfn project_globe_(lnglatz: vec3<f32>) -> vec3<f32> {\n let lambda = radians(lnglatz.x);\n let phi = radians(lnglatz.y);\n let cosPhi = cos(phi);\n let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n return vec3<f32>(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\n\n// Projects positions (with an optional 64-bit low part) from the input\n// coordinate system to the common space.\nfn project_position_vec4_f64(position: vec4<f32>, position64Low: vec3<f32>) -> vec4<f32> {\n var position_world = project.modelMatrix * position;\n\n // Work around for a Mac+NVIDIA bug:\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4<f32>(\n project_mercator_(position_world.xy),\n _project_size_at_latitude_m(position_world.z, position_world.y),\n position_world.w\n );\n }\n if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w);\n }\n }\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4<f32>(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) {\n return vec4<f32>(\n project_mercator_(position_world.xy) - project.commonOrigin.xy,\n project_size_float(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project.projectionMode == PROJECTION_MODE_IDENTITY ||\n (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w);\n }\n\n return project_offset_(position_world) +\n project_offset_(project.modelMatrix * vec4<f32>(position64Low, 0.0));\n}\n\n// Overloaded versions for different input types.\nfn project_position_vec4_f32(position: vec4<f32>) -> vec4<f32> {\n return project_position_vec4_f64(position, ZERO_64_LOW);\n}\n\nfn project_position_vec3_f64(position: vec3<f32>, position64Low: vec3<f32>) -> vec3<f32> {\n let projected_position = project_position_vec4_f64(vec4<f32>(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nfn project_position_vec3_f32(position: vec3<f32>) -> vec3<f32> {\n let projected_position = project_position_vec4_f64(vec4<f32>(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nfn project_position_vec2_f32(position: vec2<f32>) -> vec2<f32> {\n let projected_position = project_position_vec4_f64(vec4<f32>(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\n// Transforms a common space position to clip space.\nfn project_common_position_to_clipspace_with_projection(position: vec4<f32>, viewProjectionMatrix: mat4x4<f32>, center: vec4<f32>) -> vec4<f32> {\n return viewProjectionMatrix * position + center;\n}\n\n// Uses the project viewProjectionMatrix and center.\nfn project_common_position_to_clipspace(position: vec4<f32>) -> vec4<f32> {\n return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center);\n}\n\n// Returns a clip space offset corresponding to a given number of screen pixels.\nfn project_pixel_size_to_clipspace(pixels: vec2<f32>) -> vec2<f32> {\n let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0;\n return offset * project.focalDistance;\n}\n\nfn project_meter_size_to_pixel(meters: f32) -> f32 {\n return project_size_float(meters) * project.scale;\n}\n\nfn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 {\n if (unit == UNIT_METERS) {\n return project_meter_size_to_pixel(size);\n } else if (unit == UNIT_COMMON) {\n return size * project.scale;\n }\n // UNIT_PIXELS: no scaling applied.\n return size;\n}\n\nfn project_pixel_size_float(pixels: f32) -> f32 {\n return pixels / project.scale;\n}\n\nfn project_pixel_size_vec2(pixels: vec2<f32>) -> vec2<f32> {\n return pixels / project.scale;\n}\n`,fa=Object.keys(Ko).map((t=>`const int COORDINATE_SYSTEM_${t} = ${Ko[t]};`)).join(""),da=Object.keys(qo).map((t=>`const int PROJECTION_MODE_${t} = ${qo[t]};`)).join(""),pa=Object.keys(Yo).map((t=>`const int UNIT_${t.toUpperCase()} = ${Yo[t]};`)).join(""),ga={};var ma={name:"project",dependencies:[{name:"fp32",vs:"#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n\n// All these functions are for substituting tan() function from Intel GPU only\nconst float TWO_PI = 6.2831854820251465;\nconst float PI_2 = 1.5707963705062866;\nconst float PI_16 = 0.1963495463132858;\n\nconst float SIN_TABLE_0 = 0.19509032368659973;\nconst float SIN_TABLE_1 = 0.3826834261417389;\nconst float SIN_TABLE_2 = 0.5555702447891235;\nconst float SIN_TABLE_3 = 0.7071067690849304;\n\nconst float COS_TABLE_0 = 0.9807852506637573;\nconst float COS_TABLE_1 = 0.9238795042037964;\nconst float COS_TABLE_2 = 0.8314695954322815;\nconst float COS_TABLE_3 = 0.7071067690849304;\n\nconst float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3!\nconst float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5!\nconst float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7!\nconst float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9!\n\nfloat sin_taylor_fp32(float a) {\n float r, s, t, x;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n x = -a * a;\n s = a;\n r = a;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_3;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_5;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_7;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_9;\n s = s + t;\n\n return s;\n}\n\nvoid sincos_taylor_fp32(float a, out float sin_t, out float cos_t) {\n if (a == 0.0) {\n sin_t = 0.0;\n cos_t = 1.0;\n }\n sin_t = sin_taylor_fp32(a);\n cos_t = sqrt(1.0 - sin_t * sin_t);\n}\n\nfloat tan_taylor_fp32(float a) {\n float sin_a;\n float cos_a;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n // 2pi range reduction\n float z = floor(a / TWO_PI);\n float r = a - TWO_PI * z;\n\n float t;\n float q = floor(r / PI_2 + 0.5);\n int j = int(q);\n\n if (j < -2 || j > 2) {\n return 1.0 / 0.0;\n }\n\n t = r - PI_2 * q;\n\n q = floor(t / PI_16 + 0.5);\n int k = int(q);\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return 1.0 / 0.0;\n } else {\n t = t - PI_16 * q;\n }\n\n float u = 0.0;\n float v = 0.0;\n\n float sin_t, cos_t;\n float s, c;\n sincos_taylor_fp32(t, sin_t, cos_t);\n\n if (k == 0) {\n s = sin_t;\n c = cos_t;\n } else {\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0;\n v = SIN_TABLE_0;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1;\n v = SIN_TABLE_1;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2;\n v = SIN_TABLE_2;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3;\n v = SIN_TABLE_3;\n }\n if (k > 0) {\n s = u * sin_t + v * cos_t;\n c = u * cos_t - v * sin_t;\n } else {\n s = u * sin_t - v * cos_t;\n c = u * cos_t + v * sin_t;\n }\n }\n\n if (j == 0) {\n sin_a = s;\n cos_a = c;\n } else if (j == 1) {\n sin_a = c;\n cos_a = -s;\n } else if (j == -1) {\n sin_a = -c;\n cos_a = s;\n } else {\n sin_a = -s;\n cos_a = -c;\n }\n return sin_a / cos_a;\n}\n#endif\n\nfloat tan_fp32(float a) {\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n return tan_taylor_fp32(a);\n#else\n return tan(a);\n#endif\n}\n"},to],source:ua,vs:`${fa}\n${da}\n${pa}\nuniform projectUniforms {\nbool wrapLongitude;\nint coordinateSystem;\nvec3 commonUnitsPerMeter;\nint projectionMode;\nfloat scale;\nvec3 commonUnitsPerWorldUnit;\nvec3 commonUnitsPerWorldUnit2;\nvec4 center;\nmat4 modelMatrix;\nmat4 viewProjectionMatrix;\nvec2 viewportSize;\nfloat devicePixelRatio;\nfloat focalDistance;\nvec3 cameraPosition;\nvec3 coordinateOrigin;\nvec3 commonOrigin;\nbool pseudoMeters;\n} project;\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / (PI * 2.0);\nconst vec3 ZERO_64_LOW = vec3(0.0);\nconst float EARTH_RADIUS = 6370972.0;\nconst float GLOBE_RADIUS = 256.0;\nfloat project_size_at_latitude(float lat) {\nfloat y = clamp(lat, -89.9, 89.9);\nreturn 1.0 / cos(radians(y));\n}\nfloat project_size() {\nif (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR &&\nproject.coordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\nproject.pseudoMeters == false) {\nif (geometry.position.w == 0.0) {\nreturn project_size_at_latitude(geometry.worldPosition.y);\n}\nfloat y = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\nfloat y2 = y * y;\nfloat y4 = y2 * y2;\nfloat y6 = y4 * y2;\nreturn 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n}\nreturn 1.0;\n}\nfloat project_size_at_latitude(float meters, float lat) {\nreturn meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat);\n}\nfloat project_size(float meters) {\nreturn meters * project.commonUnitsPerMeter.z * project_size();\n}\nvec2 project_size(vec2 meters) {\nreturn meters * project.commonUnitsPerMeter.xy * project_size();\n}\nvec3 project_size(vec3 meters) {\nreturn meters * project.commonUnitsPerMeter * project_size();\n}\nvec4 project_size(vec4 meters) {\nreturn vec4(meters.xyz * project.commonUnitsPerMeter, meters.w);\n}\nmat3 project_get_orientation_matrix(vec3 up) {\nvec3 uz = normalize(up);\nvec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0));\nvec3 uy = cross(uz, ux);\nreturn mat3(ux, uy, uz);\n}\nbool project_needs_rotation(vec3 commonPosition, out mat3 transform) {\nif (project.projectionMode == PROJECTION_MODE_GLOBE) {\ntransform = project_get_orientation_matrix(commonPosition);\nreturn true;\n}\nreturn false;\n}\nvec3 project_normal(vec3 vector) {\nvec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0);\nvec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter);\nmat3 rotation;\nif (project_needs_rotation(geometry.position.xyz, rotation)) {\nn = rotation * n;\n}\nreturn n;\n}\nvec4 project_offset_(vec4 offset) {\nfloat dy = offset.y;\nvec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy;\nreturn vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\nvec2 project_mercator_(vec2 lnglat) {\nfloat x = lnglat.x;\nif (project.wrapLongitude) {\nx = mod(x + 180., 360.0) - 180.;\n}\nfloat y = clamp(lnglat.y, -89.9, 89.9);\nreturn vec2(\nradians(x) + PI,\nPI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5))\n) * WORLD_SCALE;\n}\nvec3 project_globe_(vec3 lnglatz) {\nfloat lambda = radians(lnglatz.x);\nfloat phi = radians(lnglatz.y);\nfloat cosPhi = cos(phi);\nfloat D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\nreturn vec3(\nsin(lambda) * cosPhi,\n-cos(lambda) * cosPhi,\nsin(phi)\n) * D;\n}\nvec4 project_position(vec4 position, vec3 position64Low) {\nvec4 position_world = project.modelMatrix * position;\nif (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) {\nif (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\nreturn vec4(\nproject_mercator_(position_world.xy),\nproject_size_at_latitude(position_world.z, position_world.y),\nposition_world.w\n);\n}\nif (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\nposition_world.xyz += project.coordinateOrigin;\n}\n}\nif (project.projectionMode == PROJECTION_MODE_GLOBE) {\nif (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\nreturn vec4(\nproject_globe_(position_world.xyz),\nposition_world.w\n);\n}\n}\nif (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\nif (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\nif (abs(position_world.y - project.coordinateOrigin.y) > 0.25) {\nreturn vec4(\nproject_mercator_(position_world.xy) - project.commonOrigin.xy,\nproject_size(position_world.z),\nposition_world.w\n);\n}\n}\n}\nif (project.projectionMode == PROJECTION_MODE_IDENTITY ||\n(project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n(project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\nproject.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\nposition_world.xyz -= project.coordinateOrigin;\n}\nreturn project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0));\n}\nvec4 project_position(vec4 position) {\nreturn project_position(position, ZERO_64_LOW);\n}\nvec3 project_position(vec3 position, vec3 position64Low) {\nvec4 projected_position = project_position(vec4(position, 1.0), position64Low);\nreturn projected_position.xyz;\n}\nvec3 project_position(vec3 position) {\nvec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW);\nreturn projected_position.xyz;\n}\nvec2 project_position(vec2 position) {\nvec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW);\nreturn projected_position.xy;\n}\nvec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) {\nreturn viewProjectionMatrix * position + center;\n}\nvec4 project_common_position_to_clipspace(vec4 position) {\nreturn project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center);\n}\nvec2 project_pixel_size_to_clipspace(vec2 pixels) {\nvec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0;\nreturn offset * project.focalDistance;\n}\nfloat project_size_to_pixel(float meters) {\nreturn project_size(meters) * project.scale;\n}\nfloat project_size_to_pixel(float size, int unit) {\nif (unit == UNIT_METERS) return project_size_to_pixel(size);\nif (unit == UNIT_COMMON) return size * project.scale;\nreturn size;\n}\nfloat project_pixel_size(float pixels) {\nreturn pixels / project.scale;\n}\nvec2 project_pixel_size(vec2 pixels) {\nreturn pixels / project.scale;\n}\n`,getUniforms:function(t=ga){return"viewport"in t?ha(t):{}},uniformTypes:{wrapLongitude:"f32",coordinateSystem:"i32",commonUnitsPerMeter:"vec3<f32>",projectionMode:"i32",scale:"f32",commonUnitsPerWorldUnit:"vec3<f32>",commonUnitsPerWorldUnit2:"vec3<f32>",center:"vec4<f32>",modelMatrix:"mat4x4<f32>",viewProjectionMatrix:"mat4x4<f32>",viewportSize:"vec2<f32>",devicePixelRatio:"f32",focalDistance:"f32",cameraPosition:"vec3<f32>",coordinateOrigin:"vec3<f32>",commonOrigin:"vec3<f32>",pseudoMeters:"f32"}},_a={name:"project32",dependencies:[ma],source:"// Define a structure to hold both the clip-space position and the common position.\nstruct ProjectResult {\n clipPosition: vec4<f32>,\n commonPosition: vec4<f32>,\n};\n\n// This function mimics the GLSL version with the 'out' parameter by returning both values.\nfn project_position_to_clipspace_and_commonspace(\n position: vec3<f32>,\n position64Low: vec3<f32>,\n offset: vec3<f32>\n) -> ProjectResult {\n // Compute the projected position.\n let projectedPosition: vec3<f32> = project_position_vec3_f64(position, position64Low);\n\n // Start with the provided offset.\n var finalOffset: vec3<f32> = offset;\n\n // Get whether a rotation is needed and the rotation matrix.\n let rotationResult = project_needs_rotation(projectedPosition);\n\n // If rotation is needed, update the offset.\n if (rotationResult.needsRotation) {\n finalOffset = rotationResult.transform * offset;\n }\n\n // Compute the common position.\n let commonPosition: vec4<f32> = vec4<f32>(projectedPosition + finalOffset, 1.0);\n\n // Convert to clip-space.\n let clipPosition: vec4<f32> = project_common_position_to_clipspace(commonPosition);\n\n return ProjectResult(clipPosition, commonPosition);\n}\n\n// A convenience overload that returns only the clip-space position.\nfn project_position_to_clipspace(\n position: vec3<f32>,\n position64Low: vec3<f32>,\n offset: vec3<f32>\n) -> vec4<f32> {\n return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition;\n}\n",vs:"vec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition\n) {\n vec3 projectedPosition = project_position(position, position64Low);\n mat3 rotation;\n if (project_needs_rotation(projectedPosition, rotation)) {\n // offset is specified as ENU\n // when in globe projection, rotate offset so that the ground alighs with the surface of the globe\n offset = rotation * offset;\n }\n commonPosition = vec4(projectedPosition + offset, 1.0);\n return project_common_position_to_clipspace(commonPosition);\n}\n\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset\n) {\n vec4 commonPosition;\n return project_position_to_clipspace(position, position64Low, offset, commonPosition);\n}\n"};function va(t,e){const n=gr([],e,t);return pr(n,n,1/n[3]),n}function ba(t,e){const n=t%e;return n<0?e+n:n}function ya(t,e,n){return n*e+(1-n)*t}function wa(t,e,n){return t<e?e:t>n?n:t}const xa=Math.log2||function(t){return Math.log(t)*Math.LOG2E};function Ea(t,e){if(!t)throw new Error(e||"@math.gl/web-mercator: assertion failed.")}const Ta=Math.PI,Aa=Ta/4,Sa=Ta/180,Ca=180/Ta,Pa=512,Ma=85.051129,Ra=1.5;function La(t){return Math.pow(2,t)}function Oa(t){return xa(t)}function Ia(t){const[e,n]=t;return Ea(Number.isFinite(e)),Ea(Number.isFinite(n)&&n>=-90&&n<=90,"invalid latitude"),[Pa*(e*Sa+Ta)/(2*Ta),Pa*(Ta+Math.log(Math.tan(Aa+n*Sa*.5)))/(2*Ta)]}function ka(t){const[e,n]=t,i=e/Pa*(2*Ta)-Ta,s=2*(Math.atan(Math.exp(n/Pa*(2*Ta)-Ta))-Aa);return[i*Ca,s*Ca]}function Da(t){const{latitude:e}=t;Ea(Number.isFinite(e));return Oa(4003e4*Math.cos(e*Sa))-9}function Na(t){return 12790407194604047e-21/Math.cos(t*Sa)}function Fa(t){const{latitude:e,longitude:n,highPrecision:i=!1}=t;Ea(Number.isFinite(e)&&Number.isFinite(n));const s=Math.cos(e*Sa),r=512/360,o=r/s,a=12790407194604047e-21/s,c={unitsPerMeter:[a,a,a],metersPerUnit:[1/a,1/a,1/a],unitsPerDegree:[r,o,a],degreesPerUnit:[.703125,1/o,1/a]};if(i){const t=Sa*Math.tan(e*Sa)/s,n=12790407194604047e-21*t,i=n/o*a;c.unitsPerDegree2=[0,r*t/2,n],c.unitsPerMeter2=[i,0,i]}return c}function Ba(t,e){const[n,i,s]=t,[r,o,a]=e,{unitsPerMeter:c,unitsPerMeter2:l}=Fa({longitude:n,latitude:i,highPrecision:!0}),h=Ia(t);h[0]+=r*(c[0]+l[0]*o),h[1]+=o*(c[1]+l[1]*o);const u=ka(h),f=(s||0)+(a||0);return Number.isFinite(s)||Number.isFinite(a)?[u[0],u[1],f]:u}function $a(t){return 2*Math.atan(.5/t)*Ca}function Ua(t){return.5/Math.tan(.5*t*Sa)}function za(t,e){const[n,i,s=0]=t;return Ea(Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(s)),va(e,[n,i,s,1])}function ja(t,e,n=0){const[i,s,r]=t;if(Ea(Number.isFinite(i)&&Number.isFinite(s),"invalid pixel coordinate"),Number.isFinite(r))return va(e,[i,s,r,1]);const o=va(e,[i,s,0,1]),a=va(e,[i,s,1,1]),c=o[2],l=a[2];return ks([],o,a,c===l?0:((n||0)-c)/(l-c))}const Ga=Math.PI/180;function Wa(t,e,n){const{pixelUnprojectionMatrix:i}=t,s=va(i,[e,0,1,1]),r=va(i,[e,t.height,1,1]),o=ka(ks([],s,r,(n*t.distanceScales.unitsPerMeter[2]-s[2])/(r[2]-s[2])));return o.push(n),o}const Va="\nuniform shadowUniforms {\n bool drawShadowMap;\n bool useShadowMap;\n vec4 color;\n highp int lightId;\n float lightCount;\n mat4 viewProjectionMatrix0;\n mat4 viewProjectionMatrix1;\n vec4 projectCenter0;\n vec4 projectCenter1;\n} shadow;\n",Ha=`\n${Va}\n\nconst int max_lights = 2;\n\nout vec3 shadow_vPosition[max_lights];\n\nvec4 shadow_setVertexPosition(vec4 position_commonspace) {\n mat4 viewProjectionMatrices[max_lights];\n viewProjectionMatrices[0] = shadow.viewProjectionMatrix0;\n viewProjectionMatrices[1] = shadow.viewProjectionMatrix1;\n vec4 projectCenters[max_lights];\n projectCenters[0] = shadow.projectCenter0;\n projectCenters[1] = shadow.projectCenter1;\n\n if (shadow.drawShadowMap) {\n return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]);\n }\n if (shadow.useShadowMap) {\n for (int i = 0; i < max_lights; i++) {\n if(i < int(shadow.lightCount)) {\n vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]);\n shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0;\n }\n }\n }\n return gl_Position;\n}\n\n`,Xa=`\n${Va}\n\nconst int max_lights = 2;\nuniform sampler2D shadow_uShadowMap0;\nuniform sampler2D shadow_uShadowMap1;\n\nin vec3 shadow_vPosition[max_lights];\n\nconst vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0);\nconst vec4 bitUnpackShift = 1.0 / bitPackShift;\nconst vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n\nfloat shadow_getShadowWeight(vec3 position, sampler2D shadowMap) {\n vec4 rgbaDepth = texture(shadowMap, position.xy);\n\n float z = dot(rgbaDepth, bitUnpackShift);\n return smoothstep(0.001, 0.01, position.z - z);\n}\n\nvec4 shadow_filterShadowColor(vec4 color) {\n if (shadow.drawShadowMap) {\n vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift);\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n return rgbaDepth;\n }\n if (shadow.useShadowMap) {\n float shadowAlpha = 0.0;\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0);\n if(shadow.lightCount > 1.0) {\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1);\n }\n shadowAlpha *= shadow.color.a / shadow.lightCount;\n float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha);\n\n return vec4(\n mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha),\n blendedAlpha\n );\n }\n return color;\n}\n\n`,Za=na((function({viewport:t,center:e}){return new xr(t.viewProjectionMatrix).invert().transform(e)})),Ka=na((function({viewport:t,shadowMatrices:e}){const n=[],i=t.pixelUnprojectionMatrix,s=t.isGeospatial?void 0:1,r=[[0,0,s],[t.width,0,s],[0,t.height,s],[t.width,t.height,s],[0,0,-1],[t.width,0,-1],[0,t.height,-1],[t.width,t.height,-1]].map((t=>function(t,e){const[n,i,s]=t,r=ja([n,i,s],e);return Number.isFinite(s)?r:[r[0],r[1],0]}(t,i)));for(const i of e){const e=i.clone().translate(new Js(t.center).negate()),s=r.map((t=>e.transform(t))),o=(new xr).ortho({left:Math.min(...s.map((t=>t[0]))),right:Math.max(...s.map((t=>t[0]))),bottom:Math.min(...s.map((t=>t[1]))),top:Math.max(...s.map((t=>t[1]))),near:Math.min(...s.map((t=>-t[2]))),far:Math.max(...s.map((t=>-t[2])))});n.push(o.multiplyRight(i))}return n})),qa=[0,0,0,1],Ya=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0];var Ja={name:"shadow",dependencies:[ma],vs:Ha,fs:Xa,inject:{"vs:DECKGL_FILTER_GL_POSITION":"\n position = shadow_setVertexPosition(geometry.position);\n ","fs:DECKGL_FILTER_COLOR":"\n color = shadow_filterShadowColor(color);\n "},getUniforms:function(t){const{shadowEnabled:e=!0,project:n}=t;if(!(e&&n&&t.shadowMatrices&&t.shadowMatrices.length))return{drawShadowMap:!1,useShadowMap:!1,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};const i=ma.getUniforms(n),s=Za({viewport:n.viewport,center:i.center}),r=[],o=Ka({shadowMatrices:t.shadowMatrices,viewport:n.viewport}).slice();for(let e=0;e<t.shadowMatrices.length;e++){const t=o[e],a=t.clone().translate(new Js(n.viewport.center).negate());i.coordinateSystem===Ko.LNGLAT&&i.projectionMode===qo.WEB_MERCATOR?(o[e]=a,r[e]=s):(o[e]=t.clone().multiplyRight(Ya),r[e]=a.transform(s))}const a={drawShadowMap:Boolean(t.drawToShadowMap),useShadowMap:!!t.shadowMaps&&t.shadowMaps.length>0,color:t.shadowColor||qa,lightId:t.shadowLightId||0,lightCount:t.shadowMatrices.length,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};for(let t=0;t<o.length;t++)a[`viewProjectionMatrix${t}`]=o[t],a[`projectCenter${t}`]=r[t];for(let e=0;e<2;e++)a[`shadow_uShadowMap${e}`]=t.shadowMaps&&t.shadowMaps[e]||t.dummyShadowMap;return a},uniformTypes:{drawShadowMap:"f32",useShadowMap:"f32",color:"vec4<f32>",lightId:"i32",lightCount:"f32",viewProjectionMatrix0:"mat4x4<f32>",viewProjectionMatrix1:"mat4x4<f32>",projectCenter0:"vec4<f32>",projectCenter1:"vec4<f32>"}},Qa={...Dr,defaultUniforms:{...Dr.defaultUniforms,useFloatColors:!1},inject:{"vs:DECKGL_FILTER_GL_POSITION":"\n // for picking depth values\n picking_setPickingAttribute(position.z / position.w);\n ","vs:DECKGL_FILTER_COLOR":"\n picking_setPickingColor(geometry.pickingColor);\n ","fs:DECKGL_FILTER_COLOR":{order:99,injection:"\n // use highlight color if this fragment belongs to the selected object.\n color = picking_filterHighlightColor(color);\n\n // use picking color if rendering to picking FBO.\n color = picking_filterPickingColor(color);\n "}}};const tc=[to],ec=["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)"],nc=[];function ic(t){const e=Et.getDefaultShaderAssembler();for(const t of tc)e.addDefaultModule(t);e._hookFunctions.length=0;const n="glsl"===t?ec:nc;for(const t of n)e.addShaderHook(t);return e}const sc=[255,255,255],rc=1;let oc=0;class ac{constructor(t={}){this.type="ambient";const{color:e=sc}=t,{intensity:n=rc}=t;this.id=t.id||"ambient-"+oc++,this.color=e,this.intensity=n}}const cc=[255,255,255],lc=1,hc=[0,0,-1];let uc=0;class fc{constructor(t={}){this.type="directional";const{color:e=cc}=t,{intensity:n=lc}=t,{direction:i=hc}=t,{_shadow:s=!1}=t;this.id=t.id||"directional-"+uc++,this.color=e,this.intensity=n,this.type="directional",this.direction=new Js(i).normalize().toArray(),this.shadow=s}getProjectedLight(t){return this}}class dc{constructor(t,e={id:"pass"}){const{id:n}=e;this.id=n,this.device=t,this.props={...e}}setProps(t){Object.assign(this.props,t)}render(t){}cleanup(){}}class pc extends dc{constructor(){super(...arguments),this._lastRenderIndex=-1}render(t){const[e,n]=this.device.canvasContext.getDrawingBufferSize(),i=t.clearCanvas??!0,s=t.clearColor??(!!i&&[0,0,0,0]),r=!!i&&1,o=!!i&&0,a={viewport:[0,0,e,n]};t.colorMask&&(a.colorMask=t.colorMask??15),t.scissorRect&&(a.scissorRect=t.scissorRect);const c=this.device.beginRenderPass({framebuffer:t.target,parameters:a,clearColor:s,clearDepth:r,clearStencil:o});try{return this._drawLayers(c,t)}finally{c.end(),this.device.submit()}}_drawLayers(t,e){const{target:n,shaderModuleProps:i,viewports:s,views:r,onViewportActive:o,clearStack:a=!0}=e;e.pass=e.pass||"unknown",a&&(this._lastRenderIndex=-1);const c=[];for(const a of s){const s=r&&r[a.id];o?.(a);const l=this._getDrawLayerParams(a,e),h=a.subViewports||[a];for(const r of h){const o=this._drawLayersInViewport(t,{target:n,shaderModuleProps:i,viewport:r,view:s,pass:e.pass,layers:e.layers},l);c.push(o)}}return c}_getDrawLayerParams(t,{layers:e,pass:n,isPicking:i=!1,layerFilter:s,cullRect:r,effects:o,shaderModuleProps:a},c=!1){const l=[],h=gc(this._lastRenderIndex+1),u={layer:e[0],viewport:t,isPicking:i,renderPass:n,cullRect:r},f={};for(let i=0;i<e.length;i++){const r=e[i],d=this._shouldDrawLayer(r,u,s,f),p={shouldDrawLayer:d};d&&!c&&(p.shouldDrawLayer=!0,p.layerRenderIndex=h(r,d),p.shaderModuleProps=this._getShaderModuleProps(r,o,n,a),p.layerParameters={...r.context.deck?.props.parameters,...this.getLayerParameters(r,i,t)}),l[i]=p}return l}_drawLayersInViewport(t,{layers:e,shaderModuleProps:n,pass:i,target:s,viewport:r,view:o},a){const c=function(t,{shaderModuleProps:e,target:n,viewport:i}){const s=e?.project?.devicePixelRatio??t.canvasContext.cssToDeviceRatio(),[,r]=t.canvasContext.getDrawingBufferSize();return[i.x*s,(n?n.height:r)-(i.y+i.height)*s,i.width*s,i.height*s]}(this.device,{shaderModuleProps:n,target:s,viewport:r});if(o){const{clear:t,clearColor:e,clearDepth:n,clearStencil:i}=o.props;if(t){let t=[0,0,0,0],r=1,o=0;Array.isArray(e)?t=[...e.slice(0,3),e[3]||255].map((t=>t/255)):!1===e&&(t=!1),void 0!==n&&(r=n),void 0!==i&&(o=i),this.device.beginRenderPass({framebuffer:s,parameters:{viewport:c,scissorRect:c},clearColor:t,clearDepth:r,clearStencil:o}).end()}}const l={totalCount:e.length,visibleCount:0,compositeCount:0,pickableCount:0};t.setParameters({viewport:c});for(let n=0;n<e.length;n++){const s=e[n],o=a[n],{shouldDrawLayer:c}=o;if(c&&s.props.pickable&&l.pickableCount++,s.isComposite&&l.compositeCount++,s.isDrawable&&o.shouldDrawLayer){const{layerRenderIndex:e,shaderModuleProps:n,layerParameters:a}=o;l.visibleCount++,this._lastRenderIndex=Math.max(this._lastRenderIndex,e),n.project&&(n.project.viewport=r),s.context.renderPass=t;try{s._drawLayer({renderPass:t,shaderModuleProps:n,uniforms:{layerIndex:e},parameters:a})}catch(t){s.raiseError(t,`drawing ${s} to ${i}`)}}}return l}shouldDrawLayer(t){return!0}getShaderModuleProps(t,e,n){return null}getLayerParameters(t,e,n){return t.props.parameters}_shouldDrawLayer(t,e,n,i){if(!t.props.visible||!this.shouldDrawLayer(t))return!1;e.layer=t;let s=t.parent;for(;s;){if(!s.props.visible||!s.filterSubLayer(e))return!1;e.layer=s,s=s.parent}if(n){const t=e.layer.id;if(t in i||(i[t]=n(e)),!i[t])return!1}return t.activateViewport(e.viewport),!0}_getShaderModuleProps(t,e,n,i){const s=this.device.canvasContext.cssToDeviceRatio(),r=t.internalState?.propsInTransition||t.props,o={layer:r,picking:{isActive:!1},project:{viewport:t.context.viewport,devicePixelRatio:s,modelMatrix:r.modelMatrix,coordinateSystem:r.coordinateSystem,coordinateOrigin:r.coordinateOrigin,autoWrapLongitude:t.wrapLongitude}};if(e)for(const n of e)mc(o,n.getShaderModuleProps?.(t,o));return mc(o,this.getShaderModuleProps(t,e,o),i)}}function gc(t=0,e={}){const n={},i=(s,r)=>{const o=s.props._offset,a=s.id,c=s.parent&&s.parent.id;let l;if(c&&!(c in e)&&i(s.parent,!1),c in n){const t=n[c]=n[c]||gc(e[c],e);l=t(s,r),n[a]=t}else Number.isFinite(o)?(l=o+(e[c]||0),n[a]=null):l=t;return r&&l>=t&&(t=l+1),e[a]=l,l};return i}function mc(t,...e){for(const n of e)if(n)for(const e in n)t[e]?Object.assign(t[e],n[e]):t[e]=n[e];return t}class _c extends pc{constructor(t,e){super(t,e);const n=t.createTexture({format:"rgba8unorm",width:1,height:1,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}}),i=t.createTexture({format:"depth16unorm",width:1,height:1});this.fbo=t.createFramebuffer({id:"shadowmap",width:1,height:1,colorAttachments:[n],depthStencilAttachment:i})}delete(){this.fbo&&(this.fbo.destroy(),this.fbo=null)}getShadowMap(){return this.fbo.colorAttachments[0].texture}render(t){const e=this.fbo,n=this.device.canvasContext.cssToDeviceRatio(),i=t.viewports[0],s=i.width*n,r=i.height*n;s===e.width&&r===e.height||e.resize({width:s,height:r}),super.render({...t,clearColor:[1,1,1,1],target:e,pass:"shadow"})}getLayerParameters(t,e,n){return{...t.props.parameters,blend:!1,depthWriteEnabled:!0,depthCompare:"less-equal"}}shouldDrawLayer(t){return!1!==t.props.shadowEnabled}getShaderModuleProps(t,e,n){return{shadow:{project:n.project,drawToShadowMap:!0}}}}const vc={color:[255,255,255],intensity:1},bc=[{color:[255,255,255],intensity:1,direction:[-1,3,-1]},{color:[255,255,255],intensity:.9,direction:[1,-8,-2.5]}],yc=[0,0,0,200/255];class wc{constructor(t={}){this.id="lighting-effect",this.shadowColor=yc,this.shadow=!1,this.directionalLights=[],this.pointLights=[],this.shadowPasses=[],this.dummyShadowMap=null,this.setProps(t)}setup(t){this.context=t;const{device:e,deck:n}=t;this.shadow&&!this.dummyShadowMap&&(this._createShadowPasses(e),n._addDefaultShaderModule(Ja),this.dummyShadowMap=e.createTexture({width:1,height:1}))}setProps(t){this.ambientLight=void 0,this.directionalLights=[],this.pointLights=[];for(const e in t){const n=t[e];switch(n.type){case"ambient":this.ambientLight=n;break;case"directional":this.directionalLights.push(n);break;case"point":this.pointLights.push(n)}}this._applyDefaultLights(),this.shadow=this.directionalLights.some((t=>t.shadow)),this.context&&this.setup(this.context),this.props=t}preRender({layers:t,layerFilter:e,viewports:n,onViewportActive:i,views:s}){if(this.shadow){this.shadowMatrices=this._calculateMatrices();for(let r=0;r<this.shadowPasses.length;r++)this.shadowPasses[r].render({layers:t,layerFilter:e,viewports:n,onViewportActive:i,views:s,shaderModuleProps:{shadow:{shadowLightId:r,dummyShadowMap:this.dummyShadowMap,shadowMatrices:this.shadowMatrices}}})}}getShaderModuleProps(t,e){const n=this.shadow?{project:e.project,shadowMaps:this.shadowPasses.map((t=>t.getShadowMap())),dummyShadowMap:this.dummyShadowMap,shadowColor:this.shadowColor,shadowMatrices:this.shadowMatrices}:{},i={enabled:!0,ambientLight:this.ambientLight,directionalLights:this.directionalLights.map((e=>e.getProjectedLight({layer:t}))),pointLights:this.pointLights.map((e=>e.getProjectedLight({layer:t})))},s=t.props.material;return{shadow:n,lighting:i,phongMaterial:s,gouraudMaterial:s}}cleanup(t){for(const t of this.shadowPasses)t.delete();this.shadowPasses.length=0,this.dummyShadowMap&&(this.dummyShadowMap.destroy(),this.dummyShadowMap=null,t.deck._removeDefaultShaderModule(Ja))}_calculateMatrices(){const t=[];for(const e of this.directionalLights){const n=(new xr).lookAt({eye:new Js(e.direction).negate()});t.push(n)}return t}_createShadowPasses(t){for(let e=0;e<this.directionalLights.length;e++){const n=new _c(t);this.shadowPasses[e]=n}}_applyDefaultLights(){const{ambientLight:t,pointLights:e,directionalLights:n}=this;t||0!==e.length||0!==n.length||(this.ambientLight=new ac(vc),this.directionalLights.push(new fc(bc[0]),new fc(bc[1])))}}var xc=new class{constructor(t={}){this._pool=[],this.opts={overAlloc:2,poolSize:100},this.setOptions(t)}setOptions(t){Object.assign(this.opts,t)}allocate(t,e,{size:n=1,type:i,padding:s=0,copy:r=!1,initialize:o=!1,maxCount:a}){const c=i||t&&t.constructor||Float32Array,l=e*n+s;if(ArrayBuffer.isView(t)){if(l<=t.length)return t;if(l*t.BYTES_PER_ELEMENT<=t.buffer.byteLength)return new c(t.buffer,0,l)}let h=1/0;a&&(h=a*n+s);const u=this._allocate(c,l,o,h);return t&&r?u.set(t):o||u.fill(0,0,4),this._release(t),u}release(t){this._release(t)}_allocate(t,e,n,i){let s=Math.max(Math.ceil(e*this.opts.overAlloc),1);s>i&&(s=i);const r=this._pool,o=t.BYTES_PER_ELEMENT*s,a=r.findIndex((t=>t.byteLength>=o));if(a>=0){const e=new t(r.splice(a,1)[0],0,s);return n&&e.fill(0),e}return new t(s)}_release(t){if(!ArrayBuffer.isView(t))return;const e=this._pool,{buffer:n}=t,{byteLength:i}=n,s=e.findIndex((t=>t.byteLength>=i));s<0?e.push(n):(s>0||e.length<this.opts.poolSize)&&e.splice(s,0,n),e.length>this.opts.poolSize&&e.shift()}};function Ec(t,e){const n=t%e;return n<0?e+n:n}const Tc=new Js;function Ac(t,e,n,i){Tc.set(t,e,n);const s=Tc.len();return{distance:i/s,normal:new Js(-t/s,-e/s,-n/s)}}function Sc(t){return t-Math.fround(t)}let Cc;function Pc(t,e){const{size:n=1,startIndex:i=0}=e,s=void 0!==e.endIndex?e.endIndex:t.length,r=(s-i)/n;Cc=xc.allocate(Cc,r,{type:Float32Array,size:2*n});let o=i,a=0;for(;o<s;){for(let e=0;e<n;e++){const i=t[o++];Cc[a+e]=i,Cc[a+e+n]=Sc(i)}a+=2*n}return Cc.subarray(0,r*n*2)}function Mc(t){let e=null,n=!1;for(const i of t)i&&(e?(n||(e=[[e[0][0],e[0][1]],[e[1][0],e[1][1]]],n=!0),e[0][0]=Math.min(e[0][0],i[0][0]),e[0][1]=Math.min(e[0][1],i[0][1]),e[1][0]=Math.max(e[1][0],i[1][0]),e[1][1]=Math.max(e[1][1],i[1][1])):e=i);return e}const Rc=Math.PI/180,Lc=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],Oc=[0,0,0],Ic={unitsPerMeter:[1,1,1],metersPerUnit:[1,1,1]};class kc{constructor(t={}){this._frustumPlanes={},this.id=t.id||this.constructor.displayName||"viewport",this.x=t.x||0,this.y=t.y||0,this.width=t.width||1,this.height=t.height||1,this.zoom=t.zoom||0,this.padding=t.padding,this.distanceScales=t.distanceScales||Ic,this.focalDistance=t.focalDistance||1,this.position=t.position||Oc,this.modelMatrix=t.modelMatrix||null;const{longitude:e,latitude:n}=t;this.isGeospatial=Number.isFinite(n)&&Number.isFinite(e),this._initProps(t),this._initMatrices(t),this.equals=this.equals.bind(this),this.project=this.project.bind(this),this.unproject=this.unproject.bind(this),this.projectPosition=this.projectPosition.bind(this),this.unprojectPosition=this.unprojectPosition.bind(this),this.projectFlat=this.projectFlat.bind(this),this.unprojectFlat=this.unprojectFlat.bind(this)}get subViewports(){return null}get metersPerPixel(){return this.distanceScales.metersPerUnit[2]/this.scale}get projectionMode(){return this.isGeospatial?this.zoom<12?qo.WEB_MERCATOR:qo.WEB_MERCATOR_AUTO_OFFSET:qo.IDENTITY}equals(t){return t instanceof kc&&(this===t||t.width===this.width&&t.height===this.height&&t.scale===this.scale&&ws(t.projectionMatrix,this.projectionMatrix)&&ws(t.viewMatrix,this.viewMatrix))}project(t,{topLeft:e=!0}={}){const n=za(this.projectPosition(t),this.pixelProjectionMatrix),[i,s]=n,r=e?s:this.height-s;return 2===t.length?[i,r]:[i,r,n[2]]}unproject(t,{topLeft:e=!0,targetZ:n}={}){const[i,s,r]=t,o=ja([i,e?s:this.height-s,r],this.pixelUnprojectionMatrix,n&&n*this.distanceScales.unitsPerMeter[2]),[a,c,l]=this.unprojectPosition(o);return Number.isFinite(r)?[a,c,l]:Number.isFinite(n)?[a,c,n]:[a,c]}projectPosition(t){const[e,n]=this.projectFlat(t);return[e,n,(t[2]||0)*this.distanceScales.unitsPerMeter[2]]}unprojectPosition(t){const[e,n]=this.unprojectFlat(t);return[e,n,(t[2]||0)*this.distanceScales.metersPerUnit[2]]}projectFlat(t){if(this.isGeospatial){const e=Ia(t);return e[1]=bs(e[1],-318,830),e}return t}unprojectFlat(t){return this.isGeospatial?ka(t):t}getBounds(t={}){const e={targetZ:t.z||0},n=this.unproject([0,0],e),i=this.unproject([this.width,0],e),s=this.unproject([0,this.height],e),r=this.unproject([this.width,this.height],e);return[Math.min(n[0],i[0],s[0],r[0]),Math.min(n[1],i[1],s[1],r[1]),Math.max(n[0],i[0],s[0],r[0]),Math.max(n[1],i[1],s[1],r[1])]}getDistanceScales(t){return t&&this.isGeospatial?Fa({longitude:t[0],latitude:t[1],highPrecision:!0}):this.distanceScales}containsPixel({x:t,y:e,width:n=1,height:i=1}){return t<this.x+this.width&&this.x<t+n&&e<this.y+this.height&&this.y<e+i}getFrustumPlanes(){return this._frustumPlanes.near||Object.assign(this._frustumPlanes,{left:Ac((t=this.viewProjectionMatrix)[3]+t[0],t[7]+t[4],t[11]+t[8],t[15]+t[12]),right:Ac(t[3]-t[0],t[7]-t[4],t[11]-t[8],t[15]-t[12]),bottom:Ac(t[3]+t[1],t[7]+t[5],t[11]+t[9],t[15]+t[13]),top:Ac(t[3]-t[1],t[7]-t[5],t[11]-t[9],t[15]-t[13]),near:Ac(t[3]+t[2],t[7]+t[6],t[11]+t[10],t[15]+t[14]),far:Ac(t[3]-t[2],t[7]-t[6],t[11]-t[10],t[15]-t[14])}),this._frustumPlanes;var t}panByPosition(t,e,n){return null}_initProps(t){const e=t.longitude,n=t.latitude;this.isGeospatial&&(Number.isFinite(t.zoom)||(this.zoom=Da({latitude:n})+Math.log2(this.focalDistance)),this.distanceScales=t.distanceScales||Fa({latitude:n,longitude:e}));const i=Math.pow(2,this.zoom);this.scale=i;const{position:s,modelMatrix:r}=t;let o=Oc;if(s&&(o=r?new xr(r).transformAsVector(s,[]):s),this.isGeospatial){const t=this.projectPosition([e,n,0]);this.center=new Js(o).scale(this.distanceScales.unitsPerMeter).add(t)}else this.center=this.projectPosition(o)}_initMatrices(t){const{viewMatrix:e=Lc,projectionMatrix:n=null,orthographic:i=!1,fovyRadians:s,fovy:r=75,near:o=.1,far:a=1e3,padding:c=null,focalDistance:l=1}=t;this.viewMatrixUncentered=e,this.viewMatrix=(new xr).multiplyRight(e).translate(new Js(this.center).negate()),this.projectionMatrix=n||function({width:t,height:e,orthographic:n,fovyRadians:i,focalDistance:s,padding:r,near:o,far:a}){const c=t/e,l=n?(new xr).orthographic({fovy:i,aspect:c,focalDistance:s,near:o,far:a}):(new xr).perspective({fovy:i,aspect:c,near:o,far:a});if(r){const{left:n=0,right:i=0,top:s=0,bottom:o=0}=r,a=bs((n+t-i)/2,0,t)-t/2,c=bs((s+e-o)/2,0,e)-e/2;l[8]-=2*a/t,l[9]+=2*c/e}return l}({width:this.width,height:this.height,orthographic:i,fovyRadians:s||r*Rc,focalDistance:l,padding:c,near:o,far:a});const h=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];var u;lr(h,h,this.projectionMatrix),lr(h,h,this.viewMatrix),this.viewProjectionMatrix=h,this.viewMatrixInverse=cr([],this.viewMatrix)||this.viewMatrix,this.cameraPosition=[(u=this.viewMatrixInverse)[12],u[13],u[14]];const f=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],d=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];ur(f,f,[this.width/2,-this.height/2,1]),hr(f,f,[1,-1,0]),lr(d,f,this.viewProjectionMatrix),this.pixelProjectionMatrix=d,this.pixelUnprojectionMatrix=cr([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],this.pixelProjectionMatrix),this.pixelUnprojectionMatrix||F.warn("Pixel project matrix not invertible")()}}kc.displayName="Viewport";class Dc extends kc{constructor(t={}){const{latitude:e=0,longitude:n=0,zoom:i=0,pitch:s=0,bearing:r=0,nearZMultiplier:o=.1,farZMultiplier:a=1.01,nearZ:c,farZ:l,orthographic:h=!1,projectionMatrix:u,repeat:f=!1,worldOffset:d=0,position:p,padding:g,legacyMeterSizes:m=!1}=t;let{width:_,height:v,altitude:b=1.5}=t;const y=Math.pow(2,i);let w;_=_||1,v=v||1;let x=null;if(u)b=u[5]/2,w=$a(b);else{let n;if(t.fovy?(w=t.fovy,b=Ua(w)):w=$a(b),g){const{top:t=0,bottom:e=0}=g;n=[0,bs((t+v-e)/2,0,v)-v/2]}x=function(t){const{width:e,height:n,altitude:i,pitch:s=0,offset:r,center:o,scale:a,nearZMultiplier:c=1,farZMultiplier:l=1}=t;let{fovy:h=$a(Ra)}=t;void 0!==i&&(h=$a(i));const u=h*Sa,f=s*Sa,d=Ua(h);let p=d;o&&(p+=o[2]*a/Math.cos(f)/n);const g=u*(.5+(r?r[1]:0)/n),m=Math.sin(g)*p/Math.sin(wa(Math.PI/2-f-g,.01,Math.PI-.01)),_=Math.sin(f)*m+p;return{fov:u,aspect:e/n,focalDistance:d,near:c,far:Math.min(_*l,10*p)}}({width:_,height:v,scale:y,center:p&&[0,0,p[2]*Na(e)],offset:n,pitch:s,fovy:w,nearZMultiplier:o,farZMultiplier:a}),Number.isFinite(c)&&(x.near=c),Number.isFinite(l)&&(x.far=l)}let E=function(t){const{height:e,pitch:n,bearing:i,altitude:s,scale:r,center:o}=t,a=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];hr(a,a,[0,0,-s]),fr(a,a,-n*Sa),dr(a,a,i*Sa);const c=r/e;return ur(a,a,[c,c,c]),o&&hr(a,a,function(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}([],o)),a}({height:v,pitch:s,bearing:r,scale:y,altitude:b});d&&(E=(new xr).translate([512*d,0,0]).multiplyLeft(E)),super({...t,width:_,height:v,viewMatrix:E,longitude:n,latitude:e,zoom:i,...x,fovy:w,focalDistance:b}),this.latitude=e,this.longitude=n,this.zoom=i,this.pitch=s,this.bearing=r,this.altitude=b,this.fovy=w,this.orthographic=h,this._subViewports=f?[]:null,this._pseudoMeters=m,Object.freeze(this)}get subViewports(){if(this._subViewports&&!this._subViewports.length){const t=this.getBounds(),e=Math.floor((t[0]+180)/360),n=Math.ceil((t[2]-180)/360);for(let t=e;t<=n;t++){const e=t?new Dc({...this,worldOffset:t}):this;this._subViewports.push(e)}}return this._subViewports}projectPosition(t){if(this._pseudoMeters)return super.projectPosition(t);const[e,n]=this.projectFlat(t);return[e,n,(t[2]||0)*Na(t[1])]}unprojectPosition(t){if(this._pseudoMeters)return super.unprojectPosition(t);const[e,n]=this.unprojectFlat(t);return[e,n,(t[2]||0)/Na(n)]}addMetersToLngLat(t,e){return Ba(t,e)}panByPosition(t,e,n){const i=ja(e,this.pixelUnprojectionMatrix),s=Rs([],this.projectFlat(t),Is([],i)),r=Rs([],this.center,s),[o,a]=this.unprojectFlat(r);return{longitude:o,latitude:a}}getBounds(t={}){const e=function(t,e=0){const{width:n,height:i,unproject:s}=t,r={targetZ:e},o=s([0,i],r),a=s([n,i],r);let c,l;return(t.fovy?.5*t.fovy*Ga:Math.atan(.5/t.altitude))>(90-t.pitch)*Ga-.01?(c=Wa(t,0,e),l=Wa(t,n,e)):(c=s([0,0],r),l=s([n,0],r)),[o,a,l,c]}(this,t.z||0);return[Math.min(e[0][0],e[1][0],e[2][0],e[3][0]),Math.min(e[0][1],e[1][1],e[2][1],e[3][1]),Math.max(e[0][0],e[1][0],e[2][0],e[3][0]),Math.max(e[0][1],e[1][1],e[2][1],e[3][1])]}fitBounds(t,e={}){const{width:n,height:i}=this,{longitude:s,latitude:r,zoom:o}=function(t){const{width:e,height:n,bounds:i,minExtent:s=0,maxZoom:r=24,offset:o=[0,0]}=t,[[a,c],[l,h]]=i,u=function(t=0){return"number"==typeof t?{top:t,bottom:t,left:t,right:t}:(Ea(Number.isFinite(t.top)&&Number.isFinite(t.bottom)&&Number.isFinite(t.left)&&Number.isFinite(t.right)),t)}(t.padding),f=Ia([a,wa(h,-85.051129,Ma)]),d=Ia([l,wa(c,-85.051129,Ma)]),p=[Math.max(Math.abs(d[0]-f[0]),s),Math.max(Math.abs(d[1]-f[1]),s)],g=[e-u.left-u.right-2*Math.abs(o[0]),n-u.top-u.bottom-2*Math.abs(o[1])];Ea(g[0]>0&&g[1]>0);const m=g[0]/p[0],_=g[1]/p[1],v=ka([(d[0]+f[0])/2+(u.right-u.left)/2/m,(d[1]+f[1])/2+(u.top-u.bottom)/2/_]),b=Math.min(r,xa(Math.abs(Math.min(m,_))));return Ea(Number.isFinite(b)),{longitude:v[0],latitude:v[1],zoom:b}}({width:n,height:i,bounds:t,...e});return new Dc({width:n,height:i,longitude:s,latitude:r,zoom:o})}}Dc.displayName="WebMercatorViewport";const Nc=[0,0,0];function Fc(t,e,n=!1){const i=e.projectPosition(t);if(n&&e instanceof Dc){const[n,s,r=0]=t,o=e.getDistanceScales([n,s]);i[2]=r*o.unitsPerMeter[2]}return i}function Bc(t,{viewport:e,modelMatrix:n,coordinateSystem:i,coordinateOrigin:s,offsetMode:r}){let[o,a,c=0]=t;switch(n&&([o,a,c]=gr([],[o,a,c,1],n)),i){case Ko.LNGLAT:return Fc([o,a,c],e,r);case Ko.LNGLAT_OFFSETS:return Fc([o+s[0],a+s[1],c+(s[2]||0)],e,r);case Ko.METER_OFFSETS:return Fc(Ba(s,[o,a,c]),e,r);default:return e.isGeospatial?[o+s[0],a+s[1],c+s[2]]:e.projectPosition([o,a,c])}}function $c(t,e){const{viewport:n,coordinateSystem:i,coordinateOrigin:s,modelMatrix:r,fromCoordinateSystem:o,fromCoordinateOrigin:a}=function(t){const{viewport:e,modelMatrix:n,coordinateOrigin:i}=t;let{coordinateSystem:s,fromCoordinateSystem:r,fromCoordinateOrigin:o}=t;return s===Ko.DEFAULT&&(s=e.isGeospatial?Ko.LNGLAT:Ko.CARTESIAN),void 0===r&&(r=s),void 0===o&&(o=i),{viewport:e,coordinateSystem:s,coordinateOrigin:i,modelMatrix:n,fromCoordinateSystem:r,fromCoordinateOrigin:o}}(e),{autoOffset:c=!0}=e,{geospatialOrigin:l=Nc,shaderCoordinateOrigin:h=Nc,offsetMode:u=!1}=c?la(n,i,s):{},f=Bc(t,{viewport:n,modelMatrix:r,coordinateSystem:o,coordinateOrigin:a,offsetMode:u});if(u){const t=n.projectPosition(l||h);Hs(f,f,t)}return f}let Uc=1,zc=1;class jc{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(t){const{delay:e=0,duration:n=Number.POSITIVE_INFINITY,rate:i=1,repeat:s=1}=t,r=Uc++,o={time:0,delay:e,duration:n,rate:i,repeat:s};return this._setChannelTime(o,this.time),this.channels.set(r,o),r}removeChannel(t){this.channels.delete(t);for(const[e,n]of this.animations)n.channel===t&&this.detachAnimation(e)}isFinished(t){const e=this.channels.get(t);return void 0!==e&&this.time>=e.delay+e.duration*e.repeat}getTime(t){if(void 0===t)return this.time;const e=this.channels.get(t);return void 0===e?-1:e.time}setTime(t){this.time=Math.max(0,t);const e=this.channels.values();for(const t of e)this._setChannelTime(t,this.time);const n=this.animations.values();for(const t of n){const{animation:e,channel:n}=t;e.setTime(this.getTime(n))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(t,e){const n=zc++;return this.animations.set(n,{animation:t,channel:e}),t.setTime(this.getTime(e)),n}detachAnimation(t){this.animations.delete(t)}update(t){this.playing&&(-1===this.lastEngineTime&&(this.lastEngineTime=t),this.setTime(this.time+(t-this.lastEngineTime)),this.lastEngineTime=t)}_setChannelTime(t,e){const n=e-t.delay;n>=t.duration*t.repeat?t.time=t.duration*t.rate:(t.time=Math.max(0,n)%t.duration,t.time*=t.rate)}}let Gc=0;class Wc{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:t=>console.error(t),stats:he.stats.get("animation-loop-"+Gc++),autoResizeViewport:!1};device=null;canvas=null;props;animationProps=null;timeline=null;stats;cpuTime;gpuTime;frameRate;display;needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;constructor(t){if(this.props={...Wc.defaultAnimationLoopProps,...t},!(t=this.props).device)throw new Error("No device provided");this.stats=t.stats||new Ct({id:"animation-loop-stats"}),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.frameRate=this.stats.get("Frame Rate"),this.setProps({autoResizeViewport:t.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)}delete(){this.destroy()}reportError(t){this.props.onError(t),this._error=t}setNeedsRedraw(t){return this.needsRedraw=this.needsRedraw||t,this}setProps(t){return"autoResizeViewport"in t&&(this.props.autoResizeViewport=t.autoResizeViewport||!1),this}async start(){if(this._running)return this;this._running=!0;try{return this._initialized||(this._initialized=!0,await this._initDevice(),this._initialize(),await this.props.onInitialize(this._getAnimationProps())),this._running?(this._cancelAnimationFrame(),this._requestAnimationFrame(),this):null}catch(t){const e=t instanceof Error?t:new Error("Unknown error");throw this.props.onError(e),e}}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}redraw(){return this.device?.isLost||this._error||(this._beginFrameTimers(),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(t){return this.timeline=t,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise((t=>{this._resolveNextFrame=t}))),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()}_setDisplay(t){this.display&&(this.display.destroy(),this.display.animationLoop=null),t&&(t.animationLoop=this),this.display=t}_requestAnimationFrame(){var t;this._running&&(this._animationFrameId=(t=this._animationFrame.bind(this),"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame(t):setTimeout(t,1e3/60)))}_cancelAnimationFrame(){var t;null!==this._animationFrameId&&(t=this._animationFrameId,"undefined"!=typeof window&&window.cancelAnimationFrame?window.cancelAnimationFrame(t):clearTimeout(t),this._animationFrameId=null)}_animationFrame(){this._running&&(this.redraw(),this._requestAnimationFrame())}_renderFrame(t){this.display?this.display._renderFrame(t):(this.props.onRender(this._getAnimationProps()),this.device?.submit())}_clearNeedsRedraw(){this.needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){const t=this.device?.getDefaultCanvasContext();if(!this.device||!t)throw new Error("loop");const e=t?.canvas;this.animationProps={animationLoop:this,device:this.device,canvasContext:t,canvas:e,useDevicePixels:t.props.useDevicePixels,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;const{width:t,height:e,aspect:n}=this._getSizeAndAspect();t===this.animationProps.width&&e===this.animationProps.height||this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=t,this.animationProps.height=e,this.animationProps.aspect=n,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){const t=document.createElement("div");document.body.appendChild(t),t.style.position="relative";const e=document.createElement("div");e.style.position="absolute",e.style.left="10px",e.style.bottom="10px",e.style.width="300px",e.style.background="white",this.canvas instanceof HTMLCanvasElement&&t.appendChild(this.canvas),t.appendChild(e);const n=this.props.onAddHTML(e);n&&(e.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};const[t,e]=this.device?.getDefaultCanvasContext().getDevicePixelSize()||[1,1];let n=1;const i=this.device?.getDefaultCanvasContext().canvas;return i&&i.clientHeight?n=i.clientWidth/i.clientHeight:t>0&&e>0&&(n=t/e),{width:t,height:e,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(){this.frameRate.timeEnd(),this.frameRate.timeStart(),this.cpuTime.timeStart()}_endFrameTimers(){this.cpuTime.timeEnd()}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(t){t instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[t.offsetX,t.offsetY])}_onMouseleave(t){this._getAnimationProps()._mousePosition=null}}const Vc={};function Hc(t="id"){return Vc[t]=Vc[t]||1,`${t}-${Vc[t]++}`}class Xc{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(t){if(this.id=t.id||Hc("geometry"),this.topology=t.topology,this.indices=t.indices||null,this.attributes=t.attributes,this.vertexCount=t.vertexCount,this.bufferLayout=t.bufferLayout||[],this.indices&&!(this.indices.usage&It.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(const t of Object.values(this.attributes))t.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(t){return t.byteLength/12}}class Zc{static defaultProps={...Ce.defaultProps};static getDefaultPipelineFactory(t){return t._lumaData.defaultPipelineFactory=t._lumaData.defaultPipelineFactory||new Zc(t),t._lumaData.defaultPipelineFactory}device;cachingEnabled;destroyPolicy;debug;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};get[Symbol.toStringTag](){return"PipelineFactory"}toString(){return`PipelineFactory(${this.device.id})`}constructor(t){this.device=t,this.cachingEnabled=t.props._cachePipelines,this.destroyPolicy=t.props._cacheDestroyPolicy,this.debug=t.props.debugFactories}createRenderPipeline(t){if(!this.cachingEnabled)return this.device.createRenderPipeline(t);const e={...Ce.defaultProps,...t},n=this._renderPipelineCache,i=this._hashRenderPipeline(e);let s=n[i]?.pipeline;return s?(n[i].useCount++,this.debug&&Mt.log(3,`${this}: ${n[i].pipeline} reused, count=${n[i].useCount}, (id=${t.id})`)()):(s=this.device.createRenderPipeline({...e,id:e.id?`${e.id}-cached`:Hc("unnamed-cached")}),s.hash=i,n[i]={pipeline:s,useCount:1},this.debug&&Mt.log(3,`${this}: ${s} created, count=${n[i].useCount}`)()),s}createComputePipeline(t){if(!this.cachingEnabled)return this.device.createComputePipeline(t);const e={...Me.defaultProps,...t},n=this._computePipelineCache,i=this._hashComputePipeline(e);let s=n[i]?.pipeline;return s?(n[i].useCount++,this.debug&&Mt.log(3,`${this}: ${n[i].pipeline} reused, count=${n[i].useCount}, (id=${t.id})`)()):(s=this.device.createComputePipeline({...e,id:e.id?`${e.id}-cached`:void 0}),s.hash=i,n[i]={pipeline:s,useCount:1},this.debug&&Mt.log(3,`${this}: ${s} created, count=${n[i].useCount}`)()),s}release(t){if(!this.cachingEnabled)return void t.destroy();const e=this._getCache(t),n=t.hash;e[n].useCount--,0===e[n].useCount?(this._destroyPipeline(t),this.debug&&Mt.log(3,`${this}: ${t} released and destroyed`)()):e[n].useCount<0?(Mt.error(`${this}: ${t} released, useCount < 0, resetting`)(),e[n].useCount=0):this.debug&&Mt.log(3,`${this}: ${t} released, count=${e[n].useCount}`)()}_destroyPipeline(t){const e=this._getCache(t);switch(this.destroyPolicy){case"never":return!1;case"unused":return delete e[t.hash],t.destroy(),!0}}_getCache(t){let e;if(t instanceof Me&&(e=this._computePipelineCache),t instanceof Ce&&(e=this._renderPipelineCache),!e)throw new Error(`${this}`);if(!e[t.hash])throw new Error(`${this}: ${t} matched incorrect entry`);return e}_hashComputePipeline(t){const{type:e}=this.device;return`${e}/C/${this._getHash(t.shader.source)}`}_hashRenderPipeline(t){const e=t.vs?this._getHash(t.vs.source):0,n=t.fs?this._getHash(t.fs.source):0,i=this._getHash(JSON.stringify(t.bufferLayout)),{type:s}=this.device;if("webgl"===s)return`${s}/R/${e}/${n}V-BL${i}`;{const r=this._getHash(JSON.stringify(t.parameters));return`${s}/R/${e}/${n}V-T${t.topology}P${r}BL${i}`}}_getHash(t){return void 0===this._hashes[t]&&(this._hashes[t]=this._hashCounter++),this._hashes[t]}}class Kc{static defaultProps={...Te.defaultProps};static getDefaultShaderFactory(t){return t._lumaData.defaultShaderFactory||=new Kc(t),t._lumaData.defaultShaderFactory}device;cachingEnabled;destroyPolicy;debug;_cache={};get[Symbol.toStringTag](){return"ShaderFactory"}toString(){return`${this[Symbol.toStringTag]}(${this.device.id})`}constructor(t){this.device=t,this.cachingEnabled=t.props._cacheShaders,this.destroyPolicy=t.props._cacheDestroyPolicy,this.debug=!0}createShader(t){if(!this.cachingEnabled)return this.device.createShader(t);const e=this._hashShader(t);let n=this._cache[e];if(n)n.useCount++,this.debug&&Mt.log(3,`${this}: Reusing shader ${n.shader.id} count=${n.useCount}`)();else{const i=this.device.createShader({...t,id:t.id?`${t.id}-cached`:void 0});this._cache[e]=n={shader:i,useCount:1},this.debug&&Mt.log(3,`${this}: Created new shader ${i.id}`)()}return n.shader}release(t){if(!this.cachingEnabled)return void t.destroy();const e=this._hashShader(t),n=this._cache[e];if(n)if(n.useCount--,0===n.useCount)"unused"===this.destroyPolicy&&(delete this._cache[e],n.shader.destroy(),this.debug&&Mt.log(3,`${this}: Releasing shader ${t.id}, destroyed`)());else{if(n.useCount<0)throw new Error(`ShaderFactory: Shader ${t.id} released too many times`);this.debug&&Mt.log(3,`${this}: Releasing shader ${t.id} count=${n.useCount}`)()}}_hashShader(t){return`${t.stage}:${t.source}`}}let qc=null,Yc=null;function Jc(t,e,n){if(t===e)return!0;if(!n||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Jc(t[i],e[i],n-1))return!1;return!0}if(Array.isArray(e))return!1;if("object"==typeof t&&"object"==typeof e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!e.hasOwnProperty(s))return!1;if(!Jc(t[s],e[s],n-1))return!1}return!0}return!1}class Qc{bufferLayouts;constructor(t){this.bufferLayouts=t}getBufferLayout(t){return this.bufferLayouts.find((e=>e.name===t))||null}getAttributeNamesForBuffer(t){return t.attributes?t.attributes?.map((t=>t.attribute)):[t.name]}mergeBufferLayouts(t,e){const n=[...t];for(const t of e){const e=n.findIndex((e=>e.name===t.name));e<0?n.push(t):n[e]=t}return n}getBufferIndex(t){const e=this.bufferLayouts.findIndex((e=>e.name===t));return-1===e&&Mt.warn(`BufferLayout: Missing buffer for "${t}".`)(),e}}function tl(t){const e={bindings:{},uniforms:{}};return Object.keys(t).forEach((n=>{const i=t[n];var s;!function(t){return function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}(t)||function(t){return!!Array.isArray(t)&&(0===t.length||"number"==typeof t[0])}(t)}(s=i)&&"number"!=typeof s&&"boolean"!=typeof s?e.bindings[n]=i:e.uniforms[n]=i})),e}class el{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(t,e){Object.assign(this.options,e);const n=rt(Object.values(t).filter((t=>t.dependencies)));for(const e of n)t[e.name]=e;Mt.log(1,"Creating ShaderInputs with modules",Object.keys(t))(),this.modules=t,this.moduleUniforms={},this.moduleBindings={};for(const[e,n]of Object.entries(t))this._addModule(n),n.name&&e!==n.name&&!this.options.disableWarnings&&Mt.warn(`Module name: ${e} vs ${n.name}`)()}destroy(){}setProps(t){for(const e of Object.keys(t)){const n=e,i=t[n]||{},s=this.modules[n];if(!s){this.options.disableWarnings||Mt.warn(`Module ${e} not found`)();continue}const r=this.moduleUniforms[n],o=this.moduleBindings[n],a=s.getUniforms?.(i,r)||i,{uniforms:c,bindings:l}=tl(a);this.moduleUniforms[n]={...r,...c},this.moduleBindings[n]={...o,...l}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindingValues(){const t={};for(const e of Object.values(this.moduleBindings))Object.assign(t,e);return t}getDebugTable(){const t={};for(const[e,n]of Object.entries(this.moduleUniforms))for(const[i,s]of Object.entries(n))t[`${e}.${i}`]={type:this.modules[e].uniformTypes?.[i],value:String(s)};return t}_addModule(t){const e=t.name;this.moduleUniforms[e]=t.defaultUniforms||{},this.moduleBindings[e]={}}}const nl=["+X","-X","+Y","-Y","+Z","-Z"],il=["+X","-X","+Y","-Y","+Z","-Z"];class sl{device;id;props;texture;sampler;view;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get[Symbol.toStringTag](){return"AsyncTexture"}toString(){return`AsyncTexture:"${this.id}"(${this.isReady?"ready":"loading"})`}constructor(t,e){this.device=t;const n=Hc("async-texture");this.props={...sl.defaultProps,id:n,...e},this.id=this.props.id,e={...e},"string"==typeof e?.data&&"2d"===e.dimension&&(e.data=async function(t){const e=new Image;return e.crossOrigin="anonymous",e.src=t.startsWith("http")?t:""+t,await e.decode(),await createImageBitmap(e)}(e.data)),e.mipmaps&&(e.mipLevels="auto"),this.ready=new Promise(((t,e)=>{this.resolveReady=()=>{this.isReady=!0,t()},this.rejectReady=e})),this.initAsync(e)}async initAsync(t){const e=t.data,n=await rl(e).then(void 0,this.rejectReady);if(this.destroyed)return;const i=this.props.width&&this.props.height?{width:this.props.width,height:this.props.height}:this.getTextureDataSize(n);if(!i)throw new Error("Texture size could not be determined");const s={...i,...t,data:void 0,mipLevels:1},r=this.device.getMipLevelCount(s.width,s.height);if(s.mipLevels="auto"===this.props.mipLevels?r:Math.min(r,this.props.mipLevels),this.texture=this.device.createTexture(s),this.sampler=this.texture.sampler,this.view=this.texture.view,t.data)switch(this.props.dimension){case"1d":this._setTexture1DData(this.texture,n);break;case"2d":this._setTexture2DData(n);break;case"3d":this._setTexture3DData(this.texture,n);break;case"2d-array":this._setTextureArrayData(this.texture,n);break;case"cube":this._setTextureCubeData(this.texture,n);break;case"cube-array":this._setTextureCubeArrayData(this.texture,n)}this.props.mipmaps&&this.generateMipmaps(),Mt.info(1,`${this} loaded`),this.resolveReady()}destroy(){this.texture&&(this.texture.destroy(),this.texture=null),this.destroyed=!0}generateMipmaps(){this.texture.generateMipmapsWebGL()}setSampler(t={}){this.texture.setSampler(t instanceof ve?t:this.device.createSampler(t))}resize(t){if(!this.isReady)throw new Error("Cannot resize texture before it is ready");if(t.width===this.texture.width&&t.height===this.texture.height)return!1;if(this.texture){const e=this.texture;this.texture=e.clone(t),e.destroy()}return!0}isTextureLevelData(t){const e=t?.data;return ArrayBuffer.isView(e)}getTextureDataSize(t){if(!t)return null;if(ArrayBuffer.isView(t))return null;if(Array.isArray(t))return this.getTextureDataSize(t[0]);if(this.device.isExternalImage(t))return this.device.getExternalImageSize(t);if(t&&"object"==typeof t&&t.constructor===Object){const e=Object.values(t)[0];return{width:e.width,height:e.height}}throw new Error("texture size deduction failed")}getCubeFaceDepth(t){switch(t){case"+X":return 0;case"-X":return 1;case"+Y":return 2;case"-Y":return 3;case"+Z":return 4;case"-Z":return 5;default:throw new Error(t)}}setTextureData(t){}_setTexture1DData(t,e){throw new Error("setTexture1DData not supported in WebGL.")}_setTexture2DData(t,e=0){if(!this.texture)throw new Error("Texture not initialized");const n=this._normalizeTextureData(t);n.length>1&&!1!==this.props.mipmaps&&Mt.warn(`Texture ${this.id} mipmap and multiple LODs.`)();for(let t=0;t<n.length;t++){const i=n[t];this.device.isExternalImage(i)?this.texture.copyExternalImage({image:i,depth:e,mipLevel:t,flipY:!0}):this.texture.copyImageData({data:i.data,mipLevel:t})}}_setTexture3DData(t,e){if("3d"!==this.texture?.props.dimension)throw new Error(this.id);for(let t=0;t<e.length;t++)this._setTexture2DData(e[t],t)}_setTextureCubeData(t,e){if("cube"!==this.texture?.props.dimension)throw new Error(this.id);for(const[t,n]of Object.entries(e)){const e=il.indexOf(t);this._setTexture2DData(n,e)}}_setTextureArrayData(t,e){if("2d-array"!==this.texture?.props.dimension)throw new Error(this.id);for(let t=0;t<e.length;t++)this._setTexture2DData(e[t],t)}_setTextureCubeArrayData(t,e){throw new Error("setTextureCubeArrayData not supported in WebGL2.")}_setTextureCubeFaceData(t,e,n,i=0){Array.isArray(e)&&e.length>1&&!1!==this.props.mipmaps&&Mt.warn(`${this.id} has mipmap and multiple LODs.`)();const s=nl.indexOf(n);this._setTexture2DData(e,s)}_normalizeTextureData(t){const e=this.texture;let n;return n=ArrayBuffer.isView(t)?[{data:t,width:e.width,height:e.height}]:Array.isArray(t)?t:[t],n}static defaultProps={...ye.defaultProps,data:null,mipmaps:!1}}async function rl(t){if(t=await t,Array.isArray(t))return await Promise.all(t.map(rl));if(t&&"object"==typeof t&&t.constructor===Object){const e=t,n=await Promise.all(Object.values(e)),i=Object.keys(e),s={};for(let t=0;t<i.length;t++)s[i[t]]=n[t];return s}return t}class ol{static defaultProps={...Ce.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],geometry:null,indexBuffer:null,attributes:{},constantAttributes:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:Et.getDefaultShaderAssembler(),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_destroyed=!1;_lastDrawTimestamp=-1;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(t,e){this.props={...ol.defaultProps,...e},this.id=(e=this.props).id||Hc("model"),this.device=t,Object.assign(this.userData,e.userData);const n=Object.fromEntries(this.props.modules?.map((t=>[t.name,t]))||[]),i=e.shaderInputs||new el(n,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(i);const s=function(t){return{type:t.type,shaderLanguage:t.info.shadingLanguage,shaderLanguageVersion:t.info.shadingLanguageVersion,gpu:t.info.gpu,features:t.features}}(t),r=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if("webgpu"===this.device.type&&this.props.source){const{source:t,getUniforms:e}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:s,...this.props,modules:r});this.source=t,this._getModuleUniforms=e,this.props.shaderLayout||=function(t){const e={attributes:[],bindings:[]};let n;try{n=function(t){try{return new hs(t)}catch(t){if(t instanceof Error)throw t;let e="WGSL parse error";throw"object"==typeof t&&t?.message&&(e+=`: ${t.message} `),"object"==typeof t&&t?.token&&(e+=t.token.line||""),new Error(e,{cause:t})}}(t)}catch(t){return Mt.error(t.message)(),e}for(const t of n.uniforms){const n=[];for(const e of t.type?.members||[])n.push({name:e.name,type:us(e.type)});e.bindings.push({type:"uniform",name:t.name,group:t.group,location:t.binding,members:n})}for(const t of n.textures)e.bindings.push({type:"texture",name:t.name,group:t.group,location:t.binding});for(const t of n.samplers)e.bindings.push({type:"sampler",name:t.name,group:t.group,location:t.binding});const i=n.entry.vertex[0],s=i?.inputs.length||0;for(let t=0;t<s;t++){const n=i.inputs[t];if("location"===n.locationType){const t=us(n.type);e.attributes.push({name:n.name,location:Number(n.location),type:t})}}return e}(this.source)}else{const{vs:t,fs:e,getUniforms:n}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:s,...this.props,modules:r});this.vs=t,this.fs=e,this._getModuleUniforms=n}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,e.geometry&&this.setGeometry(e.geometry),this.pipelineFactory=e.pipelineFactory||Zc.getDefaultPipelineFactory(this.device),this.shaderFactory=e.shaderFactory||Kc.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in e&&(this.isInstanced=e.isInstanced),e.instanceCount&&this.setInstanceCount(e.instanceCount),e.vertexCount&&this.setVertexCount(e.vertexCount),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback),Object.seal(this)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&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");const t=this._needsRedraw;return this._needsRedraw=!1,t}setNeedsRedraw(t){this._needsRedraw||=t}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(t){const e=this._areBindingsLoading();if(e)return Mt.info(2,`>>> DRAWING ABORTED ${this.id}: ${e} not loaded`)(),!1;try{t.pushDebugGroup(`${this}.predraw(${t})`),this.predraw()}finally{t.popDebugGroup()}let n;try{t.pushDebugGroup(`${this}.draw(${t})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline();const e=this._getBindings();this.pipeline.setBindings(e,{disableWarnings:this.props.disableWarnings});const{indexBuffer:i}=this.vertexArray;n=this.pipeline.draw({renderPass:t,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:i?i.byteLength/("uint32"===i.indexType?4:2):void 0,transformFeedback:this.transformFeedback||void 0,parameters:this.parameters,topology:this.topology})}finally{t.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(t),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):this._needsRedraw="waiting for resource initialization",n}setGeometry(t){this._gpuGeometry?.destroy();const e=t&&function(t,e){if(e instanceof Xc)return e;const n=function(t,e){if(e.indices)return t.createBuffer({usage:It.INDEX,data:e.indices.value})}(t,e),{attributes:i,bufferLayout:s}=function(t,e){const n=[],i={};for(const[s,r]of Object.entries(e.attributes)){let e=s;switch(s){case"POSITION":e="positions";break;case"NORMAL":e="normals";break;case"TEXCOORD_0":e="texCoords";break;case"COLOR_0":e="colors"}if(r){i[e]=t.createBuffer({data:r.value,id:`${s}-buffer`});const{value:o,size:a,normalized:c}=r;n.push({name:e,format:Ut(o,a,c)})}}return{attributes:i,bufferLayout:n,vertexCount:e._calculateVertexCount(e.attributes,e.indices)}}(t,e);return new Xc({topology:e.topology||"triangle-list",bufferLayout:s,vertexCount:e.vertexCount,indices:n,attributes:i})}(this.device,t);if(e){this.setTopology(e.topology||"triangle-list");const t=new Qc(this.bufferLayout);this.bufferLayout=t.mergeBufferLayouts(e.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(e)}this._gpuGeometry=e}setTopology(t){t!==this.topology&&(this.topology=t,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(t){const e=new Qc(this.bufferLayout);this.bufferLayout=this._gpuGeometry?e.mergeBufferLayouts(t,this._gpuGeometry.bufferLayout):t,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(t){Jc(t,this.parameters,2)||(this.parameters=t,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(t){this.instanceCount=t,void 0===this.isInstanced&&t>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(t){this.vertexCount=t,this.setNeedsRedraw("vertexCount")}setShaderInputs(t){this.shaderInputs=t,this._uniformStore=new Xe(this.shaderInputs.modules);for(const[t,e]of Object.entries(this.shaderInputs.modules))if(al(e)){const e=this._uniformStore.getManagedUniformBuffer(this.device,t);this.bindings[`${t}Uniforms`]=e}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this.shaderInputs.getBindingValues()),this.setNeedsRedraw("shaderInputs")}setBindings(t){Object.assign(this.bindings,t),this.setNeedsRedraw("bindings")}setTransformFeedback(t){this.transformFeedback=t,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(t){this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(t,e){const n=e?.disableWarnings??this.props.disableWarnings;t.indices&&Mt.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=function(t,e){const n=Object.fromEntries(t.attributes.map((t=>[t.name,t.location]))),i=e.slice();return i.sort(((t,e)=>{const i=t.attributes?t.attributes.map((t=>t.attribute)):[t.name],s=e.attributes?e.attributes.map((t=>t.attribute)):[e.name];return Math.min(...i.map((t=>n[t])))-Math.min(...s.map((t=>n[t])))})),i}(this.pipeline.shaderLayout,this.bufferLayout);const i=new Qc(this.bufferLayout);for(const[e,s]of Object.entries(t)){const t=i.getBufferLayout(e);if(!t){n||Mt.warn(`Model(${this.id}): Missing layout for buffer "${e}".`)();continue}const r=i.getAttributeNamesForBuffer(t);let o=!1;for(const t of r){const e=this._attributeInfos[t];if(e){const t="webgpu"===this.device.type?i.getBufferIndex(e.bufferName):e.location;this.vertexArray.setBuffer(t,s),o=!0}}o||n||Mt.warn(`Model(${this.id}): Ignoring buffer "${s.id}" for unknown attribute "${e}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(t,e){for(const[n,i]of Object.entries(t)){const t=this._attributeInfos[n];t?this.vertexArray.setConstantWebGL(t.location,i):(e?.disableWarnings??this.props.disableWarnings)||Mt.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(const t of Object.values(this.bindings))if(t instanceof sl&&!t.isReady)return t.id;return!1}_getBindings(){const t={};for(const[e,n]of Object.entries(this.bindings))n instanceof sl?n.isReady&&(t[e]=n.texture):t[e]=n;return t}_getBindingsUpdateTimestamp(){let t=0;for(const e of Object.values(this.bindings))e instanceof we?t=Math.max(t,e.texture.updateTimestamp):e instanceof It||e instanceof ye?t=Math.max(t,e.updateTimestamp):e instanceof sl?t=e.texture?Math.max(t,e.texture.updateTimestamp):1/0:e instanceof ve||(t=Math.max(t,e.buffer.updateTimestamp));return t}_setGeometryAttributes(t){const e={...t.attributes};for(const[t]of Object.entries(e))this.pipeline.shaderLayout.attributes.find((e=>e.name===t))||"positions"===t||delete e[t];this.vertexCount=t.vertexCount,this.setIndexBuffer(t.indices||null),this.setAttributes(t.attributes,{disableWarnings:!0}),this.setAttributes(e,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(t){this._pipelineNeedsUpdate||=t,this.setNeedsRedraw(t)}_updatePipeline(){if(this._pipelineNeedsUpdate){let t=null,e=null;this.pipeline&&(Mt.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),t=this.pipeline.vs,e=this.pipeline.fs),this._pipelineNeedsUpdate=!1;const n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders});let i=null;this.source?i=n:this.fs&&(i=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,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindings:this._getBindings(),vs:n,fs:i}),this._attributeInfos=Ne(this.pipeline.shaderLayout,this.bufferLayout),t&&this.shaderFactory.release(t),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){const t=Mt.level>3?0:1e4;Mt.level<2||Date.now()-this._lastLogTime<t||(this._lastLogTime=Date.now(),this._logOpen=!0,Mt.group(2,`>>> DRAWING MODEL ${this.id}`,{collapsed:Mt.level<=2})())}_logDrawCallEnd(){if(this._logOpen){const t=function(t){const e={},n="Values";if(0===t.attributes.length&&!t.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(const i of t.attributes)i&&(e[`in ${i.location} ${i.name}: ${i.type}`]={[n]:i.stepMode||"vertex"});for(const i of t.varyings||[])e[`out ${i.location} ${i.name}`]={[n]:JSON.stringify(i)};return e}(this.pipeline.shaderLayout);Mt.table(2,t)();const e=this.shaderInputs.getDebugTable();Mt.table(2,e)();const n=this._getAttributeDebugTable();Mt.table(2,this._attributeInfos)(),Mt.table(2,n)(),Mt.groupEnd(2)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(t){const e=this.device.props.debugFramebuffers;if(this._drawCount++,!e)return;const n=t.props.framebuffer;n&&function(t,{id:e,opaque:n,top:i="0",left:s="0",rgbaScale:r=1}){qc||(qc=document.createElement("canvas"),qc.id=e,qc.title=e,qc.style.zIndex="100",qc.style.position="absolute",qc.style.top=i,qc.style.left=s,qc.style.border="blue 5px solid",qc.style.transform="scaleY(-1)",document.body.appendChild(qc),Yc=qc.getContext("2d")),qc.width===t.width&&qc.height===t.height||(qc.width=t.width/2,qc.height=t.height/2,qc.style.width="400px",qc.style.height="400px");const o=t.device.readPixelsToArrayWebGL(t),a=Yc?.createImageData(t.width,t.height);if(a){const t=0;for(let e=0;e<o.length;e+=4)a.data[t+e+0]=o[e+0]*r,a.data[t+e+1]=o[e+1]*r,a.data[t+e+2]=o[e+2]*r,a.data[t+e+3]=n?255:o[e+3]*r;Yc?.putImageData(a,0,0)}}(n,{id:n.id,minimap:!0})}_getAttributeDebugTable(){const t={};for(const[e,n]of Object.entries(this._attributeInfos)){const i=this.vertexArray.attributes[n.location];t[n.location]={name:e,type:n.shaderType,values:i?this._getBufferOrConstantValues(i,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){const{indexBuffer:e}=this.vertexArray,n="uint32"===e.indexType?new Uint32Array(e.debugData):new Uint16Array(e.debugData);t.indices={name:"indices",type:e.indexType,values:n.toString()}}return t}_getBufferOrConstantValues(t,e){const n=Ft(e);return(t instanceof It?new n(t.debugData):t).toString()}}function al(t){return Boolean(t.uniformTypes&&!function(t){for(const e in t)return!1;return!0}(t.uniformTypes))}class cl{device;model;transformFeedback;static defaultProps={...ol.defaultProps,outputs:void 0,feedbackBuffers:void 0};static isSupported(t){return"webgl"===t?.info?.type}constructor(t,e=cl.defaultProps){if(!cl.isSupported(t))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=t,this.model=new ol(this.device,{id:e.id||"buffer-transform-model",fs:e.fs||Tt(),topology:e.topology||"point-list",varyings:e.outputs||e.varyings,...e}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:e.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(t){t?.inputBuffers&&this.model.setAttributes(t.inputBuffers),t?.outputBuffers&&this.transformFeedback.setBuffers(t.outputBuffers);const e=this.device.beginRenderPass(t);this.model.draw(e),e.end()}getBuffer(t){return this.transformFeedback.getBuffer(t)}readAsync(t){const e=this.getBuffer(t);if(!e)throw new Error("BufferTransform#getBuffer");if(e instanceof It)return e.readAsync();const{buffer:n,byteOffset:i=0,byteLength:s=n.byteLength}=e;return n.readAsync(i,s)}}class ll{id;topology;vertexCount;indices;attributes;userData={};constructor(t){const{attributes:e={},indices:n=null,vertexCount:i=null}=t;this.id=t.id||Hc("geometry"),this.topology=t.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(const[t,n]of Object.entries(e)){const e=ArrayBuffer.isView(n)?{value:n}:n;if(!ArrayBuffer.isView(e.value))throw new Error(`${this._print(t)}: must be typed array or object with value as typed array`);if("POSITION"!==t&&"positions"!==t||e.size||(e.size=3),"indices"===t){if(this.indices)throw new Error("Multiple indices detected");this.indices=e}else this.attributes[t]=e}this.indices&&void 0!==this.indices.isIndexed&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=i||this._calculateVertexCount(this.attributes,this.indices)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(t){return`Geometry ${this.id} attribute ${t}`}_setAttributes(t,e){return this}_calculateVertexCount(t,e){if(e)return e.value.length;let n=1/0;for(const e of Object.values(t)){const{value:t,size:i,constant:s}=e;!s&&t&&void 0!==i&&i>=1&&(n=Math.min(n,t.length/i))}return n}}const hl={blendColorOperation:"add",blendColorSrcFactor:"one",blendColorDstFactor:"zero",blendAlphaOperation:"add",blendAlphaSrcFactor:"constant",blendAlphaDstFactor:"zero"};class ul extends pc{constructor(){super(...arguments),this._colorEncoderState=null}render(t){return"pickingFBO"in t?this._drawPickingBuffer(t):super.render(t)}_drawPickingBuffer({layers:t,layerFilter:e,views:n,viewports:i,onViewportActive:s,pickingFBO:r,deviceRect:{x:o,y:a,width:c,height:l},cullRect:h,effects:u,pass:f="picking",pickZ:d,shaderModuleProps:p}){this.pickZ=d;const g=this._resetColorEncoder(d),m=[o,a,c,l],_=super.render({target:r,layers:t,layerFilter:e,views:n,viewports:i,onViewportActive:s,cullRect:h,effects:u?.filter((t=>t.useInPicking)),pass:f,isPicking:!0,shaderModuleProps:p,clearColor:[0,0,0,0],colorMask:15,scissorRect:m});return this._colorEncoderState=null,{decodePickingColor:g&&fl.bind(null,g),stats:_}}shouldDrawLayer(t){const{pickable:e,operation:n}=t.props;return e&&n.includes("draw")||n.includes("terrain")||n.includes("mask")}getShaderModuleProps(t,e,n){return{picking:{isActive:1,isAttribute:this.pickZ},lighting:{enabled:!1}}}getLayerParameters(t,e,n){const i={...t.props.parameters},{pickable:s,operation:r}=t.props;return this._colorEncoderState?s&&r.includes("draw")?(Object.assign(i,hl),i.blend=!0,i.blendColor=function(t,e,n){const{byLayer:i,byAlpha:s}=t;let r,o=i.get(e);return o?(o.viewports.push(n),r=o.a):(r=i.size+1,r<=255?(o={a:r,layer:e,viewports:[n]},i.set(e,o),s[r]=o):(F.warn("Too many pickable layers, only picking the first 255")(),r=0)),[0,0,0,r/255]}(this._colorEncoderState,t,n)):r.includes("terrain")&&(i.blend=!1):i.blend=!1,i}_resetColorEncoder(t){return this._colorEncoderState=t?null:{byLayer:new Map,byAlpha:[]},this._colorEncoderState}}function fl(t,e){const n=t.byAlpha[e[3]];return n&&{pickedLayer:n.layer,pickedViewports:n.viewports,pickedObjectIndex:n.layer.decodePickingColor(e)}}const dl=Symbol.for("component"),pl=Symbol.for("propTypes"),gl=Symbol.for("deprecatedProps"),ml=Symbol.for("asyncPropDefaults"),_l=Symbol.for("asyncPropOriginal"),vl=Symbol.for("asyncPropResolved");function bl(t,e=()=>!0){return Array.isArray(t)?yl(t,e,[]):e(t)?[t]:[]}function yl(t,e,n){let i=-1;for(;++i<t.length;){const s=t[i];Array.isArray(s)?yl(s,e,n):e(s)&&n.push(s)}return n}function wl({target:t,source:e,start:n=0,count:i=1}){const s=e.length,r=i*s;let o=0;for(let i=n;o<s;o++)t[i++]=e[o];for(;o<r;)o<r-o?(t.copyWithin(n+o,n,n+o),o*=2):(t.copyWithin(n+o,n,n+r-o),o=r);return t}class xl{constructor(t,e,n){this._loadCount=0,this._subscribers=new Set,this.id=t,this.context=n,this.setData(e)}subscribe(t){this._subscribers.add(t)}unsubscribe(t){this._subscribers.delete(t)}inUse(){return this._subscribers.size>0}delete(){}getData(){return this.isLoaded?this._error?Promise.reject(this._error):this._content:this._loader.then((()=>this.getData()))}setData(t,e){if(t===this._data&&!e)return;this._data=t;const n=++this._loadCount;let i=t;"string"==typeof t&&(i=u(t)),i instanceof Promise?(this.isLoaded=!1,this._loader=i.then((t=>{this._loadCount===n&&(this.isLoaded=!0,this._error=void 0,this._content=t)})).catch((t=>{this._loadCount===n&&(this.isLoaded=!0,this._error=t||!0)}))):(this.isLoaded=!0,this._error=void 0,this._content=t);for(const t of this._subscribers)t.onChange(this.getData())}}class El{constructor(t){this.protocol=t.protocol||"resource://",this._context={device:t.device,gl:t.device?.gl,resourceManager:this},this._resources={},this._consumers={},this._pruneRequest=null}contains(t){return!!t.startsWith(this.protocol)||t in this._resources}add({resourceId:t,data:e,forceUpdate:n=!1,persistent:i=!0}){let s=this._resources[t];s?s.setData(e,n):(s=new xl(t,e,this._context),this._resources[t]=s),s.persistent=i}remove(t){const e=this._resources[t];e&&(e.delete(),delete this._resources[t])}unsubscribe({consumerId:t}){const e=this._consumers[t];if(e){for(const t in e){const n=e[t],i=this._resources[n.resourceId];i&&i.unsubscribe(n)}delete this._consumers[t],this.prune()}}subscribe({resourceId:t,onChange:e,consumerId:n,requestId:i="default"}){const{_resources:s,protocol:r}=this;t.startsWith(r)&&(s[t=t.replace(r,"")]||this.add({resourceId:t,data:null,persistent:!1}));const o=s[t];if(this._track(n,i,o,e),o)return o.getData()}prune(){this._pruneRequest||(this._pruneRequest=setTimeout((()=>this._prune()),0))}finalize(){for(const t in this._resources)this._resources[t].delete()}_track(t,e,n,i){const s=this._consumers,r=s[t]=s[t]||{};let o=r[e];const a=o&&o.resourceId&&this._resources[o.resourceId];a&&(a.unsubscribe(o),this.prune()),n&&(o?(o.onChange=i,o.resourceId=n.id):o={onChange:i,resourceId:n.id},r[e]=o,n.subscribe(o))}_prune(){this._pruneRequest=null;for(const t of Object.keys(this._resources)){const e=this._resources[t];e.persistent||e.inUse()||(e.delete(),delete this._resources[t])}}}class Tl{constructor(t,e){this._lastRenderedLayers=[],this._needsRedraw=!1,this._needsUpdate=!1,this._nextLayers=null,this._debug=!1,this._defaultShaderModulesChanged=!1,this.activateViewport=t=>{U("layerManager.activateViewport",this,t),t&&(this.context.viewport=t)};const{deck:n,stats:i,viewport:s,timeline:r}=e||{};this.layers=[],this.resourceManager=new El({device:t,protocol:"deck://"}),this.context={mousePosition:null,userData:{},layerManager:this,device:t,gl:t?.gl,deck:n,shaderAssembler:ic(t?.info?.shadingLanguage||"glsl"),defaultShaderModules:[Zr],renderPass:void 0,stats:i||new Ct({id:"deck.gl"}),viewport:s||new kc({id:"DEFAULT-INITIAL-VIEWPORT"}),timeline:r||new jc,resourceManager:this.resourceManager,onError:void 0},Object.seal(this)}finalize(){this.resourceManager.finalize();for(const t of this.layers)this._finalizeLayer(t)}needsRedraw(t={clearRedrawFlags:!1}){let e=this._needsRedraw;t.clearRedrawFlags&&(this._needsRedraw=!1);for(const n of this.layers){const i=n.getNeedsRedraw(t);e=e||i}return e}needsUpdate(){return this._nextLayers&&this._nextLayers!==this._lastRenderedLayers?"layers changed":this._defaultShaderModulesChanged?"shader modules changed":this._needsUpdate}setNeedsRedraw(t){this._needsRedraw=this._needsRedraw||t}setNeedsUpdate(t){this._needsUpdate=this._needsUpdate||t}getLayers({layerIds:t}={}){return t?this.layers.filter((e=>t.find((t=>0===e.id.indexOf(t))))):this.layers}setProps(t){"debug"in t&&(this._debug=t.debug),"userData"in t&&(this.context.userData=t.userData),"layers"in t&&(this._nextLayers=t.layers),"onError"in t&&(this.context.onError=t.onError)}setLayers(t,e){U("layerManager.setLayers",this,e,t),this._lastRenderedLayers=t;const n=bl(t,Boolean);for(const t of n)t.context=this.context;this._updateLayers(this.layers,n)}updateLayers(){const t=this.needsUpdate();t&&(this.setNeedsRedraw(`updating layers: ${t}`),this.setLayers(this._nextLayers||this._lastRenderedLayers,t)),this._nextLayers=null}addDefaultShaderModule(t){const{defaultShaderModules:e}=this.context;e.find((e=>e.name===t.name))||(e.push(t),this._defaultShaderModulesChanged=!0)}removeDefaultShaderModule(t){const{defaultShaderModules:e}=this.context,n=e.findIndex((e=>e.name===t.name));n>=0&&(e.splice(n,1),this._defaultShaderModulesChanged=!0)}_handleError(t,e,n){n.raiseError(e,`${t} of ${n}`)}_updateLayers(t,e){const n={};for(const e of t)n[e.id]?F.warn(`Multiple old layers with same id ${e.id}`)():n[e.id]=e;if(this._defaultShaderModulesChanged){for(const e of t)e.setNeedsUpdate(),e.setChangeFlags({extensionsChanged:!0});this._defaultShaderModulesChanged=!1}const i=[];this._updateSublayersRecursively(e,n,i),this._finalizeOldLayers(n);let s=!1;for(const t of i)if(t.hasUniformTransition()){s=`Uniform transition in ${t}`;break}this._needsUpdate=s,this.layers=i}_updateSublayersRecursively(t,e,n){for(const i of t){i.context=this.context;const t=e[i.id];null===t&&F.warn(`Multiple new layers with same id ${i.id}`)(),e[i.id]=null;let s=null;try{this._debug&&t!==i&&i.validateProps(),t?(this._transferLayerState(t,i),this._updateLayer(i)):this._initializeLayer(i),n.push(i),s=i.isComposite?i.getSubLayers():null}catch(t){this._handleError("matching",t,i)}s&&this._updateSublayersRecursively(s,e,n)}}_finalizeOldLayers(t){for(const e in t){const n=t[e];n&&this._finalizeLayer(n)}}_initializeLayer(t){try{t._initialize(),t.lifecycle="Initialized"}catch(e){this._handleError("initialization",e,t)}}_transferLayerState(t,e){e._transferState(t),e.lifecycle="Matched. State transferred from previous layer",e!==t&&(t.lifecycle="Discarded. Awaiting garbage collection")}_updateLayer(t){try{t._update()}catch(e){this._handleError("update",e,t)}}_finalizeLayer(t){this._needsRedraw=this._needsRedraw||`finalized ${t}`,t.lifecycle="No longer matched. Awaiting garbage collection";try{t._finalize(),t.lifecycle="Finalized! Awaiting garbage collection"}catch(e){this._handleError("finalization",e,t)}}}function Al(t,e,n){if(t===e)return!0;if(!n||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Al(t[i],e[i],n-1))return!1;return!0}if(Array.isArray(e))return!1;if("object"==typeof t&&"object"==typeof e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!e.hasOwnProperty(s))return!1;if(!Al(t[s],e[s],n-1))return!1}return!0}return!1}class Sl{constructor(t){this.views=[],this.width=100,this.height=100,this.viewState={},this.controllers={},this.timeline=t.timeline,this._viewports=[],this._viewportMap={},this._isUpdating=!1,this._needsRedraw="First render",this._needsUpdate="Initialize",this._eventManager=t.eventManager,this._eventCallbacks={onViewStateChange:t.onViewStateChange,onInteractionStateChange:t.onInteractionStateChange},Object.seal(this),this.setProps(t)}finalize(){for(const t in this.controllers){const e=this.controllers[t];e&&e.finalize()}this.controllers={}}needsRedraw(t={clearRedrawFlags:!1}){const e=this._needsRedraw;return t.clearRedrawFlags&&(this._needsRedraw=!1),e}setNeedsUpdate(t){this._needsUpdate=this._needsUpdate||t,this._needsRedraw=this._needsRedraw||t}updateViewStates(){for(const t in this.controllers){const e=this.controllers[t];e&&e.updateTransition()}}getViewports(t){return t?this._viewports.filter((e=>e.containsPixel(t))):this._viewports}getViews(){const t={};return this.views.forEach((e=>{t[e.id]=e})),t}getView(t){return this.views.find((e=>e.id===t))}getViewState(t){const e="string"==typeof t?this.getView(t):t,n=e&&this.viewState[e.getViewStateId()]||this.viewState;return e?e.filterViewState(n):n}getViewport(t){return this._viewportMap[t]}unproject(t,e){const n=this.getViewports(),i={x:t[0],y:t[1]};for(let s=n.length-1;s>=0;--s){const r=n[s];if(r.containsPixel(i)){const n=t.slice();return n[0]-=r.x,n[1]-=r.y,r.unproject(n,e)}}return null}setProps(t){t.views&&this._setViews(t.views),t.viewState&&this._setViewState(t.viewState),("width"in t||"height"in t)&&this._setSize(t.width,t.height),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(t,e){t===this.width&&e===this.height||(this.width=t,this.height=e,this.setNeedsUpdate("Size changed"))}_setViews(t){t=bl(t,Boolean),this._diffViews(t,this.views)&&this.setNeedsUpdate("views changed"),this.views=t}_setViewState(t){t?(!Al(t,this.viewState,3)&&this.setNeedsUpdate("viewState changed"),this.viewState=t):F.warn("missing `viewState` or `initialViewState`")()}_createController(t,e){return new(0,e.type)({timeline:this.timeline,eventManager:this._eventManager,onViewStateChange:this._eventCallbacks.onViewStateChange,onStateChange:this._eventCallbacks.onInteractionStateChange,makeViewport:e=>this.getView(t.id)?.makeViewport({viewState:e,width:this.width,height:this.height})})}_updateController(t,e,n,i){const s=t.controller;if(s&&n){const r={...e,...s,id:t.id,x:n.x,y:n.y,width:n.width,height:n.height};return i&&i.constructor===s.type||(i=this._createController(t,r)),i&&i.setProps(r),i}return null}_rebuildViewports(){const{views:t}=this,e=this.controllers;this._viewports=[],this.controllers={};let n=!1;for(let i=t.length;i--;){const s=t[i],r=this.getViewState(s),o=s.makeViewport({viewState:r,width:this.width,height:this.height});let a=e[s.id];const c=Boolean(s.controller);c&&!a&&(n=!0),!n&&c||!a||(a.finalize(),a=null),this.controllers[s.id]=this._updateController(s,r,o,a),o&&this._viewports.unshift(o)}for(const t in e){const n=e[t];n&&!this.controllers[t]&&n.finalize()}this._buildViewportMap()}_buildViewportMap(){this._viewportMap={},this._viewports.forEach((t=>{t.id&&(this._viewportMap[t.id]=this._viewportMap[t.id]||t)}))}_diffViews(t,e){return t.length!==e.length||t.some(((n,i)=>!t[i].equals(e[i])))}}const Cl=/^(?:\d+\.?\d*|\.\d+)$/;function Pl(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{const e=function(t){const e=[];let n=0;for(;n<t.length;){const i=t[n];if(/\s/.test(i))n++;else if("+"!==i&&"-"!==i&&"("!==i&&")"!==i&&"%"!==i)if(Ol(i)||"."===i){const s=n;let r="."===i;for(n++;n<t.length;){const e=t[n];if(Ol(e))n++;else{if("."!==e||r)break;r=!0,n++}}const o=t.slice(s,n);if(!Cl.test(o))throw new Error("Invalid number token");e.push({type:"number",value:parseFloat(o)})}else{if(!Il(i))throw new Error("Invalid token in position string");{const i=n;for(;n<t.length&&Il(t[n]);)n++;const s=t.slice(i,n).toLowerCase();e.push({type:"word",value:s})}}else e.push({type:"symbol",value:i}),n++}return e}(t);return new Ll(e).parseExpression()}catch(e){const n=e instanceof Error?e.message:String(e);throw new Error(`Could not parse position string ${t}: ${n}`)}default:throw new Error(`Could not parse position string ${t}`)}}function Ml(t,e){switch(t.type){case"literal":return t.value;case"percentage":return Math.round(t.value*e);case"binary":const n=Ml(t.left,e),i=Ml(t.right,e);return"+"===t.operator?n+i:n-i;default:throw new Error("Unknown layout expression type")}}function Rl(t,e){return Ml(t,e)}class Ll{constructor(t){this.index=0,this.tokens=t}parseExpression(){const t=this.parseBinaryExpression();if(this.index<this.tokens.length)throw new Error("Unexpected token at end of expression");return t}parseBinaryExpression(){let t=this.parseFactor(),e=this.peek();for(;kl(e);){this.index++;const n=this.parseFactor();t={type:"binary",operator:e.value,left:t,right:n},e=this.peek()}return t}parseFactor(){const t=this.peek();if(!t)throw new Error("Unexpected end of expression");if("symbol"===t.type&&"+"===t.value)return this.index++,this.parseFactor();if("symbol"===t.type&&"-"===t.value)return this.index++,{type:"binary",operator:"-",left:{type:"literal",value:0},right:this.parseFactor()};if("symbol"===t.type&&"("===t.value){this.index++;const t=this.parseBinaryExpression();if(!this.consumeSymbol(")"))throw new Error("Missing closing parenthesis");return t}if("word"===t.type&&"calc"===t.value){if(this.index++,!this.consumeSymbol("("))throw new Error("Missing opening parenthesis after calc");const t=this.parseBinaryExpression();if(!this.consumeSymbol(")"))throw new Error("Missing closing parenthesis");return t}if("number"===t.type){this.index++;const e=t.value,n=this.peek();return n&&"symbol"===n.type&&"%"===n.value?(this.index++,{type:"percentage",value:e/100}):n&&"word"===n.type&&"px"===n.value?(this.index++,{type:"literal",value:e}):{type:"literal",value:e}}throw new Error("Unexpected token in expression")}consumeSymbol(t){const e=this.peek();return!(!e||"symbol"!==e.type||e.value!==t||(this.index++,0))}peek(){return this.tokens[this.index]||null}}function Ol(t){return t>="0"&&t<="9"}function Il(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}function kl(t){return Boolean(t&&"symbol"===t.type&&("+"===t.value||"-"===t.value))}class Dl{constructor(t){const{id:e,x:n=0,y:i=0,width:s="100%",height:r="100%",padding:o=null}=t;this.id=e||this.constructor.displayName||"view",this.props={...t,id:this.id},this._x=Pl(n),this._y=Pl(i),this._width=Pl(s),this._height=Pl(r),this._padding=o&&{left:Pl(o.left||0),right:Pl(o.right||0),top:Pl(o.top||0),bottom:Pl(o.bottom||0)},this.equals=this.equals.bind(this),Object.seal(this)}equals(t){return this===t||this.constructor===t.constructor&&Al(this.props,t.props,2)}clone(t){return new(0,this.constructor)({...this.props,...t})}makeViewport({width:t,height:e,viewState:n}){n=this.filterViewState(n);const i=this.getDimensions({width:t,height:e});return i.height&&i.width?new(this.getViewportType(n))({...n,...this.props,...i}):null}getViewStateId(){const{viewState:t}=this.props;return"string"==typeof t?t:t?.id||this.id}filterViewState(t){if(this.props.viewState&&"object"==typeof this.props.viewState){if(!this.props.viewState.id)return this.props.viewState;const e={...t};for(const t in this.props.viewState)"id"!==t&&(e[t]=this.props.viewState[t]);return e}return t}getDimensions({width:t,height:e}){const n={x:Rl(this._x,t),y:Rl(this._y,e),width:Rl(this._width,t),height:Rl(this._height,e)};return this._padding&&(n.padding={left:Rl(this._padding.left,t),top:Rl(this._padding.top,e),right:Rl(this._padding.right,t),bottom:Rl(this._padding.bottom,e)}),n}get controller(){const t=this.props.controller;return t?!0===t?{type:this.ControllerType}:"function"==typeof t?{type:t}:{type:this.ControllerType,...t}:null}}class Nl{constructor(t){this._inProgress=!1,this._handle=null,this.time=0,this.settings={duration:0},this._timeline=t}get inProgress(){return this._inProgress}start(t){this.cancel(),this.settings=t,this._inProgress=!0,this.settings.onStart?.(this)}end(){this._inProgress&&(this._timeline.removeChannel(this._handle),this._handle=null,this._inProgress=!1,this.settings.onEnd?.(this))}cancel(){this._inProgress&&(this.settings.onInterrupt?.(this),this._timeline.removeChannel(this._handle),this._handle=null,this._inProgress=!1)}update(){if(!this._inProgress)return!1;if(null===this._handle){const{_timeline:t,settings:e}=this;this._handle=t.addChannel({delay:t.getTime(),duration:e.duration})}return this.time=this._timeline.getTime(this._handle),this._onUpdate(),this.settings.onUpdate?.(this),this._timeline.isFinished(this._handle)&&this.end(),!0}_onUpdate(){}}const Fl=()=>{},Bl={BREAK:1,SNAP_TO_END:2,IGNORE:3},$l=t=>t,Ul=Bl.BREAK;class zl{constructor(t){this._onTransitionUpdate=t=>{const{time:e,settings:{interpolator:n,startProps:i,endProps:s,duration:r,easing:o}}=t,a=o(e/r),c=n.interpolateProps(i,s,a);this.propsInTransition=this.getControllerState({...this.props,...c}).getViewportProps(),this.onViewStateChange({viewState:this.propsInTransition,oldViewState:this.props})},this.getControllerState=t.getControllerState,this.propsInTransition=null,this.transition=new Nl(t.timeline),this.onViewStateChange=t.onViewStateChange||Fl,this.onStateChange=t.onStateChange||Fl}finalize(){this.transition.cancel()}getViewportInTransition(){return this.propsInTransition}processViewStateChange(t){let e=!1;const n=this.props;if(this.props=t,!n||this._shouldIgnoreViewportChange(n,t))return!1;if(this._isTransitionEnabled(t)){let i=n;if(this.transition.inProgress){const{interruption:t,endProps:e}=this.transition.settings;i={...n,...t===Bl.SNAP_TO_END?e:this.propsInTransition||n}}this._triggerTransition(i,t),e=!0}else this.transition.cancel();return e}updateTransition(){this.transition.update()}_isTransitionEnabled(t){const{transitionDuration:e,transitionInterpolator:n}=t;return(e>0||"auto"===e)&&Boolean(n)}_isUpdateDueToCurrentTransition(t){return!(!this.transition.inProgress||!this.propsInTransition)&&this.transition.settings.interpolator.arePropsEqual(t,this.propsInTransition)}_shouldIgnoreViewportChange(t,e){return this.transition.inProgress?this.transition.settings.interruption===Bl.IGNORE||this._isUpdateDueToCurrentTransition(e):!this._isTransitionEnabled(e)||e.transitionInterpolator.arePropsEqual(t,e)}_triggerTransition(t,e){const n=this.getControllerState(t),i=this.getControllerState(e).shortestPathFrom(n),s=e.transitionInterpolator,r=s.getDuration?s.getDuration(t,e):e.transitionDuration;if(0===r)return;const o=s.initializeProps(t,i);this.propsInTransition={};const a={duration:r,easing:e.transitionEasing||$l,interpolator:s,interruption:e.transitionInterruption||Ul,startProps:o.start,endProps:o.end,onStart:e.onTransitionStart,onUpdate:this._onTransitionUpdate,onInterrupt:this._onTransitionEnd(e.onTransitionInterrupt),onEnd:this._onTransitionEnd(e.onTransitionEnd)};this.transition.start(a),this.onStateChange({inTransition:!0}),this.updateTransition()}_onTransitionEnd(t){return e=>{this.propsInTransition=null,this.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1}),t?.(e)}}}function jl(t,e){if(!t)throw new Error(e||"deck.gl: assertion failed.")}class Gl{constructor(t){const{compare:e,extract:n,required:i}=t;this._propsToCompare=e,this._propsToExtract=n||e,this._requiredProps=i}arePropsEqual(t,e){for(const n of this._propsToCompare)if(!(n in t)||!(n in e)||!ws(t[n],e[n]))return!1;return!0}initializeProps(t,e){const n={},i={};for(const s of this._propsToExtract)(s in t||s in e)&&(n[s]=t[s],i[s]=e[s]);return this._checkRequiredProps(n),this._checkRequiredProps(i),{start:n,end:i}}getDuration(t,e){return e.transitionDuration}_checkRequiredProps(t){this._requiredProps&&this._requiredProps.forEach((e=>{const n=t[e];jl(Number.isFinite(n)||Array.isArray(n),`${e} is required for transition`)}))}}const Wl=Math.PI/180,Vl=180/Math.PI,Hl=6370972,Xl=256;function Zl(){const t=4018225162502676e-20,e=Math.PI/180*Xl;return{unitsPerMeter:[t,t,t],unitsPerMeter2:[0,0,0],metersPerUnit:[24886.609375,24886.609375,24886.609375],unitsPerDegree:[e,e,t],unitsPerDegree2:[0,0,0],degreesPerUnit:[1/e,1/e,24886.609375]}}class Kl extends kc{constructor(t={}){const{longitude:e=0,zoom:n=0,nearZMultiplier:i=.5,farZMultiplier:s=1,resolution:r=10}=t;let{latitude:o=0,height:a,altitude:c=1.5,fovy:l}=t;o=Math.max(Math.min(o,Ma),-85.051129),a=a||1,l?c=Ua(l):l=$a(c);const h=Math.pow(2,n-ql(o)),u=t.nearZ??i,f=t.farZ??(c+512*h/a)*s,d=(new xr).lookAt({eye:[0,-c,0],up:[0,0,1]});d.rotateX(o*Wl),d.rotateZ(-e*Wl),d.scale(h/a),super({...t,height:a,viewMatrix:d,longitude:e,latitude:o,zoom:n,distanceScales:Zl(),fovy:l,focalDistance:c,near:u,far:f}),this.scale=h,this.latitude=o,this.longitude=e,this.fovy=l,this.resolution=r}get projectionMode(){return qo.GLOBE}getDistanceScales(){return this.distanceScales}getBounds(t={}){const e={targetZ:t.z||0},n=this.unproject([0,this.height/2],e),i=this.unproject([this.width/2,0],e),s=this.unproject([this.width,this.height/2],e),r=this.unproject([this.width/2,this.height],e);return s[0]<this.longitude&&(s[0]+=360),n[0]>this.longitude&&(n[0]-=360),[Math.min(n[0],s[0],i[0],r[0]),Math.min(n[1],s[1],i[1],r[1]),Math.max(n[0],s[0],i[0],r[0]),Math.max(n[1],s[1],i[1],r[1])]}unproject(t,{topLeft:e=!0,targetZ:n}={}){const[i,s,r]=t,o=e?s:this.height-s,{pixelUnprojectionMatrix:a}=this;let c;if(Number.isFinite(r))c=Yl(a,[i,o,r,1]);else{const t=Yl(a,[i,o,-1,1]),e=Yl(a,[i,o,1,1]),s=((n||0)/Hl+1)*Xl,r=Zs(Hs([],t,e)),l=Zs(t),h=Zs(e),u=(4*l*h-(r-l-h)**2)/16*4/r;c=function(t,e,n,i){const s=e[0],r=e[1],o=e[2];return t[0]=s+i*(n[0]-s),t[1]=r+i*(n[1]-r),t[2]=o+i*(n[2]-o),t}([],t,e,(Math.sqrt(l-u)-Math.sqrt(Math.max(0,s*s-u)))/Math.sqrt(r))}const[l,h,u]=this.unprojectPosition(c);return Number.isFinite(r)?[l,h,u]:Number.isFinite(n)?[l,h,n]:[l,h]}projectPosition(t){const[e,n,i=0]=t,s=e*Wl,r=n*Wl,o=Math.cos(r),a=(i/Hl+1)*Xl;return[Math.sin(s)*o*a,-Math.cos(s)*o*a,Math.sin(r)*a]}unprojectPosition(t){const[e,n,i]=t,s=Xs(t),r=Math.asin(i/s);return[Math.atan2(e,-n)*Vl,r*Vl,(s/Xl-1)*Hl]}projectFlat(t){return t}unprojectFlat(t){return t}panByPosition([t,e,n],i,s){const r=.25/Math.pow(2,this.zoom-ql(this.latitude)),o=t+r*(s[0]-i[0]);let a=e-r*(s[1]-i[1]);a=Math.max(Math.min(a,Ma),-85.051129);const c={longitude:o,latitude:a,zoom:n-ql(e)};return c.zoom+=ql(c.latitude),c}}function ql(t){const e=Math.PI*Math.cos(t*Math.PI/180);return Math.log2(e)}function Yl(t,e){const n=gr([],e,t);return pr(n,n,1/n[3]),n}Kl.displayName="GlobeViewport";const Jl=["longitude","latitude","zoom","bearing","pitch"],Ql=["longitude","latitude","zoom"];class th extends Gl{constructor(t={}){const e=Array.isArray(t)?t:t.transitionProps,n=Array.isArray(t)?{}:t;n.transitionProps=Array.isArray(e)?{compare:e,required:e}:e||{compare:Jl,required:Ql},super(n.transitionProps),this.opts=n}initializeProps(t,e){const n=super.initializeProps(t,e),{makeViewport:i,around:s}=this.opts;if(i&&s)if(i(t)instanceof Kl)F.warn("around not supported in GlobeView")();else{const r=i(t),o=i(e),a=r.unproject(s);n.start.around=s,Object.assign(n.end,{around:o.project(a),aroundPosition:a,width:e.width,height:e.height})}return n}interpolateProps(t,e,n){const i={};for(const s of this._propsToExtract)i[s]=ys(t[s]||0,e[s]||0,n);if(e.aroundPosition&&this.opts.makeViewport){const s=this.opts.makeViewport({...e,...i});Object.assign(i,s.panByPosition(e.aroundPosition,ys(t.around,e.around,n)))}return i}}const eh={transitionDuration:0},nh=t=>1-(1-t)*(1-t),ih=["wheel"],sh=["panstart","panmove","panend"],rh=["pinchstart","pinchmove","pinchend"],oh=["multipanstart","multipanmove","multipanend"],ah=["dblclick"],ch=["keydown"],lh={};class hh{constructor(t){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 zl({...t,getControllerState:t=>new this.ControllerState(t),onViewStateChange:this._onTransition.bind(this),onStateChange:this._setInteractionState.bind(this)}),this.handleEvent=this.handleEvent.bind(this),this.eventManager=t.eventManager,this.onViewStateChange=t.onViewStateChange||(()=>{}),this.onStateChange=t.onStateChange||(()=>{}),this.makeViewport=t.makeViewport}set events(t){this.toggleEvents(this._customEvents,!1),this.toggleEvents(t,!0),this._customEvents=t,this.props&&this.setProps(this.props)}finalize(){for(const t in this._events)this._events[t]&&this.eventManager?.off(t,this.handleEvent);this.transitionManager.finalize()}handleEvent(t){this._controllerState=void 0;const e=this._eventStartBlocked;switch(t.type){case"panstart":return!e&&this._onPanStart(t);case"panmove":return this._onPan(t);case"panend":return this._onPanEnd(t);case"pinchstart":return!e&&this._onPinchStart(t);case"pinchmove":return this._onPinch(t);case"pinchend":return this._onPinchEnd(t);case"multipanstart":return!e&&this._onMultiPanStart(t);case"multipanmove":return this._onMultiPan(t);case"multipanend":return this._onMultiPanEnd(t);case"dblclick":return this._onDoubleClick(t);case"wheel":return this._onWheel(t);case"keydown":return this._onKeyDown(t);default:return!1}}get controllerState(){return this._controllerState=this._controllerState||new this.ControllerState({makeViewport:this.makeViewport,...this.props,...this.state}),this._controllerState}getCenter(t){const{x:e,y:n}=this.props,{offsetCenter:i}=t;return[i.x-e,i.y-n]}isPointInBounds(t,e){const{width:n,height:i}=this.props;if(e&&e.handled)return!1;const s=t[0]>=0&&t[0]<=n&&t[1]>=0&&t[1]<=i;return s&&e&&e.stopPropagation(),s}isFunctionKeyPressed(t){const{srcEvent:e}=t;return Boolean(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}isDragging(){return this._interactionState.isDragging||!1}blockEvents(t){const e=setTimeout((()=>{this._eventStartBlocked===e&&(this._eventStartBlocked=null)}),t);this._eventStartBlocked=e}setProps(t){t.dragMode&&(this.dragMode=t.dragMode),this.props=t,"transitionInterpolator"in t||(t.transitionInterpolator=this._getTransitionProps().transitionInterpolator),this.transitionManager.processViewStateChange(t);const{inertia:e}=t;this.inertia=Number.isFinite(e)?e:!0===e?300:0;const{scrollZoom:n=!0,dragPan:i=!0,dragRotate:s=!0,doubleClickZoom:r=!0,touchZoom:o=!0,touchRotate:a=!1,keyboard:c=!0}=t,l=Boolean(this.onViewStateChange);this.toggleEvents(ih,l&&n),this.toggleEvents(sh,l),this.toggleEvents(rh,l&&(o||a)),this.toggleEvents(oh,l&&a),this.toggleEvents(ah,l&&r),this.toggleEvents(ch,l&&c),this.scrollZoom=n,this.dragPan=i,this.dragRotate=s,this.doubleClickZoom=r,this.touchZoom=o,this.touchRotate=a,this.keyboard=c}updateTransition(){this.transitionManager.updateTransition()}toggleEvents(t,e){this.eventManager&&t.forEach((t=>{this._events[t]!==e&&(this._events[t]=e,e?this.eventManager.on(t,this.handleEvent):this.eventManager.off(t,this.handleEvent))}))}updateViewport(t,e=null,n={}){const i={...t.getViewportProps(),...e},s=this.controllerState!==t;if(this.state=t.getState(),this._setInteractionState(n),s){const t=this.controllerState&&this.controllerState.getViewportProps();this.onViewStateChange&&this.onViewStateChange({viewState:i,interactionState:this._interactionState,oldViewState:t,viewId:this.props.id})}}_onTransition(t){this.onViewStateChange({...t,interactionState:this._interactionState,viewId:this.props.id})}_setInteractionState(t){Object.assign(this._interactionState,t),this.onStateChange(this._interactionState)}_onPanStart(t){const e=this.getCenter(t);if(!this.isPointInBounds(e,t))return!1;let n=this.isFunctionKeyPressed(t)||t.rightButton||!1;(this.invertPan||"pan"===this.dragMode)&&(n=!n);const i=this.controllerState[n?"panStart":"rotateStart"]({pos:e});return this._panMove=n,this.updateViewport(i,eh,{isDragging:!0}),!0}_onPan(t){return!!this.isDragging()&&(this._panMove?this._onPanMove(t):this._onPanRotate(t))}_onPanEnd(t){return!!this.isDragging()&&(this._panMove?this._onPanMoveEnd(t):this._onPanRotateEnd(t))}_onPanMove(t){if(!this.dragPan)return!1;const e=this.getCenter(t),n=this.controllerState.pan({pos:e});return this.updateViewport(n,eh,{isDragging:!0,isPanning:!0}),!0}_onPanMoveEnd(t){const{inertia:e}=this;if(this.dragPan&&e&&t.velocity){const n=this.getCenter(t),i=this.controllerState.pan({pos:[n[0]+t.velocityX*e/2,n[1]+t.velocityY*e/2]}).panEnd();this.updateViewport(i,{...this._getTransitionProps(),transitionDuration:e,transitionEasing:nh},{isDragging:!1,isPanning:!0})}else{const t=this.controllerState.panEnd();this.updateViewport(t,null,{isDragging:!1,isPanning:!1})}return!0}_onPanRotate(t){if(!this.dragRotate)return!1;const e=this.getCenter(t),n=this.controllerState.rotate({pos:e});return this.updateViewport(n,eh,{isDragging:!0,isRotating:!0}),!0}_onPanRotateEnd(t){const{inertia:e}=this;if(this.dragRotate&&e&&t.velocity){const n=this.getCenter(t),i=this.controllerState.rotate({pos:[n[0]+t.velocityX*e/2,n[1]+t.velocityY*e/2]}).rotateEnd();this.updateViewport(i,{...this._getTransitionProps(),transitionDuration:e,transitionEasing:nh},{isDragging:!1,isRotating:!0})}else{const t=this.controllerState.rotateEnd();this.updateViewport(t,null,{isDragging:!1,isRotating:!1})}return!0}_onWheel(t){if(!this.scrollZoom)return!1;const e=this.getCenter(t);if(!this.isPointInBounds(e,t))return!1;t.srcEvent.preventDefault();const{speed:n=.01,smooth:i=!1}=!0===this.scrollZoom?{}:this.scrollZoom,{delta:s}=t;let r=2/(1+Math.exp(-Math.abs(s*n)));s<0&&0!==r&&(r=1/r);const o=i?{...this._getTransitionProps({around:e}),transitionDuration:250}:eh,a=this.controllerState.zoom({pos:e,scale:r});return this.updateViewport(a,o,{isZooming:!0,isPanning:!0}),i||this._setInteractionState({isZooming:!1,isPanning:!1}),!0}_onMultiPanStart(t){const e=this.getCenter(t);if(!this.isPointInBounds(e,t))return!1;const n=this.controllerState.rotateStart({pos:e});return this.updateViewport(n,eh,{isDragging:!0}),!0}_onMultiPan(t){if(!this.touchRotate)return!1;if(!this.isDragging())return!1;const e=this.getCenter(t);e[0]-=t.deltaX;const n=this.controllerState.rotate({pos:e});return this.updateViewport(n,eh,{isDragging:!0,isRotating:!0}),!0}_onMultiPanEnd(t){if(!this.isDragging())return!1;const{inertia:e}=this;if(this.touchRotate&&e&&t.velocityY){const n=this.getCenter(t),i=[n[0],n[1]+=t.velocityY*e/2],s=this.controllerState.rotate({pos:i});this.updateViewport(s,{...this._getTransitionProps(),transitionDuration:e,transitionEasing:nh},{isDragging:!1,isRotating:!0}),this.blockEvents(e)}else{const t=this.controllerState.rotateEnd();this.updateViewport(t,null,{isDragging:!1,isRotating:!1})}return!0}_onPinchStart(t){const e=this.getCenter(t);if(!this.isPointInBounds(e,t))return!1;const n=this.controllerState.zoomStart({pos:e}).rotateStart({pos:e});return lh._startPinchRotation=t.rotation,lh._lastPinchEvent=t,this.updateViewport(n,eh,{isDragging:!0}),!0}_onPinch(t){if(!this.touchZoom&&!this.touchRotate)return!1;if(!this.isDragging())return!1;let e=this.controllerState;if(this.touchZoom){const{scale:n}=t,i=this.getCenter(t);e=e.zoom({pos:i,scale:n})}if(this.touchRotate){const{rotation:n}=t;e=e.rotate({deltaAngleX:lh._startPinchRotation-n})}return this.updateViewport(e,eh,{isDragging:!0,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:this.touchRotate}),lh._lastPinchEvent=t,!0}_onPinchEnd(t){if(!this.isDragging())return!1;const{inertia:e}=this,{_lastPinchEvent:n}=lh;if(this.touchZoom&&e&&n&&t.scale!==n.scale){const i=this.getCenter(t);let s=this.controllerState.rotateEnd();const r=Math.log2(t.scale),o=(r-Math.log2(n.scale))/(t.deltaTime-n.deltaTime),a=Math.pow(2,r+o*e/2);s=s.zoom({pos:i,scale:a}).zoomEnd(),this.updateViewport(s,{...this._getTransitionProps({around:i}),transitionDuration:e,transitionEasing:nh},{isDragging:!1,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:!1}),this.blockEvents(e)}else{const t=this.controllerState.zoomEnd().rotateEnd();this.updateViewport(t,null,{isDragging:!1,isPanning:!1,isZooming:!1,isRotating:!1})}return lh._startPinchRotation=null,lh._lastPinchEvent=null,!0}_onDoubleClick(t){if(!this.doubleClickZoom)return!1;const e=this.getCenter(t);if(!this.isPointInBounds(e,t))return!1;const n=this.isFunctionKeyPressed(t),i=this.controllerState.zoom({pos:e,scale:n?.5:2});return this.updateViewport(i,this._getTransitionProps({around:e}),{isZooming:!0,isPanning:!0}),this.blockEvents(100),!0}_onKeyDown(t){if(!this.keyboard)return!1;const e=this.isFunctionKeyPressed(t),{zoomSpeed:n,moveSpeed:i,rotateSpeedX:s,rotateSpeedY:r}=!0===this.keyboard?{}:this.keyboard,{controllerState:o}=this;let a;const c={};switch(t.srcEvent.code){case"Minus":a=e?o.zoomOut(n).zoomOut(n):o.zoomOut(n),c.isZooming=!0;break;case"Equal":a=e?o.zoomIn(n).zoomIn(n):o.zoomIn(n),c.isZooming=!0;break;case"ArrowLeft":e?(a=o.rotateLeft(s),c.isRotating=!0):(a=o.moveLeft(i),c.isPanning=!0);break;case"ArrowRight":e?(a=o.rotateRight(s),c.isRotating=!0):(a=o.moveRight(i),c.isPanning=!0);break;case"ArrowUp":e?(a=o.rotateUp(r),c.isRotating=!0):(a=o.moveUp(i),c.isPanning=!0);break;case"ArrowDown":e?(a=o.rotateDown(r),c.isRotating=!0):(a=o.moveDown(i),c.isPanning=!0);break;default:return!1}return this.updateViewport(a,this._getTransitionProps(),c),!0}_getTransitionProps(t){const{transition:e}=this;return e&&e.transitionInterpolator?t?{...e,transitionInterpolator:new th({...t,...e.transitionInterpolator.opts,makeViewport:this.controllerState.makeViewport})}:e:eh}}class uh{constructor(t,e){this._viewportProps=this.applyConstraints(t),this._state=e}getViewportProps(){return this._viewportProps}getState(){return this._state}}class fh extends uh{constructor(t){const{width:e,height:n,latitude:i,longitude:s,zoom:r,bearing:o=0,pitch:a=0,altitude:c=1.5,position:l=[0,0,0],maxZoom:h=20,minZoom:u=0,maxPitch:f=60,minPitch:d=0,startPanLngLat:p,startZoomLngLat:g,startRotatePos:m,startBearing:_,startPitch:v,startZoom:b,normalize:y=!0}=t;jl(Number.isFinite(s)),jl(Number.isFinite(i)),jl(Number.isFinite(r)),super({width:e,height:n,latitude:i,longitude:s,zoom:r,bearing:o,pitch:a,altitude:c,maxZoom:h,minZoom:u,maxPitch:f,minPitch:d,normalize:y,position:l},{startPanLngLat:p,startZoomLngLat:g,startRotatePos:m,startBearing:_,startPitch:v,startZoom:b}),this.makeViewport=t.makeViewport}panStart({pos:t}){return this._getUpdatedState({startPanLngLat:this._unproject(t)})}pan({pos:t,startPos:e}){const n=this.getState().startPanLngLat||this._unproject(e);if(!n)return this;const i=this.makeViewport(this.getViewportProps()).panByPosition(n,t);return this._getUpdatedState(i)}panEnd(){return this._getUpdatedState({startPanLngLat:null})}rotateStart({pos:t}){return this._getUpdatedState({startRotatePos:t,startBearing:this.getViewportProps().bearing,startPitch:this.getViewportProps().pitch})}rotate({pos:t,deltaAngleX:e=0,deltaAngleY:n=0}){const{startRotatePos:i,startBearing:s,startPitch:r}=this.getState();if(!i||void 0===s||void 0===r)return this;let o;return o=t?this._getNewRotation(t,i,r,s):{bearing:s+e,pitch:r+n},this._getUpdatedState(o)}rotateEnd(){return this._getUpdatedState({startBearing:null,startPitch:null})}zoomStart({pos:t}){return this._getUpdatedState({startZoomLngLat:this._unproject(t),startZoom:this.getViewportProps().zoom})}zoom({pos:t,startPos:e,scale:n}){let{startZoom:i,startZoomLngLat:s}=this.getState();if(s||(i=this.getViewportProps().zoom,s=this._unproject(e)||this._unproject(t)),!s)return this;const{maxZoom:r,minZoom:o}=this.getViewportProps();let a=i+Math.log2(n);a=bs(a,o,r);const c=this.makeViewport({...this.getViewportProps(),zoom:a});return this._getUpdatedState({zoom:a,...c.panByPosition(s,t)})}zoomEnd(){return this._getUpdatedState({startZoomLngLat:null,startZoom:null})}zoomIn(t=2){return this._zoomFromCenter(t)}zoomOut(t=2){return this._zoomFromCenter(1/t)}moveLeft(t=100){return this._panFromCenter([t,0])}moveRight(t=100){return this._panFromCenter([-t,0])}moveUp(t=100){return this._panFromCenter([0,t])}moveDown(t=100){return this._panFromCenter([0,-t])}rotateLeft(t=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing-t})}rotateRight(t=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing+t})}rotateUp(t=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch+t})}rotateDown(t=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch-t})}shortestPathFrom(t){const e=t.getViewportProps(),n={...this.getViewportProps()},{bearing:i,longitude:s}=n;return Math.abs(i-e.bearing)>180&&(n.bearing=i<0?i+360:i-360),Math.abs(s-e.longitude)>180&&(n.longitude=s<0?s+360:s-360),n}applyConstraints(t){const{maxZoom:e,minZoom:n,zoom:i}=t;t.zoom=bs(i,n,e);const{maxPitch:s,minPitch:r,pitch:o}=t;t.pitch=bs(o,r,s);const{normalize:a=!0}=t;return a&&Object.assign(t,function(t){const{width:e,height:n,pitch:i=0}=t;let{longitude:s,latitude:r,zoom:o,bearing:a=0}=t;(s<-180||s>180)&&(s=ba(s+180,360)-180),(a<-180||a>180)&&(a=ba(a+180,360)-180);const c=xa(n/512);if(o<=c)o=c,r=0;else{const t=n/2/Math.pow(2,o),e=ka([0,t])[1];if(r<e)r=e;else{const e=ka([0,512-t])[1];r>e&&(r=e)}}return{width:e,height:n,longitude:s,latitude:r,zoom:o,pitch:i,bearing:a}}(t)),t}_zoomFromCenter(t){const{width:e,height:n}=this.getViewportProps();return this.zoom({pos:[e/2,n/2],scale:t})}_panFromCenter(t){const{width:e,height:n}=this.getViewportProps();return this.pan({startPos:[e/2,n/2],pos:[e/2+t[0],n/2+t[1]]})}_getUpdatedState(t){return new this.constructor({makeViewport:this.makeViewport,...this.getViewportProps(),...this.getState(),...t})}_unproject(t){const e=this.makeViewport(this.getViewportProps());return t&&e.unproject(t)}_getNewRotation(t,e,n,i){const s=t[0]-e[0],r=t[1]-e[1],o=t[1],a=e[1],{width:c,height:l}=this.getViewportProps(),h=s/c;let u=0;r>0?Math.abs(l-a)>5&&(u=r/(a-l)*1.2):r<0&&a>5&&(u=1-o/a),u=bs(u,-1,1);const{minPitch:f,maxPitch:d}=this.getViewportProps();let p=n;return u>0?p=n+u*(d-n):u<0&&(p=n-u*(f-n)),{pitch:p,bearing:i+180*h}}}class dh extends hh{constructor(){super(...arguments),this.ControllerState=fh,this.transition={transitionDuration:300,transitionInterpolator:new th({transitionProps:{compare:["longitude","latitude","zoom","bearing","pitch","position"],required:["longitude","latitude","zoom"]}})},this.dragMode="pan"}setProps(t){t.position=t.position||[0,0,0];const e=this.props;super.setProps(t),(!e||e.height!==t.height)&&this.updateViewport(new this.ControllerState({makeViewport:this.makeViewport,...t,...this.state}))}}class ph extends Dl{constructor(t={}){super(t)}getViewportType(){return Dc}get ControllerType(){return dh}}ph.displayName="MapView";const gh=new wc;class mh{constructor(t){this._resolvedEffects=[],this._defaultEffects=[],this.effects=[],this._context=t,this._needsRedraw="Initial render",this._setEffects([])}addDefaultEffect(t){const e=this._defaultEffects;if(!e.find((e=>e.id===t.id))){const n=e.findIndex((e=>(e.order??1/0)-(t.order??1/0)>0));n<0?e.push(t):e.splice(n,0,t),t.setup(this._context),this._setEffects(this.effects)}}setProps(t){"effects"in t&&(Al(t.effects,this.effects,1)||this._setEffects(t.effects))}needsRedraw(t={clearRedrawFlags:!1}){const e=this._needsRedraw;return t.clearRedrawFlags&&(this._needsRedraw=!1),e}getEffects(){return this._resolvedEffects}_setEffects(t){const e={};for(const t of this.effects)e[t.id]=t;const n=[];for(const i of t){const t=e[i.id];let s=i;t&&t!==i?t.setProps?(t.setProps(i.props),s=t):t.cleanup(this._context):t||i.setup(this._context),n.push(s),delete e[i.id]}for(const t in e)e[t].cleanup(this._context);this.effects=n,this._resolvedEffects=n.concat(this._defaultEffects),t.some((t=>t instanceof wc))||this._resolvedEffects.push(gh),this._needsRedraw="effects changed"}finalize(){for(const t of this._resolvedEffects)t.cleanup(this._context);this.effects.length=0,this._resolvedEffects.length=0,this._defaultEffects.length=0}}class _h extends pc{shouldDrawLayer(t){const{operation:e}=t.props;return e.includes("draw")||e.includes("terrain")}}class vh{constructor(t){this.device=t,this.layerFilter=null,this.drawPickingColors=!1,this.drawLayersPass=new _h(t),this.pickLayersPass=new ul(t),this.renderCount=0,this._needsRedraw="Initial render",this.renderBuffers=[],this.lastPostProcessEffect=null}setProps(t){this.layerFilter!==t.layerFilter&&(this.layerFilter=t.layerFilter,this._needsRedraw="layerFilter changed"),this.drawPickingColors!==t.drawPickingColors&&(this.drawPickingColors=t.drawPickingColors,this._needsRedraw="drawPickingColors changed")}renderLayers(t){if(!t.viewports.length)return;const e=this.drawPickingColors?this.pickLayersPass:this.drawLayersPass,n={layerFilter:this.layerFilter,isPicking:this.drawPickingColors,...t};n.effects&&this._preRender(n.effects,n);const i=this.lastPostProcessEffect?this.renderBuffers[0]:n.target;this.lastPostProcessEffect&&(n.clearColor=[0,0,0,0],n.clearCanvas=!0);const s=e.render({...n,target:i});n.effects&&(this.lastPostProcessEffect&&(n.clearCanvas=void 0===t.clearCanvas||t.clearCanvas),this._postRender(n.effects,n)),this.renderCount++,U("deckRenderer.renderLayers",this,s,t)}needsRedraw(t={clearRedrawFlags:!1}){const e=this._needsRedraw;return t.clearRedrawFlags&&(this._needsRedraw=!1),e}finalize(){const{renderBuffers:t}=this;for(const e of t)e.delete();t.length=0}_preRender(t,e){this.lastPostProcessEffect=null,e.preRenderStats=e.preRenderStats||{};for(const n of t)e.preRenderStats[n.id]=n.preRender(e),n.postRender&&(this.lastPostProcessEffect=n.id);this.lastPostProcessEffect&&this._resizeRenderBuffers()}_resizeRenderBuffers(){const{renderBuffers:t}=this,e=this.device.canvasContext.getDrawingBufferSize(),[n,i]=e;0===t.length&&[0,1].map((e=>{const s=this.device.createTexture({sampler:{minFilter:"linear",magFilter:"linear"},width:n,height:i});t.push(this.device.createFramebuffer({id:`deck-renderbuffer-${e}`,colorAttachments:[s]}))}));for(const n of t)n.resize(e)}_postRender(t,e){const{renderBuffers:n}=this,i={...e,inputBuffer:n[0],swapBuffer:n[1]};for(const s of t)if(s.postRender){i.target=s.id===this.lastPostProcessEffect?e.target:void 0;const t=s.postRender(i);i.inputBuffer=t,i.swapBuffer=t===n[0]?n[1]:n[0]}}}const bh={pickedColor:null,pickedObjectIndex:-1};function yh({pickedColors:t,decodePickingColor:e,deviceX:n,deviceY:i,deviceRadius:s,deviceRect:r}){const{x:o,y:a,width:c,height:l}=r;let h=s*s,u=-1,f=0;for(let e=0;e<l;e++){const s=e+a-i,r=s*s;if(r>h)f+=4*c;else for(let e=0;e<c;e++){if(t[f+3]-1>=0){const t=e+o-n,i=t*t+r;i<=h&&(h=i,u=f)}f+=4}}if(u>=0){const n=t.slice(u,u+4),i=e(n);if(i){const t=Math.floor(u/4/c),e=u/4-t*c;return{...i,pickedColor:n,pickedX:o+e,pickedY:a+t}}F.error("Picked non-existent layer. Is picking buffer corrupt?")()}return bh}function wh({pickedColors:t,decodePickingColor:e}){const n=new Map;if(t)for(let i=0;i<t.length;i+=4)if(t[i+3]-1>=0){const s=t.slice(i,i+4),r=s.join(",");if(!n.has(r)){const t=e(s);t?n.set(r,{...t,color:s}):F.error("Picked non-existent layer. Is picking buffer corrupt?")()}}return Array.from(n.values())}function xh({pickInfo:t,viewports:e,pixelRatio:n,x:i,y:s,z:r}){let o,a=e[0];if(e.length>1&&(a=function(t,e){for(let n=t.length-1;n>=0;n--){const i=t[n];if(i.containsPixel(e))return i}return t[0]}(t?.pickedViewports||e,{x:i,y:s})),a){const t=[i-a.x,s-a.y];void 0!==r&&(t[2]=r),o=a.unproject(t)}return{color:null,layer:null,viewport:a,index:-1,picked:!1,x:i,y:s,pixel:[i,s],coordinate:o,devicePixel:t&&"pickedX"in t?[t.pickedX,t.pickedY]:void 0,pixelRatio:n}}function Eh(t){const{pickInfo:e,lastPickedInfo:n,mode:i,layers:s}=t,{pickedColor:r,pickedLayer:o,pickedObjectIndex:a}=e,c=o?[o]:[];if("hover"===i){const t=n.layerId,e=o?o.props.id:null;if(e!==t||a!==n.index){if(e!==t){const e=s.find((e=>e.props.id===t));e&&c.unshift(e)}n.layerId=e,n.index=a,n.info=null}}const l=xh(t),h=new Map;return h.set(null,l),c.forEach((t=>{let e={...l};t===o&&(e.color=r,e.index=a,e.picked=!0),e=Th({layer:t,info:e,mode:i});const s=e.layer;t===o&&"hover"===i&&(n.info=e),h.set(s.id,e),"hover"===i&&s.updateAutoHighlight(e)})),h}function Th({layer:t,info:e,mode:n}){for(;t&&e;){const i=e.layer||null;e.sourceLayer=i,e.layer=t,e=t.getPickingInfo({info:e,mode:n,sourceLayer:i}),t=t.parent}return e}class Ah{constructor(t){this._pickable=!0,this.device=t,this.pickLayersPass=new ul(t),this.lastPickedInfo={index:-1,layerId:null,info:null}}setProps(t){"layerFilter"in t&&(this.layerFilter=t.layerFilter),"_pickable"in t&&(this._pickable=t._pickable)}finalize(){this.pickingFBO&&this.pickingFBO.destroy(),this.depthFBO&&this.depthFBO.destroy()}pickObjectAsync(t){return this._pickClosestObjectAsync(t)}pickObjectsAsync(t){return this._pickVisibleObjectsAsync(t)}pickObject(t){return this._pickClosestObject(t)}pickObjects(t){return this._pickVisibleObjects(t)}getLastPickedObject({x:t,y:e,layers:n,viewports:i},s=this.lastPickedInfo.info){const r=s&&s.layer&&s.layer.id,o=s&&s.viewport&&s.viewport.id,a=r?n.find((t=>t.id===r)):null,c=o&&i.find((t=>t.id===o))||i[0],l=c&&c.unproject([t-c.x,e-c.y]),h={x:t,y:e,viewport:c,coordinate:l,layer:a};return{...s,...h}}_resizeBuffer(){if(!this.pickingFBO&&(this.pickingFBO=this.device.createFramebuffer({colorAttachments:["rgba8unorm"],depthStencilAttachment:"depth16unorm"}),this.device.isTextureFormatRenderable("rgba32float"))){const t=this.device.createFramebuffer({colorAttachments:["rgba32float"],depthStencilAttachment:"depth16unorm"});this.depthFBO=t}const{canvas:t}=this.device.getDefaultCanvasContext();this.pickingFBO?.resize({width:t.width,height:t.height}),this.depthFBO?.resize({width:t.width,height:t.height})}_getPickable(t){if(!1===this._pickable)return null;const e=t.filter((t=>this.pickLayersPass.shouldDrawLayer(t)&&!t.isComposite));return e.length?e:null}async _pickClosestObjectAsync({layers:t,views:e,viewports:n,x:i,y:s,radius:r=0,depth:o=1,mode:a="query",unproject3D:c,onViewportActive:l,effects:h}){const u=this.device.canvasContext.cssToDeviceRatio(),f=this._getPickable(t);if(!f||0===n.length)return{result:[],emptyInfo:xh({viewports:n,x:i,y:s,pixelRatio:u})};this._resizeBuffer();const d=this.device.canvasContext.cssToDevicePixels([i,s],!0),p=[d.x+Math.floor(d.width/2),d.y+Math.floor(d.height/2)],g=Math.round(r*u),{width:m,height:_}=this.pickingFBO,v=this._getPickingRect({deviceX:p[0],deviceY:p[1],deviceRadius:g,deviceWidth:m,deviceHeight:_}),b={x:i-r,y:s-r,width:2*r+1,height:2*r+1};let y;const w=[],x=new Set;for(let t=0;t<o;t++){let r,d;if(r=v?yh({...this._drawAndSample({layers:f,views:e,viewports:n,onViewportActive:l,deviceRect:v,cullRect:b,effects:h,pass:`picking:${a}`}),deviceX:p[0],deviceY:p[1],deviceRadius:g,deviceRect:v}):{pickedColor:null,pickedObjectIndex:-1},r.pickedLayer&&c&&this.depthFBO){const{pickedColors:t}=this._drawAndSample({layers:[r.pickedLayer],views:e,viewports:n,onViewportActive:l,deviceRect:{x:r.pickedX,y:r.pickedY,width:1,height:1},cullRect:b,effects:h,pass:`picking:${a}:z`},!0);t[3]&&(d=t[0])}r.pickedLayer&&t+1<o&&(x.add(r.pickedLayer),r.pickedLayer.disablePickingIndex(r.pickedObjectIndex)),y=Eh({pickInfo:r,lastPickedInfo:this.lastPickedInfo,mode:a,layers:f,viewports:n,x:i,y:s,z:d,pixelRatio:u});for(const t of y.values())t.layer&&w.push(t);if(!r.pickedColor)break}for(const t of x)t.restorePickingColors();return{result:w,emptyInfo:y.get(null)}}_pickClosestObject({layers:t,views:e,viewports:n,x:i,y:s,radius:r=0,depth:o=1,mode:a="query",unproject3D:c,onViewportActive:l,effects:h}){const u=this.device.canvasContext.cssToDeviceRatio(),f=this._getPickable(t);if(!f||0===n.length)return{result:[],emptyInfo:xh({viewports:n,x:i,y:s,pixelRatio:u})};this._resizeBuffer();const d=this.device.canvasContext.cssToDevicePixels([i,s],!0),p=[d.x+Math.floor(d.width/2),d.y+Math.floor(d.height/2)],g=Math.round(r*u),{width:m,height:_}=this.pickingFBO,v=this._getPickingRect({deviceX:p[0],deviceY:p[1],deviceRadius:g,deviceWidth:m,deviceHeight:_}),b={x:i-r,y:s-r,width:2*r+1,height:2*r+1};let y;const w=[],x=new Set;for(let t=0;t<o;t++){let r,d;if(r=v?yh({...this._drawAndSample({layers:f,views:e,viewports:n,onViewportActive:l,deviceRect:v,cullRect:b,effects:h,pass:`picking:${a}`}),deviceX:p[0],deviceY:p[1],deviceRadius:g,deviceRect:v}):{pickedColor:null,pickedObjectIndex:-1},r.pickedLayer&&c&&this.depthFBO){const{pickedColors:t}=this._drawAndSample({layers:[r.pickedLayer],views:e,viewports:n,onViewportActive:l,deviceRect:{x:r.pickedX,y:r.pickedY,width:1,height:1},cullRect:b,effects:h,pass:`picking:${a}:z`},!0);t[3]&&(d=t[0])}r.pickedLayer&&t+1<o&&(x.add(r.pickedLayer),r.pickedLayer.disablePickingIndex(r.pickedObjectIndex)),y=Eh({pickInfo:r,lastPickedInfo:this.lastPickedInfo,mode:a,layers:f,viewports:n,x:i,y:s,z:d,pixelRatio:u});for(const t of y.values())t.layer&&w.push(t);if(!r.pickedColor)break}for(const t of x)t.restorePickingColors();return{result:w,emptyInfo:y.get(null)}}async _pickVisibleObjectsAsync({layers:t,views:e,viewports:n,x:i,y:s,width:r=1,height:o=1,mode:a="query",maxObjects:c=null,onViewportActive:l,effects:h}){const u=this._getPickable(t);if(!u||0===n.length)return[];this._resizeBuffer();const f=this.device.canvasContext.cssToDeviceRatio(),d=this.device.canvasContext.cssToDevicePixels([i,s],!0),p=d.x,g=d.y+d.height,m=this.device.canvasContext.cssToDevicePixels([i+r,s+o],!0),_=m.y,v=wh(this._drawAndSample({layers:u,views:e,viewports:n,onViewportActive:l,deviceRect:{x:p,y:_,width:m.x+m.width-p,height:g-_},cullRect:{x:i,y:s,width:r,height:o},effects:h,pass:`picking:${a}`})),b=new Map,y=[],w=Number.isFinite(c);for(let t=0;t<v.length&&!(w&&y.length>=c);t++){const e=v[t];let n={color:e.pickedColor,layer:null,index:e.pickedObjectIndex,picked:!0,x:i,y:s,pixelRatio:f};n=Th({layer:e.pickedLayer,info:n,mode:a});const r=n.layer.id;b.has(r)||b.set(r,new Set);const o=b.get(r),c=n.object??n.index;o.has(c)||(o.add(c),y.push(n))}return y}_pickVisibleObjects({layers:t,views:e,viewports:n,x:i,y:s,width:r=1,height:o=1,mode:a="query",maxObjects:c=null,onViewportActive:l,effects:h}){const u=this._getPickable(t);if(!u||0===n.length)return[];this._resizeBuffer();const f=this.device.canvasContext.cssToDeviceRatio(),d=this.device.canvasContext.cssToDevicePixels([i,s],!0),p=d.x,g=d.y+d.height,m=this.device.canvasContext.cssToDevicePixels([i+r,s+o],!0),_=m.y,v=wh(this._drawAndSample({layers:u,views:e,viewports:n,onViewportActive:l,deviceRect:{x:p,y:_,width:m.x+m.width-p,height:g-_},cullRect:{x:i,y:s,width:r,height:o},effects:h,pass:`picking:${a}`})),b=new Map,y=[],w=Number.isFinite(c);for(let t=0;t<v.length&&!(w&&y.length>=c);t++){const e=v[t];let n={color:e.pickedColor,layer:null,index:e.pickedObjectIndex,picked:!0,x:i,y:s,pixelRatio:f};n=Th({layer:e.pickedLayer,info:n,mode:a});const r=n.layer.id;b.has(r)||b.set(r,new Set);const o=b.get(r),c=n.object??n.index;o.has(c)||(o.add(c),y.push(n))}return y}async _drawAndSampleAsync({layers:t,views:e,viewports:n,onViewportActive:i,deviceRect:s,cullRect:r,effects:o,pass:a},c=!1){const l=c?this.depthFBO:this.pickingFBO,h={layers:t,layerFilter:this.layerFilter,views:e,viewports:n,onViewportActive:i,pickingFBO:l,deviceRect:s,cullRect:r,effects:o,pass:a,pickZ:c,preRenderStats:{},isPicking:!0};for(const t of o)t.useInPicking&&(h.preRenderStats[t.id]=t.preRender(h));const{decodePickingColor:u}=this.pickLayersPass.render(h),{x:f,y:d,width:p,height:g}=s,m=new(c?Float32Array:Uint8Array)(p*g*4);return this.device.readPixelsToArrayWebGL(l,{sourceX:f,sourceY:d,sourceWidth:p,sourceHeight:g,target:m}),{pickedColors:m,decodePickingColor:u}}_drawAndSample({layers:t,views:e,viewports:n,onViewportActive:i,deviceRect:s,cullRect:r,effects:o,pass:a},c=!1){const l=c?this.depthFBO:this.pickingFBO,h={layers:t,layerFilter:this.layerFilter,views:e,viewports:n,onViewportActive:i,pickingFBO:l,deviceRect:s,cullRect:r,effects:o,pass:a,pickZ:c,preRenderStats:{},isPicking:!0};for(const t of o)t.useInPicking&&(h.preRenderStats[t.id]=t.preRender(h));const{decodePickingColor:u}=this.pickLayersPass.render(h),{x:f,y:d,width:p,height:g}=s,m=new(c?Float32Array:Uint8Array)(p*g*4);return this.device.readPixelsToArrayWebGL(l,{sourceX:f,sourceY:d,sourceWidth:p,sourceHeight:g,target:m}),{pickedColors:m,decodePickingColor:u}}_getPickingRect({deviceX:t,deviceY:e,deviceRadius:n,deviceWidth:i,deviceHeight:s}){const r=Math.max(0,t-n),o=Math.max(0,e-n),a=Math.min(i,t+n+1)-r,c=Math.min(s,e+n+1)-o;return a<=0||c<=0?null:{x:r,y:o,width:a,height:c}}}const Sh={"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}},Ch="top-left",Ph="root";class Mh{constructor({deck:t,parentElement:e}){this.defaultWidgets=[],this.widgets=[],this.resolvedWidgets=[],this.containers={},this.lastViewports={},this.deck=t,e?.classList.add("deck-widget-container"),this.parentElement=e}getWidgets(){return this.resolvedWidgets}setProps(t){if(t.widgets&&!Al(t.widgets,this.widgets,1)){const e=t.widgets.filter(Boolean);this._setWidgets(e)}}finalize(){for(const t of this.getWidgets())this._removeWidget(t);this.defaultWidgets.length=0,this.resolvedWidgets.length=0;for(const t in this.containers)this.containers[t].remove()}addDefault(t){this.defaultWidgets.find((e=>e.id===t.id))||(this._addWidget(t),this.defaultWidgets.push(t),this._setWidgets(this.widgets))}onRedraw({viewports:t,layers:e}){const n=t.reduce(((t,e)=>(t[e.id]=e,t)),{});for(const i of this.getWidgets()){const{viewId:s}=i;if(s){const t=n[s];t&&(i.onViewportChange&&i.onViewportChange(t),i.onRedraw?.({viewports:[t],layers:e}))}else{if(i.onViewportChange)for(const e of t)i.onViewportChange(e);i.onRedraw?.({viewports:t,layers:e})}}this.lastViewports=n,this._updateContainers()}onHover(t,e){for(const n of this.getWidgets()){const{viewId:i}=n;i&&i!==t.viewport?.id||n.onHover?.(t,e)}}onEvent(t,e){const n=Jo[e.type];if(n)for(const i of this.getWidgets()){const{viewId:s}=i;s&&s!==t.viewport?.id||i[n]?.(t,e)}}_setWidgets(t){const e={};for(const t of this.resolvedWidgets)e[t.id]=t;this.resolvedWidgets.length=0;for(const t of this.defaultWidgets)e[t.id]=null,this.resolvedWidgets.push(t);for(let n of t){const t=e[n.id];t?t.viewId!==n.viewId||t.placement!==n.placement?(this._removeWidget(t),this._addWidget(n)):n!==t&&(t.setProps(n.props),n=t):this._addWidget(n),e[n.id]=null,this.resolvedWidgets.push(n)}for(const t in e){const n=e[t];n&&this._removeWidget(n)}this.widgets=t}_addWidget(t){const{viewId:e=null,placement:n=Ch}=t,i=t.props._container??e;t.widgetManager=this,t.deck=this.deck,t.rootElement=t._onAdd({deck:this.deck,viewId:e}),t.rootElement&&this._getContainer(i,n).append(t.rootElement),t.updateHTML()}_removeWidget(t){t.onRemove?.(),t.rootElement&&t.rootElement.remove(),t.rootElement=void 0,t.deck=void 0,t.widgetManager=void 0}_getContainer(t,e){if(t&&"string"!=typeof t)return t;const n=t||Ph;let i=this.containers[n];i||(i=document.createElement("div"),i.style.pointerEvents="none",i.style.position="absolute",i.style.overflow="hidden",this.parentElement?.append(i),this.containers[n]=i);let s=i.querySelector(`.${e}`);return s||(s=globalThis.document.createElement("div"),s.className=e,s.style.position="absolute",s.style.zIndex="2",Object.assign(s.style,Sh[e]),i.append(s)),s}_updateContainers(){const t=this.deck.width,e=this.deck.height;for(const n in this.containers){const i=this.lastViewports[n]||null,s=this.containers[n];n===Ph||i?(s.style.display="block",s.style.left=`${i?i.x:0}px`,s.style.top=`${i?i.y:0}px`,s.style.width=`${i?i.width:t}px`,s.style.height=`${i?i.height:e}px`):s.style.display="none"}}}function Rh(t,e){e&&Object.entries(e).map((([e,n])=>{e.startsWith("--")?t.style.setProperty(e,n):t.style[e]=n}))}function Lh(t,e){e&&Object.keys(e).map((e=>{e.startsWith("--")?t.style.removeProperty(e):t.style[e]=""}))}class Oh{constructor(t){this.viewId=null,this.props={...this.constructor.defaultProps,...t},this.id=this.props.id}setProps(t){const e=this.props,n=this.rootElement;n&&e.className!==t.className&&(e.className&&n.classList.remove(e.className),t.className&&n.classList.add(t.className)),n&&!Al(e.style,t.style,1)&&(Lh(n,e.style),Rh(n,t.style)),Object.assign(this.props,t),this.updateHTML()}updateHTML(){this.rootElement&&this.onRenderHTML(this.rootElement)}onCreateRootElement(){const t=["deck-widget",this.className,this.props.className],e=document.createElement("div");return t.filter((t=>"string"==typeof t&&t.length>0)).forEach((t=>e.classList.add(t))),Rh(e,this.props.style),e}_onAdd(t){return this.onAdd(t)??this.onCreateRootElement()}onAdd(t){}onRemove(){}onViewportChange(t){}onRedraw(t){}onHover(t,e){}onClick(t,e){}onDrag(t,e){}onDragStart(t,e){}onDragEnd(t,e){}}Oh.defaultProps={id:"widget",style:{},_container:null,className:""};const Ih={zIndex:"1",position:"absolute",pointerEvents:"none",color:"#a0a7b4",backgroundColor:"#29323c",padding:"10px",top:"0",left:"0",display:"none"};class kh extends Oh{constructor(t={}){super(t),this.id="default-tooltip",this.placement="fill",this.className="deck-tooltip",this.isVisible=!1,this.setProps(t)}onCreateRootElement(){const t=document.createElement("div");return t.className=this.className,Object.assign(t.style,Ih),t}onRenderHTML(t){}onViewportChange(t){this.isVisible&&t.id===this.lastViewport?.id&&!t.equals(this.lastViewport)&&this.setTooltip(null),this.lastViewport=t}onHover(t){const{deck:e}=this,n=e&&e.props.getTooltip;if(!n)return;const i=n(t);this.setTooltip(i,t.x,t.y)}setTooltip(t,e,n){const i=this.rootElement;if(i){if("string"==typeof t)i.innerText=t;else{if(!t)return this.isVisible=!1,void(i.style.display="none");t.text&&(i.innerText=t.text),t.html&&(i.innerHTML=t.html),t.className&&(i.className=t.className)}this.isVisible=!0,i.style.display="block",i.style.transform=`translate(${e}px, ${n}px)`,t&&"object"==typeof t&&"style"in t&&Object.assign(i.style,t.style)}}}var Dh;kh.defaultProps={...Oh.defaultProps},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"}(Dh||(Dh={}));const Nh={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:{}},Fh=t=>({drawBuffersWEBGL:e=>t.drawBuffers(e),COLOR_ATTACHMENT0_WEBGL:36064,COLOR_ATTACHMENT1_WEBGL:36065,COLOR_ATTACHMENT2_WEBGL:36066,COLOR_ATTACHMENT3_WEBGL:36067}),Bh=t=>({VERTEX_ARRAY_BINDING_OES:34229,createVertexArrayOES:()=>t.createVertexArray(),deleteVertexArrayOES:e=>t.deleteVertexArray(e),isVertexArrayOES:e=>t.isVertexArray(e),bindVertexArrayOES:e=>t.bindVertexArray(e)}),$h=t=>({VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:35070,drawArraysInstancedANGLE:(...e)=>t.drawArraysInstanced(...e),drawElementsInstancedANGLE:(...e)=>t.drawElementsInstanced(...e),vertexAttribDivisorANGLE:(...e)=>t.vertexAttribDivisor(...e)});async function Uh(t){const e=document.getElementsByTagName("head")[0];if(!e)throw new Error("loadScript");const n=document.createElement("script");return n.setAttribute("type","text/javascript"),n.setAttribute("src",t),new Promise(((i,s)=>{n.onload=i,n.onerror=e=>s(new Error(`Unable to load script '${t}': ${e}`)),e.appendChild(n)}))}let zh=null,jh=!1;const Gh={debugSpectorJS:Mt.get("debug-spectorjs"),debugSpectorJSUrl:"https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js",gl:void 0};function Wh(t){return t.luma=t.luma||{},t.luma}function Vh(t,e={}){return e.debugWebGL||e.traceWebGL?function(t,e){if(!globalThis.WebGLDebugUtils)return Mt.warn("webgl-debug not loaded")(),t;const n=Wh(t);if(n.debugContext)return n.debugContext;globalThis.WebGLDebugUtils.init({...Dh,...t});const i=globalThis.WebGLDebugUtils.makeDebugContext(t,Xh.bind(null,e),Zh.bind(null,e));for(const t in Dh)t in i||"number"!=typeof Dh[t]||(i[t]=Dh[t]);class s{}Object.setPrototypeOf(i,Object.getPrototypeOf(t)),Object.setPrototypeOf(s,i);const r=Object.create(s);return n.realContext=t,n.debugContext=r,r.debug=!0,r}(t,e):function(t){const e=Wh(t);return e.realContext?e.realContext:t}(t)}function Hh(t,e){e=Array.from(e).map((t=>void 0===t?"undefined":t));let n=globalThis.WebGLDebugUtils.glFunctionArgsToString(t,e);return n=`${n.slice(0,100)}${n.length>100?"...":""}`,`gl.${t}(${n})`}function Xh(t,e,n,i){i=Array.from(i).map((t=>void 0===t?"undefined":t));const s=globalThis.WebGLDebugUtils.glEnumToString(e),r=globalThis.WebGLDebugUtils.glFunctionArgsToString(n,i);Mt.error(`${s} in gl.${n}(${r})`)()}function Zh(t,e,n){let i="";Mt.level>=1&&(i=Hh(e,n),t.traceWebGL&&Mt.log(1,i)());for(const t of n)void 0===t&&(i=i||Hh(e,n))}const Kh=new class extends ue{type="webgl";constructor(){super(),ae.defaultProps={...ae.defaultProps,...Gh}}enforceWebGL2(t){!function(t=!0){const e=HTMLCanvasElement.prototype;if(!t&&e.originalGetContext)return e.getContext=e.originalGetContext,void(e.originalGetContext=void 0);e.originalGetContext=e.getContext,e.getContext=function(t,e){if("webgl"===t||"experimental-webgl"===t){const t=this.originalGetContext("webgl2",e);return t instanceof HTMLElement&&function(t){t.getExtension("EXT_color_buffer_float");const e={...Nh,WEBGL_disjoint_timer_query:t.getExtension("EXT_disjoint_timer_query_webgl2"),WEBGL_draw_buffers:Fh(t),OES_vertex_array_object:Bh(t),ANGLE_instanced_arrays:$h(t)},n=t.getExtension;t.getExtension=function(i){return n.call(t,i)||(i in e?e[i]:null)};const i=t.getSupportedExtensions;t.getSupportedExtensions=function(){const n=i.apply(t)||[];return n?.concat(Object.keys(e))}}(t),t}return this.originalGetContext(t,e)}}(t)}isSupported(){return"undefined"!=typeof WebGL2RenderingContext}isDeviceHandle(t){return"undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext||("undefined"!=typeof WebGLRenderingContext&&t instanceof WebGLRenderingContext&&Mt.warn("WebGL1 is not supported",t)(),!1)}async attach(t,e={}){const{WebGLDevice:n}=await Promise.resolve().then((function(){return Af}));if(t instanceof n)return t;if(t?.device instanceof n)return t.device;if(!function(t){return"undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext||Boolean(t&&Number.isFinite(t._version))}(t))throw new Error("Invalid WebGL2RenderingContext");const i=!0===e.createCanvasContext?{}:e.createCanvasContext;return new n({...e,_handle:t,createCanvasContext:{canvas:t.canvas,autoResize:!1,...i}})}async create(t={}){const{WebGLDevice:e}=await Promise.resolve().then((function(){return Af}));Mt.groupCollapsed(1,"WebGLDevice created")();try{const n=[];(t.debugWebGL||t.debug)&&n.push(async function(){E()&&!globalThis.WebGLDebugUtils&&(globalThis.global=globalThis.global||globalThis,globalThis.global.module={},await Uh("https://unpkg.com/webgl-debug@2.0.1/index.js"))}()),t.debugSpectorJS&&n.push(async function(t){if(!globalThis.SPECTOR)try{await Uh(t.debugSpectorJSUrl||Gh.debugSpectorJSUrl)}catch(t){Mt.warn(String(t))}}(t));const i=await Promise.allSettled(n);for(const t of i)"rejected"===t.status&&Mt.error(`Failed to initialize debug libraries ${t.reason}`)();const s=new e(t);return Mt.probe(1,`${s._reused?"Reusing":"Created"} device with WebGL2 ${s.props.debug?"debug ":""}context: ${s.info.vendor}, ${s.info.renderer} for canvas: ${s.canvasContext.id}`)(),Mt.table(1,s.info)(),s}finally{Mt.groupEnd(1)()}}},qh={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},Yh=(t,e,n)=>e?t.enable(n):t.disable(n),Jh=(t,e,n)=>t.hint(n,e),Qh=(t,e,n)=>t.pixelStorei(n,e),tu=(t,e,n)=>t.bindFramebuffer(36006===n?36009:36008,e),eu=(t,e,n)=>{t.bindBuffer({34964:34962,36662:36662,36663:36663,35053:35051,35055:35052}[n],e)};function nu(t){return Array.isArray(t)||ArrayBuffer.isView(t)&&!(t instanceof DataView)}const iu={3042:Yh,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:Yh,2885:(t,e)=>t.cullFace(e),2929:Yh,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:Yh,35723:Jh,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:tu,36010:tu,34964:eu,36662:eu,36663:eu,35053:eu,35055:eu,2886:(t,e)=>t.frontFace(e),33170:Jh,2849:(t,e)=>t.lineWidth(e),32823:Yh,32824:"polygonOffset",10752:"polygonOffset",35977:Yh,32926:Yh,32928:Yh,32938:"sampleCoverage",32939:"sampleCoverage",3089:Yh,3088:(t,e)=>t.scissor(...e),2960:Yh,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:Yh,10754:Yh,12288:Yh,12289:Yh,12290:Yh,12291:Yh,12292:Yh,12293:Yh,12294:Yh,12295:Yh,3333:Qh,3317:Qh,37440:Qh,37441:Qh,37443:Qh,3330:Qh,3332:Qh,3331:Qh,3314:Qh,32878:Qh,3316:Qh,3315:Qh,32877:Qh,framebuffer:(t,e)=>t.bindFramebuffer(36160,e&&"handle"in e?e.handle:e),blend:(t,e)=>e?t.enable(3042):t.disable(3042),blendColor:(t,e)=>t.blendColor(...e),blendEquation:(t,e)=>{t.blendEquationSeparate(..."number"==typeof e?[e,e]:e)},blendFunc:(t,e)=>{const n=2===e?.length?[...e,...e]:e;t.blendFuncSeparate(...n)},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=nu(e)?e:[e,e];const[n,i]=e;t.stencilMaskSeparate(1028,n),t.stencilMaskSeparate(1029,i)},stencilFunc:(t,e)=>{e=nu(e)&&3===e.length?[...e,...e]:e;const[n,i,s,r,o,a]=e;t.stencilFuncSeparate(1028,n,i,s),t.stencilFuncSeparate(1029,r,o,a)},stencilOp:(t,e)=>{e=nu(e)&&3===e.length?[...e,...e]:e;const[n,i,s,r,o,a]=e;t.stencilOpSeparate(1028,n,i,s),t.stencilOpSeparate(1029,r,o,a)},viewport:(t,e)=>t.viewport(...e)};function su(t,e,n){return void 0!==e[t]?e[t]:n[t]}const ru={blendEquation:(t,e,n)=>t.blendEquationSeparate(su(32777,e,n),su(34877,e,n)),blendFunc:(t,e,n)=>t.blendFuncSeparate(su(32969,e,n),su(32968,e,n),su(32971,e,n),su(32970,e,n)),polygonOffset:(t,e,n)=>t.polygonOffset(su(32824,e,n),su(10752,e,n)),sampleCoverage:(t,e,n)=>t.sampleCoverage(su(32938,e,n),su(32939,e,n)),stencilFuncFront:(t,e,n)=>t.stencilFuncSeparate(1028,su(2962,e,n),su(2967,e,n),su(2963,e,n)),stencilFuncBack:(t,e,n)=>t.stencilFuncSeparate(1029,su(34816,e,n),su(36003,e,n),su(36004,e,n)),stencilOpFront:(t,e,n)=>t.stencilOpSeparate(1028,su(2964,e,n),su(2965,e,n),su(2966,e,n)),stencilOpBack:(t,e,n)=>t.stencilOpSeparate(1029,su(34817,e,n),su(34818,e,n),su(34819,e,n))},ou={enable:(t,e)=>t({[e]:!0}),disable:(t,e)=>t({[e]:!1}),pixelStorei:(t,e,n)=>t({[e]:n}),hint:(t,e,n)=>t({[e]:n}),useProgram:(t,e)=>t({35725:e}),bindRenderbuffer:(t,e,n)=>t({36007:n}),bindTransformFeedback:(t,e,n)=>t({36389:n}),bindVertexArray:(t,e)=>t({34229:e}),bindFramebuffer:(t,e,n)=>{switch(e){case 36160:return t({36006:n,36010:n});case 36009:return t({36006:n});case 36008:return t({36010:n});default:return null}},bindBuffer:(t,e,n)=>{const i={34962:[34964],36662:[36662],36663:[36663],35051:[35053],35052:[35055]}[e];return i?t({[i]:n}):{valueChanged:!0}},blendColor:(t,e,n,i,s)=>t({32773:new Float32Array([e,n,i,s])}),blendEquation:(t,e)=>t({32777:e,34877:e}),blendEquationSeparate:(t,e,n)=>t({32777:e,34877:n}),blendFunc:(t,e,n)=>t({32969:e,32968:n,32971:e,32970:n}),blendFuncSeparate:(t,e,n,i,s)=>t({32969:e,32968:n,32971:i,32970:s}),clearColor:(t,e,n,i,s)=>t({3106:new Float32Array([e,n,i,s])}),clearDepth:(t,e)=>t({2931:e}),clearStencil:(t,e)=>t({2961:e}),colorMask:(t,e,n,i,s)=>t({3107:[e,n,i,s]}),cullFace:(t,e)=>t({2885:e}),depthFunc:(t,e)=>t({2932:e}),depthRange:(t,e,n)=>t({2928:new Float32Array([e,n])}),depthMask:(t,e)=>t({2930:e}),frontFace:(t,e)=>t({2886:e}),lineWidth:(t,e)=>t({2849:e}),polygonOffset:(t,e,n)=>t({32824:e,10752:n}),sampleCoverage:(t,e,n)=>t({32938:e,32939:n}),scissor:(t,e,n,i,s)=>t({3088:new Int32Array([e,n,i,s])}),stencilMask:(t,e)=>t({2968:e,36005:e}),stencilMaskSeparate:(t,e,n)=>t({[1028===e?2968:36005]:n}),stencilFunc:(t,e,n,i)=>t({2962:e,2967:n,2963:i,34816:e,36003:n,36004:i}),stencilFuncSeparate:(t,e,n,i,s)=>t({[1028===e?2962:34816]:n,[1028===e?2967:36003]:i,[1028===e?2963:36004]:s}),stencilOp:(t,e,n,i)=>t({2964:e,2965:n,2966:i,34817:e,34818:n,34819:i}),stencilOpSeparate:(t,e,n,i,s)=>t({[1028===e?2964:34817]:n,[1028===e?2965:34818]:i,[1028===e?2966:34819]:s}),viewport:(t,e,n,i,s)=>t({2978:[e,n,i,s]})},au=(t,e)=>t.isEnabled(e),cu={3042:au,2884:au,2929:au,3024:au,32823:au,32926:au,32928:au,3089:au,2960:au,35977:au},lu=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 hu(t,e){if(function(t){for(const e in t)return!1;return!0}(e))return;const n={};for(const i in e){const s=Number(i),r=iu[i];r&&("string"==typeof r?n[r]=!0:r(t,e[i],s))}const i=t.state&&t.state.cache;if(i)for(const s in n)(0,ru[s])(t,e,i)}function uu(t,e=qh){if("number"==typeof e){const n=e,i=cu[n];return i?i(t,n):t.getParameter(n)}const n=Array.isArray(e)?e:Object.keys(e),i={};for(const e of n){const n=cu[e];i[e]=n?n(t,Number(e)):t.getParameter(Number(e))}return i}function fu(t,e){if(t===e)return!0;if(du(t)&&du(e)&&t.length===e.length){for(let n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0}return!1}function du(t){return Array.isArray(t)||ArrayBuffer.isView(t)}class pu{static get(t){return t.state}gl;program=null;stateStack=[];enable=!0;cache=null;log;initialized=!1;constructor(t,e){this.gl=t,this.log=e?.log||(()=>{}),this._updateCache=this._updateCache.bind(this),Object.seal(this)}push(t={}){this.stateStack.push({})}pop(){hu(this.gl,this.stateStack[this.stateStack.length-1]),this.stateStack.pop()}trackState(t,e){if(this.cache=e?.copyState?uu(t):Object.assign({},qh),this.initialized)throw new Error("WebGLStateTracker");this.initialized=!0,this.gl.state=this,function(t){const e=t.useProgram.bind(t);t.useProgram=function(n){const i=pu.get(t);i.program!==n&&(e(n),i.program=n)}}(t);for(const e in ou)mu(t,e,ou[e]);gu(t,"getParameter"),gu(t,"isEnabled")}_updateCache(t){let e,n=!1;const i=this.stateStack.length>0?this.stateStack[this.stateStack.length-1]:null;for(const s in t){const r=t[s],o=this.cache[s];fu(r,o)||(n=!0,e=o,i&&!(s in i)&&(i[s]=o),this.cache[s]=r)}return{valueChanged:n,oldValue:e}}}function gu(t,e){const n=t[e].bind(t);t[e]=function(e){if(void 0===e||lu.has(e))return n(e);const i=pu.get(t);return e in i.cache||(i.cache[e]=n(e)),i.enable?i.cache[e]:n(e)},Object.defineProperty(t[e],"name",{value:`${e}-from-cache`,configurable:!1})}function mu(t,e,n){if(!t[e])return;const i=t[e].bind(t);t[e]=function(...e){const s=pu.get(t),{valueChanged:r,oldValue:o}=n(s._updateCache,...e);return r&&i(...e),o},Object.defineProperty(t[e],"name",{value:`${e}-to-cache`,configurable:!1})}function _u(t,e,n){return void 0===n[e]&&(n[e]=t.getExtension(e)||null),n[e]}function vu(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 bu(t){switch(t){case"uint8":case"unorm8":return 5121;case"sint8":case"snorm8":return 5120;case"uint16":case"unorm16":return 5123;case"sint16":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))}const yu="WEBGL_compressed_texture_s3tc",wu="WEBGL_compressed_texture_s3tc_srgb",xu="EXT_texture_compression_rgtc",Eu="EXT_texture_compression_bptc",Tu="EXT_texture_norm16",Au="EXT_render_snorm",Su={"float32-renderable-webgl":["EXT_color_buffer_float"],"float16-renderable-webgl":["EXT_color_buffer_half_float"],"rgb9e5ufloat-renderable-webgl":["WEBGL_render_shared_exponent"],"snorm8-renderable-webgl":[Au],"norm16-renderable-webgl":[Tu],"snorm16-renderable-webgl":[Tu,Au],"float32-filterable":["OES_texture_float_linear"],"float16-filterable-webgl":["OES_texture_half_float_linear"],"texture-filterable-anisotropic-webgl":["EXT_texture_filter_anisotropic"],"texture-blend-float-webgl":["EXT_float_blend"],"texture-compression-bc":[yu,wu,xu,Eu],"texture-compression-bc5-webgl":[xu],"texture-compression-bc7-webgl":[Eu],"texture-compression-etc2":["WEBGL_compressed_texture_etc"],"texture-compression-astc":["WEBGL_compressed_texture_astc"],"texture-compression-etc1-webgl":["WEBGL_compressed_texture_etc1"],"texture-compression-pvrtc-webgl":["WEBGL_compressed_texture_pvrtc"],"texture-compression-atc-webgl":["WEBGL_compressed_texture_atc"]},Cu={r8unorm:{gl:33321,rb:!0},r8snorm:{gl:36756},r8uint:{gl:33330,rb:!0},r8sint:{gl:33329,rb:!0},rg8unorm:{gl:33323,rb:!0},rg8snorm:{gl:36757},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},r16unorm:{gl:33322,rb:!0},r16snorm:{gl:36760},"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},rgba8uint:{gl:36220},rgba8sint:{gl:36238},bgra8unorm:{},"bgra8unorm-srgb":{},rg16uint:{gl:33338},rg16sint:{gl:33337},rg16float:{gl:33327,rb:!0},rg16unorm:{gl:33324},rg16snorm:{gl:36761},r32uint:{gl:33334,rb:!0},r32sint:{gl:33333,rb:!0},r32float:{gl:33326},rgb9e5ufloat:{gl:35901},rg11b10ufloat:{gl:35898,rb:!0},rgb10a2unorm:{gl:32857,rb:!0},rgb10a2uint:{gl:36975,rb:!0},"rgb16unorm-webgl":{gl:32852},"rgb16snorm-webgl":{gl:36762},rg32uint:{gl:33340,rb:!0},rg32sint:{gl:33339,rb:!0},rg32float:{gl:33328,rb:!0},rgba16uint:{gl:36214,rb:!0},rgba16sint:{gl:36232,rb:!0},rgba16float:{gl:34842},rgba16unorm:{gl:32859,rb:!0},rgba16snorm:{gl:36763},"rgb32float-webgl":{gl:34837,x:"EXT_color_buffer_float",dataFormat:6407,types:[5126]},rgba32uint:{gl:36208,rb:!0},rgba32sint:{gl:36226,rb:!0},rgba32float:{gl:34836,rb:!0},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:yu},"bc1-rgb-unorm-srgb-webgl":{gl:35916,x:wu},"bc1-rgba-unorm":{gl:33777,x:yu},"bc1-rgba-unorm-srgb":{gl:35916,x:wu},"bc2-rgba-unorm":{gl:33778,x:yu},"bc2-rgba-unorm-srgb":{gl:35918,x:wu},"bc3-rgba-unorm":{gl:33779,x:yu},"bc3-rgba-unorm-srgb":{gl:35919,x:wu},"bc4-r-unorm":{gl:36283,x:xu},"bc4-r-snorm":{gl:36284,x:xu},"bc5-rg-unorm":{gl:36285,x:xu},"bc5-rg-snorm":{gl:36286,x:xu},"bc6h-rgb-ufloat":{gl:36495,x:Eu},"bc6h-rgb-float":{gl:36494,x:Eu},"bc7-rgba-unorm":{gl:36492,x:Eu},"bc7-rgba-unorm-srgb":{gl:36493,x:Eu},"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:37819},"astc-10x5-unorm-srgb":{gl:37851},"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-rbg2unorm-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}};function Pu(t){const e=Cu[t],n=function(t){const e=Cu[t],n=e?.gl;if(void 0===n)throw new Error(`Unsupported texture format ${t}`);return n}(t),i=ie.getInfo(t);return i.compressed&&(e.dataFormat=n),{internalFormat:n,format:e?.dataFormat||Mu(i.channels,i.integer,i.normalized,n),type:i.dataType?bu(i.dataType):e?.types?.[0]||5121,compressed:i.compressed||!1}}function Mu(t,e,n,i){if(6408===i||6407===i)return i;switch(t){case"r":return e&&!n?36244:6403;case"rg":return e&&!n?33320:33319;case"rgb":return e&&!n?36248:6407;case"rgba":return e&&!n?36249:6408;case"bgra":throw new Error("bgra pixels not supported by WebGL");default:return 6408}}const Ru={"depth-clip-control":"EXT_depth_clamp","timer-query-webgl":"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"};class Lu extends oe{gl;extensions;testedFeatures=new Set;constructor(t,e,n){super([],n),this.gl=t,this.extensions=e,_u(t,"EXT_color_buffer_float",e)}*[Symbol.iterator](){const t=this.getFeatures();for(const e of t)this.has(e)&&(yield e);return[]}has(t){return!this.disabledFeatures?.[t]&&(this.testedFeatures.has(t)||(this.testedFeatures.add(t),function(t){return t in Su}(t)&&function(t,e,n){return(Su[e]||[]).every((e=>_u(t,e,n)))}(this.gl,t,this.extensions)&&this.features.add(t),this.getWebGLFeature(t)&&this.features.add(t)),this.features.has(t))}initializeFeatures(){const t=this.getFeatures().filter((t=>"polygon-mode-webgl"!==t));for(const e of t)this.has(e)}getFeatures(){return[...Object.keys(Ru),...Object.keys(Su)]}getWebGLFeature(t){const e=Ru[t];return"string"==typeof e?Boolean(_u(this.gl,e,this.extensions)):Boolean(e)}}class Ou extends re{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(t){super(),this.gl=t}getParameter(t){return void 0===this.limits[t]&&(this.limits[t]=this.gl.getParameter(t)),this.limits[t]||0}}class Iu extends Se{device;gl;handle;colorAttachments=[];depthStencilAttachment=null;constructor(t,e){super(t,e);const n=null===e.handle;this.device=t,this.gl=t.gl,this.handle=this.props.handle||n?this.props.handle:this.gl.createFramebuffer(),n||(t._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),this.autoCreateAttachmentTextures(),this.updateAttachments())}destroy(){super.destroy(),this.destroyed||null===this.handle||this.gl.deleteFramebuffer(this.handle)}updateAttachments(){const t=this.gl.bindFramebuffer(36160,this.handle);for(let t=0;t<this.colorAttachments.length;++t){const e=this.colorAttachments[t];e&&this._attachTextureView(36064+t,e)}if(this.depthStencilAttachment){const t=function(t){switch(ie.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}`)}}(this.depthStencilAttachment.props.format);this._attachTextureView(t,this.depthStencilAttachment)}if(this.device.props.debug){const t=this.gl.checkFramebufferStatus(36160);if(36053!==t)throw new Error(`Framebuffer ${function(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}`}}(t)}`)}this.gl.bindFramebuffer(36160,t)}_attachTextureView(t,e){const{gl:n}=this.device,{texture:i}=e,s=e.props.baseMipLevel,r=e.props.baseArrayLayer;switch(n.bindTexture(i.glTarget,i.handle),i.glTarget){case 35866:case 32879:n.framebufferTextureLayer(36160,t,i.handle,s,r);break;case 34067:const e=function(t){return t<34069?t+34069:t}(r);n.framebufferTexture2D(36160,t,e,i.handle,s);break;case 3553:n.framebufferTexture2D(36160,t,3553,i.handle,s);break;default:throw new Error("Illegal texture type")}n.bindTexture(i.glTarget,null)}}class ku extends ge{device;handle=null;_framebuffer=null;get[Symbol.toStringTag](){return"WebGLCanvasContext"}constructor(t,e){super(e),this.device=t,this._setAutoCreatedCanvasId(`${this.device.id}-canvas`),this._updateDevice()}getCurrentFramebuffer(){return this._framebuffer=this._framebuffer||new Iu(this.device,{handle:null}),this._framebuffer}_updateDevice(){}}const Du={};function Nu(t="id"){return Du[t]=Du[t]||1,`${t}-${Du[t]++}`}class Fu extends It{device;gl;handle;glTarget;glUsage;glIndexType=5123;byteLength=0;bytesUsed=0;constructor(t,e={}){var n;super(t,e),this.device=t,this.gl=this.device.gl,this.handle=("object"==typeof e?e.handle:void 0)||this.gl.createBuffer(),t._setWebGLDebugMetadata(this.handle,this,{spector:{...this.props,data:typeof this.props.data}}),this.glTarget=(n=this.props.usage)&It.INDEX?34963:n&It.VERTEX?34962:n&It.UNIFORM?35345:34962,this.glUsage=function(t){return t&It.INDEX||t&It.VERTEX?35044:t&It.UNIFORM?35048:35044}(this.props.usage),this.glIndexType="uint32"===this.props.indexType?5125:5123,e.data?this._initWithData(e.data,e.byteOffset,e.byteLength):this._initWithByteLength(e.byteLength||0)}destroy(){!this.destroyed&&this.handle&&(this.removeStats(),this.trackDeallocatedMemory(),this.gl.deleteBuffer(this.handle),this.destroyed=!0,this.handle=null)}_initWithData(t,e=0,n=t.byteLength+e){const i=this.glTarget;this.gl.bindBuffer(i,this.handle),this.gl.bufferData(i,n,this.glUsage),this.gl.bufferSubData(i,e,t),this.gl.bindBuffer(i,null),this.bytesUsed=n,this.byteLength=n,this._setDebugData(t,e,n),this.trackAllocatedMemory(n)}_initWithByteLength(t){let e=t;0===t&&(e=new Float32Array(0));const n=this.glTarget;return this.gl.bindBuffer(n,this.handle),this.gl.bufferData(n,e,this.glUsage),this.gl.bindBuffer(n,null),this.bytesUsed=t,this.byteLength=t,this._setDebugData(null,0,t),this.trackAllocatedMemory(t),this}write(t,e=0){const n=ArrayBuffer.isView(t)?t:new Uint8Array(t),i=36663;this.gl.bindBuffer(i,this.handle),this.gl.bufferSubData(i,e,n),this.gl.bindBuffer(i,null),this._setDebugData(t,e,t.byteLength)}async mapAndWriteAsync(t,e=0,n=this.byteLength-e){const i=new ArrayBuffer(n);await t(i,"copied"),this.write(i,e)}async readAsync(t=0,e){return this.readSyncWebGL(t,e)}async mapAndReadAsync(t,e=0,n){const i=await this.readAsync(e,n);return await t(i.buffer,"copied")}readSyncWebGL(t=0,e){e=e??this.byteLength-t;const n=new Uint8Array(e);return this.gl.bindBuffer(36662,this.handle),this.gl.getBufferSubData(36662,t,n,0,e),this.gl.bindBuffer(36662,null),this._setDebugData(n,t,e),n}}function Bu(t){const e=t.toLowerCase();return["warning","error","info"].includes(e)?e:"info"}class $u extends Te{device;handle;constructor(t,e){switch(super(t,e),this.device=t,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)}t._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),this._compile(this.source)}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(){const t=this.device.gl.getShaderInfoLog(this.handle);return t?function(t){const e=t.split(/\r?\n/),n=[];for(const t of e){if(t.length<=1)continue;const e=t.split(":");if(2===e.length){const[t,i]=e;n.push({message:i.trim(),type:Bu(t),lineNum:0,linePos:0});continue}const[i,s,r,...o]=e;let a=parseInt(r,10);isNaN(a)&&(a=0);let c=parseInt(s,10);isNaN(c)&&(c=0),n.push({message:o.join(":").trim(),type:Bu(i),lineNum:a,linePos:c})}return n}(t):[]}getTranslatedSource(){const t=this.device.getExtension("WEBGL_debug_shaders").WEBGL_debug_shaders;return t?.getTranslatedShaderSource(this.handle)||null}async _compile(t){t=t.startsWith("#version ")?t:`#version 300 es\n${t}`;const{gl:e}=this.device;if(e.shaderSource(this.handle,t),e.compileShader(this.handle),this.device.props.debug){if(this.device.features.has("compilation-status-async-webgl"))Mt.once(1,"Shader compilation is asynchronous")(),await this._waitForCompilationComplete(),Mt.info(2,`Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)(),this._getCompilationStatus(),this.debugShader();else if(this._getCompilationStatus(),this.debugShader(),"error"===this.compilationStatus)throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`)}else this.compilationStatus="pending"}async _waitForCompilationComplete(){const t=async t=>await new Promise((e=>setTimeout(e,t)));if(!this.device.features.has("compilation-status-async-webgl"))return void await t(10);const{gl:e}=this.device;for(;;){if(e.getShaderParameter(this.handle,37297))return;await t(10)}}_getCompilationStatus(){this.compilationStatus=this.device.gl.getShaderParameter(this.handle,35713)?"success":"error"}}function Uu(t,e){return Wu(t,e,{never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519})}function zu(t,e){return Wu(t,e,{keep:7680,zero:0,replace:7681,invert:5386,"increment-clamp":7682,"decrement-clamp":7683,"increment-wrap":34055,"decrement-wrap":34056})}function ju(t,e){return Wu(t,e,{add:32774,subtract:32778,"reverse-subtract":32779,min:32775,max:32776})}function Gu(t,e,n="color"){return Wu(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:"color"===n?32769:32771,"one-minus-constant":"color"===n?32770:32772,src1:768,"one-minus-src1":769,"src1-alpha":770,"one-minus-src1-alpha":771})}function Wu(t,e,n){if(!(e in n))throw new Error(function(t,e){return`Illegal parameter ${e} for ${t}`}(t,e));return n[e]}function Vu(t){const e={};return t.addressModeU&&(e[10242]=Hu(t.addressModeU)),t.addressModeV&&(e[10243]=Hu(t.addressModeV)),t.addressModeW&&(e[32882]=Hu(t.addressModeW)),t.magFilter&&(e[10240]=Xu(t.magFilter)),(t.minFilter||t.mipmapFilter)&&(e[10241]=function(t,e="none"){if(!e)return Xu(t);switch(e){case"none":return Xu(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}}}(t.minFilter||"linear",t.mipmapFilter)),void 0!==t.lodMinClamp&&(e[33082]=t.lodMinClamp),void 0!==t.lodMaxClamp&&(e[33083]=t.lodMaxClamp),"comparison-sampler"===t.type&&(e[34892]=34894),t.compare&&(e[34893]=Uu("compare",t.compare)),t.maxAnisotropy&&(e[34046]=t.maxAnisotropy),e}function Hu(t){switch(t){case"clamp-to-edge":return 33071;case"repeat":return 10497;case"mirror-repeat":return 33648}}function Xu(t){switch(t){case"nearest":return 9728;case"linear":return 9729}}class Zu extends ve{device;handle;parameters;constructor(t,e){super(t,e),this.device=t,this.parameters=Vu(e),this.handle=e.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(t){for(const[e,n]of Object.entries(t)){const t=Number(e);switch(t){case 33082:case 33083:this.device.gl.samplerParameterf(this.handle,t,n);break;default:this.device.gl.samplerParameteri(this.handle,t,n)}}}}function Ku(t,e,n){if(function(t){for(const e in t)return!1;return!0}(e))return n(t);const{nocatch:i=!0}=e,s=pu.get(t);let r;if(s.push(),hu(t,e),i)r=n(t),s.pop();else try{r=n(t)}finally{s.pop()}return r}class qu extends we{device;gl;handle;texture;constructor(t,e){super(t,{...ye.defaultProps,...e}),this.device=t,this.gl=this.device.gl,this.handle=null,this.texture=e.texture}}class Yu extends ye{device;gl;handle;sampler=void 0;view;glTarget;glFormat;glType;glInternalFormat;compressed;_textureUnit=0;constructor(t,e){super(t,e),this.device=t,this.gl=this.device.gl;const n=Pu(this.props.format);this.glTarget=function(t){switch(t){case"1d":break;case"2d":return 3553;case"3d":return 32879;case"cube":return 34067;case"2d-array":return 35866}throw new Error(t)}(this.props.dimension),this.glInternalFormat=n.internalFormat,this.glFormat=n.format,this.glType=n.type,this.compressed=n.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);const{dimension:i,width:s,height:r,depth:o,mipLevels:a,glTarget:c,glInternalFormat:l}=this;switch(i){case"2d":case"cube":this.gl.texStorage2D(c,a,l,s,r);break;case"2d-array":case"3d":this.gl.texStorage3D(c,a,l,s,r,o);break;default:throw new Error(i)}this.gl.bindTexture(this.glTarget,null),this._initializeData(e.data),this.setSampler(this.props.sampler),this.view=new qu(this.device,{...this.props,texture:this}),Object.seal(this)}destroy(){this.handle&&(this.gl.deleteTexture(this.handle),this.removeStats(),this.trackDeallocatedMemory("Texture"),this.destroyed=!0)}createView(t){return new qu(this.device,{...t,texture:this})}setSampler(t={}){super.setSampler(t);const e=Vu(this.sampler.props);this._setSamplerParameters(e)}copyImageData(t){const e=this._normalizeCopyImageDataOptions(t),n=e.data,{width:i,height:s,depth:r}=this,{mipLevel:o=0,byteOffset:a=0,x:c=0,y:l=0,z:h=0}=e,{glFormat:u,glType:f,compressed:d}=this,p=Ju(this.glTarget,this.dimension,h);let g;if(!this.compressed){const{bytesPerPixel:t}=this.device.getTextureFormatInfo(this.format);if(t){if(e.bytesPerRow%t!=0)throw new Error(`bytesPerRow (${e.bytesPerRow}) must be a multiple of bytesPerPixel (${t}) for ${this.format}`);g=e.bytesPerRow/t}}const m=this.compressed?{}:{...void 0!==g?{3314:g}:{},32878:e.rowsPerImage};this.gl.bindTexture(p,this.handle),Ku(this.gl,m,(()=>{switch(this.dimension){case"2d":case"cube":d?this.gl.compressedTexSubImage2D(p,o,c,l,i,s,u,n,a):this.gl.texSubImage2D(p,o,c,l,i,s,u,f,n,a);break;case"2d-array":case"3d":d?this.gl.compressedTexSubImage3D(p,o,c,l,h,i,s,r,u,n,a):this.gl.texSubImage3D(p,o,c,l,h,i,s,r,u,f,n,a)}})),this.gl.bindTexture(p,null)}copyExternalImage(t){const e=this._normalizeCopyExternalImageOptions(t);if(e.sourceX||e.sourceY)throw new Error("WebGL does not support sourceX/sourceY)");const{glFormat:n,glType:i}=this,{image:s,depth:r,mipLevel:o,x:a,y:c,z:l,width:h,height:u}=e,f=Ju(this.glTarget,this.dimension,r),d=e.flipY?{37440:!0}:{};return this.gl.bindTexture(this.glTarget,this.handle),Ku(this.gl,d,(()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(f,o,a,c,h,u,n,i,s);break;case"2d-array":case"3d":this.gl.texSubImage3D(f,o,a,c,l,h,u,r,n,i,s)}})),this.gl.bindTexture(this.glTarget,null),{width:e.width,height:e.height}}generateMipmapsWebGL(t){if(this.device.isTextureFormatRenderable(this.props.format)&&this.device.isTextureFormatFilterable(this.props.format)||(Mt.warn(`${this} is not renderable or filterable, may not be able to generate mipmaps`)(),t?.force))try{this.gl.bindTexture(this.glTarget,this.handle),this.gl.generateMipmap(this.glTarget)}catch(t){Mt.warn(`Error generating mipmap for ${this}: ${t.message}`)()}finally{this.gl.bindTexture(this.glTarget,null)}}_setSamplerParameters(t){Mt.log(2,`${this.id} sampler parameters`,this.device.getGLKeys(t))(),this.gl.bindTexture(this.glTarget,this.handle);for(const[e,n]of Object.entries(t)){const t=Number(e),i=n;switch(t){case 33082:case 33083:this.gl.texParameterf(this.glTarget,t,i);break;case 10240:case 10241:case 10242:case 10243:case 32882:case 34892:case 34893:this.gl.texParameteri(this.glTarget,t,i);break;case 34046:this.device.features.has("texture-filterable-anisotropic-webgl")&&this.gl.texParameteri(this.glTarget,t,i)}}this.gl.bindTexture(this.glTarget,null)}_getActiveUnit(){return this.gl.getParameter(34016)-33984}_bind(t){const{gl:e}=this;return void 0!==t&&(this._textureUnit=t,e.activeTexture(33984+t)),e.bindTexture(this.glTarget,this.handle),t}_unbind(t){const{gl:e}=this;return void 0!==t&&(this._textureUnit=t,e.activeTexture(33984+t)),e.bindTexture(this.glTarget,null),t}}function Ju(t,e,n){return"cube"===e?34069+n:t}function Qu(t){return tf[t]}const tf={5126:"f32",35664:"vec2<f32>",35665:"vec3<f32>",35666:"vec4<f32>",5124:"i32",35667:"vec2<i32>",35668:"vec3<i32>",35669:"vec4<i32>",5125:"u32",36294:"vec2<u32>",36295:"vec3<u32>",36296:"vec4<u32>",35670:"f32",35671:"vec2<f32>",35672:"vec3<f32>",35673:"vec4<f32>",35674:"mat2x2<f32>",35685:"mat2x3<f32>",35686:"mat2x4<f32>",35687:"mat3x2<f32>",35675:"mat3x3<f32>",35688:"mat3x4<f32>",35689:"mat4x2<f32>",35690:"mat4x3<f32>",35676:"mat4x4<f32>"},ef={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"}},nf={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 sf(t){if("]"!==t[t.length-1])return{name:t,length:1,isArray:!1};const e=/([^[]*)(\[[0-9]+\])?/.exec(t);if(!e||e.length<2)throw new Error(`Failed to parse GLSL uniform name ${t}`);return{name:e[1],length:e[2]?1:0,isArray:Boolean(e[2])}}function rf(t,e,n,i){const s=t;let r=i;!0===r&&(r=1),!1===r&&(r=0);const o="number"==typeof r?[r]:r;switch(n){case 35678:case 35680:case 35679:case 35682:case 36289:case 36292:case 36293:case 36298:case 36299:case 36300:case 36303:case 36306:case 36307:case 36308:case 36311:if("number"!=typeof i)throw new Error("samplers must be set to integers");return t.uniform1i(e,i);case 5126:return t.uniform1fv(e,o);case 35664:return t.uniform2fv(e,o);case 35665:return t.uniform3fv(e,o);case 35666:return t.uniform4fv(e,o);case 5124:case 35670:return t.uniform1iv(e,o);case 35667:case 35671:return t.uniform2iv(e,o);case 35668:case 35672:return t.uniform3iv(e,o);case 35669:case 35673:return t.uniform4iv(e,o);case 5125:return s.uniform1uiv(e,o,1);case 36294:return s.uniform2uiv(e,o,2);case 36295:return s.uniform3uiv(e,o,3);case 36296:return s.uniform4uiv(e,o,4);case 35674:return t.uniformMatrix2fv(e,!1,o);case 35675:return t.uniformMatrix3fv(e,!1,o);case 35676:return t.uniformMatrix4fv(e,!1,o);case 35685:return s.uniformMatrix2x3fv(e,!1,o);case 35686:return s.uniformMatrix2x4fv(e,!1,o);case 35687:return s.uniformMatrix3x2fv(e,!1,o);case 35688:return s.uniformMatrix3x4fv(e,!1,o);case 35689:return s.uniformMatrix4x2fv(e,!1,o);case 35690:return s.uniformMatrix4x3fv(e,!1,o)}throw new Error("Illegal uniform")}class of extends Ce{device;handle;vs;fs;introspectedLayout;uniforms={};bindings={};varyings=null;_uniformCount=0;_uniformSetters={};get[Symbol.toStringTag](){return"WEBGLRenderPipeline"}constructor(t,e){super(t,e),this.device=t,this.handle=this.props.handle||this.device.gl.createProgram(),this.device._setWebGLDebugMetadata(this.handle,this,{spector:{id:this.props.id}}),this.vs=e.vs,this.fs=e.fs;const{varyings:n,bufferMode:i=35981}=e;n&&n.length>0&&(this.varyings=n,this.device.gl.transformFeedbackVaryings(this.handle,n,i)),this._linkShaders(),Mt.time(3,`RenderPipeline ${this.id} - shaderLayout introspection`)(),this.introspectedLayout=function(t,e){const n={attributes:[],bindings:[]};n.attributes=function(t,e){const n=[],i=t.getProgramParameter(e,35721);for(let s=0;s<i;s++){const i=t.getActiveAttrib(e,s);if(!i)throw new Error("activeInfo");const{name:r,type:o}=i,a=t.getAttribLocation(e,r);if(a>=0){const t=Qu(o),e=/instance/i.test(r)?"instance":"vertex";n.push({name:r,location:a,stepMode:e,type:t})}}return n.sort(((t,e)=>t.location-e.location)),n}(t,e);const i=function(t,e){const n=(n,i)=>t.getActiveUniformBlockParameter(e,n,i),i=[],s=t.getProgramParameter(e,35382);for(let r=0;r<s;r++){const s={name:t.getActiveUniformBlockName(e,r)||"",location:n(r,35391),byteLength:n(r,35392),vertex:n(r,35396),fragment:n(r,35398),uniformCount:n(r,35394),uniforms:[]},o=n(r,35395)||[],a=t.getActiveUniforms(e,o,35383),c=t.getActiveUniforms(e,o,35384),l=t.getActiveUniforms(e,o,35387),h=t.getActiveUniforms(e,o,35388);for(let n=0;n<s.uniformCount;++n){const i=t.getActiveUniform(e,o[n]);if(!i)throw new Error("activeInfo");const r=Qu(a[n]);s.uniforms.push({name:i.name,format:r,type:a[n],arrayLength:c[n],byteOffset:l[n],byteStride:h[n]})}i.push(s)}return i.sort(((t,e)=>t.location-e.location)),i}(t,e);for(const t of i){const e=t.uniforms.map((t=>({name:t.name,format:t.format,byteOffset:t.byteOffset,byteStride:t.byteStride,arrayLength:t.arrayLength})));n.bindings.push({type:"uniform",name:t.name,group:0,location:t.location,visibility:(t.vertex?1:0)&(t.fragment?2:0),minBindingSize:t.byteLength,uniforms:e})}const s=function(t,e){const n=[],i=t.getProgramParameter(e,35718);for(let s=0;s<i;s++){const i=t.getActiveUniform(e,s);if(!i)throw new Error("activeInfo");const{name:r,size:o,type:a}=i,{name:c,isArray:l}=sf(r);let h=t.getUniformLocation(e,c);const u={location:h,name:c,size:o,type:a,isArray:l};if(n.push(u),u.size>1)for(let i=0;i<u.size;i++){const s=`${c}[${i}]`;h=t.getUniformLocation(e,s);const r={...u,name:s,location:h};n.push(r)}}return n}(t,e);let r=0;for(const t of s)if(Boolean(ef[t.type])){const{viewDimension:e,sampleType:i}=ef[t.type];n.bindings.push({type:"texture",name:t.name,group:0,location:r,viewDimension:e,sampleType:i}),t.textureUnit=r,r+=1}s.length&&(n.uniforms=s);const o=function(t,e){const n=[],i=t.getProgramParameter(e,35971);for(let s=0;s<i;s++){const i=t.getTransformFeedbackVarying(e,s);if(!i)throw new Error("activeInfo");const{name:r,type:o,size:a}=i,c=Qu(o),{type:l,components:h}=Oe(c);n.push({location:s,name:r,type:l,size:a*h})}return n.sort(((t,e)=>t.location-e.location)),n}(t,e);return o?.length&&(n.varyings=o),n}(this.device.gl,this.handle),Mt.timeEnd(3,`RenderPipeline ${this.id} - shaderLayout introspection`)(),this.shaderLayout=e.shaderLayout?function(t,e){const n={...t,attributes:t.attributes.map((t=>({...t})))};for(const t of e?.attributes||[]){const e=n.attributes.find((e=>e.name===t.name));e?(e.type=t.type||e.type,e.stepMode=t.stepMode||e.stepMode):Mt.warn(`shader layout attribute ${t.name} not present in shader`)}return n}(this.introspectedLayout,e.shaderLayout):this.introspectedLayout}destroy(){this.handle&&(this.device.gl.useProgram(null),this.device.gl.deleteProgram(this.handle),this.destroyed=!0,this.handle.destroyed=!0,this.handle=null)}setBindings(t,e){for(const[n,i]of Object.entries(t)){const t=this.shaderLayout.bindings.find((t=>t.name===n))||this.shaderLayout.bindings.find((t=>t.name===`${n}Uniforms`));if(t){switch(i||Mt.warn(`Unsetting binding "${n}" in render pipeline "${this.id}"`)(),t.type){case"uniform":if(!(i instanceof Fu||i.buffer instanceof Fu))throw new Error("buffer value");break;case"texture":if(!(i instanceof qu||i instanceof Yu||i instanceof Iu))throw new Error(`${this} Bad texture binding for ${n}`);break;case"sampler":Mt.warn(`Ignoring sampler ${n}`)();break;default:throw new Error(t.type)}this.bindings[n]=i}else{const t=this.shaderLayout.bindings.map((t=>`"${t.name}"`)).join(", ");e?.disableWarnings||Mt.warn(`No binding "${n}" in render pipeline "${this.id}", expected one of ${t}`,i)()}}}draw(t){const{renderPass:e,parameters:n=this.props.parameters,topology:i=this.props.topology,vertexArray:s,vertexCount:r,instanceCount:o,isInstanced:a=!1,firstVertex:c=0,transformFeedback:l}=t,h=function(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)}}(i),u=Boolean(s.indexBuffer),f=s.indexBuffer?.glIndexType;return"success"!==this.linkStatus?(Mt.info(2,`RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)(),!1):this._areTexturesRenderable()?(this.device.gl.useProgram(this.handle),s.bindBeforeRender(e),l&&l.begin(this.props.topology),this._applyBindings(),this._applyUniforms(),function(t,e,n,i){if(function(t){let e=!0;for(const n in t){e=!1;break}return e}(e))return i(t);const s=t;s.pushState();try{return function(t,e){const n=t,{gl:i}=n;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)}if(e.frontFace&&i.frontFace(Wu("frontFace",e.frontFace,{ccw:2305,cw:2304})),e.unclippedDepth&&t.features.has("depth-clip-control")&&i.enable(34383),void 0!==e.depthBias&&(i.enable(32823),i.polygonOffset(e.depthBias,e.depthBiasSlopeScale||0)),e.provokingVertex&&t.features.has("provoking-vertex-webgl")){const t=n.getExtension("WEBGL_provoking_vertex").WEBGL_provoking_vertex,i=Wu("provokingVertex",e.provokingVertex,{first:36429,last:36430});t?.provokingVertexWEBGL(i)}if((e.polygonMode||e.polygonOffsetLine)&&t.features.has("polygon-mode-webgl")){if(e.polygonMode){const t=n.getExtension("WEBGL_polygon_mode").WEBGL_polygon_mode,i=Wu("polygonMode",e.polygonMode,{fill:6914,line:6913});t?.polygonModeWEBGL(1028,i),t?.polygonModeWEBGL(1029,i)}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)),void 0!==e.depthWriteEnabled&&i.depthMask(e.depthWriteEnabled),e.depthCompare&&("always"!==e.depthCompare?i.enable(2929):i.disable(2929),i.depthFunc(Uu("depthCompare",e.depthCompare))),e.stencilWriteMask){const t=e.stencilWriteMask;i.stencilMaskSeparate(1028,t),i.stencilMaskSeparate(1029,t)}if(e.stencilReadMask&&Mt.warn("stencilReadMask not supported under WebGL"),e.stencilCompare){const t=e.stencilReadMask||4294967295,n=Uu("depthCompare",e.stencilCompare);"always"!==e.stencilCompare?i.enable(2960):i.disable(2960),i.stencilFuncSeparate(1028,n,0,t),i.stencilFuncSeparate(1029,n,0,t)}if(e.stencilPassOperation&&e.stencilFailOperation&&e.stencilDepthFailOperation){const t=zu("stencilPassOperation",e.stencilPassOperation),n=zu("stencilFailOperation",e.stencilFailOperation),s=zu("stencilDepthFailOperation",e.stencilDepthFailOperation);i.stencilOpSeparate(1028,n,s,t),i.stencilOpSeparate(1029,n,s,t)}switch(e.blend){case!0:i.enable(3042);break;case!1:i.disable(3042)}if(e.blendColorOperation||e.blendAlphaOperation){const t=ju("blendColorOperation",e.blendColorOperation||"add"),n=ju("blendAlphaOperation",e.blendAlphaOperation||"add");i.blendEquationSeparate(t,n);const s=Gu("blendColorSrcFactor",e.blendColorSrcFactor||"one"),r=Gu("blendColorDstFactor",e.blendColorDstFactor||"zero"),o=Gu("blendAlphaSrcFactor",e.blendAlphaSrcFactor||"one"),a=Gu("blendAlphaDstFactor",e.blendAlphaDstFactor||"zero");i.blendFuncSeparate(s,r,o,a)}}(t,e),hu(s.gl,n),i(t)}finally{s.popState()}}(this.device,n,e.glParameters,(()=>{u&&a?this.device.gl.drawElementsInstanced(h,r||0,f,c,o||0):u?this.device.gl.drawElements(h,r||0,f,c):a?this.device.gl.drawArraysInstanced(h,c,r||0,o||0):this.device.gl.drawArrays(h,c,r||0),l&&l.end()})),s.unbindAfterRender(e),!0):(Mt.info(2,`RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)(),!1)}async _linkShaders(){const{gl:t}=this.device;if(t.attachShader(this.handle,this.vs.handle),t.attachShader(this.handle,this.fs.handle),Mt.time(4,`linkProgram for ${this.id}`)(),t.linkProgram(this.handle),Mt.timeEnd(4,`linkProgram for ${this.id}`)(),!this.device.features.has("compilation-status-async-webgl")){const t=this._getLinkStatus();return void this._reportLinkStatus(t)}Mt.once(1,"RenderPipeline linking is asynchronous")(),await this._waitForLinkComplete(),Mt.info(2,`RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();const e=this._getLinkStatus();this._reportLinkStatus(e)}async _reportLinkStatus(t){if("success"!==t){const e="link-error"===t?"Link error":"Validation error";switch(this.vs.compilationStatus){case"error":throw this.vs.debugShader(),new Error(`${this} ${e} during compilation of ${this.vs}`);case"pending":await this.vs.asyncCompilationStatus,this.vs.debugShader()}switch(this.fs?.compilationStatus){case"error":throw this.fs.debugShader(),new Error(`${this} ${e} during compilation of ${this.fs}`);case"pending":await this.fs.asyncCompilationStatus,this.fs.debugShader()}const n=this.device.gl.getProgramInfoLog(this.handle);this.device.reportError(new Error(`${e} during ${t}: ${n}`),this)(),this.device.debug()}}_getLinkStatus(){const{gl:t}=this.device;return t.getProgramParameter(this.handle,35714)?(t.validateProgram(this.handle),t.getProgramParameter(this.handle,35715)?(this.linkStatus="success","success"):(this.linkStatus="error","validation-error")):(this.linkStatus="error","link-error")}async _waitForLinkComplete(){const t=async t=>await new Promise((e=>setTimeout(e,t)));if(!this.device.features.has("compilation-status-async-webgl"))return void await t(10);const{gl:e}=this.device;for(;;){if(e.getProgramParameter(this.handle,37297))return;await t(10)}}_areTexturesRenderable(){let t=!0;for(const e of this.shaderLayout.bindings)this.bindings[e.name]||this.bindings[e.name.replace(/Uniforms$/,"")]||(Mt.warn(`Binding ${e.name} not found in ${this.id}`)(),t=!1);return t}_applyBindings(){if("success"!==this.linkStatus)return;const{gl:t}=this.device;t.useProgram(this.handle);let e=0,n=0;for(const i of this.shaderLayout.bindings){const s=this.bindings[i.name]||this.bindings[i.name.replace(/Uniforms$/,"")];if(!s)throw new Error(`No value for binding ${i.name} in ${this.id}`);switch(i.type){case"uniform":const{name:r}=i,o=t.getUniformBlockIndex(this.handle,r);if(4294967295===o)throw new Error(`Invalid uniform block name ${r}`);t.uniformBlockBinding(this.handle,n,o),s instanceof Fu?t.bindBufferBase(35345,n,s.handle):t.bindBufferRange(35345,n,s.buffer.handle,s.offset||0,s.size||s.buffer.byteLength-s.offset),n+=1;break;case"texture":if(!(s instanceof qu||s instanceof Yu||s instanceof Iu))throw new Error("texture");let a;if(s instanceof qu)a=s.texture;else if(s instanceof Yu)a=s;else{if(!(s instanceof Iu&&s.colorAttachments[0]instanceof qu))throw new Error("No texture");Mt.warn("Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead")(),a=s.colorAttachments[0].texture}t.activeTexture(33984+e),t.bindTexture(a.glTarget,a.handle),e+=1;break;case"sampler":break;case"storage":case"read-only-storage":throw new Error(`binding type '${i.type}' not supported in WebGL`)}}}_applyUniforms(){for(const t of this.shaderLayout.uniforms||[]){const{name:e,location:n,type:i,textureUnit:s}=t,r=this.uniforms[e]??s;void 0!==r&&rf(this.device.gl,n,i,r)}}}class af extends Le{device;handle=null;commands=[];constructor(t){super(t,{}),this.device=t}_executeCommands(t=this.commands){for(const e of t)switch(e.name){case"copy-buffer-to-buffer":cf(this.device,e.options);break;case"copy-buffer-to-texture":lf();break;case"copy-texture-to-buffer":hf(this.device,e.options);break;case"copy-texture-to-texture":uf(this.device,e.options);break;default:throw new Error(e.name)}}}function cf(t,e){const n=e.destinationBuffer;t.gl.bindBuffer(36662,e.sourceBuffer.handle),t.gl.bindBuffer(36663,n.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 lf(){throw new Error("Not implemented")}function hf(t,e){const{sourceTexture:n,mipLevel:i=0,aspect:s="all",width:r=e.sourceTexture.width,height:o=e.sourceTexture.height,depthOrArrayLayers:a=0,origin:c=[0,0],destinationBuffer:l,byteOffset:h=0,bytesPerRow:u,rowsPerImage:f}=e;if("all"!==s)throw new Error("aspect not supported in WebGL");if(0!==i||0!==a||u||f)throw new Error("not implemented");const{framebuffer:d,destroyFramebuffer:p}=ff(n);let g;try{const e=l,n=r||d.width,i=o||d.height,s=Pu(d.colorAttachments[0].texture.props.format),a=s.format,u=s.type;t.gl.bindBuffer(35051,e.handle),g=t.gl.bindFramebuffer(36160,d.handle),t.gl.readPixels(c[0],c[1],n,i,a,u,h)}finally{t.gl.bindBuffer(35051,null),void 0!==g&&t.gl.bindFramebuffer(36160,g),p&&d.destroy()}}function uf(t,e){const{sourceTexture:n,destinationMipLevel:i=0,origin:s=[0,0],destinationOrigin:r=[0,0],destinationTexture:o}=e;let{width:a=e.destinationTexture.width,height:c=e.destinationTexture.height}=e;const{framebuffer:l,destroyFramebuffer:h}=ff(n),[u,f]=s,[d,p,g]=r,m=t.gl.bindFramebuffer(36160,l.handle);let _,v;if(!(o instanceof Yu))throw new Error("invalid destination");switch(_=o,a=Number.isFinite(a)?a:_.width,c=Number.isFinite(c)?c:_.height,_._bind(0),v=_.glTarget,v){case 3553:case 34067:t.gl.copyTexSubImage2D(v,i,d,p,u,f,a,c);break;case 35866:case 32879:t.gl.copyTexSubImage3D(v,i,d,p,g,u,f,a,c)}_&&_._unbind(),t.gl.bindFramebuffer(36160,m),h&&l.destroy()}function ff(t){if(t instanceof ye){const{width:e,height:n,id:i}=t;return{framebuffer:t.device.createFramebuffer({id:`framebuffer-for-${i}`,width:e,height:n,colorAttachments:[t]}),destroyFramebuffer:!0}}return{framebuffer:t,destroyFramebuffer:!1}}const df=[1,2,4,8];class pf extends Pe{device;handle=null;glParameters={};constructor(t,e){let n;if(super(t,e),this.device=t,!e?.parameters?.viewport)if(e?.framebuffer){const{width:t,height:i}=e.framebuffer;n=[0,0,t,i]}else{const[e,i]=t.getDefaultCanvasContext().getDrawingBufferSize();n=[0,0,e,i]}this.device.pushState(),this.setParameters({viewport:n,...this.props.parameters});const i=this.props.framebuffer;if(this.props.framebuffer&&i?.handle){const t=this.props.framebuffer.colorAttachments.map(((t,e)=>36064+e));this.device.gl.drawBuffers(t)}else this.device.gl.drawBuffers([1029]);this.clear()}end(){this.device.popState()}pushDebugGroup(t){}popDebugGroup(){}insertDebugMarker(t){}setParameters(t={}){const e={...this.glParameters};e.framebuffer=this.props.framebuffer||null,this.props.depthReadOnly&&(e.depthMask=!this.props.depthReadOnly),e.stencilMask=this.props.stencilReadOnly?0:1,e[35977]=this.props.discard,t.viewport&&(t.viewport.length>=6?(e.viewport=t.viewport.slice(0,4),e.depthRange=[t.viewport[4],t.viewport[5]]):e.viewport=t.viewport),t.scissorRect&&(e.scissorTest=!0,e.scissor=t.scissorRect),t.blendConstant&&(e.blendColor=t.blendConstant),t.stencilReference&&(console.warn("RenderPassParameters.stencilReference not yet implemented in WebGL"),e[2967]=t.stencilReference),"colorMask"in t&&(e.colorMask=df.map((e=>Boolean(e&t.colorMask)))),this.glParameters=e,hu(this.device.gl,e)}beginOcclusionQuery(t){const e=this.props.occlusionQuerySet;e?.beginOcclusionQuery()}endOcclusionQuery(){const t=this.props.occlusionQuerySet;t?.endOcclusionQuery()}clear(){const t={...this.glParameters};let e=0;this.props.clearColors&&this.props.clearColors.forEach(((t,e)=>{t&&this.clearColorBuffer(e,t)})),!1!==this.props.clearColor&&void 0===this.props.clearColors&&(e|=16384,t.clearColor=this.props.clearColor),!1!==this.props.clearDepth&&(e|=256,t.clearDepth=this.props.clearDepth),!1!==this.props.clearStencil&&(e|=1024,t.clearStencil=this.props.clearStencil),0!==e&&Ku(this.device.gl,t,(()=>{this.device.gl.clear(e)}))}clearColorBuffer(t=0,e=[0,0,0,0]){Ku(this.device.gl,{framebuffer:this.props.framebuffer},(()=>{switch(e.constructor){case Int8Array:case Int16Array:case Int32Array:this.device.gl.clearBufferiv(6144,t,e);break;case Uint8Array:case Uint8ClampedArray:case Uint16Array:case Uint32Array:this.device.gl.clearBufferuiv(6144,t,e);break;case Float32Array:this.device.gl.clearBufferfv(6144,t,e);break;default:throw new Error("clearColorBuffer: color must be typed array")}}))}}class gf extends Re{device;handle=null;commandBuffer;constructor(t,e){super(t,e),this.device=t,this.commandBuffer=new af(t)}destroy(){}finish(){return this.commandBuffer}beginRenderPass(t){return new pf(this.device,t)}beginComputePass(t){throw new Error("ComputePass not supported in WebGL")}copyBufferToBuffer(t){this.commandBuffer.commands.push({name:"copy-buffer-to-buffer",options:t})}copyBufferToTexture(t){this.commandBuffer.commands.push({name:"copy-buffer-to-texture",options:t})}copyTextureToBuffer(t){this.commandBuffer.commands.push({name:"copy-texture-to-buffer",options:t})}copyTextureToTexture(t){this.commandBuffer.commands.push({name:"copy-texture-to-texture",options:t})}pushDebugGroup(t){}popDebugGroup(){}insertDebugMarker(t){}resolveQuerySet(t,e,n){}}class mf extends $e{get[Symbol.toStringTag](){return"VertexArray"}device;handle;buffer=null;bufferValue=null;static isConstantAttributeZeroSupported(t){return"Chrome"==(E()?x()?"Electron":(w.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown":"Node")}constructor(t,e){super(t,e),this.device=t,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(t){const e=t;if(e&&34963!==e.glTarget)throw new Error("Use .setBuffer()");this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34963,e?e.handle:null),this.indexBuffer=e,this.device.gl.bindVertexArray(null)}setBuffer(t,e){const n=e;if(34963===n.glTarget)throw new Error("Use .setIndexBuffer()");const{size:i,type:s,stride:r,offset:o,normalized:a,integer:c,divisor:l}=this._getAccessor(t);this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34962,n.handle),c?this.device.gl.vertexAttribIPointer(t,i,s,r,o):this.device.gl.vertexAttribPointer(t,i,s,a,r,o),this.device.gl.bindBuffer(34962,null),this.device.gl.enableVertexAttribArray(t),this.device.gl.vertexAttribDivisor(t,l||0),this.attributes[t]=n,this.device.gl.bindVertexArray(null)}setConstantWebGL(t,e){this._enable(t,!1),this.attributes[t]=e}bindBeforeRender(){this.device.gl.bindVertexArray(this.handle),this._applyConstantAttributes()}unbindAfterRender(){this.device.gl.bindVertexArray(null)}_applyConstantAttributes(){for(let t=0;t<this.maxVertexAttributes;++t){const e=this.attributes[t];ArrayBuffer.isView(e)&&this.device.setConstantAttributeWebGL(t,e)}}_getAccessor(t){const e=this.attributeInfos[t];if(!e)throw new Error(`Unknown attribute location ${t}`);const n=bu(e.bufferDataType);return{size:e.bufferComponents,type:n,stride:e.byteStride,offset:e.byteOffset,normalized:e.normalized,integer:e.integer,divisor:"instance"===e.stepMode?1:0}}_enable(t,e=!0){const n=mf.isConstantAttributeZeroSupported(this.device);(e||n||0!==t)&&(t=Number(t),this.device.gl.bindVertexArray(this.handle),e?this.device.gl.enableVertexAttribArray(t):this.device.gl.disableVertexAttribArray(t),this.device.gl.bindVertexArray(null))}getConstantBuffer(t,e){const n=(r=e,Array.isArray(r)?new Float32Array(r):r),i=n.byteLength*t,s=n.length*t;var r;if(this.buffer&&i!==this.buffer.byteLength)throw new Error(`Buffer size is immutable, byte length ${i} !== ${this.buffer.byteLength}.`);let o=!this.buffer;if(this.buffer=this.buffer||this.device.createBuffer({byteLength:i}),o||=!function(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0}(n,this.bufferValue),o){const t=function(t,e){return new t(Ge(t.BYTES_PER_ELEMENT*e),0,e)}(e.constructor,s);!function(t){const{target:e,source:n,start:i=0,count:s=1}=t,r=n.length,o=s*r;let a=0;for(let t=i;a<r;a++)e[t++]=n[a];for(;a<o;)a<o-a?(e.copyWithin(i+a,i,i+a),a*=2):(e.copyWithin(i+a,i,i+o-a),a=o)}({target:t,source:n,start:0,count:s}),this.buffer.write(t),this.bufferValue=e}return this.buffer}}class _f extends Ue{device;gl;handle;layout;buffers={};unusedBuffers={};bindOnUse=!0;_bound=!1;constructor(t,e){super(t,e),this.device=t,this.gl=t.gl,this.handle=this.props.handle||this.gl.createTransformFeedback(),this.layout=this.props.layout,e.buffers&&this.setBuffers(e.buffers),Object.seal(this)}destroy(){this.gl.deleteTransformFeedback(this.handle),super.destroy()}begin(t="point-list"){this.gl.bindTransformFeedback(36386,this.handle),this.bindOnUse&&this._bindBuffers(),this.gl.beginTransformFeedback(function(t){switch(t){case"point-list":return 0;case"line-list":case"line-strip":return 1;case"triangle-list":case"triangle-strip":return 4;default:throw new Error(t)}}(t))}end(){this.gl.endTransformFeedback(),this.bindOnUse&&this._unbindBuffers(),this.gl.bindTransformFeedback(36386,null)}setBuffers(t){this.buffers={},this.unusedBuffers={},this.bind((()=>{for(const e in t)this.setBuffer(e,t[e])}))}setBuffer(t,e){const n=this._getVaryingIndex(t),{buffer:i,byteLength:s,byteOffset:r}=this._getBufferRange(e);if(n<0)return this.unusedBuffers[t]=i,void Mt.warn(`${this.id} unusedBuffers varying buffer ${t}`)();this.buffers[n]={buffer:i,byteLength:s,byteOffset:r},this.bindOnUse||this._bindBuffer(n,i,r,s)}getBuffer(t){if(vf(t))return this.buffers[t]||null;const e=this._getVaryingIndex(t);return e>=0?this.buffers[e]:null}bind(t=this.handle){if("function"!=typeof t)return this.gl.bindTransformFeedback(36386,t),this;let e;return this._bound?e=t():(this.gl.bindTransformFeedback(36386,this.handle),this._bound=!0,e=t(),this._bound=!1,this.gl.bindTransformFeedback(36386,null)),e}unbind(){this.bind(null)}_getBufferRange(t){if(t instanceof Fu)return{buffer:t,byteOffset:0,byteLength:t.byteLength};const{buffer:e,byteOffset:n=0,byteLength:i=t.buffer.byteLength}=t;return{buffer:e,byteOffset:n,byteLength:i}}_getVaryingIndex(t){if(vf(t))return Number(t);for(const e of this.layout.varyings||[])if(t===e.name)return e.location;return-1}_bindBuffers(){for(const t in this.buffers){const{buffer:e,byteLength:n,byteOffset:i}=this._getBufferRange(this.buffers[t]);this._bindBuffer(Number(t),e,i,n)}}_unbindBuffers(){for(const t in this.buffers)this.gl.bindBufferBase(35982,Number(t),null)}_bindBuffer(t,e,n=0,i){const s=e&&e.handle;s&&void 0!==i?this.gl.bindBufferRange(35982,t,s,n,i):this.gl.bindBufferBase(35982,t,s)}}function vf(t){return"number"==typeof t?Number.isInteger(t):/^\d+$/.test(t)}class bf extends ze{device;handle;target=null;_queryPending=!1;_pollingPromise=null;get[Symbol.toStringTag](){return"Query"}constructor(t,e){if(super(t,e),this.device=t,e.count>1)throw new Error("WebGL QuerySet can only have one value");const n=this.device.gl.createQuery();if(!n)throw new Error("WebGL query not supported");this.handle=n,Object.seal(this)}destroy(){this.device.gl.deleteQuery(this.handle)}beginTimestampQuery(){return this._begin(35007)}endTimestampQuery(){this._end()}beginOcclusionQuery(t){return this._begin(t?.conservative?36202:35887)}endOcclusionQuery(){this._end()}beginTransformFeedbackQuery(){return this._begin(35976)}endTransformFeedbackQuery(){this._end()}async resolveQuery(){return[await this.pollQuery()]}_begin(t){this._queryPending||(this.target=t,this.device.gl.beginQuery(this.target,this.handle))}_end(){this._queryPending||this.target&&(this.device.gl.endQuery(this.target),this.target=null,this._queryPending=!0)}isResultAvailable(){if(!this._queryPending)return!1;const t=this.device.gl.getQueryParameter(this.handle,34919);return t&&(this._queryPending=!1),t}isTimerDisjoint(){return this.device.gl.getParameter(36795)}getResult(){return this.device.gl.getQueryParameter(this.handle,34918)}getTimerMilliseconds(){return this.getResult()/1e6}pollQuery(t=Number.POSITIVE_INFINITY){if(this._pollingPromise)return this._pollingPromise;let e=0;return this._pollingPromise=new Promise(((n,i)=>{const s=()=>{this.isResultAvailable()?(n(this.getResult()),this._pollingPromise=null):e++>t?(i("Timed out"),this._pollingPromise=null):requestAnimationFrame(s)};requestAnimationFrame(s)})),this._pollingPromise}}function yf(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}}const wf={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 xf(t){return t instanceof Se?{framebuffer:t,deleteFramebuffer:!1}:{framebuffer:Ef(t),deleteFramebuffer:!0}}function Ef(t,e){const{device:n,width:i,height:s,id:r}=t;return n.createFramebuffer({...e,id:`framebuffer-for-${r}`,width:i,height:s,colorAttachments:[t]})}class Tf extends ae{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(t){return"unorm8x4-bgra"!==t}constructor(t){super({...t,id:t.id||Nu("webgl-device")});const e=ae._getCanvasContextProps(t);if(!e)throw new Error("WebGLDevice requires props.createCanvasContext to be set");let n=e.canvas?.gl?.device;if(n)throw new Error(`WebGL context already attached to device ${n.id}`);this.canvasContext=new ku(this,e),this.lost=new Promise((t=>{this._resolveContextLost=t}));const i={...t.webgl};"premultiplied"===e.alphaMode&&(i.premultipliedAlpha=!0),void 0!==t.powerPreference&&(i.powerPreference=t.powerPreference);const s=this.props._handle||function(t,e,n){let i="";const s={preserveDrawingBuffer:!0,...n};let r=null;if(r||=t.getContext("webgl2",s),s.failIfMajorPerformanceCaveat&&(i||="Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow."),r||n.failIfMajorPerformanceCaveat||(s.failIfMajorPerformanceCaveat=!1,r=t.getContext("webgl2",s),r.luma||={},r.luma.softwareRenderer=!0),r||(r=t.getContext("webgl",{}),r&&(r=null,i||="Your browser only supports WebGL1")),!r)throw i||="Your browser does not support WebGL",new Error(`Failed to create WebGL context: ${i}`);const{onContextLost:o,onContextRestored:a}=e;return t.addEventListener("webglcontextlost",(t=>o(t)),!1),t.addEventListener("webglcontextrestored",(t=>a(t)),!1),r.luma||={},r}(this.canvasContext.canvas,{onContextLost:()=>this._resolveContextLost?.({reason:"destroyed",message:"Entered sleep mode, or too many apps or browser tabs are using the GPU."}),onContextRestored:()=>console.log("WebGL context restored")},i);if(!s)throw new Error("WebGL context creation failed");if(n=s.device,n){if(t._reuseDevices)return Mt.log(1,`Not creating a new Device, instead returning a reference to Device ${n.id} already attached to WebGL context`,n)(),n._reused=!0,n;throw new Error(`WebGL context already attached to device ${n.id}`)}this.handle=s,this.gl=s,this.spectorJS=function(t){if(!(t={...Gh,...t}).debugSpectorJS)return null;if(!zh&&globalThis.SPECTOR&&!globalThis.luma?.spector){Mt.probe(1,"SPECTOR found and initialized. Start with `luma.spector.displayUI()`")();const{Spector:t}=globalThis.SPECTOR;zh=new t,globalThis.luma&&(globalThis.luma.spector=zh)}if(!zh)return null;if(jh||(jh=!0,zh.spyCanvases(),zh?.onCaptureStarted.add((t=>Mt.info("Spector capture started:",t)())),zh?.onCapture.add((t=>{Mt.info("Spector capture complete:",t)(),zh?.getResultUI(),zh?.resultView.display(),zh?.resultView.addCapture(t)}))),t.gl){const e=t.gl,n=e.device;zh?.startCapture(t.gl,500),e.device=n,new Promise((t=>setTimeout(t,2e3))).then((()=>{Mt.info("Spector capture stopped after 2 seconds")(),zh?.stopCapture()}))}return zh}({...this.props,gl:this.handle}),this.gl.device=this,this.gl._version=2,this.info=function(t,e){const n=t.getParameter(7936),i=t.getParameter(7937);_u(t,"WEBGL_debug_renderer_info",e);const s=e.WEBGL_debug_renderer_info,r=t.getParameter(s?s.UNMASKED_VENDOR_WEBGL:7936)||n,o=t.getParameter(s?s.UNMASKED_RENDERER_WEBGL:7937)||i,a=t.getParameter(7938),c=vu(r,o),l=function(t,e){return/Metal/i.exec(t)||/Metal/i.exec(e)?"metal":/ANGLE/i.exec(t)||/ANGLE/i.exec(e)?"opengl":"unknown"}(r,o),h=function(t,e){if(/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e))return"cpu";switch(vu(t,e)){case"intel":return"integrated";case"software":return"cpu";case"unknown":return"unknown";default:return"discrete"}}(r,o);return{type:"webgl",gpu:c,gpuType:h,gpuBackend:l,vendor:r,renderer:o,version:a,shadingLanguage:"glsl",shadingLanguageVersion:300}}(this.gl,this._extensions),this.limits=new Ou(this.gl),this.features=new Lu(this.gl,this._extensions,this.props._disabledFeatures),this.props._initializeFeatures&&this.features.initializeFeatures(),new pu(this.gl,{log:(...t)=>Mt.log(1,...t)()}).trackState(this.gl,{copyState:!1});const r=t.debugWebGL||t.debug;r&&(this.gl=Vh(this.gl,{debugWebGL:r,traceWebGL:t.debugWebGL}),Mt.warn("WebGL debug mode activated. Performance reduced.")(),t.debugWebGL&&(Mt.level=Math.max(Mt.level,1))),this.commandEncoder=new gf(this,{id:`${this}-command-encoder`})}destroy(){this.props._reuseDevices||this._reused||delete this.gl.device}get isLost(){return this.gl.isContextLost()}getTextureByteAlignment(){return 4}createCanvasContext(t){throw new Error("WebGL only supports a single canvas")}createBuffer(t){const e=this._normalizeBufferProps(t);return new Fu(this,e)}createTexture(t){return new Yu(this,t)}createExternalTexture(t){throw new Error("createExternalTexture() not implemented")}createSampler(t){return new Zu(this,t)}createShader(t){return new $u(this,t)}createFramebuffer(t){return new Iu(this,t)}createVertexArray(t){return new mf(this,t)}createTransformFeedback(t){return new _f(this,t)}createQuerySet(t){return new bf(this,t)}createRenderPipeline(t){return new of(this,t)}createComputePipeline(t){throw new Error("ComputePipeline not supported in WebGL")}createCommandEncoder(t={}){return new gf(this,t)}submit(t){t||(t=this.commandEncoder.finish(),this.commandEncoder.destroy(),this.commandEncoder=this.createCommandEncoder({id:`${this.id}-default-encoder`})),t._executeCommands()}readPixelsToArrayWebGL(t,e){return function(t,e){const{sourceX:n=0,sourceY:i=0,sourceAttachment:s=0}=e||{};let{target:r=null,sourceWidth:o,sourceHeight:a,sourceFormat:c,sourceType:l}=e||{};const{framebuffer:h,deleteFramebuffer:u}=xf(t),{gl:f,handle:d}=h;o||=h.width,a||=h.height;const p=h.colorAttachments[s]?.texture;if(!p)throw new Error(`Invalid framebuffer attachment ${s}`);c||=p?.glFormat||6408,l||=p?.glType||5121,g=r,m=l,_=c,v=o,b=a,r=g||(m||=5121,new(Ft(wf[m]))(v*b*yf(_)));var g,m,_,v,b;const y=Nt(r);l=l||nf[y];const w=f.bindFramebuffer(36160,d);return f.readBuffer(36064+s),f.readPixels(n,i,o,a,c,l,r),f.readBuffer(36064),f.bindFramebuffer(36160,w||null),u&&h.destroy(),r}(t,e)}readPixelsToBufferWebGL(t,e){return function(t,e){const{target:n,sourceX:i=0,sourceY:s=0,sourceFormat:r=6408,targetByteOffset:o=0}=e||{};let{sourceWidth:a,sourceHeight:c,sourceType:l}=e||{};const{framebuffer:h,deleteFramebuffer:u}=xf(t);a=a||h.width,c=c||h.height;const f=h;l=l||5121;let d=n;if(!d){const t=yf(r),e=function(t){switch(t){case 5121:return 1;case 33635:case 32819:case 32820:return 2;case 5126:return 4;default:return 0}}(l);d=f.device.createBuffer({byteLength:o+a*c*t*e})}const p=t.device.createCommandEncoder();return p.copyTextureToBuffer({sourceTexture:t,width:a,height:c,origin:[i,s],destinationBuffer:d,byteOffset:o}),p.destroy(),u&&h.destroy(),d}(t,e)}setParametersWebGL(t){hu(this.gl,t)}getParametersWebGL(t){return uu(this.gl,t)}withParametersWebGL(t,e){return Ku(this.gl,t,e)}resetWebGL(){Mt.warn("WebGLDevice.resetWebGL is deprecated, use only for debugging")(),hu(this.gl,qh)}_getDeviceSpecificTextureFormatCapabilities(t){return function(t,e,n){let i=e.create;const s=Cu[e.format];return void 0===s?.gl&&(i=!1),s?.x&&(i=i&&Boolean(_u(t,s.x,n))),{format:e.format,create:i&&e.create,render:i&&e.render,filter:i&&e.filter,blend:i&&e.blend,store:i&&e.store}}(this.gl,t,this._extensions)}loseDevice(){let t=!1;const e=this.getExtension("WEBGL_lose_context").WEBGL_lose_context;return e&&(t=!0,e.loseContext()),this._resolveContextLost?.({reason:"destroyed",message:"Application triggered context loss"}),t}pushState(){pu.get(this.gl).push()}popState(){pu.get(this.gl).pop()}getGLKey(t,e){const n=Number(t);for(const t in this.gl)if(this.gl[t]===n)return`GL.${t}`;return e?.emptyIfUnknown?"":String(t)}getGLKeys(t){const e={emptyIfUnknown:!0};return Object.entries(t).reduce(((t,[n,i])=>(t[`${n}:${this.getGLKey(n,e)}`]=`${i}:${this.getGLKey(i,e)}`,t)),{})}setConstantAttributeWebGL(t,e){this._constants=this._constants||new Array(this.limits.maxVertexAttributes).fill(null);const n=this._constants[t];switch(n&&function(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0}(n,e)&&Mt.info(1,`setConstantAttributeWebGL(${t}) could have been skipped, value unchanged`)(),this._constants[t]=e,e.constructor){case Float32Array:!function(t,e,n){switch(n.length){case 1:t.gl.vertexAttrib1fv(e,n);break;case 2:t.gl.vertexAttrib2fv(e,n);break;case 3:t.gl.vertexAttrib3fv(e,n);break;case 4:t.gl.vertexAttrib4fv(e,n)}}(this,t,e);break;case Int32Array:!function(t,e,n){t.gl.vertexAttribI4iv(e,n)}(this,t,e);break;case Uint32Array:!function(t,e,n){t.gl.vertexAttribI4uiv(e,n)}(this,t,e);break;default:throw new Error("constant")}}getExtension(t){return _u(this.gl,t,this._extensions),this._extensions}_setWebGLDebugMetadata(t,e,n){t.luma=e,t.__SPECTOR_Metadata={props:n.spector,id:n.spector.id}}}var Af=Object.freeze({__proto__:null,WebGLDevice:Tf});function Sf(){}const Cf={id:"",width:"100%",height:"100%",style:null,viewState:null,initialViewState:null,pickingRadius:0,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:Sf,onWebGLInitialized:Sf,onResize:Sf,onViewStateChange:Sf,onInteractionStateChange:Sf,onBeforeRender:Sf,onAfterRender:Sf,onLoad:Sf,onError:t=>F.error(t.message,t.cause)(),onHover:null,onClick:null,onDragStart:null,onDrag:null,onDragEnd:null,_onMetrics:null,getCursor:({isDragging:t})=>t?"grabbing":"grab",getTooltip:null,debug:!1,drawPickingColors:!1};class Pf{constructor(t){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 Ct({id:"deck.gl"}),this.metrics={fps:0,setPropsTime:0,updateAttributesTime:0,framesRedrawn:0,pickTime:0,pickCount:0,gpuTime:0,gpuTimePerFrame:0,cpuTime:0,cpuTimePerFrame:0,bufferMemory:0,textureMemory:0,renderbufferMemory:0,gpuMemory:0},this._metricsCounter=0,this._needsRedraw="Initial render",this._pickRequest={mode:"hover",x:-1,y:-1,radius:0,event:null,unproject3D:!1},this._lastPointerDownInfo=null,this._onPointerMove=t=>{const{_pickRequest:e}=this;if("pointerleave"===t.type)e.x=-1,e.y=-1,e.radius=0;else{if(t.leftButton||t.rightButton)return;{const n=t.offsetCenter;if(!n)return;e.x=n.x,e.y=n.y,e.radius=this.props.pickingRadius}}this.layerManager&&(this.layerManager.context.mousePosition={x:e.x,y:e.y}),e.event=t},this._onEvent=t=>{const e=Jo[t.type],n=t.offsetCenter;if(!e||!n||!this.layerManager)return;let i;const s=this.layerManager.getLayers(),r=s.some((t=>"3d"===t.props.pickable));if("click"===t.type&&r){const t=this._pick("pickObject","pickObject Time",{x:n.x,y:n.y,radius:this.props.pickingRadius,unproject3D:!0});i=t.result[0]||t.emptyInfo}else i=this.deckPicker.getLastPickedObject({x:n.x,y:n.y,layers:s,viewports:this.getViewports(n)},this._lastPointerDownInfo);const{layer:o}=i,a=o&&(o[e]||o.props[e]),c=this.props[e];let l=!1;a&&(l=a.call(o,i,t)),l||(c?.(i,t),this.widgetManager.onEvent(i,t))},this._onPointerDown=t=>{if("webgpu"===this.device?.type)return;const e=t.offsetCenter,n=this._pick("pickObject","pickObject Time",{x:e.x,y:e.y,radius:this.props.pickingRadius});this._lastPointerDownInfo=n.result[0]||n.emptyInfo},this.props={...Cf,...t},(t=this.props).viewState&&t.initialViewState&&F.warn("View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.")(),this.viewState=this.props.initialViewState,t.device&&(this.device=t.device);let e=this.device;if(!e&&t.gl){t.gl instanceof WebGLRenderingContext&&F.error("WebGL1 context not supported.")();const n=this.props.deviceProps?.onResize;e=Kh.attach(t.gl,{_cacheShaders:!0,_cachePipelines:!0,...this.props.deviceProps,onResize:(t,e)=>{const{width:i,height:s}=t.canvas;t.drawingBufferWidth=i,t.drawingBufferHeight=s,this._needsRedraw="Canvas resized",n?.(t,e)}})}e||(e=this._createDevice(t)),this.animationLoop=this._createAnimationLoop(e,t),this.setProps(t),t._typedArrayManagerProps&&xc.setOptions(t._typedArrayManagerProps),this.animationLoop.start()}finalize(){this.animationLoop?.stop(),this.animationLoop?.destroy(),this.animationLoop=null,this._lastPointerDownInfo=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(t){this.stats.get("setProps Time").timeStart(),"onLayerHover"in t&&F.removed("onLayerHover","onHover")(),"onLayerClick"in t&&F.removed("onLayerClick","onClick")(),t.initialViewState&&!Al(this.props.initialViewState,t.initialViewState,3)&&(this.viewState=t.initialViewState),Object.assign(this.props,t),this._setCanvasSize(this.props);const e=Object.create(this.props);Object.assign(e,{views:this._getViews(),width:this.width,height:this.height,viewState:this._getViewState()}),t.device&&t.device.id!==this.device?.id&&(this.animationLoop?.stop(),this.canvas!==t.device.canvasContext?.canvas&&(this.canvas?.remove(),this.eventManager?.destroy(),this.canvas=null),F.log(`recreating animation loop for new device! id=${t.device.id}`)(),this.animationLoop=this._createAnimationLoop(t.device,t),this.animationLoop.start()),this.animationLoop?.setProps(e),void 0!==t.useDevicePixels&&this.device?.canvasContext?.setProps&&this.device.canvasContext.setProps({useDevicePixels:t.useDevicePixels}),this.layerManager&&(this.viewManager.setProps(e),this.layerManager.activateViewport(this.getViewports()[0]),this.layerManager.setProps(e),this.effectManager.setProps(e),this.deckRenderer.setProps(e),this.deckPicker.setProps(e),this.widgetManager.setProps(e)),this.stats.get("setProps Time").timeEnd()}needsRedraw(t={clearRedrawFlags:!1}){if(!this.layerManager)return!1;if(this.props._animate)return"Deck._animate";let e=this._needsRedraw;t.clearRedrawFlags&&(this._needsRedraw=!1);const n=this.viewManager.needsRedraw(t),i=this.layerManager.needsRedraw(t),s=this.effectManager.needsRedraw(t),r=this.deckRenderer.needsRedraw(t);return e=e||n||i||s||r,e}redraw(t){if(!this.layerManager)return;let e=this.needsRedraw({clearRedrawFlags:!0});e=t||e,e&&(this.stats.get("Redraw Count").incrementCount(),this.props._customRender?this.props._customRender(e):this._drawLayers(e))}get isInitialized(){return null!==this.viewManager}getViews(){return jl(this.viewManager),this.viewManager.views}getView(t){return jl(this.viewManager),this.viewManager.getView(t)}getViewports(t){return jl(this.viewManager),this.viewManager.getViewports(t)}getCanvas(){return this.canvas}pickObject(t){const e=this._pick("pickObject","pickObject Time",t).result;return e.length?e[0]:null}pickMultipleObjects(t){return t.depth=t.depth||10,this._pick("pickObject","pickMultipleObjects Time",t).result}pickObjects(t){return this._pick("pickObjects","pickObjects Time",t)}_addResources(t,e=!1){for(const n in t)this.layerManager.resourceManager.add({resourceId:n,data:t[n],forceUpdate:e})}_removeResources(t){for(const e of t)this.layerManager.resourceManager.remove(e)}_addDefaultEffect(t){this.effectManager.addDefaultEffect(t)}_addDefaultShaderModule(t){this.layerManager.addDefaultShaderModule(t)}_removeDefaultShaderModule(t){this.layerManager?.removeDefaultShaderModule(t)}_pick(t,e,n){jl(this.deckPicker);const{stats:i}=this;i.get("Pick Count").incrementCount(),i.get(e).timeStart();const s=this.deckPicker[t]({layers:this.layerManager.getLayers(n),views:this.viewManager.getViews(),viewports:this.getViewports(n),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...n});return i.get(e).timeEnd(),s}_createCanvas(t){let e=t.canvas;return"string"==typeof e&&(e=document.getElementById(e),jl(e)),e||(e=document.createElement("canvas"),e.id=t.id||"deckgl-overlay",t.width&&"number"==typeof t.width&&(e.width=t.width),t.height&&"number"==typeof t.height&&(e.height=t.height),(t.parent||document.body).appendChild(e)),Object.assign(e.style,t.style),e}_setCanvasSize(t){if(!this.canvas)return;const{width:e,height:n}=t;if(e||0===e){const t=Number.isFinite(e)?`${e}px`:e;this.canvas.style.width=t}if(n||0===n){const e=Number.isFinite(n)?`${n}px`:n;this.canvas.style.position=t.style?.position||"absolute",this.canvas.style.height=e}}_updateCanvasSize(){const{canvas:t}=this;if(!t)return;const e=t.clientWidth??t.width,n=t.clientHeight??t.height;e===this.width&&n===this.height||(this.width=e,this.height=n,this.viewManager?.setProps({width:e,height:n}),this.layerManager?.activateViewport(this.getViewports()[0]),this.props.onResize({width:e,height:n}))}_createAnimationLoop(t,e){const{gl:n,onError:i}=e;return new Wc({device:t,autoResizeDrawingBuffer:!n,autoResizeViewport:!1,onInitialize:t=>this._setDevice(t.device),onRender:this._onRenderFrame.bind(this),onError:i})}_createDevice(t){const e=this.props.deviceProps?.createCanvasContext,n="object"==typeof e?e:void 0,i={adapters:[],_cacheShaders:!0,_cachePipelines:!0,...t.deviceProps};i.adapters.includes(Kh)||i.adapters.push(Kh);const s={alphaMode:"webgpu"===this.props.deviceProps?.type?"premultiplied":void 0},r=this.props.deviceProps?.onResize;return he.createDevice({_reuseDevices:!0,type:"webgl",...i,createCanvasContext:{...s,...n,canvas:this._createCanvas(t),useDevicePixels:this.props.useDevicePixels,autoResize:!0},onResize:(t,e)=>{this._needsRedraw="Canvas resized",r?.(t,e)}})}_getViewState(){return this.props.viewState||this.viewState}_getViews(){const{views:t}=this.props,e=Array.isArray(t)?t:t?[t]:[new ph({id:"default-view"})];return e.length&&this.props.controller&&(e[0].props.controller=this.props.controller),e}_onContextLost(){const{onError:t}=this.props;this.animationLoop&&t&&t(new Error("WebGL context is lost"))}_pickAndCallback(){if("webgpu"===this.device?.type)return;const{_pickRequest:t}=this;if(t.event){const e=(this.layerManager?.getLayers()||[]).some((t=>"3d"===t.props.pickable));t.unproject3D=e;const{result:n,emptyInfo:i}=this._pick("pickObject","pickObject Time",t);this.cursorState.isHovering=n.length>0;let s=i,r=!1;for(const e of n)s=e,r=e.layer?.onHover(e,t.event)||r;r||(this.props.onHover?.(s,t.event),this.widgetManager.onHover(s,t.event)),t.event=null}}_updateCursor(){const t=this.props.parent||this.canvas;t&&(t.style.cursor=this.props.getCursor(this.cursorState))}_setDevice(t){if(this.device=t,!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)),"webgl"===this.device.type&&this.device.setParametersWebGL({blend:!0,blendFunc:[770,771,1,771],polygonOffsetFill:!0,depthTest:!0,depthFunc:515}),this.props.onDeviceInitialized(this.device),"webgl"===this.device.type&&this.props.onWebGLInitialized(this.device.gl);const e=new jc;e.play(),this.animationLoop.attachTimeline(e),this.eventManager=new Zo(this.props.parent||this.canvas,{touchAction:this.props.touchAction,recognizers:Object.keys(Qo).map((t=>{const[e,n,i,s]=Qo[t],r=this.props.eventRecognizerOptions?.[t];return{recognizer:new e({...n,...r,event:t}),recognizeWith:i,requestFailure:s}})),events:{pointerdown:this._onPointerDown,pointermove:this._onPointerMove,pointerleave:this._onPointerMove}});for(const t in Jo)this.eventManager.on(t,this._onEvent);this.viewManager=new Sl({timeline:e,eventManager:this.eventManager,onViewStateChange:this._onViewStateChange.bind(this),onInteractionStateChange:this._onInteractionStateChange.bind(this),views:this._getViews(),viewState:this._getViewState(),width:this.width,height:this.height});const n=this.viewManager.getViewports()[0];this.layerManager=new Tl(this.device,{deck:this,stats:this.stats,viewport:n,timeline:e}),this.effectManager=new mh({deck:this,device:this.device}),this.deckRenderer=new vh(this.device),this.deckPicker=new Ah(this.device),this.widgetManager=new Mh({deck:this,parentElement:this.canvas?.parentElement}),this.widgetManager.addDefault(new kh),this.setProps(this.props),this._updateCanvasSize(),this.props.onLoad()}_drawLayers(t,e){const{device:n,gl:i}=this.layerManager.context;this.props.onBeforeRender({device:n,gl:i});const s={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(),...e};this.deckRenderer?.renderLayers(s),"screen"===s.pass&&this.widgetManager.onRedraw({viewports:s.viewports,layers:s.layers}),this.props.onAfterRender({device:n,gl:i})}_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(),"webgpu"!==this.device?.type&&this._pickAndCallback(),this.redraw(),this.viewManager&&this.viewManager.updateViewStates()}_onViewStateChange(t){const e=this.props.onViewStateChange(t)||t.viewState;this.viewState&&(this.viewState={...this.viewState,[t.viewId]:e},this.props.viewState||this.viewManager&&this.viewManager.setProps({viewState:this.viewState}))}_onInteractionStateChange(t){this.cursorState.isDragging=t.isDragging||!1,this.props.onInteractionStateChange(t)}_getFrameStats(){const{stats:t}=this;t.get("frameRate").timeEnd(),t.get("frameRate").timeStart();const e=this.animationLoop.stats;t.get("GPU Time").addTime(e.get("GPU Time").lastTiming),t.get("CPU Time").addTime(e.get("CPU Time").lastTiming)}_getMetrics(){const{metrics:t,stats:e}=this;t.fps=e.get("frameRate").getHz(),t.setPropsTime=e.get("setProps Time").time,t.updateAttributesTime=e.get("Update Attributes").time,t.framesRedrawn=e.get("Redraw Count").count,t.pickTime=e.get("pickObject Time").time+e.get("pickMultipleObjects Time").time+e.get("pickObjects Time").time,t.pickCount=e.get("Pick Count").count,t.gpuTime=e.get("GPU Time").time,t.cpuTime=e.get("CPU Time").time,t.gpuTimePerFrame=e.get("GPU Time").getAverageTime(),t.cpuTimePerFrame=e.get("CPU Time").getAverageTime();const n=he.stats.get("Memory Usage");t.bufferMemory=n.get("Buffer Memory").count,t.textureMemory=n.get("Texture Memory").count,t.renderbufferMemory=n.get("Renderbuffer Memory").count,t.gpuMemory=n.get("GPU Memory").count}}Pf.defaultProps=Cf,Pf.VERSION=j;const Mf=Nt;function Rf(t,e,n){return{attribute:t,format:e.size>1?`${"webgpu"===n&&"uint8"===e.type?"unorm8":e.type}x${e.size}`:e.type,byteOffset:e.offset||0}}function Lf(t){return t.stride||t.size*t.bytesPerElement}function Of(t,e){e.offset&&F.removed("shaderAttribute.offset","vertexOffset, elementOffset")();const n=Lf(t),i=(void 0!==e.vertexOffset?e.vertexOffset:t.vertexOffset||0)*n+(e.elementOffset||0)*t.bytesPerElement+(t.offset||0);return{...e,offset:i,stride:n}}class If{constructor(t,e,n){this._buffer=null,this.device=t,this.id=e.id||"",this.size=e.size||1;const i=e.logicalType||e.type,s="float64"===i;let r,{defaultValue:o}=e;o=Number.isFinite(o)?[o]:o||new Array(this.size).fill(0),r=s?"float32":!i&&e.isIndexed?"uint32":i||"float32";let a=function(t){switch(t){case"float64":return Float64Array;case"uint8":case"unorm8":return Uint8ClampedArray;default:return Ft(t)}}(i||r);this.doublePrecision=s,s&&!1===e.fp64&&(a=Float32Array),this.value=null,this.settings={...e,defaultType:a,defaultValue:o,logicalType:i,type:r,normalized:r.includes("norm"),size:this.size,bytesPerElement:a.BYTES_PER_ELEMENT},this.state={...n,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(){const t=this.getAccessor();return t.vertexOffset?t.vertexOffset*Lf(t):0}get numInstances(){return this.state.numInstances}set numInstances(t){this.state.numInstances=t}delete(){this._buffer&&(this._buffer.delete(),this._buffer=null),xc.release(this.state.allocatedValue)}getBuffer(){return this.state.constant?null:this.state.externalBuffer||this._buffer}getValue(t=this.id,e=null){const n={};if(this.state.constant){const i=this.value;if(e){const s=Of(this.getAccessor(),e),r=s.offset/i.BYTES_PER_ELEMENT;n[t]=i.subarray(r,r+(s.size||this.size))}else n[t]=i}else n[t]=this.getBuffer();return this.doublePrecision&&(n[`${t}64Low`]=this.value instanceof Float64Array?n[t]:new Float32Array(this.size)),n}_getBufferLayout(t=this.id,e=null){const n=this.getAccessor(),i=[],s={name:this.id,byteStride:Lf(n),attributes:i};if(this.doublePrecision){const s=function(t,e){const n=Of(t,e);return{high:n,low:{...n,offset:n.offset+4*t.size}}}(n,e||{});i.push(Rf(t,{...n,...s.high},this.device.type),Rf(`${t}64Low`,{...n,...s.low},this.device.type))}else if(e){const s=Of(n,e);i.push(Rf(t,{...n,...s},this.device.type))}else i.push(Rf(t,n,this.device.type));return s}setAccessor(t){this.state.bufferAccessor=t}getAccessor(){return this.state.bufferAccessor}getBounds(){if(this.state.bounds)return this.state.bounds;let t=null;if(this.state.constant&&this.value){const e=Array.from(this.value);t=[e,e]}else{const{value:e,numInstances:n,size:i}=this,s=n*i;if(e&&s&&e.length>=s){const n=new Array(i).fill(1/0),r=new Array(i).fill(-1/0);for(let t=0;t<s;)for(let s=0;s<i;s++){const i=e[t++];i<n[s]&&(n[s]=i),i>r[s]&&(r[s]=i)}t=[n,r]}}return this.state.bounds=t,t}setData(t){const{state:e}=this;let n;n=ArrayBuffer.isView(t)?{value:t}:t instanceof It?{buffer:t}:t;const i={...this.settings,...n};if(ArrayBuffer.isView(n.value)){if(!n.type)if(this.doublePrecision&&n.value instanceof Float64Array)i.type="float32";else{const t=Mf(n.value);i.type=i.normalized?t.replace("int","norm"):t}i.bytesPerElement=n.value.BYTES_PER_ELEMENT,i.stride=Lf(i)}if(e.bounds=null,n.constant){let t=n.value;if(t=this._normalizeValue(t,[],0),this.settings.normalized&&(t=this.normalizeConstant(t)),e.constant&&this._areValuesEqual(t,this.value))return!1;e.externalBuffer=null,e.constant=!0,this.value=ArrayBuffer.isView(t)?t:new Float32Array(t)}else if(n.buffer)e.externalBuffer=n.buffer,e.constant=!1,this.value=n.value||null;else if(n.value){this._checkExternalBuffer(n);let t=n.value;e.externalBuffer=null,e.constant=!1,this.value=t;let{buffer:s}=this;const r=Lf(i),o=(i.vertexOffset||0)*r;if(this.doublePrecision&&t instanceof Float64Array&&(t=Pc(t,i)),this.settings.isIndexed){const e=this.settings.defaultType;t.constructor!==e&&(t=new e(t))}const a=t.byteLength+o+2*r;(!s||s.byteLength<a)&&(s=this._createBuffer(a)),s.write(t,o)}return this.setAccessor(i),!0}updateSubBuffer(t={}){this.state.bounds=null;const e=this.value,{startOffset:n=0,endOffset:i}=t;this.buffer.write(this.doublePrecision&&e instanceof Float64Array?Pc(e,{size:this.size,startIndex:n,endIndex:i}):e.subarray(n,i),n*e.BYTES_PER_ELEMENT+this.byteOffset)}allocate(t,e=!1){const{state:n}=this,i=n.allocatedValue,s=xc.allocate(i,t+1,{size:this.size,type:this.settings.defaultType,copy:e});this.value=s;const{byteOffset:r}=this;let{buffer:o}=this;return(!o||o.byteLength<s.byteLength+r)&&(o=this._createBuffer(s.byteLength+r),e&&i&&o.write(i instanceof Float64Array?Pc(i,this):i,r)),n.allocatedValue=s,n.constant=!1,n.externalBuffer=null,this.setAccessor(this.settings),!0}_checkExternalBuffer(t){const{value:e}=t;if(!ArrayBuffer.isView(e))throw new Error(`Attribute ${this.id} value is not TypedArray`);const n=this.settings.defaultType;let i=!1;if(this.doublePrecision&&(i=e.BYTES_PER_ELEMENT<4),i)throw new Error(`Attribute ${this.id} does not support ${e.constructor.name}`);e instanceof n||!this.settings.normalized||"normalized"in t||F.warn(`Attribute ${this.id} is normalized`)()}normalizeConstant(t){switch(this.settings.type){case"snorm8":return new Float32Array(t).map((t=>(t+128)/255*2-1));case"snorm16":return new Float32Array(t).map((t=>(t+32768)/65535*2-1));case"unorm8":return new Float32Array(t).map((t=>t/255));case"unorm16":return new Float32Array(t).map((t=>t/65535));default:return t}}_normalizeValue(t,e,n){const{defaultValue:i,size:s}=this.settings;if(Number.isFinite(t))return e[n]=t,e;if(!t){let t=s;for(;--t>=0;)e[n+t]=i[t];return e}switch(s){case 4:e[n+3]=Number.isFinite(t[3])?t[3]:i[3];case 3:e[n+2]=Number.isFinite(t[2])?t[2]:i[2];case 2:e[n+1]=Number.isFinite(t[1])?t[1]:i[1];case 1:e[n+0]=Number.isFinite(t[0])?t[0]:i[0];break;default:let r=s;for(;--r>=0;)e[n+r]=Number.isFinite(t[r])?t[r]:i[r]}return e}_areValuesEqual(t,e){if(!t||!e)return!1;const{size:n}=this;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}_createBuffer(t){this._buffer&&this._buffer.destroy();const{isIndexed:e,type:n}=this.settings;return this._buffer=this.device.createBuffer({...this._buffer?.props,id:this.id,usage:(e?It.INDEX:It.VERTEX)|It.COPY_DST,indexType:e?n:void 0,byteLength:t}),this._buffer}}const kf=[],Df=[];function Nf(t,e=0,n=1/0){let i=kf;const s={index:-1,data:t,target:[]};return t?"function"==typeof t[Symbol.iterator]?i=t:t.length>0&&(Df.length=t.length,i=Df):i=kf,(e>0||Number.isFinite(n))&&(i=(Array.isArray(i)?i:Array.from(i)).slice(e,n),s.index=e-1),{iterable:i,objectInfo:s}}function Ff(t){return t&&t[Symbol.asyncIterator]}function Bf(t,e){const{size:n,stride:i,offset:s,startIndices:r,nested:o}=e,a=t.BYTES_PER_ELEMENT,c=i?i/a:n,l=s?s/a:0,h=Math.floor((t.length-l)/c);return(e,{index:i,target:s})=>{if(!r){const e=i*c+l;for(let i=0;i<n;i++)s[i]=t[e+i];return s}const a=r[i],u=r[i+1]||h;let f;if(o){f=new Array(u-a);for(let e=a;e<u;e++){const i=e*c+l;s=new Array(n);for(let e=0;e<n;e++)s[e]=t[i+e];f[e-a]=s}}else if(c===n)f=t.subarray(a*n+l,u*n+l);else{f=new t.constructor((u-a)*n);let e=0;for(let i=a;i<u;i++){const s=i*c+l;for(let i=0;i<n;i++)f[e++]=t[s+i]}}return f}}const $f=[],Uf=[[0,1/0]],zf={interpolation:{duration:0,easing:t=>t},spring:{stiffness:.05,damping:.5}};function jf(t,e){if(!t)return null;Number.isFinite(t)&&(t={type:"interpolation",duration:t});const n=t.type||"interpolation";return{...zf[n],...e,...t,type:n}}class Gf extends If{constructor(t,e){super(t,e,{startIndices:null,lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,layoutChanged:!1,updateRanges:Uf}),this.constant=!1,this.settings.update=e.update||(e.accessor?this._autoUpdater:void 0),Object.seal(this.settings),Object.seal(this.state),this._validateAttributeUpdaters()}get startIndices(){return this.state.startIndices}set startIndices(t){this.state.startIndices=t}needsUpdate(){return this.state.needsUpdate}needsRedraw({clearChangedFlags:t=!1}={}){const e=this.state.needsRedraw;return this.state.needsRedraw=e&&!t,e}layoutChanged(){return this.state.layoutChanged}setAccessor(t){var e,n,i;(e=this.state).layoutChanged||(e.layoutChanged=(n=t,i=this.getAccessor(),!(n.type===i.type&&n.size===i.size&&Lf(n)===Lf(i)&&(n.offset||0)===(i.offset||0)))),super.setAccessor(t)}getUpdateTriggers(){const{accessor:t}=this.settings;return[this.id].concat("function"!=typeof t&&t||[])}supportsTransition(){return Boolean(this.settings.transition)}getTransitionSetting(t){if(!t||!this.supportsTransition())return null;const{accessor:e}=this.settings,n=this.settings.transition,i=Array.isArray(e)?t[e.find((e=>t[e]))]:t[e];return jf(i,n)}setNeedsUpdate(t=this.id,e){if(this.state.needsUpdate=this.state.needsUpdate||t,this.setNeedsRedraw(t),e){const{startRow:t=0,endRow:n=1/0}=e;this.state.updateRanges=function(t,e){if(t===Uf)return t;if(e[0]<0&&(e[0]=0),e[0]>=e[1])return t;const n=[],i=t.length;let s=0;for(let r=0;r<i;r++){const i=t[r];i[1]<e[0]?(n.push(i),s=r+1):i[0]>e[1]?n.push(i):e=[Math.min(i[0],e[0]),Math.max(i[1],e[1])]}return n.splice(s,0,e),n}(this.state.updateRanges,[t,n])}else this.state.updateRanges=Uf}clearNeedsUpdate(){this.state.needsUpdate=!1,this.state.updateRanges=$f}setNeedsRedraw(t=this.id){this.state.needsRedraw=this.state.needsRedraw||t}allocate(t){const{state:e,settings:n}=this;return!n.noAlloc&&!!n.update&&(super.allocate(t,e.updateRanges!==Uf),!0)}updateBuffer({numInstances:t,data:e,props:n,context:i}){if(!this.needsUpdate())return!1;const{state:{updateRanges:s},settings:{update:r,noAlloc:o}}=this;let a=!0;if(r){for(const[o,a]of s)r.call(i,this,{data:e,startRow:o,endRow:a,props:n,numInstances:t});if(this.value)if(this.constant||!this.buffer||this.buffer.byteLength<this.value.byteLength+this.byteOffset)this.setData({value:this.value,constant:this.constant}),this.constant=!1;else for(const[e,n]of s){const i=Number.isFinite(e)?this.getVertexOffset(e):0,s=Number.isFinite(n)?this.getVertexOffset(n):o||!Number.isFinite(t)?this.value.length:t*this.size;super.updateSubBuffer({startOffset:i,endOffset:s})}this._checkAttributeArray()}else a=!1;return this.clearNeedsUpdate(),this.setNeedsRedraw(),a}setConstantValue(t,e){const n="webgpu"===this.device.type;if(n||void 0===e||"function"==typeof e){if(n&&"function"!=typeof e){const t=this._normalizeValue(e,[],0);this._areValuesEqual(t,this.value)||this.setNeedsUpdate("WebGPU constant updated")}return!1}const i=this.settings.transform&&t?this.settings.transform.call(t,e):e;return this.setData({constant:!0,value:i})&&this.setNeedsRedraw(),this.clearNeedsUpdate(),!0}setExternalBuffer(t){const{state:e}=this;return t?(this.clearNeedsUpdate(),e.lastExternalBuffer===t||(e.lastExternalBuffer=t,this.setNeedsRedraw(),this.setData(t)),!0):(e.lastExternalBuffer=null,!1)}setBinaryValue(t,e=null){const{state:n,settings:i}=this;if(!t)return n.binaryValue=null,n.binaryAccessor=null,!1;if(i.noAlloc)return!1;if(n.binaryValue===t)return this.clearNeedsUpdate(),!0;if(n.binaryValue=t,this.setNeedsRedraw(),i.transform||e!==this.startIndices){ArrayBuffer.isView(t)&&(t={value:t});const s=t;jl(ArrayBuffer.isView(s.value),`invalid ${i.accessor}`);const r=Boolean(s.size)&&s.size!==this.size;return n.binaryAccessor=Bf(s.value,{size:s.size||this.size,stride:s.stride,offset:s.offset,startIndices:e,nested:r}),!1}return this.clearNeedsUpdate(),this.setData(t),!0}getVertexOffset(t){const{startIndices:e}=this;return(e?t<e.length?e[t]:this.numInstances:t)*this.size}getValue(){const t=this.settings.shaderAttributes,e=super.getValue();if(!t)return e;for(const n in t)Object.assign(e,super.getValue(n,t[n]));return e}getBufferLayout(t){this.state.layoutChanged=!1;const e=this.settings.shaderAttributes,n=super._getBufferLayout(),{stepMode:i}=this.settings;if(n.stepMode="dynamic"===i?t?t.isInstanced?"instance":"vertex":"instance":i??"vertex",!e)return n;for(const t in e){const i=super._getBufferLayout(t,e[t]);n.attributes.push(...i.attributes)}return n}_autoUpdater(t,{data:e,startRow:n,endRow:i,props:s,numInstances:r}){if(t.constant&&"webgpu"!==this.context.device.type)return;const{settings:o,state:a,value:c,size:l,startIndices:h}=t,{accessor:u,transform:f}=o;let d=a.binaryAccessor||("function"==typeof u?u:s[u]);"function"!=typeof d&&"string"==typeof u&&(d=()=>s[u]),jl("function"==typeof d,`accessor "${u}" is not a function`);let p=t.getVertexOffset(n);const{iterable:g,objectInfo:m}=Nf(e,n,i);for(const e of g){m.index++;let n=d(e,m);if(f&&(n=f.call(this,n)),h){const e=(m.index<h.length-1?h[m.index+1]:r)-h[m.index];if(n&&Array.isArray(n[0])){let e=p;for(const i of n)t._normalizeValue(i,c,e),e+=l}else n&&n.length>l?c.set(n,p):(t._normalizeValue(n,m.target,0),wl({target:c,source:m.target,start:p,count:e}));p+=e*l}else t._normalizeValue(n,c,p),p+=l}}_validateAttributeUpdaters(){const{settings:t}=this;if(!t.noAlloc&&"function"!=typeof t.update)throw new Error(`Attribute ${this.id} missing update or accessor`)}_checkAttributeArray(){const{value:t}=this,e=Math.min(4,this.size);if(t&&t.length>=e){let n=!0;switch(e){case 4:n=n&&Number.isFinite(t[3]);case 3:n=n&&Number.isFinite(t[2]);case 2:n=n&&Number.isFinite(t[1]);case 1:n=n&&Number.isFinite(t[0]);break;default:n=!1}if(!n)throw new Error(`Illegal attribute generated for ${this.id}`)}}}function Wf(t){const{source:e,target:n,start:i=0,size:s,getData:r}=t,o=e.length,a=(t.end||n.length)-i;if(o>a)return void n.set(e.subarray(0,a),i);if(n.set(e,i),!r)return;let c=o;for(;c<a;){const t=r(c,e);for(let e=0;e<s;e++)n[i+c]=t[e]||0,c++}}function Vf(t){switch(t){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`No defined attribute type for size "${t}"`)}}function Hf(t){switch(t){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("invalid type size")}}function Xf(t){t.push(t.shift())}function Zf({device:t,source:e,target:n}){return(!n||n.byteLength<e.byteLength)&&(n?.destroy(),n=t.createBuffer({byteLength:e.byteLength,usage:e.usage})),n}function Kf({device:t,buffer:e,attribute:n,fromLength:i,toLength:s,fromStartIndices:r,getData:o=t=>t}){const a=n.doublePrecision&&n.value instanceof Float64Array?2:1,c=n.size*a,l=n.byteOffset,h=n.settings.bytesPerElement<4?l/n.settings.bytesPerElement*4:l,u=n.startIndices,f=n.isConstant;if((!r||!u)&&e&&i>=s)return e;const d=n.value instanceof Float64Array?Float32Array:n.value.constructor,p=f?n.value:new d(n.getBuffer().readSyncWebGL(l,s*d.BYTES_PER_ELEMENT).buffer);if(n.settings.normalized&&!f){const t=o;o=(e,i)=>n.normalizeConstant(t(e,i))}const g=f?(t,e)=>o(p,e):(t,e)=>o(p.subarray(t+l,t+l+c),e),m=e?new Float32Array(e.readSyncWebGL(h,4*i).buffer):new Float32Array(0),_=new Float32Array(s);return function({source:t,target:e,size:n,getData:i,sourceStartIndices:s,targetStartIndices:r}){if(!s||!r)return Wf({source:t,target:e,size:n,getData:i}),e;let o=0,a=0;const c=i&&((t,e)=>i(t+a,e)),l=Math.min(s.length,r.length);for(let i=1;i<l;i++){const l=s[i]*n,h=r[i]*n;Wf({source:t.subarray(o,l),target:e,start:a,end:h,size:n,getData:c}),o=l,a=h}a<e.length&&Wf({source:[],target:e,start:a,size:n,getData:c})}({source:m,target:_,sourceStartIndices:r,targetStartIndices:u,size:c,getData:g}),(!e||e.byteLength<_.byteLength+h)&&(e?.destroy(),e=t.createBuffer({byteLength:_.byteLength+h,usage:35050})),e.write(_,h),e}class qf{constructor({device:t,attribute:e,timeline:n}){this.buffers=[],this.currentLength=0,this.device=t,this.transition=new Nl(n),this.attribute=e,this.attributeInTransition=function(t){const{device:e,settings:n,value:i}=t,s=new Gf(e,n);return s.setData({value:i instanceof Float64Array?new Float64Array(0):new Float32Array(0),normalized:n.normalized}),s}(e),this.currentStartIndices=e.startIndices}get inProgress(){return this.transition.inProgress}start(t,e,n=1/0){this.settings=t,this.currentStartIndices=this.attribute.startIndices,this.currentLength=function(t,e){const{doublePrecision:n,settings:i,value:s,size:r}=t,o=n&&s instanceof Float64Array?2:1;let a=0;const{shaderAttributes:c}=t.settings;if(c)for(const t of Object.values(c))a=Math.max(a,t.vertexOffset??0);return(i.noAlloc?s.length:(e+a)*r)*o}(this.attribute,e),this.transition.start({...t,duration:n})}update(){const t=this.transition.update();return t&&this.onUpdate(),t}setBuffer(t){this.attributeInTransition.setData({buffer:t,normalized:this.attribute.settings.normalized,value:this.attributeInTransition.value})}cancel(){this.transition.cancel()}delete(){this.cancel();for(const t of this.buffers)t.destroy();this.buffers.length=0}}const Yf={name:"interpolation",vs:"uniform interpolationUniforms {\n float time;\n} interpolation;\n",uniformTypes:{time:"f32"}};function Jf(t){return t.doublePrecision&&t.value instanceof Float64Array}const Qf={name:"spring",vs:"uniform springUniforms {\n float damping;\n float stiffness;\n} spring;\n",uniformTypes:{damping:"f32",stiffness:"f32"}},td={interpolation:class extends qf{constructor({device:t,attribute:e,timeline:n}){super({device:t,attribute:e,timeline:n}),this.type="interpolation",this.transform=function(t,e){const n=e.size,i=Vf(n),s=Hf(n),r=e.getBufferLayout();return Jf(e)?new cl(t,{vs:"#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aFrom64Low;\nin ATTRIBUTE_TYPE aTo;\nin ATTRIBUTE_TYPE aTo64Low;\nout ATTRIBUTE_TYPE vCurrent;\nout ATTRIBUTE_TYPE vCurrent64Low;\n\nvec2 mix_fp64(vec2 a, vec2 b, float x) {\n vec2 range = sub_fp64(b, a);\n return sum_fp64(a, mul_fp64(range, vec2(x, 0.0)));\n}\n\nvoid main(void) {\n for (int i=0; i<ATTRIBUTE_SIZE; i++) {\n vec2 value = mix_fp64(vec2(aFrom[i], aFrom64Low[i]), vec2(aTo[i], aTo64Low[i]), interpolation.time);\n vCurrent[i] = value.x;\n vCurrent64Low[i] = value.y;\n }\n gl_Position = vec4(0.0);\n}\n",bufferLayout:[{name:"aFrom",byteStride:8*n,attributes:[{attribute:"aFrom",format:s,byteOffset:0},{attribute:"aFrom64Low",format:s,byteOffset:4*n}]},{name:"aTo",byteStride:8*n,attributes:[{attribute:"aTo",format:s,byteOffset:0},{attribute:"aTo64Low",format:s,byteOffset:4*n}]}],modules:[kr,Yf],defines:{ATTRIBUTE_TYPE:i,ATTRIBUTE_SIZE:n},moduleSettings:{},varyings:["vCurrent","vCurrent64Low"],bufferMode:35980,disableWarnings:!0}):new cl(t,{vs:"#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, interpolation.time);\n gl_Position = vec4(0.0);\n}\n",bufferLayout:[{name:"aFrom",format:s},{name:"aTo",format:r.attributes[0].format}],modules:[Yf],defines:{ATTRIBUTE_TYPE:i},varyings:["vCurrent"],disableWarnings:!0})}(t,e)}start(t,e){const n=this.currentLength,i=this.currentStartIndices;if(super.start(t,e,t.duration),t.duration<=0)return void this.transition.cancel();const{buffers:s,attribute:r}=this;Xf(s),s[0]=Kf({device:this.device,buffer:s[0],attribute:r,fromLength:n,toLength:this.currentLength,fromStartIndices:i,getData:t.enter}),s[1]=Zf({device:this.device,source:s[0],target:s[1]}),this.setBuffer(s[1]);const{transform:o}=this,a=o.model;let c=Math.floor(this.currentLength/r.size);Jf(r)&&(c/=2),a.setVertexCount(c),r.isConstant?(a.setAttributes({aFrom:s[0]}),a.setConstantAttributes({aTo:r.value})):a.setAttributes({aFrom:s[0],aTo:r.getBuffer()}),o.transformFeedback.setBuffers({vCurrent:s[1]})}onUpdate(){const{duration:t,easing:e}=this.settings,{time:n}=this.transition;let i=n/t;e&&(i=e(i));const{model:s}=this.transform;s.shaderInputs.setProps({interpolation:{time:i}}),this.transform.run({discard:!0})}delete(){super.delete(),this.transform.destroy()}},spring:class extends qf{constructor({device:t,attribute:e,timeline:n}){super({device:t,attribute:e,timeline:n}),this.type="spring",this.texture=function(t){return t.createTexture({data:new Uint8Array(4),format:"rgba8unorm",width:1,height:1})}(t),this.framebuffer=function(t,e){return t.createFramebuffer({id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,colorAttachments:[e]})}(t,this.texture),this.transform=function(t,e){const n=Vf(e.size),i=Hf(e.size);return new cl(t,{vs:"#version 300 es\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nin ATTRIBUTE_TYPE aPrev;\nin ATTRIBUTE_TYPE aCur;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vNext;\nout float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE force = delta * spring.stiffness;\n ATTRIBUTE_TYPE resistance = velocity * spring.damping;\n return force - resistance + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n",fs:"#version 300 es\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nin float vIsTransitioningFlag;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n fragColor = vec4(1.0);\n}",bufferLayout:[{name:"aPrev",format:i},{name:"aCur",format:i},{name:"aTo",format:e.getBufferLayout().attributes[0].format}],varyings:["vNext"],modules:[Qf],defines:{ATTRIBUTE_TYPE:n},parameters:{depthCompare:"always",blendColorOperation:"max",blendColorSrcFactor:"one",blendColorDstFactor:"one",blendAlphaOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one"}})}(t,e)}start(t,e){const n=this.currentLength,i=this.currentStartIndices;super.start(t,e);const{buffers:s,attribute:r}=this;for(let e=0;e<2;e++)s[e]=Kf({device:this.device,buffer:s[e],attribute:r,fromLength:n,toLength:this.currentLength,fromStartIndices:i,getData:t.enter});s[2]=Zf({device:this.device,source:s[0],target:s[2]}),this.setBuffer(s[1]);const{model:o}=this.transform;o.setVertexCount(Math.floor(this.currentLength/r.size)),r.isConstant?o.setConstantAttributes({aTo:r.value}):o.setAttributes({aTo:r.getBuffer()})}onUpdate(){const{buffers:t,transform:e,framebuffer:n,transition:i}=this,s=this.settings;e.model.setAttributes({aPrev:t[0],aCur:t[1]}),e.transformFeedback.setBuffers({vNext:t[2]}),e.model.shaderInputs.setProps({spring:{stiffness:s.stiffness,damping:s.damping}}),e.run({framebuffer:n,discard:!1,parameters:{viewport:[0,0,1,1]},clearColor:[0,0,0,0]}),Xf(t),this.setBuffer(t[1]),this.device.readPixelsToArrayWebGL(n)[0]>0||i.end()}delete(){super.delete(),this.transform.destroy(),this.texture.destroy(),this.framebuffer.destroy()}}};class ed{constructor(t,{id:e,timeline:n}){if(!t)throw new Error("AttributeTransitionManager is constructed without device");this.id=e,this.device=t,this.timeline=n,this.transitions={},this.needsRedraw=!1,this.numInstances=1}finalize(){for(const t in this.transitions)this._removeTransition(t)}update({attributes:t,transitions:e,numInstances:n}){this.numInstances=n||1;for(const n in t){const i=t[n],s=i.getTransitionSetting(e);s&&this._updateAttribute(n,i,s)}for(const n in this.transitions){const i=t[n];i&&i.getTransitionSetting(e)||this._removeTransition(n)}}hasAttribute(t){const e=this.transitions[t];return e&&e.inProgress}getAttributes(){const t={};for(const e in this.transitions){const n=this.transitions[e];n.inProgress&&(t[e]=n.attributeInTransition)}return t}run(){if(0===this.numInstances)return!1;for(const t in this.transitions)this.transitions[t].update()&&(this.needsRedraw=!0);const t=this.needsRedraw;return this.needsRedraw=!1,t}_removeTransition(t){this.transitions[t].delete(),delete this.transitions[t]}_updateAttribute(t,e,n){const i=this.transitions[t];let s=!i||i.type!==n.type;if(s){i&&this._removeTransition(t);const r=td[n.type];r?this.transitions[t]=new r({attribute:e,timeline:this.timeline,device:this.device}):(F.error(`unsupported transition type '${n.type}'`)(),s=!1)}(s||e.needsRedraw())&&(this.needsRedraw=!0,this.transitions[t].start(n,this.numInstances))}}const nd="attributeManager.invalidate";class id{constructor(t,{id:e="attribute-manager",stats:n,timeline:i}={}){this.mergeBoundsMemoized=na(Mc),this.id=e,this.device=t,this.attributes={},this.updateTriggers={},this.needsRedraw=!0,this.userData={},this.stats=n,this.attributeTransitionManager=new ed(t,{id:`${e}-transitions`,timeline:i}),Object.seal(this)}finalize(){for(const t in this.attributes)this.attributes[t].delete();this.attributeTransitionManager.finalize()}getNeedsRedraw(t={clearRedrawFlags:!1}){const e=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!t.clearRedrawFlags,e&&this.id}setNeedsRedraw(){this.needsRedraw=!0}add(t){this._add(t)}addInstanced(t){this._add(t,{stepMode:"instance"})}remove(t){for(const e of t)void 0!==this.attributes[e]&&(this.attributes[e].delete(),delete this.attributes[e])}invalidate(t,e){const n=this._invalidateTrigger(t,e);U(nd,this,t,n)}invalidateAll(t){for(const e in this.attributes)this.attributes[e].setNeedsUpdate(e,t);U(nd,this,"all")}update({data:t,numInstances:e,startIndices:n=null,transitions:i,props:s={},buffers:r={},context:o={}}){let a=!1;U("attributeManager.updateStart",this),this.stats&&this.stats.get("Update Attributes").timeStart();for(const i in this.attributes){const c=this.attributes[i],l=c.settings.accessor;c.startIndices=n,c.numInstances=e,s[i]&&F.removed(`props.${i}`,`data.attributes.${i}`)(),c.setExternalBuffer(r[i])||c.setBinaryValue("string"==typeof l?r[l]:void 0,t.startIndices)||"string"==typeof l&&!r[l]&&c.setConstantValue(o,s[l])||c.needsUpdate()&&(a=!0,this._updateAttribute({attribute:c,numInstances:e,data:t,props:s,context:o})),this.needsRedraw=this.needsRedraw||c.needsRedraw()}a&&U("attributeManager.updateEnd",this,e),this.stats&&this.stats.get("Update Attributes").timeEnd(),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:e,transitions:i})}updateTransition(){const{attributeTransitionManager:t}=this,e=t.run();return this.needsRedraw=this.needsRedraw||e,e}getAttributes(){return{...this.attributes,...this.attributeTransitionManager.getAttributes()}}getBounds(t){const e=t.map((t=>this.attributes[t]?.getBounds()));return this.mergeBoundsMemoized(e)}getChangedAttributes(t={clearChangedFlags:!1}){const{attributes:e,attributeTransitionManager:n}=this,i={...n.getAttributes()};for(const s in e){const r=e[s];r.needsRedraw(t)&&!n.hasAttribute(s)&&(i[s]=r)}return i}getBufferLayouts(t){return Object.values(this.getAttributes()).map((e=>e.getBufferLayout(t)))}_add(t,e){for(const n in t){const i=t[n],s={...i,id:n,size:(i.isIndexed?1:i.size)||1,...e};this.attributes[n]=new Gf(this.device,s)}this._mapUpdateTriggersToAttributes()}_mapUpdateTriggersToAttributes(){const t={};for(const e in this.attributes)this.attributes[e].getUpdateTriggers().forEach((n=>{t[n]||(t[n]=[]),t[n].push(e)}));this.updateTriggers=t}_invalidateTrigger(t,e){const{attributes:n,updateTriggers:i}=this,s=i[t];return s&&s.forEach((t=>{const i=n[t];i&&i.setNeedsUpdate(i.id,e)})),s}_updateAttribute(t){const{attribute:e,numInstances:n}=t;U("attribute.updateStart",e),e.constant?e.setConstantValue(t.context,e.value):(e.allocate(n)&&U("attribute.allocate",e,n),e.updateBuffer(t)&&(this.needsRedraw=!0,U("attribute.updateEnd",e,n)))}}const sd=1e-5;function rd(t,e,n,i,s){const r=e-t;return(n-e)*s+-r*i+r+e}function od(t,e){if(Array.isArray(t)){let n=0;for(let i=0;i<t.length;i++){const s=t[i]-e[i];n+=s*s}return Math.sqrt(n)}return Math.abs(t-e)}const ad={interpolation:class extends Nl{get value(){return this._value}_onUpdate(){const{time:t,settings:{fromValue:e,toValue:n,duration:i,easing:s}}=this,r=s(t/i);this._value=ys(e,n,r)}},spring:class extends Nl{get value(){return this._currValue}_onUpdate(){const{fromValue:t,toValue:e,damping:n,stiffness:i}=this.settings,{_prevValue:s=t,_currValue:r=t}=this;let o=function(t,e,n,i,s){if(Array.isArray(n)){const r=[];for(let o=0;o<n.length;o++)r[o]=rd(t[o],e[o],n[o],i,s);return r}return rd(t,e,n,i,s)}(s,r,e,n,i);const a=od(o,e),c=od(o,r);a<sd&&c<sd&&(o=e,this.end()),this._prevValue=r,this._currValue=o}}};class cd{constructor(t){this.transitions=new Map,this.timeline=t}get active(){return this.transitions.size>0}add(t,e,n,i){const{transitions:s}=this;if(s.has(t)){const n=s.get(t),{value:i=n.settings.fromValue}=n;e=i,this.remove(t)}if(!(i=jf(i)))return;const r=ad[i.type];if(!r)return void F.error(`unsupported transition type '${i.type}'`)();const o=new r(this.timeline);o.start({...i,fromValue:e,toValue:n}),s.set(t,o)}remove(t){const{transitions:e}=this;e.has(t)&&(e.get(t).cancel(),e.delete(t))}update(){const t={};for(const[e,n]of this.transitions)n.update(),t[e]=n.value,n.inProgress||this.remove(e);return t}clear(){for(const t of this.transitions.keys())this.remove(t)}}function ld(t,e){if(!t.transitions)return!1;const n={},i=t[pl];let s=!1;for(const r in t.transitions){const o=i[r],a=o&&o.type;("number"===a||"color"===a||"array"===a)&&ud(t[r],e[r],o)&&(n[r]=!0,s=!0)}return!!s&&n}function hd({newProps:t,oldProps:e,ignoreProps:n={},propTypes:i={},triggerName:s="props"}){if(e===t)return!1;if("object"!=typeof t||null===t)return`${s} changed shallowly`;if("object"!=typeof e||null===e)return`${s} changed shallowly`;for(const r of Object.keys(t))if(!(r in n)){if(!(r in e))return`${s}.${r} added`;const n=ud(t[r],e[r],i[r]);if(n)return`${s}.${r} ${n}`}for(const r of Object.keys(e))if(!(r in n)){if(!(r in t))return`${s}.${r} dropped`;if(!Object.hasOwnProperty.call(t,r)){const n=ud(t[r],e[r],i[r]);if(n)return`${s}.${r} ${n}`}}return!1}function ud(t,e,n){let i=n&&n.equal;return i&&!i(t,e,n)?"changed deeply":i||(i=t&&e&&t.equals,!i||i.call(t,e))?i||e===t?null:"changed shallowly":"changed deeply"}function fd(t,e){if(null===e)return!0;const n=e.extensions,{extensions:i}=t;if(i===n)return!1;if(!n||!i)return!0;if(i.length!==n.length)return!0;for(let t=0;t<i.length;t++)if(!i[t].equals(n[t]))return!0;return!1}function dd(t,e,n){let i=t.updateTriggers[n];i=null==i?{}:i;let s=e.updateTriggers[n];return s=null==s?{}:s,hd({oldProps:s,newProps:i,triggerName:n})}function pd(t){if(null===(e=t)||"object"!=typeof e)throw new Error("count(): argument not an object");var e;if("function"==typeof t.count)return t.count();if(Number.isFinite(t.size))return t.size;if(Number.isFinite(t.length))return t.length;if(function(t){return null!==t&&"object"==typeof t&&t.constructor===Object}(t))return Object.keys(t).length;throw new Error("count(): argument not a container")}function gd(t,e){if(!e)return t;const n={...t,...e};if("defines"in e&&(n.defines={...t.defines,...e.defines}),"modules"in e&&(n.modules=(t.modules||[]).concat(e.modules),e.modules.some((t=>"project64"===t.name)))){const t=n.modules.findIndex((t=>"project32"===t.name));t>=0&&n.modules.splice(t,1)}if("inject"in e)if(t.inject){const i={...t.inject};for(const t in e.inject)i[t]=(i[t]||"")+e.inject[t];n.inject=i}else n.inject=e.inject;return n}const md={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},_d={},vd={boolean:{validate:()=>!0,equal:(t,e)=>Boolean(t)===Boolean(e)},number:{validate:(t,e)=>Number.isFinite(t)&&(!("max"in e)||t<=e.max)&&(!("min"in e)||t>=e.min)},color:{validate:(t,e)=>e.optional&&!t||wd(t)&&(3===t.length||4===t.length),equal:(t,e)=>Al(t,e,1)},accessor:{validate(t,e){const n=xd(t);return"function"===n||n===xd(e.value)},equal:(t,e)=>"function"==typeof e||Al(t,e,1)},array:{validate:(t,e)=>e.optional&&!t||wd(t),equal(t,e,n){const{compare:i}=n,s=Number.isInteger(i)?i:i?1:0;return i?Al(t,e,s):t===e}},object:{equal(t,e,n){if(n.ignore)return!0;const{compare:i}=n,s=Number.isInteger(i)?i:i?1:0;return i?Al(t,e,s):t===e}},function:{validate:(t,e)=>e.optional&&!t||"function"==typeof t,equal:(t,e,n)=>!n.compare&&!1!==n.ignore||t===e},data:{transform:(t,e,n)=>{if(!t)return t;const{dataTransform:i}=n.props;return i?i(t):"string"==typeof t.shape&&t.shape.endsWith("-table")&&Array.isArray(t.data)?t.data:t}},image:{transform:(t,e,n)=>{const i=n.context;return i&&i.device?function(t,e,n,i){if(n instanceof ye)return n;n.constructor&&"Object"!==n.constructor.name&&(n={data:n});let s=null;n.compressed&&(s={minFilter:"linear",mipmapFilter:n.data.length>1?"nearest":"linear"});const{width:r,height:o}=n.data,a=e.createTexture({...n,sampler:{...md,...s,...i},mipLevels:e.getMipLevelCount(r,o)});return a.generateMipmapsWebGL(),_d[a.id]=t,a}(n.id,i.device,t,{...e.parameters,...n.props.textureParameters}):null},release:(t,e,n)=>{var i;(i=t)&&i instanceof ye&&_d[i.id]===n.id&&(i.delete(),delete _d[i.id])}}};function bd(t,e){switch(xd(e)){case"object":return yd(t,e);case"array":return yd(t,{type:"array",value:e,compare:!1});case"boolean":return yd(t,{type:"boolean",value:e});case"number":return yd(t,{type:"number",value:e});case"function":return yd(t,{type:"function",value:e,compare:!0});default:return{name:t,type:"unknown",value:e}}}function yd(t,e){return"type"in e?{name:t,...vd[e.type],...e}:"value"in e?{name:t,type:xd(e.value),...e}:{name:t,type:"object",value:e}}function wd(t){return Array.isArray(t)||ArrayBuffer.isView(t)}function xd(t){return wd(t)?"array":null===t?"null":typeof t}function Ed(t,e){if(!(t instanceof Pd.constructor))return{};let n="_mergedDefaultProps";if(e)for(const t of e){const e=t.constructor;e&&(n+=`:${e.extensionName||e.name}`)}return Sd(t,n)||(t[n]=function(t,e){if(!t.prototype)return null;const n=Ed(Object.getPrototypeOf(t)),i=function(t){const e={},n={},i={};for(const[s,r]of Object.entries(t)){const t=r?.deprecatedFor;if(t)i[s]=Array.isArray(t)?t:[t];else{const t=bd(s,r);e[s]=t,n[s]=t.value}}return{propTypes:e,defaultProps:n,deprecatedProps:i}}(Sd(t,"defaultProps")||{}),s=Object.assign(Object.create(null),n,i.defaultProps),r=Object.assign(Object.create(null),n?.[pl],i.propTypes),o=Object.assign(Object.create(null),n?.[gl],i.deprecatedProps);for(const t of e){const e=Ed(t.constructor);e&&(Object.assign(s,e),Object.assign(r,e[pl]),Object.assign(o,e[gl]))}return function(t,e){const n=function(t){const e=t.componentName;return e||F.warn(`${t.name}.componentName not specified`)(),e||t.name}(e);Object.defineProperties(t,{id:{writable:!0,value:n}})}(s,t),function(t,e){const n={},i={};for(const t in e){const s=e[t],{name:r,value:o}=s;s.async&&(n[r]=o,i[r]=Td(r))}t[ml]=n,t[_l]={},Object.defineProperties(t,i)}(s,r),function(t,e){for(const n in e)Object.defineProperty(t,n,{enumerable:!1,set(t){const i=`${this.id}: ${n}`;for(const i of e[n])Ad(this,i)||(this[i]=t);F.deprecated(i,e[n].join("/"))()}})}(s,o),s[pl]=r,s[gl]=o,0!==e.length||Ad(t,"_propTypes")||(t._propTypes=r),s}(t,e||[]))}function Td(t){return{enumerable:!0,set(e){"string"==typeof e||e instanceof Promise||Ff(e)?this[_l][t]=e:this[vl][t]=e},get(){if(this[vl]){if(t in this[vl])return this[vl][t]||this[ml][t];if(t in this[_l]){const e=this[dl]&&this[dl].internalState;if(e&&e.hasAsyncProp(t))return e.getAsyncProp(t)||this[ml][t]}}return this[ml][t]}}}function Ad(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Sd(t,e){return Ad(t,e)&&t[e]}let Cd=0;class Pd{constructor(...t){this.props=function(t,e){let n;for(let t=e.length-1;t>=0;t--){const i=e[t];"extensions"in i&&(n=i.extensions)}const i=Ed(t.constructor,n),s=Object.create(i);s[dl]=t,s[_l]={},s[vl]={};for(let t=0;t<e.length;++t){const n=e[t];for(const t in n)s[t]=n[t]}return Object.freeze(s),s}(this,t),this.id=this.props.id,this.count=Cd++}clone(t){const{props:e}=this,n={};for(const t in e[ml])t in e[vl]?n[t]=e[vl][t]:t in e[_l]&&(n[t]=e[_l][t]);return new this.constructor({...e,...n,...t})}}Pd.componentName="Component",Pd.defaultProps={};const Md=Object.freeze({});class Rd{constructor(t){this.component=t,this.asyncProps={},this.onAsyncPropUpdated=()=>{},this.oldProps=null,this.oldAsyncProps=null}finalize(){for(const t in this.asyncProps){const e=this.asyncProps[t];e&&e.type&&e.type.release&&e.type.release(e.resolvedValue,e.type,this.component)}this.asyncProps={},this.component=null,this.resetOldProps()}getOldProps(){return this.oldAsyncProps||this.oldProps||Md}resetOldProps(){this.oldAsyncProps=null,this.oldProps=this.component?this.component.props:null}hasAsyncProp(t){return t in this.asyncProps}getAsyncProp(t){const e=this.asyncProps[t];return e&&e.resolvedValue}isAsyncPropLoading(t){if(t){const e=this.asyncProps[t];return Boolean(e&&e.pendingLoadCount>0&&e.pendingLoadCount!==e.resolvedLoadCount)}for(const t in this.asyncProps)if(this.isAsyncPropLoading(t))return!0;return!1}reloadAsyncProp(t,e){this._watchPromise(t,Promise.resolve(e))}setAsyncProps(t){this.component=t[dl]||this.component;const e=t[vl]||{},n=t[_l]||t,i=t[ml]||{};for(const t in e){const n=e[t];this._createAsyncPropData(t,i[t]),this._updateAsyncProp(t,n),e[t]=this.getAsyncProp(t)}for(const t in n){const e=n[t];this._createAsyncPropData(t,i[t]),this._updateAsyncProp(t,e)}}_fetch(t,e){return null}_onResolve(t,e){}_onError(t,e){}_updateAsyncProp(t,e){this._didAsyncInputValueChange(t,e)&&("string"==typeof e&&(e=this._fetch(t,e)),e instanceof Promise?this._watchPromise(t,e):Ff(e)?this._resolveAsyncIterable(t,e):this._setPropValue(t,e))}_freezeAsyncOldProps(){if(!this.oldAsyncProps&&this.oldProps){this.oldAsyncProps=Object.create(this.oldProps);for(const t in this.asyncProps)Object.defineProperty(this.oldAsyncProps,t,{enumerable:!0,value:this.oldProps[t]})}}_didAsyncInputValueChange(t,e){const n=this.asyncProps[t];return e!==n.resolvedValue&&e!==n.lastValue&&(n.lastValue=e,!0)}_setPropValue(t,e){this._freezeAsyncOldProps();const n=this.asyncProps[t];n&&(e=this._postProcessValue(n,e),n.resolvedValue=e,n.pendingLoadCount++,n.resolvedLoadCount=n.pendingLoadCount)}_setAsyncPropValue(t,e,n){const i=this.asyncProps[t];i&&n>=i.resolvedLoadCount&&void 0!==e&&(this._freezeAsyncOldProps(),i.resolvedValue=e,i.resolvedLoadCount=n,this.onAsyncPropUpdated(t,e))}_watchPromise(t,e){const n=this.asyncProps[t];if(n){n.pendingLoadCount++;const i=n.pendingLoadCount;e.then((e=>{this.component&&(e=this._postProcessValue(n,e),this._setAsyncPropValue(t,e,i),this._onResolve(t,e))})).catch((e=>{this._onError(t,e)}))}}async _resolveAsyncIterable(t,e){if("data"!==t)return void this._setPropValue(t,e);const n=this.asyncProps[t];if(!n)return;n.pendingLoadCount++;const i=n.pendingLoadCount;let s=[],r=0;for await(const n of e){if(!this.component)return;const{dataTransform:e}=this.component.props;s=e?e(n,s):s.concat(n),Object.defineProperty(s,"__diff",{enumerable:!1,value:[{startRow:r,endRow:s.length}]}),r=s.length,this._setAsyncPropValue(t,s,i)}this._onResolve(t,s)}_postProcessValue(t,e){const n=t.type;return n&&this.component&&(n.release&&n.release(t.resolvedValue,n,this.component),n.transform)?n.transform(e,n,this.component):e}_createAsyncPropData(t,e){if(!this.asyncProps[t]){const n=this.component&&this.component.props[pl];this.asyncProps[t]={type:n&&n[t],lastValue:null,resolvedValue:e,pendingLoadCount:0,resolvedLoadCount:0}}}}class Ld extends Rd{constructor({attributeManager:t,layer:e}){super(e),this.attributeManager=t,this.needsRedraw=!0,this.needsUpdate=!0,this.subLayers=null,this.usesPickingColorCache=!1}get layer(){return this.component}_fetch(t,e){const n=this.layer,i=n?.props.fetch;return i?i(e,{propName:t,layer:n}):super._fetch(t,e)}_onResolve(t,e){const n=this.layer;if(n){const i=n.props.onDataLoad;"data"===t&&i&&i(e,{propName:t,layer:n})}}_onError(t,e){const n=this.layer;n&&n.raiseError(e,`loading ${t} of ${this.layer}`)}}const Od=2**24-1,Id=Object.freeze([]),kd=na((({oldViewport:t,viewport:e})=>t.equals(e)));let Dd=new Uint8ClampedArray(0);const Nd={data:{type:"data",value:Id,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:n,loaders:i,loadOptions:s,signal:r})=>{const{resourceManager:o}=n.context;s=s||n.getLoadOptions(),i=i||n.props.loaders,r&&(s={...s,fetch:{...s?.fetch,signal:r}});let a=o.contains(t);return a||s||(o.add({resourceId:t,data:u(t,i),persistent:!1}),a=!0),a?o.subscribe({resourceId:t,onChange:t=>n.internalState?.reloadAsyncProp(e,t),consumerId:n.id,requestId:e}):u(t,i,s)}},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:Ko.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,100*-t]},highlightedObjectIndex:null,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}};class Fd extends Pd{constructor(){super(...arguments),this.internalState=null,this.lifecycle="Awaiting state",this.parent=null}static get componentName(){return Object.prototype.hasOwnProperty.call(this,"layerName")?this.layerName:""}get root(){let t=this;for(;t.parent;)t=t.parent;return t}toString(){return`${this.constructor.layerName||this.constructor.name}({id: '${this.props.id}'})`}project(t){jl(this.internalState);const e=this.internalState.viewport||this.context.viewport,n=Bc(t,{viewport:e,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),[i,s,r]=za(n,e.pixelProjectionMatrix);return 2===t.length?[i,s]:[i,s,r]}unproject(t){return jl(this.internalState),(this.internalState.viewport||this.context.viewport).unproject(t)}projectPosition(t,e){return jl(this.internalState),$c(t,{viewport:this.internalState.viewport||this.context.viewport,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem,...e})}get isComposite(){return!1}get isDrawable(){return!0}setState(t){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,t),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()}get wrapLongitude(){return this.props.wrapLongitude}isPickable(){return this.props.pickable&&this.props.visible}getModels(){const t=this.state;return t&&(t.models||t.model&&[t.model])||[]}setShaderModuleProps(...t){for(const e of this.getModels())e.shaderInputs.setProps(...t)}getAttributeManager(){return this.internalState&&this.internalState.attributeManager}getCurrentLayer(){return this.internalState&&this.internalState.layer}getLoadOptions(){return this.props.loadOptions}use64bitPositions(){const{coordinateSystem:t}=this.props;return t===Ko.DEFAULT||t===Ko.LNGLAT||t===Ko.CARTESIAN}onHover(t,e){return this.props.onHover&&this.props.onHover(t,e)||!1}onClick(t,e){return this.props.onClick&&this.props.onClick(t,e)||!1}nullPickingColor(){return[0,0,0]}encodePickingColor(t,e=[]){return e[0]=t+1&255,e[1]=t+1>>8&255,e[2]=t+1>>8>>8&255,e}decodePickingColor(t){jl(t instanceof Uint8Array);const[e,n,i]=t;return e+256*n+65536*i-1}getNumInstances(){return Number.isFinite(this.props.numInstances)?this.props.numInstances:this.state&&void 0!==this.state.numInstances?this.state.numInstances:pd(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(t){t=gd(t,{disableWarnings:!0,modules:this.context.defaultShaderModules});for(const e of this.props.extensions)t=gd(t,e.getShaders.call(this,e));return t}shouldUpdateState(t){return t.changeFlags.propsOrDataChanged}updateState(t){const e=this.getAttributeManager(),{dataChanged:n}=t.changeFlags;if(n&&e)if(Array.isArray(n))for(const t of n)e.invalidateAll(t);else e.invalidateAll();if(e){const{props:n}=t,i=this.internalState.hasPickingBuffer,s=Number.isInteger(n.highlightedObjectIndex)||Boolean(n.pickable)||n.extensions.some((t=>t.getNeedsPickingBuffer.call(this,t)));if(i!==s){this.internalState.hasPickingBuffer=s;const{pickingColors:t,instancePickingColors:n}=e.attributes,i=t||n;i&&(s&&i.constant&&(i.constant=!1,e.invalidate(i.id)),i.value||s||(i.constant=!0,i.value=[0,0,0]))}}}finalizeState(t){for(const t of this.getModels())t.destroy();const e=this.getAttributeManager();e&&e.finalize(),this.context&&this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState&&(this.internalState.uniformTransitions.clear(),this.internalState.finalize())}draw(t){for(const e of this.getModels())e.draw(t.renderPass)}getPickingInfo({info:t}){const{index:e}=t;return e>=0&&Array.isArray(this.props.data)&&(t.object=this.props.data[e]),t}raiseError(t,e){e&&(t=new Error(`${e}: ${t.message}`,{cause:t})),this.props.onError?.(t)||this.context?.onError?.(t,this)}getNeedsRedraw(t={clearRedrawFlags:!1}){return this._getNeedsRedraw(t)}needsUpdate(){return!!this.internalState&&(this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams()))}hasUniformTransition(){return this.internalState?.uniformTransitions.active||!1}activateViewport(t){if(!this.internalState)return;const e=this.internalState.viewport;this.internalState.viewport=t,e&&kd({oldViewport:e,viewport:t})||(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}invalidateAttribute(t="all"){const e=this.getAttributeManager();e&&("all"===t?e.invalidateAll():e.invalidate(t))}updateAttributes(t){let e=!1;for(const n in t)t[n].layoutChanged()&&(e=!0);for(const n of this.getModels())this._setModelAttributes(n,t,e)}_updateAttributes(){const t=this.getAttributeManager();if(!t)return;const e=this.props,n=this.getNumInstances(),i=this.getStartIndices();t.update({data:e.data,numInstances:n,startIndices:i,props:e,transitions:e.transitions,buffers:e.data.attributes,context:this});const s=t.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(s)}_updateAttributeTransition(){const t=this.getAttributeManager();t&&t.updateTransition()}_updateUniformTransition(){const{uniformTransitions:t}=this.internalState;if(t.active){const e=t.update(),n=Object.create(this.props);for(const t in e)Object.defineProperty(n,t,{value:e[t]});return n}return this.props}calculateInstancePickingColors(t,{numInstances:e}){if(t.constant)return;const n=Math.floor(Dd.length/4);if(this.internalState.usesPickingColorCache=!0,n<e){e>Od&&F.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),Dd=xc.allocate(Dd,e,{size:4,copy:!0,maxCount:Math.max(e,Od)});const t=Math.floor(Dd.length/4),i=[0,0,0];for(let e=n;e<t;e++)this.encodePickingColor(e,i),Dd[4*e+0]=i[0],Dd[4*e+1]=i[1],Dd[4*e+2]=i[2],Dd[4*e+3]=0}t.value=Dd.subarray(0,4*e)}_setModelAttributes(t,e,n=!1){if(!Object.keys(e).length)return;if(n){const n=this.getAttributeManager();t.setBufferLayout(n.getBufferLayouts(t)),e=n.getAttributes()}const i=t.userData?.excludeAttributes||{},s={},r={};for(const n in e){if(i[n])continue;const o=e[n].getValue();for(const i in o){const a=o[i];a instanceof It?e[n].settings.isIndexed?t.setIndexBuffer(a):s[i]=a:a&&(r[i]=a)}}t.setAttributes(s),t.setConstantAttributes(r)}disablePickingIndex(t){const e=this.props.data;if(!("attributes"in e))return void this._disablePickingIndex(t);const{pickingColors:n,instancePickingColors:i}=this.getAttributeManager().attributes,s=n||i,r=s&&e.attributes&&e.attributes[s.id];if(r&&r.value){const n=r.value,i=this.encodePickingColor(t);for(let t=0;t<e.length;t++){const e=s.getVertexOffset(t);n[e]===i[0]&&n[e+1]===i[1]&&n[e+2]===i[2]&&this._disablePickingIndex(t)}}else this._disablePickingIndex(t)}_disablePickingIndex(t){const{pickingColors:e,instancePickingColors:n}=this.getAttributeManager().attributes,i=e||n;if(!i)return;const s=i.getVertexOffset(t),r=i.getVertexOffset(t+1);i.buffer.write(new Uint8Array(r-s),s)}restorePickingColors(){const{pickingColors:t,instancePickingColors:e}=this.getAttributeManager().attributes,n=t||e;n&&(this.internalState.usesPickingColorCache&&n.value.buffer!==Dd.buffer&&(n.value=Dd.subarray(0,n.value.length)),n.updateSubBuffer({startOffset:0}))}_initialize(){jl(!this.internalState),jl(Number.isFinite(this.props.coordinateSystem)),U("layer.initialize",this);const t=this._getAttributeManager();t&&t.addInstanced({instancePickingColors:{type:"uint8",size:4,noAlloc:!0,update:this.calculateInstancePickingColors}}),this.internalState=new Ld({attributeManager:t,layer:this}),this._clearChangeFlags(),this.state={},Object.defineProperty(this.state,"attributeManager",{get:()=>(F.deprecated("layer.state.attributeManager","layer.getAttributeManager()")(),t)}),this.internalState.uniformTransitions=new cd(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props),this.initializeState(this.context);for(const t of this.props.extensions)t.initializeState.call(this,this.context,t);this.setChangeFlags({dataChanged:"init",propsChanged:"init",viewportChanged:!0,extensionsChanged:!0}),this._update()}_transferState(t){U("layer.matched",this,this===t);const{state:e,internalState:n}=t;this!==t&&(this.internalState=n,this.state=e,this.internalState.setAsyncProps(this.props),this._diffProps(this.props,this.internalState.getOldProps()))}_update(){const t=this.needsUpdate();if(U("layer.update",this,t),!t)return;const e=this.props,n=this.context,i=this.internalState,s=n.viewport,r=this._updateUniformTransition();i.propsInTransition=r,n.viewport=i.viewport||s,this.props=r;try{const t=this._getUpdateParams(),e=this.getModels();if(n.device)this.updateState(t);else try{this.updateState(t)}catch(t){}for(const e of this.props.extensions)e.updateState.call(this,t,e);this.setNeedsRedraw(),this._updateAttributes();const i=this.getModels()[0]!==e[0];this._postUpdate(t,i)}finally{n.viewport=s,this.props=e,this._clearChangeFlags(),i.needsUpdate=!1,i.resetOldProps()}}_finalize(){U("layer.finalize",this),this.finalizeState(this.context);for(const t of this.props.extensions)t.finalizeState.call(this,this.context,t)}_drawLayer({renderPass:t,shaderModuleProps:e=null,uniforms:n={},parameters:i={}}){this._updateAttributeTransition();const s=this.props,r=this.context;this.props=this.internalState.propsInTransition||s;try{e&&this.setShaderModuleProps(e);const{getPolygonOffset:s}=this.props,o=s&&s(n)||[0,0];r.device instanceof Tf&&r.device.setParametersWebGL({polygonOffset:o});for(const t of this.getModels())t.setParameters("webgpu"===t.device.type?{...t.parameters,...i}:i);if(r.device instanceof Tf)r.device.withParametersWebGL(i,(()=>{const s={renderPass:t,shaderModuleProps:e,uniforms:n,parameters:i,context:r};for(const t of this.props.extensions)t.draw.call(this,s,t);this.draw(s)}));else{const s={renderPass:t,shaderModuleProps:e,uniforms:n,parameters:i,context:r};for(const t of this.props.extensions)t.draw.call(this,s,t);this.draw(s)}}finally{this.props=s}}getChangeFlags(){return this.internalState?.changeFlags}setChangeFlags(t){if(!this.internalState)return;const{changeFlags:e}=this.internalState;for(const n in t)if(t[n]){let i=!1;if("dataChanged"===n){const s=t[n],r=e[n];s&&Array.isArray(r)&&(e.dataChanged=Array.isArray(s)?r.concat(s):s,i=!0)}e[n]||(e[n]=t[n],i=!0),i&&U("layer.changeFlag",this,n,t)}const n=Boolean(e.dataChanged||e.updateTriggersChanged||e.propsChanged||e.extensionsChanged);e.propsOrDataChanged=n,e.somethingChanged=n||e.viewportChanged||e.stateChanged}_clearChangeFlags(){this.internalState.changeFlags={dataChanged:!1,propsChanged:!1,updateTriggersChanged:!1,viewportChanged:!1,stateChanged:!1,extensionsChanged:!1,propsOrDataChanged:!1,somethingChanged:!1}}_diffProps(t,e){const n=function(t,e){const n=hd({newProps:t,oldProps:e,propTypes:t[pl],ignoreProps:{data:null,updateTriggers:null,extensions:null,transitions:null}}),i=function(t,e){if(null===e)return"oldProps is null, initial diff";let n=!1;const{dataComparator:i,_dataDiff:s}=t;return i?i(t.data,e.data)||(n="Data comparator detected a change"):t.data!==e.data&&(n="A new data container was supplied"),n&&s&&(n=s(t.data,e.data)||n),n}(t,e);let s=!1;return i||(s=function(t,e){if(null===e)return{all:!0};if("all"in t.updateTriggers&&dd(t,e,"all"))return{all:!0};const n={};let i=!1;for(const s in t.updateTriggers)"all"!==s&&dd(t,e,s)&&(n[s]=!0,i=!0);return!!i&&n}(t,e)),{dataChanged:i,propsChanged:n,updateTriggersChanged:s,extensionsChanged:fd(t,e),transitionsChanged:ld(t,e)}}(t,e);if(n.updateTriggersChanged)for(const t in n.updateTriggersChanged)n.updateTriggersChanged[t]&&this.invalidateAttribute(t);if(n.transitionsChanged)for(const i in n.transitionsChanged)this.internalState.uniformTransitions.add(i,e[i],t[i],t.transitions?.[i]);return this.setChangeFlags(n)}validateProps(){!function(t){const e=t[pl];for(const n in e){const i=e[n],{validate:s}=i;if(s&&!s(t[n],i))throw new Error(`Invalid prop ${n}: ${t[n]}`)}}(this.props)}updateAutoHighlight(t){this.props.autoHighlight&&!Number.isInteger(this.props.highlightedObjectIndex)&&this._updateAutoHighlight(t)}_updateAutoHighlight(t){const e={highlightedObjectColor:t.picked?t.color:null},{highlightColor:n}=this.props;t.picked&&"function"==typeof n&&(e.highlightColor=n(t)),this.setShaderModuleProps({picking:e}),this.setNeedsRedraw()}_getAttributeManager(){const t=this.context;return new id(t.device,{id:this.props.id,stats:t.stats,timeline:t.timeline})}_postUpdate(t,e){const{props:n,oldProps:i}=t,s=this.state.model;s?.isInstanced&&s.setInstanceCount(this.getNumInstances());const{autoHighlight:r,highlightedObjectIndex:o,highlightColor:a}=n;if(e||i.autoHighlight!==r||i.highlightedObjectIndex!==o||i.highlightColor!==a){const t={};Array.isArray(a)&&(t.highlightColor=a),(e||i.autoHighlight!==r||o!==i.highlightedObjectIndex)&&(t.highlightedObjectColor=Number.isFinite(o)&&o>=0?this.encodePickingColor(o):null),this.setShaderModuleProps({picking:t})}}_getUpdateParams(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}_getNeedsRedraw(t){if(!this.internalState)return!1;let e=!1;e=e||this.internalState.needsRedraw&&this.id;const n=this.getAttributeManager(),i=!!n&&n.getNeedsRedraw(t);if(e=e||i,e)for(const t of this.props.extensions)t.onNeedsRedraw.call(this,t);return this.internalState.needsRedraw=this.internalState.needsRedraw&&!t.clearRedrawFlags,e}_onAsyncPropUpdated(){this._diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}}Fd.defaultProps=Nd,Fd.layerName="Layer";class Bd extends Fd{get isComposite(){return!0}get isDrawable(){return!1}get isLoaded(){return super.isLoaded&&this.getSubLayers().every((t=>t.isLoaded))}getSubLayers(){return this.internalState&&this.internalState.subLayers||[]}initializeState(t){}setState(t){super.setState(t),this.setNeedsUpdate()}getPickingInfo({info:t}){const{object:e}=t;return e&&e.__source&&e.__source.parent&&e.__source.parent.id===this.id?(t.object=e.__source.object,t.index=e.__source.index,t):t}filterSubLayer(t){return!0}shouldRenderSubLayer(t,e){return e&&e.length}getSubLayerClass(t,e){const{_subLayerProps:n}=this.props;return n&&n[t]&&n[t].type||e}getSubLayerRow(t,e,n){return t.__source={parent:this,object:e,index:n},t}getSubLayerAccessor(t){if("function"==typeof t){const e={index:-1,data:this.props.data,target:[]};return(n,i)=>n&&n.__source?(e.index=n.__source.index,t(n.__source.object,e)):t(n,i)}return t}getSubLayerProps(t={}){const{opacity:e,pickable:n,visible:i,parameters:s,getPolygonOffset:r,highlightedObjectIndex:o,autoHighlight:a,highlightColor:c,coordinateSystem:l,coordinateOrigin:h,wrapLongitude:u,positionFormat:f,modelMatrix:d,extensions:p,fetch:g,operation:m,_subLayerProps:_}=this.props,v={id:"",updateTriggers:{},opacity:e,pickable:n,visible:i,parameters:s,getPolygonOffset:r,highlightedObjectIndex:o,autoHighlight:a,highlightColor:c,coordinateSystem:l,coordinateOrigin:h,wrapLongitude:u,positionFormat:f,modelMatrix:d,extensions:p,fetch:g,operation:m},b=_&&t.id&&_[t.id],y=b&&b.updateTriggers,w=t.id||"sublayer";if(b){const e=this.props[pl],n=t.type?t.type._propTypes:{};for(const t in b){const i=n[t]||e[t];i&&"accessor"===i.type&&(b[t]=this.getSubLayerAccessor(b[t]))}}Object.assign(v,t,b),v.id=`${this.props.id}-${w}`,v.updateTriggers={all:this.props.updateTriggers?.all,...t.updateTriggers,...y};for(const t of p){const e=t.getSubLayerProps.call(this,t);e&&Object.assign(v,e,{updateTriggers:Object.assign(v.updateTriggers,e.updateTriggers)})}return v}_updateAutoHighlight(t){for(const e of this.getSubLayers())e.updateAutoHighlight(t)}_getAttributeManager(){return null}_postUpdate(t,e){let n=this.internalState.subLayers;const i=!n||this.needsUpdate();i&&(n=bl(this.renderLayers(),Boolean),this.internalState.subLayers=n),U("compositeLayer.renderLayers",this,i,n);for(const t of n)t.parent=this}}Bd.layerName="CompositeLayer";class $d{constructor(t){this.indexStarts=[0],this.vertexStarts=[0],this.vertexCount=0,this.instanceCount=0;const{attributes:e={}}=t;this.typedArrayManager=xc,this.attributes={},this._attributeDefs=e,this.opts=t,this.updateGeometry(t)}updateGeometry(t){Object.assign(this.opts,t);const{data:e,buffers:n={},getGeometry:i,geometryBuffer:s,positionFormat:r,dataChanged:o,normalize:a=!0}=this.opts;if(this.data=e,this.getGeometry=i,this.positionSize=s&&s.size||("XY"===r?2:3),this.buffers=n,this.normalize=a,s&&(jl(e.startIndices),this.getGeometry=this.getGeometryFromBuffer(s),a||(n.vertexPositions=s)),this.geometryBuffer=n.vertexPositions,Array.isArray(o))for(const t of o)this._rebuildGeometry(t);else this._rebuildGeometry()}updatePartialGeometry({startRow:t,endRow:e}){this._rebuildGeometry({startRow:t,endRow:e})}getGeometryFromBuffer(t){const e=t.value||t;return ArrayBuffer.isView(e)?Bf(e,{size:this.positionSize,offset:t.offset,stride:t.stride,startIndices:this.data.startIndices}):null}_allocate(t,e){const{attributes:n,buffers:i,_attributeDefs:s,typedArrayManager:r}=this;for(const o in s)if(o in i)r.release(n[o]),n[o]=null;else{const i=s[o];i.copy=e,n[o]=r.allocate(n[o],t,i)}}_forEachGeometry(t,e,n){const{data:i,getGeometry:s}=this,{iterable:r,objectInfo:o}=Nf(i,e,n);for(const e of r)o.index++,t(s?s(e,o):null,o.index)}_rebuildGeometry(t){if(!this.data)return;let{indexStarts:e,vertexStarts:n,instanceCount:i}=this;const{data:s,geometryBuffer:r}=this,{startRow:o=0,endRow:a=1/0}=t||{},c={};if(t||(e=[0],n=[0]),this.normalize||!r)this._forEachGeometry(((t,e)=>{const i=t&&this.normalizeGeometry(t);c[e]=i,n[e+1]=n[e]+(i?this.getGeometrySize(i):0)}),o,a),i=n[n.length-1];else if(n=s.startIndices,i=n[s.length]||0,ArrayBuffer.isView(r))i=i||r.length/this.positionSize;else if(r instanceof It)i=i||r.byteLength/(4*this.positionSize);else if(r.buffer)i=i||r.buffer.byteLength/(r.stride||4*this.positionSize);else if(r.value){const t=r.value;i=i||t.length/(r.stride/t.BYTES_PER_ELEMENT||this.positionSize)}this._allocate(i,Boolean(t)),this.indexStarts=e,this.vertexStarts=n,this.instanceCount=i;const l={};this._forEachGeometry(((t,s)=>{const r=c[s]||t;l.vertexStart=n[s],l.indexStart=e[s],l.geometrySize=(s<n.length-1?n[s+1]:i)-n[s],l.geometryIndex=s,this.updateGeometryAttributes(r,l)}),o,a),this.vertexCount=e[e.length-1]}}const Ud=new Uint32Array([0,2,1,0,3,2]),zd=new Float32Array([0,1,0,0,1,0,1,1]);function jd(t,e,n){return ys(ys(t[0],t[1],n),ys(t[3],t[2],n),e)}const Gd="uniform bitmapUniforms {\n vec4 bounds;\n float coordinateConversion;\n float desaturate;\n vec3 tintColor;\n vec4 transparentColor;\n} bitmap;\n",Wd={name:"bitmap",vs:Gd,fs:Gd,uniformTypes:{bounds:"vec4<f32>",coordinateConversion:"f32",desaturate:"f32",tintColor:"vec3<f32>",transparentColor:"vec4<f32>"}},Vd={image:{type:"image",value:null,async:!0},bounds:{type:"array",value:[1,0,0,1],compare:!0},_imageCoordinateSystem:Ko.DEFAULT,desaturate:{type:"number",min:0,max:1,value:0},transparentColor:{type:"color",value:[0,0,0,0]},tintColor:{type:"color",value:[255,255,255]},textureParameters:{type:"object",ignore:!0,value:null}};class Hd extends Fd{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME bitmap-layer-vertex-shader\n\nin vec2 texCoords;\nin vec3 positions;\nin vec3 positions64Low;\n\nout vec2 vTexCoord;\nout vec2 vTexPos;\n\nconst vec3 pickingColor = vec3(1.0, 0.0, 0.0);\n\nvoid main(void) {\n geometry.worldPosition = positions;\n geometry.uv = texCoords;\n geometry.pickingColor = pickingColor;\n\n gl_Position = project_position_to_clipspace(positions, positions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vTexCoord = texCoords;\n\n if (bitmap.coordinateConversion < -0.5) {\n vTexPos = geometry.position.xy + project.commonOrigin.xy;\n } else if (bitmap.coordinateConversion > 0.5) {\n vTexPos = geometry.worldPosition.xy;\n }\n\n vec4 color = vec4(0.0);\n DECKGL_FILTER_COLOR(color, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME bitmap-layer-fragment-shader\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D bitmapTexture;\n\nin vec2 vTexCoord;\nin vec2 vTexPos;\n\nout vec4 fragColor;\n\n/* projection utils */\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / PI / 2.0;\n\n// from degrees to Web Mercator\nvec2 lnglat_to_mercator(vec2 lnglat) {\n float x = lnglat.x;\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// from Web Mercator to degrees\nvec2 mercator_to_lnglat(vec2 xy) {\n xy /= WORLD_SCALE;\n return degrees(vec2(\n xy.x - PI,\n atan(exp(xy.y - PI)) * 2.0 - PI * 0.5\n ));\n}\n/* End projection utils */\n\n// apply desaturation\nvec3 color_desaturate(vec3 color) {\n float luminance = (color.r + color.g + color.b) * 0.333333333;\n return mix(color, vec3(luminance), bitmap.desaturate);\n}\n\n// apply tint\nvec3 color_tint(vec3 color) {\n return color * bitmap.tintColor;\n}\n\n// blend with background color\nvec4 apply_opacity(vec3 color, float alpha) {\n if (bitmap.transparentColor.a == 0.0) {\n return vec4(color, alpha);\n }\n float blendedAlpha = alpha + bitmap.transparentColor.a * (1.0 - alpha);\n float highLightRatio = alpha / blendedAlpha;\n vec3 blendedRGB = mix(bitmap.transparentColor.rgb, color, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nvec2 getUV(vec2 pos) {\n return vec2(\n (pos.x - bitmap.bounds[0]) / (bitmap.bounds[2] - bitmap.bounds[0]),\n (pos.y - bitmap.bounds[3]) / (bitmap.bounds[1] - bitmap.bounds[3])\n );\n}\n\n\nvec3 packUVsIntoRGB(vec2 uv) {\n // Extract the top 8 bits. We want values to be truncated down so we can add a fraction\n vec2 uv8bit = floor(uv * 256.);\n\n // Calculate the normalized remainders of u and v parts that do not fit into 8 bits\n // Scale and clamp to 0-1 range\n vec2 uvFraction = fract(uv * 256.);\n vec2 uvFraction4bit = floor(uvFraction * 16.);\n\n // Remainder can be encoded in blue channel, encode as 4 bits for pixel coordinates\n float fractions = uvFraction4bit.x + uvFraction4bit.y * 16.;\n\n return vec3(uv8bit, fractions) / 255.;\n}\n\n\nvoid main(void) {\n vec2 uv = vTexCoord;\n if (bitmap.coordinateConversion < -0.5) {\n vec2 lnglat = mercator_to_lnglat(vTexPos);\n uv = getUV(lnglat);\n } else if (bitmap.coordinateConversion > 0.5) {\n vec2 commonPos = lnglat_to_mercator(vTexPos);\n uv = getUV(commonPos);\n }\n vec4 bitmapColor = texture(bitmapTexture, uv);\n\n fragColor = apply_opacity(color_tint(color_desaturate(bitmapColor.rgb)), bitmapColor.a * layer.opacity);\n\n geometry.uv = uv;\n DECKGL_FILTER_COLOR(fragColor, geometry);\n\n if (bool(picking.isActive) && !bool(picking.isAttribute)) {\n // Since instance information is not used, we can use picking color for pixel index\n fragColor.rgb = packUVsIntoRGB(uv);\n }\n}\n",modules:[_a,Qa,Wd]})}initializeState(){const t=this.getAttributeManager();t.remove(["instancePickingColors"]);const e=!0;t.add({indices:{size:1,isIndexed:!0,update:t=>t.value=this.state.mesh.indices,noAlloc:e},positions:{size:3,type:"float64",fp64:this.use64bitPositions(),update:t=>t.value=this.state.mesh.positions,noAlloc:e},texCoords:{size:2,update:t=>t.value=this.state.mesh.texCoords,noAlloc:e}})}updateState({props:t,oldProps:e,changeFlags:n}){const i=this.getAttributeManager();if(n.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),i.invalidateAll()),t.bounds!==e.bounds){const t=this.state.mesh,e=this._createMesh();this.state.model.setVertexCount(e.vertexCount);for(const n in e)t&&t[n]!==e[n]&&i.invalidate(n);this.setState({mesh:e,...this._getCoordinateUniforms()})}else t._imageCoordinateSystem!==e._imageCoordinateSystem&&this.setState(this._getCoordinateUniforms())}getPickingInfo(t){const{image:e}=this.props,n=t.info;if(!n.color||!e)return n.bitmap=null,n;const{width:i,height:s}=e;n.index=0;const r=function(t){const[e,n,i]=t;return[(e+(15&i)/16)/256,(n+(240&i)/256)/256]}(n.color);return n.bitmap={size:{width:i,height:s},uv:r,pixel:[Math.floor(r[0]*i),Math.floor(r[1]*s)]},n}disablePickingIndex(){this.setState({disablePicking:!0})}restorePickingColors(){this.setState({disablePicking:!1})}_updateAutoHighlight(t){super._updateAutoHighlight({...t,color:this.encodePickingColor(0)})}_createMesh(){const{bounds:t}=this.props;let e=t;return Xd(t)&&(e=[[t[0],t[1]],[t[0],t[3]],[t[2],t[3]],[t[2],t[1]]]),function(t,e){if(!e)return function(t){const e=new Float64Array(12);for(let n=0;n<t.length;n++)e[3*n+0]=t[n][0],e[3*n+1]=t[n][1],e[3*n+2]=t[n][2]||0;return{vertexCount:6,positions:e,indices:Ud,texCoords:zd}}(t);const n=Math.max(Math.abs(t[0][0]-t[3][0]),Math.abs(t[1][0]-t[2][0])),i=Math.max(Math.abs(t[1][1]-t[0][1]),Math.abs(t[2][1]-t[3][1])),s=Math.ceil(n/e)+1,r=Math.ceil(i/e)+1,o=(s-1)*(r-1)*6,a=new Uint32Array(o),c=new Float32Array(s*r*2),l=new Float64Array(s*r*3);let h=0,u=0;for(let e=0;e<s;e++){const n=e/(s-1);for(let i=0;i<r;i++){const s=i/(r-1),o=jd(t,n,s);l[3*h+0]=o[0],l[3*h+1]=o[1],l[3*h+2]=o[2]||0,c[2*h+0]=n,c[2*h+1]=1-s,e>0&&i>0&&(a[u++]=h-r,a[u++]=h-r-1,a[u++]=h-1,a[u++]=h-r,a[u++]=h-1,a[u++]=h),h++}}return{vertexCount:o,positions:l,indices:a,texCoords:c}}(e,this.context.viewport.resolution)}_getModel(){return new ol(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),topology:"triangle-list",isInstanced:!1})}draw(t){const{shaderModuleProps:e}=t,{model:n,coordinateConversion:i,bounds:s,disablePicking:r}=this.state,{image:o,desaturate:a,transparentColor:c,tintColor:l}=this.props;if((!e.picking.isActive||!r)&&o&&n){const t={bitmapTexture:o,bounds:s,coordinateConversion:i,desaturate:a,tintColor:l.slice(0,3).map((t=>t/255)),transparentColor:c.map((t=>t/255))};n.shaderInputs.setProps({bitmap:t}),n.draw(this.context.renderPass)}}_getCoordinateUniforms(){const{LNGLAT:t,CARTESIAN:e,DEFAULT:n}=Ko;let{_imageCoordinateSystem:i}=this.props;if(i!==n){const{bounds:n}=this.props;if(!Xd(n))throw new Error("_imageCoordinateSystem only supports rectangular bounds");const s=this.context.viewport.resolution?t:e;if(i=i===t?t:e,i===t&&s===e)return{coordinateConversion:-1,bounds:n};if(i===e&&s===t){const t=Ia([n[0],n[1]]),e=Ia([n[2],n[3]]);return{coordinateConversion:1,bounds:[t[0],t[1],e[0],e[1]]}}}return{coordinateConversion:0,bounds:[0,0,0,0]}}}function Xd(t){return Number.isFinite(t[0])}Hd.layerName="BitmapLayer",Hd.defaultProps=Vd;const Zd="uniform iconUniforms {\n float sizeScale;\n vec2 iconsTextureDim;\n float sizeBasis;\n float sizeMinPixels;\n float sizeMaxPixels;\n bool billboard;\n highp int sizeUnits;\n float alphaCutoff;\n} icon;\n",Kd={name:"icon",vs:Zd,fs:Zd,uniformTypes:{sizeScale:"f32",iconsTextureDim:"vec2<f32>",sizeBasis:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",billboard:"f32",sizeUnits:"i32",alphaCutoff:"f32"}},qd=()=>{},Yd={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},Jd={x:0,y:0,width:0,height:0};function Qd(t,e,n,i){const s=Math.min(n/e.width,i/e.height),r=Math.floor(e.width*s),o=Math.floor(e.height*s);return 1===s?{image:e,width:r,height:o}:(t.canvas.height=o,t.canvas.width=r,t.clearRect(0,0,r,o),t.drawImage(e,0,0,e.width,e.height,0,0,r,o),{image:t.canvas,width:r,height:o})}function tp(t){return t&&(t.id||t.url)}function ep(t,e,n){for(let i=0;i<e.length;i++){const{icon:s,xOffset:r}=e[i];t[tp(s)]={...s,x:r,y:n}}}class np{constructor(t,{onUpdate:e=qd,onError:n=qd}){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=4,this._canvasWidth=1024,this._canvasHeight=0,this._canvas=null,this.device=t,this.onUpdate=e,this.onError=n}finalize(){this._texture?.delete()}getTexture(){return this._texture||this._externalTexture}getIconMapping(t){const e=this._autoPacking?tp(t):t;return this._mapping[e]||Jd}setProps({loadOptions:t,autoPacking:e,iconAtlas:n,iconMapping:i,textureParameters:s}){t&&(this._loadOptions=t),void 0!==e&&(this._autoPacking=e),i&&(this._mapping=i),n&&(this._texture?.delete(),this._texture=null,this._externalTexture=n),s&&(this._samplerParameters=s)}get isLoaded(){return 0===this._pendingCount}packIcons(t,e){if(!this._autoPacking||"undefined"==typeof document)return;const n=Object.values(function(t,e,n){if(!t||!e)return null;n=n||{};const i={},{iterable:s,objectInfo:r}=Nf(t);for(const t of s){r.index++;const s=e(t,r),o=tp(s);if(!s)throw new Error("Icon is missing.");if(!s.url)throw new Error("Icon url is missing.");i[o]||n[o]&&s.url===n[o].url||(i[o]={...s,source:t,sourceIndex:r.index})}return i}(t,e,this._mapping)||{});if(n.length>0){const{mapping:t,xOffset:e,yOffset:i,rowHeight:s,canvasHeight:r}=function({icons:t,buffer:e,mapping:n={},xOffset:i=0,yOffset:s=0,rowHeight:r=0,canvasWidth:o}){let a=[];for(let c=0;c<t.length;c++){const l=t[c];if(!n[tp(l)]){const{height:t,width:c}=l;i+c+e>o&&(ep(n,a,s),i=0,s=r+s+e,r=0,a=[]),a.push({icon:l,xOffset:i}),i=i+c+e,r=Math.max(r,t)}}return a.length>0&&ep(n,a,s),{mapping:n,rowHeight:r,xOffset:i,yOffset:s,canvasWidth:o,canvasHeight:(c=r+s+e,Math.pow(2,Math.ceil(Math.log2(c))))};var c}({icons:n,buffer:this._buffer,canvasWidth:this._canvasWidth,mapping:this._mapping,rowHeight:this._rowHeight,xOffset:this._xOffset,yOffset:this._yOffset});this._rowHeight=s,this._mapping=t,this._xOffset=e,this._yOffset=i,this._canvasHeight=r,this._texture||(this._texture=this.device.createTexture({format:"rgba8unorm",data:null,width:this._canvasWidth,height:this._canvasHeight,sampler:this._samplerParameters||Yd,mipLevels:this.device.getMipLevelCount(this._canvasWidth,this._canvasHeight)})),this._texture.height!==this._canvasHeight&&(this._texture=function(t,e,n,i){const{width:s,height:r,device:o}=t,a=o.createTexture({format:"rgba8unorm",width:e,height:n,sampler:i,mipLevels:o.getMipLevelCount(e,n)}),c=o.createCommandEncoder();return c.copyTextureToTexture({sourceTexture:t,destinationTexture:a,width:s,height:r}),c.finish(),a.generateMipmapsWebGL(),t.destroy(),a}(this._texture,this._canvasWidth,this._canvasHeight,this._samplerParameters||Yd)),this.onUpdate(!0),this._canvas=this._canvas||document.createElement("canvas"),this._loadIcons(n)}}_loadIcons(t){const e=this._canvas.getContext("2d",{willReadFrequently:!0});for(const n of t)this._pendingCount++,u(n.url,this._loadOptions).then((t=>{const i=tp(n),s=this._mapping[i],{x:r,y:o,width:a,height:c}=s,{image:l,width:h,height:u}=Qd(e,t,a,c),f=r+(a-h)/2,d=o+(c-u)/2;this._texture?.copyExternalImage({image:l,x:f,y:d,width:h,height:u}),s.x=f,s.y=d,s.width=h,s.height=u,this._texture?.generateMipmapsWebGL(),this.onUpdate(h!==a||u!==c)})).catch((t=>{this.onError({url:n.url,source:n.source,sourceIndex:n.sourceIndex,loadOptions:this._loadOptions,error:t})})).finally((()=>{this._pendingCount--}))}}const ip=[0,0,0,255],sp={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:ip},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}};class rp extends Fd{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME icon-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = angle * PI / 180.0;\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\ngeometry.pickingColor = instancePickingColors;\nuv = positions;\nvec2 iconSize = instanceIconFrames.zw;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\nicon.sizeMinPixels, icon.sizeMaxPixels\n);\nfloat iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y;\nfloat instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint;\nvec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\npixelOffset += instancePixelOffset;\npixelOffset.y *= -1.0;\nif (icon.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nDECKGL_FILTER_SIZE(offset_common, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvTextureCoords = mix(\ninstanceIconFrames.xy,\ninstanceIconFrames.xy + iconSize,\n(positions.xy + 1.0) / 2.0\n) / icon.iconsTextureDim;\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\nvColorMode = instanceColorModes;\n}\n",fs:"#version 300 es\n#define SHADER_NAME icon-layer-fragment-shader\nprecision highp float;\nuniform sampler2D iconsTexture;\nin float vColorMode;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nvec4 texColor = texture(iconsTexture, vTextureCoords);\nvec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\nfloat a = texColor.a * layer.opacity * vColor.a;\nif (a < icon.alphaCutoff) {\ndiscard;\n}\nfragColor = vec4(color, a);\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",modules:[_a,Qa,Kd]})}initializeState(){this.state={iconManager:new np(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},instanceOffsets:{size:2,accessor:"getIcon",transform:this.getInstanceOffset},instanceIconFrames:{size:4,accessor:"getIcon",transform:this.getInstanceIconFrame},instanceColorModes:{size:1,type:"uint8",accessor:"getIcon",transform:this.getInstanceColorMode},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:ip},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instancePixelOffset:{size:2,transition:!0,accessor:"getPixelOffset"}})}updateState(t){super.updateState(t);const{props:e,oldProps:n,changeFlags:i}=t,s=this.getAttributeManager(),{iconAtlas:r,iconMapping:o,data:a,getIcon:c,textureParameters:l}=e,{iconManager:h}=this.state;if("string"==typeof r)return;const u=r||this.internalState.isAsyncPropLoading("iconAtlas");h.setProps({loadOptions:e.loadOptions,autoPacking:!u,iconAtlas:r,iconMapping:u?o:null,textureParameters:l}),u?n.iconMapping!==e.iconMapping&&s.invalidate("getIcon"):(i.dataChanged||i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getIcon))&&h.packIcons(a,c),i.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),s.invalidateAll())}get isLoaded(){return super.isLoaded&&this.state.iconManager.isLoaded}finalizeState(t){super.finalizeState(t),this.state.iconManager.finalize()}draw({}){const{sizeScale:t,sizeBasis:e,sizeMinPixels:n,sizeMaxPixels:i,sizeUnits:s,billboard:r,alphaCutoff:o}=this.props,{iconManager:a}=this.state,c=a.getTexture();if(c){const a=this.state.model;a.shaderInputs.setProps({icon:{iconsTexture:c,iconsTextureDim:[c.width,c.height],sizeUnits:Yo[s],sizeScale:t,sizeBasis:"height"===e?1:0,sizeMinPixels:n,sizeMaxPixels:i,billboard:r,alphaCutoff:o}}),a.draw(this.context.renderPass)}}_getModel(){return new ol(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new ll({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array([-1,-1,1,-1,-1,1,1,1])}}}),isInstanced:!0})}_onUpdate(t){t?(this.getAttributeManager()?.invalidate("getIcon"),this.setNeedsUpdate()):this.setNeedsRedraw()}_onError(t){const e=this.getCurrentLayer()?.props.onIconError;e?e(t):F.error(t.error.message)()}getInstanceOffset(t){const{width:e,height:n,anchorX:i=e/2,anchorY:s=n/2}=this.state.iconManager.getIconMapping(t);return[e/2-i,n/2-s]}getInstanceColorMode(t){return this.state.iconManager.getIconMapping(t).mask?1:0}getInstanceIconFrame(t){const{x:e,y:n,width:i,height:s}=this.state.iconManager.getIconMapping(t);return[e,n,i,s]}}rp.defaultProps=sp,rp.layerName="IconLayer";const op="uniform scatterplotUniforms {\n float radiusScale;\n float radiusMinPixels;\n float radiusMaxPixels;\n float lineWidthScale;\n float lineWidthMinPixels;\n float lineWidthMaxPixels;\n float stroked;\n float filled;\n bool antialiasing;\n bool billboard;\n highp int radiusUnits;\n highp int lineWidthUnits;\n} scatterplot;\n",ap={name:"scatterplot",vs:op,fs:op,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"}},cp=[0,0,0,255],lp={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:cp},getLineColor:{type:"accessor",value:cp},getLineWidth:{type:"accessor",value:1},strokeWidth:{deprecatedFor:"getLineWidth"},outline:{deprecatedFor:"stroked"},getColor:{deprecatedFor:["getFillColor","getLineColor"]}};class hp extends Fd{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME scatterplot-layer-vertex-shader\nin vec3 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceRadius;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin vec3 instancePickingColors;\nout vec4 vFillColor;\nout vec4 vLineColor;\nout vec2 unitPosition;\nout float innerUnitRadius;\nout float outerRadiusPixels;\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\nouterRadiusPixels = clamp(\nproject_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits),\nscatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n);\nfloat lineWidthPixels = clamp(\nproject_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits),\nscatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n);\nouterRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\nfloat edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0;\nunitPosition = edgePadding * positions.xy;\ngeometry.uv = unitPosition;\ngeometry.pickingColor = instancePickingColors;\ninnerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels;\nif (scatterplot.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = edgePadding * positions * outerRadiusPixels;\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vFillColor, geometry);\nvLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME scatterplot-layer-fragment-shader\nprecision highp float;\nin vec4 vFillColor;\nin vec4 vLineColor;\nin vec2 unitPosition;\nin float innerUnitRadius;\nin float outerRadiusPixels;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = unitPosition;\nfloat distToCenter = length(unitPosition) * outerRadiusPixels;\nfloat inCircle = scatterplot.antialiasing ?\nsmoothedge(distToCenter, outerRadiusPixels) :\nstep(distToCenter, outerRadiusPixels);\nif (inCircle == 0.0) {\ndiscard;\n}\nif (scatterplot.stroked > 0.5) {\nfloat isLine = scatterplot.antialiasing ?\nsmoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\nstep(innerUnitRadius * outerRadiusPixels, distToCenter);\nif (scatterplot.filled > 0.5) {\nfragColor = mix(vFillColor, vLineColor, isLine);\n} else {\nif (isLine == 0.0) {\ndiscard;\n}\nfragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n}\n} else if (scatterplot.filled < 0.5) {\ndiscard;\n} else {\nfragColor = vFillColor;\n}\nfragColor.a *= inCircle;\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"// Main shaders\n\nstruct ScatterplotUniforms {\n radiusScale: f32,\n radiusMinPixels: f32,\n radiusMaxPixels: f32,\n lineWidthScale: f32,\n lineWidthMinPixels: f32,\n lineWidthMaxPixels: f32,\n stroked: f32,\n filled: i32,\n antialiasing: i32,\n billboard: i32,\n radiusUnits: i32,\n lineWidthUnits: i32,\n};\n\nstruct ConstantAttributeUniforms {\n instancePositions: vec3<f32>,\n instancePositions64Low: vec3<f32>,\n instanceRadius: f32,\n instanceLineWidths: f32,\n instanceFillColors: vec4<f32>,\n instanceLineColors: vec4<f32>,\n instancePickingColors: vec3<f32>,\n\n instancePositionsConstant: i32,\n instancePositions64LowConstant: i32,\n instanceRadiusConstant: i32,\n instanceLineWidthsConstant: i32,\n instanceFillColorsConstant: i32,\n instanceLineColorsConstant: i32,\n instancePickingColorsConstant: i32\n};\n\n@group(0) @binding(2) var<uniform> scatterplot: ScatterplotUniforms;\n\nstruct ConstantAttributes {\n instancePositions: vec3<f32>,\n instancePositions64Low: vec3<f32>,\n instanceRadius: f32,\n instanceLineWidths: f32,\n instanceFillColors: vec4<f32>,\n instanceLineColors: vec4<f32>,\n instancePickingColors: vec3<f32>\n};\n\nconst constants = ConstantAttributes(\n vec3<f32>(0.0),\n vec3<f32>(0.0),\n 0.0,\n 0.0,\n vec4<f32>(0.0, 0.0, 0.0, 1.0),\n vec4<f32>(0.0, 0.0, 0.0, 1.0),\n vec3<f32>(0.0)\n);\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceRadius: f32,\n @location(4) instanceLineWidths: f32,\n @location(5) instanceFillColors: vec4<f32>,\n @location(6) instanceLineColors: vec4<f32>,\n @location(7) instancePickingColors: vec3<f32>\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vFillColor: vec4<f32>,\n @location(1) vLineColor: vec4<f32>,\n @location(2) unitPosition: vec2<f32>,\n @location(3) innerUnitRadius: f32,\n @location(4) outerRadiusPixels: f32,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n // Draw an inline geometry constant array clip space triangle to verify that rendering works.\n // var positions = array<vec2<f32>, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5));\n // if (attributes.instanceIndex == 0) {\n // varyings.position = vec4<f32>(positions[attributes.vertexIndex], 0.0, 1.0);\n // return varyings;\n // }\n\n // var geometry: Geometry;\n // geometry.worldPosition = instancePositions;\n\n // Multiply out radius and clamp to limits\n varyings.outerRadiusPixels = clamp(\n project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n\n // Multiply out line width and clamp to limits\n let lineWidthPixels = clamp(\n project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accommodate edge smoothing\n let edgePadding = select(\n (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels,\n 1.0,\n scatterplot.antialiasing != 0\n );\n\n // position on the containing square in [-1, 1] space\n varyings.unitPosition = edgePadding * attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = attributes.instancePickingColors;\n\n varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels;\n\n if (scatterplot.billboard != 0) {\n varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3<f32>(0.0)); // TODO , geometry.position);\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels;\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position.x = clipPixels.x;\n varyings.position.y = clipPixels.y;\n } else {\n let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels);\n // DECKGL_FILTER_SIZE(offset, geometry);\n varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position);\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vFillColor = vec4<f32>(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * color.opacity);\n // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry);\n varyings.vLineColor = vec4<f32>(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * color.opacity);\n // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry);\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n // var geometry: Geometry;\n // geometry.uv = unitPosition;\n\n let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels;\n let inCircle = select(\n smoothedge(distToCenter, varyings.outerRadiusPixels),\n step(distToCenter, varyings.outerRadiusPixels),\n scatterplot.antialiasing != 0\n );\n\n if (inCircle == 0.0) {\n discard;\n }\n\n var fragColor: vec4<f32>;\n\n if (scatterplot.stroked != 0) {\n let isLine = select(\n smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n scatterplot.antialiasing != 0\n );\n\n if (scatterplot.filled != 0) {\n fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4<f32>(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine);\n }\n } else if (scatterplot.filled == 0) {\n discard;\n } else {\n fragColor = varyings.vFillColor;\n }\n\n fragColor.a *= inCircle;\n // DECKGL_FILTER_COLOR(fragColor, geometry);\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n // return vec4<f32>(0, 0, 1, 1);\n}\n",modules:[_a,Kr,Qa,ap]})}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(t){super.updateState(t),t.changeFlags.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({}){const{radiusUnits:t,radiusScale:e,radiusMinPixels:n,radiusMaxPixels:i,stroked:s,filled:r,billboard:o,antialiasing:a,lineWidthUnits:c,lineWidthScale:l,lineWidthMinPixels:h,lineWidthMaxPixels:u}=this.props,f=this.state.model;f.shaderInputs.setProps({scatterplot:{stroked:s,filled:r,billboard:o,antialiasing:a,radiusUnits:Yo[t],radiusScale:e,radiusMinPixels:n,radiusMaxPixels:i,lineWidthUnits:Yo[c],lineWidthScale:l,lineWidthMinPixels:h,lineWidthMaxPixels:u}}),"webgpu"===this.context.device.type&&(f.instanceCount=this.props.data.length),f.draw(this.context.renderPass)}_getModel(){const t="webgpu"===this.context.device.type?{depthWriteEnabled:!0,depthCompare:"less-equal"}:void 0;return new ol(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new ll({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array([-1,-1,0,1,-1,0,-1,1,0,1,1,0])}}}),isInstanced:!0,parameters:t})}}hp.defaultProps=lp,hp.layerName="ScatterplotLayer";const up={CLOCKWISE:1,COUNTER_CLOCKWISE:-1};function fp(t,e,n={}){const i=function(t,e={}){return Math.sign(function(t,e={}){const{start:n=0,end:i=t.length,plane:s="xy"}=e,r=e.size||2;let o=0;const a=dp[s[0]],c=dp[s[1]];for(let e=n,s=i-r;e<i;e+=r)o+=(t[e+a]-t[s+a])*(t[e+c]+t[s+c]),s=e;return o/2}(t,e))}(t,n);return i!==e&&(function(t,e){const{start:n=0,end:i=t.length,size:s=2}=e,r=(i-n)/s,o=Math.floor(r/2);for(let e=0;e<o;++e){const i=n+e*s,o=n+(r-1-e)*s;for(let e=0;e<s;++e){const n=t[i+e];t[i+e]=t[o+e],t[o+e]=n}}}(t,n),!0)}const dp={x:0,y:1,z:2};function pp(t,e){const n=e.length,i=t.length;if(i>0){let s=!0;for(let r=0;r<n;r++)if(t[i-n+r]!==e[r]){s=!1;break}if(s)return!1}for(let s=0;s<n;s++)t[i+s]=e[s];return!0}function gp(t,e){const n=e.length;for(let i=0;i<n;i++)t[i]=e[i]}function mp(t,e,n,i,s=[]){const r=i+e*n;for(let e=0;e<n;e++)s[e]=t[r+e];return s}function _p(t,e,n,i,s=[]){let r,o;if(8&n)r=(i[3]-t[1])/(e[1]-t[1]),o=3;else if(4&n)r=(i[1]-t[1])/(e[1]-t[1]),o=1;else if(2&n)r=(i[2]-t[0])/(e[0]-t[0]),o=2;else{if(!(1&n))return null;r=(i[0]-t[0])/(e[0]-t[0]),o=0}for(let n=0;n<t.length;n++)s[n]=(1&o)===n?i[o]:r*(e[n]-t[n])+t[n];return s}function vp(t,e){let n=0;return t[0]<e[0]?n|=1:t[0]>e[2]&&(n|=2),t[1]<e[1]?n|=4:t[1]>e[3]&&(n|=8),n}function bp(t,e){const{size:n=2,broken:i=!1,gridResolution:s=10,gridOffset:r=[0,0],startIndex:o=0,endIndex:a=t.length}=e||{},c=(a-o)/n;let l=[];const h=[l],u=mp(t,0,n,o);let f,d;const p=xp(u,s,r,[]),g=[];pp(l,u);for(let e=1;e<c;e++){for(f=mp(t,e,n,o,f),d=vp(f,p);d;){_p(u,f,d,p,g);const t=vp(g,p);t&&(_p(u,g,t,p,g),d=t),pp(l,g),gp(u,g),Ep(p,s,d),i&&l.length>n&&(l=[],h.push(l),pp(l,u)),d=vp(f,p)}pp(l,f),gp(u,f)}return i?h:h[0]}function yp(t,e=null,n){if(!t.length)return[];const{size:i=2,gridResolution:s=10,gridOffset:r=[0,0],edgeTypes:o=!1}=n||{},a=[],c=[{pos:t,types:o?new Array(t.length/i).fill(1):null,holes:e||[]}],l=[[],[]];let h=[];for(;c.length;){const{pos:t,types:e,holes:n}=c.shift();Tp(t,i,n[0]||t.length,l),h=xp(l[0],s,r,h);const u=vp(l[1],h);if(u){let s=wp(t,e,i,0,n[0]||t.length,h,u);const r={pos:s[0].pos,types:s[0].types,holes:[]},a={pos:s[1].pos,types:s[1].types,holes:[]};c.push(r,a);for(let c=0;c<n.length;c++)s=wp(t,e,i,n[c],n[c+1]||t.length,h,u),s[0]&&(r.holes.push(r.pos.length),r.pos=Ap(r.pos,s[0].pos),o&&(r.types=Ap(r.types,s[0].types))),s[1]&&(a.holes.push(a.pos.length),a.pos=Ap(a.pos,s[1].pos),o&&(a.types=Ap(a.types,s[1].types)))}else{const i={positions:t};o&&(i.edgeTypes=e),n.length&&(i.holeIndices=n),a.push(i)}}return a}function wp(t,e,n,i,s,r,o){const a=(s-i)/n,c=[],l=[],h=[],u=[],f=[];let d,p,g;const m=mp(t,a-1,n,i);let _=Math.sign(8&o?m[1]-r[3]:m[0]-r[2]),v=e&&e[a-1],b=0,y=0;for(let s=0;s<a;s++)d=mp(t,s,n,i,d),p=Math.sign(8&o?d[1]-r[3]:d[0]-r[2]),g=e&&e[i/n+s],p&&_&&_!==p&&(_p(m,d,o,r,f),pp(c,f)&&h.push(v),pp(l,f)&&u.push(v)),p<=0?(pp(c,d)&&h.push(g),b-=p):h.length&&(h[h.length-1]=0),p>=0?(pp(l,d)&&u.push(g),y+=p):u.length&&(u[u.length-1]=0),gp(m,d),_=p,v=g;return[b?{pos:c,types:e&&h}:null,y?{pos:l,types:e&&u}:null]}function xp(t,e,n,i){const s=Math.floor((t[0]-n[0])/e)*e+n[0],r=Math.floor((t[1]-n[1])/e)*e+n[1];return i[0]=s,i[1]=r,i[2]=s+e,i[3]=r+e,i}function Ep(t,e,n){8&n?(t[1]+=e,t[3]+=e):4&n?(t[1]-=e,t[3]-=e):2&n?(t[0]+=e,t[2]+=e):1&n&&(t[0]-=e,t[2]-=e)}function Tp(t,e,n,i){let s=1/0,r=-1/0,o=1/0,a=-1/0;for(let i=0;i<n;i+=e){const e=t[i],n=t[i+1];s=e<s?e:s,r=e>r?e:r,o=n<o?n:o,a=n>a?n:a}return i[0][0]=s,i[0][1]=o,i[1][0]=r,i[1][1]=a,i}function Ap(t,e){for(let n=0;n<e.length;n++)t.push(e[n]);return t}function Sp(t,e,n,i){let s=-1,r=-1;for(let o=n+1;o<i;o+=e){const e=Math.abs(t[o]);e>s&&(s=e,r=o-1)}return r}function Cp(t,e,n,i,s=85.051129){const r=t[n],o=t[i-e];if(Math.abs(r-o)>180){const i=mp(t,0,e,n);i[0]+=360*Math.round((o-r)/360),pp(t,i),i[1]=Math.sign(i[1])*s,pp(t,i),i[0]=r,pp(t,i)}}function Pp(t,e,n,i){let s,r=t[0];for(let o=n;o<i;o+=e){s=t[o];const e=s-r;(e>180||e<-180)&&(s-=360*Math.round(e/360)),t[o]=r=s}}function Mp(t,e){let n;const i=t.length/e;for(let s=0;s<i&&(n=t[s*e],(n+180)%360==0);s++);const s=360*-Math.round(n/360);if(0!==s)for(let n=0;n<i;n++)t[n*e]+=s}class Rp extends $d{constructor(t){super({...t,attributes:{positions:{size:3,padding:18,initialize:!0,type:t.fp64?Float64Array:Float32Array},segmentTypes:{size:1,type:Uint8ClampedArray}}})}get(t){return this.attributes[t]}getGeometryFromBuffer(t){return this.normalize?super.getGeometryFromBuffer(t):null}normalizeGeometry(t){return this.normalize?function(t,e,n,i){let s;if(Array.isArray(t[0])){s=new Array(t.length*e);for(let n=0;n<t.length;n++)for(let i=0;i<e;i++)s[n*e+i]=t[n][i]||0}else s=t;return n?bp(s,{size:e,gridResolution:n}):i?function(t,e){const{size:n=2,startIndex:i=0,endIndex:s=t.length,normalize:r=!0}=e||{},o=t.slice(i,s);Pp(o,n,0,s-i);const a=bp(o,{size:n,broken:!0,gridResolution:360,gridOffset:[-180,-180]});if(r)for(const t of a)Mp(t,n);return a}(s,{size:e}):s}(t,this.positionSize,this.opts.resolution,this.opts.wrapLongitude):t}getGeometrySize(t){if(Lp(t)){let e=0;for(const n of t)e+=this.getGeometrySize(n);return e}const e=this.getPathLength(t);return e<2?0:this.isClosed(t)?e<3?0:e+2:e}updateGeometryAttributes(t,e){if(0!==e.geometrySize)if(t&&Lp(t))for(const n of t){const t=this.getGeometrySize(n);e.geometrySize=t,this.updateGeometryAttributes(n,e),e.vertexStart+=t}else this._updateSegmentTypes(t,e),this._updatePositions(t,e)}_updateSegmentTypes(t,e){const n=this.attributes.segmentTypes,i=!!t&&this.isClosed(t),{vertexStart:s,geometrySize:r}=e;n.fill(0,s,s+r),i?(n[s]=4,n[s+r-2]=4):(n[s]+=1,n[s+r-2]+=2),n[s+r-1]=4}_updatePositions(t,e){const{positions:n}=this.attributes;if(!n||!t)return;const{vertexStart:i,geometrySize:s}=e,r=new Array(3);for(let e=i,o=0;o<s;e++,o++)this.getPointOnPath(t,o,r),n[3*e]=r[0],n[3*e+1]=r[1],n[3*e+2]=r[2]}getPathLength(t){return t.length/this.positionSize}getPointOnPath(t,e,n=[]){const{positionSize:i}=this;e*i>=t.length&&(e+=1-t.length/i);const s=e*i;return n[0]=t[s],n[1]=t[s+1],n[2]=3===i&&t[s+2]||0,n}isClosed(t){if(!this.normalize)return Boolean(this.opts.loop);const{positionSize:e}=this,n=t.length-e;return t[0]===t[n]&&t[1]===t[n+1]&&(2===e||t[2]===t[n+2])}}function Lp(t){return Array.isArray(t[0])}const Op="uniform pathUniforms {\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n float jointType;\n float capType;\n float miterLimit;\n bool billboard;\n highp int widthUnits;\n} path;\n",Ip={name:"path",vs:Op,fs:Op,uniformTypes:{widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",jointType:"f32",capType:"f32",miterLimit:"f32",billboard:"f32",widthUnits:"i32"}},kp=[0,0,0,255],Dp={widthUnits:"meters",widthScale:{type:"number",min:0,value:1},widthMinPixels:{type:"number",min:0,value:0},widthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},jointRounded:!1,capRounded:!1,miterLimit:{type:"number",min:0,value:4},billboard:!1,_pathType:null,getPath:{type:"accessor",value:t=>t.path},getColor:{type:"accessor",value:kp},getWidth:{type:"accessor",value:1},rounded:{deprecatedFor:["jointRounded","capRounded"]}},Np={enter:(t,e)=>e.length?e.subarray(e.length-t.length):t};class Fp extends Fd{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME path-layer-vertex-shader\nin vec2 positions;\nin float instanceTypes;\nin vec3 instanceStartPositions;\nin vec3 instanceEndPositions;\nin vec3 instanceLeftPositions;\nin vec3 instanceRightPositions;\nin vec3 instanceLeftPositions64Low;\nin vec3 instanceStartPositions64Low;\nin vec3 instanceEndPositions64Low;\nin vec3 instanceRightPositions64Low;\nin float instanceStrokeWidths;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nuniform float opacity;\nout vec4 vColor;\nout vec2 vCornerOffset;\nout float vMiterLength;\nout vec2 vPathPosition;\nout float vPathLength;\nout float vJointType;\nconst float EPSILON = 0.001;\nconst vec3 ZERO_OFFSET = vec3(0.0);\nfloat flipIfTrue(bool flag) {\nreturn -(float(flag) * 2. - 1.);\n}\nvec3 getLineJoinOffset(\nvec3 prevPoint, vec3 currPoint, vec3 nextPoint,\nvec2 width\n) {\nbool isEnd = positions.x > 0.0;\nfloat sideOfPath = positions.y;\nfloat isJoint = float(sideOfPath == 0.0);\nvec3 deltaA3 = (currPoint - prevPoint);\nvec3 deltaB3 = (nextPoint - currPoint);\nmat3 rotationMatrix;\nbool needsRotation = !path.billboard && project_needs_rotation(currPoint, rotationMatrix);\nif (needsRotation) {\ndeltaA3 = deltaA3 * rotationMatrix;\ndeltaB3 = deltaB3 * rotationMatrix;\n}\nvec2 deltaA = deltaA3.xy / width;\nvec2 deltaB = deltaB3.xy / width;\nfloat lenA = length(deltaA);\nfloat lenB = length(deltaB);\nvec2 dirA = lenA > 0. ? normalize(deltaA) : vec2(0.0, 0.0);\nvec2 dirB = lenB > 0. ? normalize(deltaB) : vec2(0.0, 0.0);\nvec2 perpA = vec2(-dirA.y, dirA.x);\nvec2 perpB = vec2(-dirB.y, dirB.x);\nvec2 tangent = dirA + dirB;\ntangent = length(tangent) > 0. ? normalize(tangent) : perpA;\nvec2 miterVec = vec2(-tangent.y, tangent.x);\nvec2 dir = isEnd ? dirA : dirB;\nvec2 perp = isEnd ? perpA : perpB;\nfloat L = isEnd ? lenA : lenB;\nfloat sinHalfA = abs(dot(miterVec, perp));\nfloat cosHalfA = abs(dot(dirA, miterVec));\nfloat turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\nfloat cornerPosition = sideOfPath * turnDirection;\nfloat miterSize = 1.0 / max(sinHalfA, EPSILON);\nmiterSize = mix(\nmin(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\nmiterSize,\nstep(0.0, cornerPosition)\n);\nvec2 offsetVec = mix(miterVec * miterSize, perp, step(0.5, cornerPosition))\n* (sideOfPath + isJoint * turnDirection);\nbool isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\nbool isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\nbool isCap = isStartCap || isEndCap;\nif (isCap) {\noffsetVec = mix(perp * sideOfPath, dir * path.capType * 4.0 * flipIfTrue(isStartCap), isJoint);\nvJointType = path.capType;\n} else {\nvJointType = path.jointType;\n}\nvPathLength = L;\nvCornerOffset = offsetVec;\nvMiterLength = dot(vCornerOffset, miterVec * turnDirection);\nvMiterLength = isCap ? isJoint : vMiterLength;\nvec2 offsetFromStartOfPath = vCornerOffset + deltaA * float(isEnd);\nvPathPosition = vec2(\ndot(offsetFromStartOfPath, perp),\ndot(offsetFromStartOfPath, dir)\n);\ngeometry.uv = vPathPosition;\nfloat isValid = step(instanceTypes, 3.5);\nvec3 offset = vec3(offsetVec * width * isValid, 0.0);\nif (needsRotation) {\noffset = rotationMatrix * offset;\n}\nreturn offset;\n}\nvoid clipLine(inout vec4 position, vec4 refPosition) {\nif (position.w < EPSILON) {\nfloat r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\nposition = refPosition + (position - refPosition) * r;\n}\n}\nvoid main() {\ngeometry.pickingColor = instancePickingColors;\nvColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\nfloat isEnd = positions.x;\nvec3 prevPosition = mix(instanceLeftPositions, instanceStartPositions, isEnd);\nvec3 prevPosition64Low = mix(instanceLeftPositions64Low, instanceStartPositions64Low, isEnd);\nvec3 currPosition = mix(instanceStartPositions, instanceEndPositions, isEnd);\nvec3 currPosition64Low = mix(instanceStartPositions64Low, instanceEndPositions64Low, isEnd);\nvec3 nextPosition = mix(instanceEndPositions, instanceRightPositions, isEnd);\nvec3 nextPosition64Low = mix(instanceEndPositions64Low, instanceRightPositions64Low, isEnd);\ngeometry.worldPosition = currPosition;\nvec2 widthPixels = vec2(clamp(\nproject_size_to_pixel(instanceStrokeWidths * path.widthScale, path.widthUnits),\npath.widthMinPixels, path.widthMaxPixels) / 2.0);\nvec3 width;\nif (path.billboard) {\nvec4 prevPositionScreen = project_position_to_clipspace(prevPosition, prevPosition64Low, ZERO_OFFSET);\nvec4 currPositionScreen = project_position_to_clipspace(currPosition, currPosition64Low, ZERO_OFFSET, geometry.position);\nvec4 nextPositionScreen = project_position_to_clipspace(nextPosition, nextPosition64Low, ZERO_OFFSET);\nclipLine(prevPositionScreen, currPositionScreen);\nclipLine(nextPositionScreen, currPositionScreen);\nclipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\nwidth = vec3(widthPixels, 0.0);\nDECKGL_FILTER_SIZE(width, geometry);\nvec3 offset = getLineJoinOffset(\nprevPositionScreen.xyz / prevPositionScreen.w,\ncurrPositionScreen.xyz / currPositionScreen.w,\nnextPositionScreen.xyz / nextPositionScreen.w,\nproject_pixel_size_to_clipspace(width.xy)\n);\nDECKGL_FILTER_GL_POSITION(currPositionScreen, geometry);\ngl_Position = vec4(currPositionScreen.xyz + offset * currPositionScreen.w, currPositionScreen.w);\n} else {\nprevPosition = project_position(prevPosition, prevPosition64Low);\ncurrPosition = project_position(currPosition, currPosition64Low);\nnextPosition = project_position(nextPosition, nextPosition64Low);\nwidth = vec3(project_pixel_size(widthPixels), 0.0);\nDECKGL_FILTER_SIZE(width, geometry);\nvec3 offset = getLineJoinOffset(prevPosition, currPosition, nextPosition, width.xy);\ngeometry.position = vec4(currPosition + offset, 1.0);\ngl_Position = project_common_position_to_clipspace(geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME path-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 vCornerOffset;\nin float vMiterLength;\nin vec2 vPathPosition;\nin float vPathLength;\nin float vJointType;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = vPathPosition;\nif (vPathPosition.y < 0.0 || vPathPosition.y > vPathLength) {\nif (vJointType > 0.5 && length(vCornerOffset) > 1.0) {\ndiscard;\n}\nif (vJointType < 0.5 && vMiterLength > path.miterLimit + 1.0) {\ndiscard;\n}\n}\nfragColor = vColor;\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",modules:[_a,Qa,Ip]})}get wrapLongitude(){return!1}getBounds(){return this.getAttributeManager()?.getBounds(["vertexPositions"])}initializeState(){const t=!0;this.getAttributeManager().addInstanced({vertexPositions:{size:3,vertexOffset:1,type:"float64",fp64:this.use64bitPositions(),transition:Np,accessor:"getPath",update:this.calculatePositions,noAlloc:t,shaderAttributes:{instanceLeftPositions:{vertexOffset:0},instanceStartPositions:{vertexOffset:1},instanceEndPositions:{vertexOffset:2},instanceRightPositions:{vertexOffset:3}}},instanceTypes:{size:1,type:"uint8",update:this.calculateSegmentTypes,noAlloc:t},instanceStrokeWidths:{size:1,accessor:"getWidth",transition:Np,defaultValue:1},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",accessor:"getColor",transition:Np,defaultValue:kp},instancePickingColors:{size:4,type:"uint8",accessor:(t,{index:e,target:n})=>this.encodePickingColor(t&&t.__source?t.__source.index:e,n)}}),this.setState({pathTesselator:new Rp({fp64:this.use64bitPositions()})})}updateState(t){super.updateState(t);const{props:e,changeFlags:n}=t,i=this.getAttributeManager();if(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getPath)){const{pathTesselator:t}=this.state,s=e.data.attributes||{};t.updateGeometry({data:e.data,geometryBuffer:s.getPath,buffers:s,normalize:!e._pathType,loop:"loop"===e._pathType,getGeometry:e.getPath,positionFormat:e.positionFormat,wrapLongitude:e.wrapLongitude,resolution:this.context.viewport.resolution,dataChanged:n.dataChanged}),this.setState({numInstances:t.instanceCount,startIndices:t.vertexStarts}),n.dataChanged||i.invalidateAll()}n.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),i.invalidateAll())}getPickingInfo(t){const e=super.getPickingInfo(t),{index:n}=e,i=this.props.data;return i[0]&&i[0].__source&&(e.object=i.find((t=>t.__source.index===n))),e}disablePickingIndex(t){const e=this.props.data;if(e[0]&&e[0].__source)for(let n=0;n<e.length;n++)e[n].__source.index===t&&this._disablePickingIndex(n);else super.disablePickingIndex(t)}draw({}){const{jointRounded:t,capRounded:e,billboard:n,miterLimit:i,widthUnits:s,widthScale:r,widthMinPixels:o,widthMaxPixels:a}=this.props,c=this.state.model,l={jointType:Number(t),capType:Number(e),billboard:n,widthUnits:Yo[s],widthScale:r,miterLimit:i,widthMinPixels:o,widthMaxPixels:a};c.shaderInputs.setProps({path:l}),c.draw(this.context.renderPass)}_getModel(){return new ol(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new ll({topology:"triangle-list",attributes:{indices:new Uint16Array([0,1,2,1,4,2,1,3,4,3,5,4]),positions:{value:new Float32Array([0,0,0,-1,0,1,1,-1,1,1,1,0]),size:2}}}),isInstanced:!0})}calculatePositions(t){const{pathTesselator:e}=this.state;t.startIndices=e.vertexStarts,t.value=e.get("positions")}calculateSegmentTypes(t){const{pathTesselator:e}=this.state;t.startIndices=e.vertexStarts,t.value=e.get("segmentTypes")}}Fp.defaultProps=Dp,Fp.layerName="PathLayer";var Bp,$p={exports:{}},Up=function(){if(Bp)return $p.exports;function t(t,n,s){s=s||2;var r,o,a,h,u,d,p,g=n&&n.length,m=g?n[0]*s:t.length,_=e(t,0,m,s,!0),v=[];if(!_||_.next===_.prev)return v;if(g&&(_=function(t,n,i,s){var r,o,a,h=[];for(r=0,o=n.length;r<o;r++)(a=e(t,n[r]*s,r<o-1?n[r+1]*s:t.length,s,!1))===a.next&&(a.steiner=!0),h.push(f(a));for(h.sort(c),r=0;r<h.length;r++)i=l(h[r],i);return i}(t,n,_,s)),t.length>80*s){r=a=t[0],o=h=t[1];for(var b=s;b<m;b+=s)(u=t[b])<r&&(r=u),(d=t[b+1])<o&&(o=d),u>a&&(a=u),d>h&&(h=d);p=0!==(p=Math.max(a-r,h-o))?32767/p:0}return i(_,v,s,r,o,p,0),v}function e(t,e,n,i,s){var r,o;if(s===A(t,e,n,i)>0)for(r=e;r<n;r+=i)o=x(r,t[r],t[r+1],o);else for(r=n-i;r>=e;r-=i)o=x(r,t[r],t[r+1],o);return o&&m(o,o.next)&&(E(o),o=o.next),o}function n(t,e){if(!t)return t;e||(e=t);var n,i=t;do{if(n=!1,i.steiner||!m(i,i.next)&&0!==g(i.prev,i,i.next))i=i.next;else{if(E(i),(i=e=i.prev)===i.next)break;n=!0}}while(n||i!==e);return e}function i(t,e,c,l,h,f,d){if(t){!d&&f&&function(t,e,n,i){var s=t;do{0===s.z&&(s.z=u(s.x,s.y,e,n,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,n,i,s,r,o,a,c,l=1;do{for(n=t,t=null,r=null,o=0;n;){for(o++,i=n,a=0,e=0;e<l&&(a++,i=i.nextZ);e++);for(c=l;a>0||c>0&&i;)0!==a&&(0===c||!i||n.z<=i.z)?(s=n,n=n.nextZ,a--):(s=i,i=i.nextZ,c--),r?r.nextZ=s:t=s,s.prevZ=r,r=s;n=i}r.nextZ=null,l*=2}while(o>1)}(s)}(t,l,h,f);for(var p,g,m=t;t.prev!==t.next;)if(p=t.prev,g=t.next,f?r(t,l,h,f):s(t))e.push(p.i/c|0),e.push(t.i/c|0),e.push(g.i/c|0),E(t),t=g.next,m=g.next;else if((t=g)===m){d?1===d?i(t=o(n(t),e,c),e,c,l,h,f,2):2===d&&a(t,e,c,l,h,f):i(n(t),e,c,l,h,f,1);break}}}function s(t){var e=t.prev,n=t,i=t.next;if(g(e,n,i)>=0)return!1;for(var s=e.x,r=n.x,o=i.x,a=e.y,c=n.y,l=i.y,h=s<r?s<o?s:o:r<o?r:o,u=a<c?a<l?a:l:c<l?c:l,f=s>r?s>o?s:o:r>o?r:o,p=a>c?a>l?a:l:c>l?c:l,m=i.next;m!==e;){if(m.x>=h&&m.x<=f&&m.y>=u&&m.y<=p&&d(s,a,r,c,o,l,m.x,m.y)&&g(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function r(t,e,n,i){var s=t.prev,r=t,o=t.next;if(g(s,r,o)>=0)return!1;for(var a=s.x,c=r.x,l=o.x,h=s.y,f=r.y,p=o.y,m=a<c?a<l?a:l:c<l?c:l,_=h<f?h<p?h:p:f<p?f:p,v=a>c?a>l?a:l:c>l?c:l,b=h>f?h>p?h:p:f>p?f:p,y=u(m,_,e,n,i),w=u(v,b,e,n,i),x=t.prevZ,E=t.nextZ;x&&x.z>=y&&E&&E.z<=w;){if(x.x>=m&&x.x<=v&&x.y>=_&&x.y<=b&&x!==s&&x!==o&&d(a,h,c,f,l,p,x.x,x.y)&&g(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,E.x>=m&&E.x<=v&&E.y>=_&&E.y<=b&&E!==s&&E!==o&&d(a,h,c,f,l,p,E.x,E.y)&&g(E.prev,E,E.next)>=0)return!1;E=E.nextZ}for(;x&&x.z>=y;){if(x.x>=m&&x.x<=v&&x.y>=_&&x.y<=b&&x!==s&&x!==o&&d(a,h,c,f,l,p,x.x,x.y)&&g(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;E&&E.z<=w;){if(E.x>=m&&E.x<=v&&E.y>=_&&E.y<=b&&E!==s&&E!==o&&d(a,h,c,f,l,p,E.x,E.y)&&g(E.prev,E,E.next)>=0)return!1;E=E.nextZ}return!0}function o(t,e,i){var s=t;do{var r=s.prev,o=s.next.next;!m(r,o)&&_(r,s,s.next,o)&&y(r,o)&&y(o,r)&&(e.push(r.i/i|0),e.push(s.i/i|0),e.push(o.i/i|0),E(s),E(s.next),s=t=o),s=s.next}while(s!==t);return n(s)}function a(t,e,s,r,o,a){var c=t;do{for(var l=c.next.next;l!==c.prev;){if(c.i!==l.i&&p(c,l)){var h=w(c,l);return c=n(c,c.next),h=n(h,h.next),i(c,e,s,r,o,a,0),void i(h,e,s,r,o,a,0)}l=l.next}c=c.next}while(c!==t)}function c(t,e){return t.x-e.x}function l(t,e){var i=function(t,e){var n,i=e,s=t.x,r=t.y,o=-1/0;do{if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){var a=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=s&&a>o&&(o=a,n=i.x<i.next.x?i:i.next,a===s))return n}i=i.next}while(i!==e);if(!n)return null;var c,l=n,u=n.x,f=n.y,p=1/0;i=n;do{s>=i.x&&i.x>=u&&s!==i.x&&d(r<f?s:o,r,u,f,r<f?o:s,r,i.x,i.y)&&(c=Math.abs(r-i.y)/(s-i.x),y(i,t)&&(c<p||c===p&&(i.x>n.x||i.x===n.x&&h(n,i)))&&(n=i,p=c)),i=i.next}while(i!==l);return n}(t,e);if(!i)return e;var s=w(i,t);return n(s,s.next),n(i,i.next)}function h(t,e){return g(t.prev,t,e.prev)<0&&g(e.next,t,t.next)<0}function u(t,e,n,i,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*s|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x<n.x||e.x===n.x&&e.y<n.y)&&(n=e),e=e.next}while(e!==t);return n}function d(t,e,n,i,s,r,o,a){return(s-o)*(e-a)>=(t-o)*(r-a)&&(t-o)*(i-a)>=(n-o)*(e-a)&&(n-o)*(r-a)>=(s-o)*(i-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&_(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(y(t,e)&&y(e,t)&&function(t,e){var n=t,i=!1,s=(t.x+e.x)/2,r=(t.y+e.y)/2;do{n.y>r!=n.next.y>r&&n.next.y!==n.y&&s<(n.next.x-n.x)*(r-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(g(t.prev,t,e.prev)||g(t,e.prev,e))||m(t,e)&&g(t.prev,t,t.next)>0&&g(e.prev,e,e.next)>0)}function g(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function m(t,e){return t.x===e.x&&t.y===e.y}function _(t,e,n,i){var s=b(g(t,e,n)),r=b(g(t,e,i)),o=b(g(n,i,t)),a=b(g(n,i,e));return s!==r&&o!==a||!(0!==s||!v(t,n,e))||!(0!==r||!v(t,i,e))||!(0!==o||!v(n,t,i))||!(0!==a||!v(n,e,i))}function v(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function b(t){return t>0?1:t<0?-1:0}function y(t,e){return g(t.prev,t,t.next)<0?g(t,e,t.next)>=0&&g(t,t.prev,e)>=0:g(t,e,t.prev)<0||g(t,t.next,e)<0}function w(t,e){var n=new T(t.i,t.x,t.y),i=new T(e.i,e.x,e.y),s=t.next,r=e.prev;return t.next=e,e.prev=t,n.next=s,s.prev=n,i.next=n,n.prev=i,r.next=i,i.prev=r,i}function x(t,e,n,i){var s=new T(t,e,n);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function E(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function T(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,n,i){for(var s=0,r=e,o=n-i;r<n;r+=i)s+=(t[o]-t[r])*(t[r+1]+t[o+1]),o=r;return s}return Bp=1,$p.exports=t,$p.exports.default=t,t.deviation=function(t,e,n,i){var s=e&&e.length,r=Math.abs(A(t,0,s?e[0]*n:t.length,n));if(s)for(var o=0,a=e.length;o<a;o++)r-=Math.abs(A(t,e[o]*n,o<a-1?e[o+1]*n:t.length,n));var c=0;for(o=0;o<i.length;o+=3){var l=i[o]*n,h=i[o+1]*n,u=i[o+2]*n;c+=Math.abs((t[l]-t[u])*(t[h+1]-t[l+1])-(t[l]-t[h])*(t[u+1]-t[l+1]))}return 0===r&&0===c?0:Math.abs((c-r)/r)},t.flatten=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},i=0,s=0;s<t.length;s++){for(var r=0;r<t[s].length;r++)for(var o=0;o<e;o++)n.vertices.push(t[s][r][o]);s>0&&n.holes.push(i+=t[s-1].length)}return n},$p.exports}(),zp=p(Up);const jp=up.CLOCKWISE,Gp=up.COUNTER_CLOCKWISE,Wp={};function Vp(t){return"positions"in t?t.positions:t}function Hp(t){return"holeIndices"in t?t.holeIndices:null}function Xp(t,e,n,i,s){let r=e;const o=n.length;for(let e=0;e<o;e++)for(let s=0;s<i;s++)t[r++]=n[e][s]||0;if(!function(t){const e=t[0],n=t[t.length-1];return e[0]===n[0]&&e[1]===n[1]&&e[2]===n[2]}(n))for(let e=0;e<i;e++)t[r++]=n[0][e]||0;return Wp.start=e,Wp.end=r,Wp.size=i,fp(t,s,Wp),r}function Zp(t,e,n,i,s=0,r,o){const a=(r=r||n.length)-s;if(a<=0)return e;let c=e;for(let e=0;e<a;e++)t[c++]=n[s+e];if(!function(t,e,n,i){for(let s=0;s<e;s++)if(t[n+s]!==t[i-e+s])return!1;return!0}(n,i,s,r))for(let e=0;e<i;e++)t[c++]=n[s+e];return Wp.start=e,Wp.end=c,Wp.size=i,fp(t,o,Wp),c}function Kp(t,e){!function(t){if(t=t&&t.positions||t,!Array.isArray(t)&&!ArrayBuffer.isView(t))throw new Error("invalid polygon")}(t);const n=[],i=[];if("positions"in t){const{positions:s,holeIndices:r}=t;if(r){let t=0;for(let o=0;o<=r.length;o++)t=Zp(n,t,s,e,r[o-1],r[o],0===o?jp:Gp),i.push(t);return i.pop(),{positions:n,holeIndices:i}}t=s}if(!function(t){return Array.isArray(t[0])}(t))return Zp(n,0,t,e,0,n.length,jp),n;if(!function(t){return t.length>=1&&t[0].length>=2&&Number.isFinite(t[0][0])}(t)){let s=0;for(const[r,o]of t.entries())s=Xp(n,s,o,e,0===r?jp:Gp),i.push(s);return i.pop(),{positions:n,holeIndices:i}}return Xp(n,0,t,e,jp),n}function qp(t,e,n){const i=t.length/3;let s=0;for(let r=0;r<i;r++){const o=(r+1)%i;s+=t[3*r+e]*t[3*o+n],s-=t[3*o+e]*t[3*r+n]}return Math.abs(s/2)}function Yp(t,e,n,i){const s=t.length/3;for(let r=0;r<s;r++){const s=3*r,o=t[s+1],a=t[s+2];t[s+e]=t[s+0],t[s+n]=o,t[s+i]=a}}class Jp extends $d{constructor(t){const{fp64:e,IndexType:n=Uint32Array}=t;super({...t,attributes:{positions:{size:3,type:e?Float64Array:Float32Array},vertexValid:{type:Uint16Array,size:1},indices:{type:n,size:1}}})}get(t){const{attributes:e}=this;return"indices"===t?e.indices&&e.indices.subarray(0,this.vertexCount):e[t]}updateGeometry(t){super.updateGeometry(t);const e=this.buffers.indices;if(e)this.vertexCount=(e.value||e).length;else if(this.data&&!this.getGeometry)throw new Error("missing indices buffer")}normalizeGeometry(t){if(this.normalize){const e=Kp(t,this.positionSize);return this.opts.resolution?yp(Vp(e),Hp(e),{size:this.positionSize,gridResolution:this.opts.resolution,edgeTypes:!0}):this.opts.wrapLongitude?function(t,e=null,n){const{size:i=2,normalize:s=!0,edgeTypes:r=!1}=n||{};e=e||[];const o=[],a=[];let c=0,l=0;for(let s=0;s<=e.length;s++){const r=e[s]||t.length,h=l,u=Sp(t,i,c,r);for(let e=u;e<r;e++)o[l++]=t[e];for(let e=c;e<u;e++)o[l++]=t[e];Pp(o,i,h,l),Cp(o,i,h,l,n?.maxLatitude),c=r,a[s]=l}a.pop();const h=yp(o,a,{size:i,gridResolution:360,gridOffset:[-180,-180],edgeTypes:r});if(s)for(const t of h)Mp(t.positions,i);return h}(Vp(e),Hp(e),{size:this.positionSize,maxLatitude:86,edgeTypes:!0}):e}return t}getGeometrySize(t){if(Qp(t)){let e=0;for(const n of t)e+=this.getGeometrySize(n);return e}return Vp(t).length/this.positionSize}getGeometryFromBuffer(t){return this.normalize||!this.buffers.indices?super.getGeometryFromBuffer(t):null}updateGeometryAttributes(t,e){if(t&&Qp(t))for(const n of t){const t=this.getGeometrySize(n);e.geometrySize=t,this.updateGeometryAttributes(n,e),e.vertexStart+=t,e.indexStart=this.indexStarts[e.geometryIndex+1]}else{const n=t;this._updateIndices(n,e),this._updatePositions(n,e),this._updateVertexValid(n,e)}}_updateIndices(t,{geometryIndex:e,vertexStart:n,indexStart:i}){const{attributes:s,indexStarts:r,typedArrayManager:o}=this;let a=s.indices;if(!a||!t)return;let c=i;const l=function(t,e,n,i){let s=Hp(t);s&&(s=s.map((t=>t/e)));let r=Vp(t);const o=i&&3===e;if(n){const t=r.length;r=r.slice();const i=[];for(let s=0;s<t;s+=e){i[0]=r[s],i[1]=r[s+1],o&&(i[2]=r[s+2]);const t=n(i);r[s]=t[0],r[s+1]=t[1],o&&(r[s+2]=t[2])}}if(o){const t=qp(r,0,1),e=qp(r,0,2),i=qp(r,1,2);if(!t&&!e&&!i)return[];t>e&&t>i||(e>i?(n||(r=r.slice()),Yp(r,0,2,1)):(n||(r=r.slice()),Yp(r,2,0,1)))}return zp(r,s,e)}(t,this.positionSize,this.opts.preproject,this.opts.full3d);a=o.allocate(a,i+l.length,{copy:!0});for(let t=0;t<l.length;t++)a[c++]=l[t]+n;r[e+1]=i+l.length,s.indices=a}_updatePositions(t,{vertexStart:e,geometrySize:n}){const{attributes:{positions:i},positionSize:s}=this;if(!i||!t)return;const r=Vp(t);for(let t=e,o=0;o<n;t++,o++){const e=r[o*s+1],n=s>2?r[o*s+2]:0;i[3*t]=r[o*s],i[3*t+1]=e,i[3*t+2]=n}}_updateVertexValid(t,{vertexStart:e,geometrySize:n}){const{positionSize:i}=this,s=this.attributes.vertexValid,r=t&&Hp(t);if(t&&t.edgeTypes?s.set(t.edgeTypes,e):s.fill(1,e,e+n),r)for(let t=0;t<r.length;t++)s[e+r[t]/i-1]=0;s[e+n-1]=0}}function Qp(t){return Array.isArray(t)&&t.length>0&&!Number.isFinite(t[0])}const tg="uniform solidPolygonUniforms {\n bool extruded;\n bool isWireframe;\n float elevationScale;\n} solidPolygon;\n",eg={name:"solidPolygon",vs:tg,fs:tg,uniformTypes:{extruded:"f32",isWireframe:"f32",elevationScale:"f32"}};var ng="in vec4 fillColors;\nin vec4 lineColors;\nin vec3 pickingColors;\nout vec4 vColor;\nstruct PolygonProps {\nvec3 positions;\nvec3 positions64Low;\nvec3 normal;\nfloat elevations;\n};\nvec3 project_offset_normal(vec3 vector) {\nif (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\nproject.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\nreturn normalize(vector * project.commonUnitsPerWorldUnit);\n}\nreturn project_normal(vector);\n}\nvoid calculatePosition(PolygonProps props) {\nvec3 pos = props.positions;\nvec3 pos64Low = props.positions64Low;\nvec3 normal = props.normal;\nvec4 colors = solidPolygon.isWireframe ? lineColors : fillColors;\ngeometry.worldPosition = props.positions;\ngeometry.pickingColor = pickingColors;\nif (solidPolygon.extruded) {\npos.z += props.elevations * solidPolygon.elevationScale;\n}\ngl_Position = project_position_to_clipspace(pos, pos64Low, vec3(0.), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nif (solidPolygon.extruded) {\n#ifdef IS_SIDE_VERTEX\nnormal = project_offset_normal(normal);\n#else\nnormal = project_normal(normal);\n#endif\ngeometry.normal = normal;\nvec3 lightColor = lighting_getLightColor(colors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, colors.a * layer.opacity);\n} else {\nvColor = vec4(colors.rgb, colors.a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",ig=`#version 300 es\n#define SHADER_NAME solid-polygon-layer-vertex-shader\nin vec3 vertexPositions;\nin vec3 vertexPositions64Low;\nin float elevations;\n${ng}\nvoid main(void) {\nPolygonProps props;\nprops.positions = vertexPositions;\nprops.positions64Low = vertexPositions64Low;\nprops.elevations = elevations;\nprops.normal = vec3(0.0, 0.0, 1.0);\ncalculatePosition(props);\n}\n`,sg=`#version 300 es\n#define SHADER_NAME solid-polygon-layer-vertex-shader-side\n#define IS_SIDE_VERTEX\nin vec2 positions;\nin vec3 vertexPositions;\nin vec3 nextVertexPositions;\nin vec3 vertexPositions64Low;\nin vec3 nextVertexPositions64Low;\nin float elevations;\nin float instanceVertexValid;\n${ng}\nvoid main(void) {\nif(instanceVertexValid < 0.5){\ngl_Position = vec4(0.);\nreturn;\n}\nPolygonProps props;\nvec3 pos;\nvec3 pos64Low;\nvec3 nextPos;\nvec3 nextPos64Low;\n#if RING_WINDING_ORDER_CW == 1\npos = vertexPositions;\npos64Low = vertexPositions64Low;\nnextPos = nextVertexPositions;\nnextPos64Low = nextVertexPositions64Low;\n#else\npos = nextVertexPositions;\npos64Low = nextVertexPositions64Low;\nnextPos = vertexPositions;\nnextPos64Low = vertexPositions64Low;\n#endif\nprops.positions = mix(pos, nextPos, positions.x);\nprops.positions64Low = mix(pos64Low, nextPos64Low, positions.x);\nprops.normal = vec3(\npos.y - nextPos.y + (pos64Low.y - nextPos64Low.y),\nnextPos.x - pos.x + (nextPos64Low.x - pos64Low.x),\n0.0);\nprops.elevations = elevations * positions.y;\ncalculatePosition(props);\n}\n`;const rg=[0,0,0,255],og={filled:!0,extruded:!1,wireframe:!1,_normalize:!0,_windingOrder:"CW",_full3d:!1,elevationScale:{type:"number",min:0,value:1},getPolygon:{type:"accessor",value:t=>t.polygon},getElevation:{type:"accessor",value:1e3},getFillColor:{type:"accessor",value:rg},getLineColor:{type:"accessor",value:rg},material:!0},ag={enter:(t,e)=>e.length?e.subarray(e.length-t.length):t};class cg extends Fd{getShaders(t){return super.getShaders({vs:"top"===t?ig:sg,fs:"#version 300 es\n#define SHADER_NAME solid-polygon-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nout vec4 fragColor;\nvoid main(void) {\nfragColor = vColor;\ngeometry.uv = vec2(0.);\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",defines:{RING_WINDING_ORDER_CW:this.props._normalize||"CCW"!==this.props._windingOrder?1:0},modules:[_a,Vr,Qa,eg]})}get wrapLongitude(){return!1}getBounds(){return this.getAttributeManager()?.getBounds(["vertexPositions"])}initializeState(){const{viewport:t}=this.context;let{coordinateSystem:e}=this.props;const{_full3d:n}=this.props;let i;t.isGeospatial&&e===Ko.DEFAULT&&(e=Ko.LNGLAT),e===Ko.LNGLAT&&(i=n?t.projectPosition.bind(t):t.projectFlat.bind(t)),this.setState({numInstances:0,polygonTesselator:new Jp({preproject:i,fp64:this.use64bitPositions(),IndexType:Uint32Array})});const s=this.getAttributeManager(),r=!0;s.remove(["instancePickingColors"]),s.add({indices:{size:1,isIndexed:!0,update:this.calculateIndices,noAlloc:r},vertexPositions:{size:3,type:"float64",stepMode:"dynamic",fp64:this.use64bitPositions(),transition:ag,accessor:"getPolygon",update:this.calculatePositions,noAlloc:r,shaderAttributes:{nextVertexPositions:{vertexOffset:1}}},instanceVertexValid:{size:1,type:"uint16",stepMode:"instance",update:this.calculateVertexValid,noAlloc:r},elevations:{size:1,stepMode:"dynamic",transition:ag,accessor:"getElevation"},fillColors:{size:this.props.colorFormat.length,type:"unorm8",stepMode:"dynamic",transition:ag,accessor:"getFillColor",defaultValue:rg},lineColors:{size:this.props.colorFormat.length,type:"unorm8",stepMode:"dynamic",transition:ag,accessor:"getLineColor",defaultValue:rg},pickingColors:{size:4,type:"uint8",stepMode:"dynamic",accessor:(t,{index:e,target:n})=>this.encodePickingColor(t&&t.__source?t.__source.index:e,n)}})}getPickingInfo(t){const e=super.getPickingInfo(t),{index:n}=e,i=this.props.data;return i[0]&&i[0].__source&&(e.object=i.find((t=>t.__source.index===n))),e}disablePickingIndex(t){const e=this.props.data;if(e[0]&&e[0].__source)for(let n=0;n<e.length;n++)e[n].__source.index===t&&this._disablePickingIndex(n);else super.disablePickingIndex(t)}draw({}){const{extruded:t,filled:e,wireframe:n,elevationScale:i}=this.props,{topModel:s,sideModel:r,wireframeModel:o,polygonTesselator:a}=this.state,c={extruded:Boolean(t),elevationScale:i,isWireframe:!1};o&&n&&(o.setInstanceCount(a.instanceCount-1),o.shaderInputs.setProps({solidPolygon:{...c,isWireframe:!0}}),o.draw(this.context.renderPass)),r&&e&&(r.setInstanceCount(a.instanceCount-1),r.shaderInputs.setProps({solidPolygon:c}),r.draw(this.context.renderPass)),s&&e&&(s.setVertexCount(a.vertexCount),s.shaderInputs.setProps({solidPolygon:c}),s.draw(this.context.renderPass))}updateState(t){super.updateState(t),this.updateGeometry(t);const{props:e,oldProps:n,changeFlags:i}=t,s=this.getAttributeManager();(i.extensionsChanged||e.filled!==n.filled||e.extruded!==n.extruded)&&(this.state.models?.forEach((t=>t.destroy())),this.setState(this._getModels()),s.invalidateAll())}updateGeometry({props:t,changeFlags:e}){if(e.dataChanged||e.updateTriggersChanged&&(e.updateTriggersChanged.all||e.updateTriggersChanged.getPolygon)){const{polygonTesselator:n}=this.state,i=t.data.attributes||{};n.updateGeometry({data:t.data,normalize:t._normalize,geometryBuffer:i.getPolygon,buffers:i,getGeometry:t.getPolygon,positionFormat:t.positionFormat,wrapLongitude:t.wrapLongitude,resolution:this.context.viewport.resolution,fp64:this.use64bitPositions(),dataChanged:e.dataChanged,full3d:t._full3d}),this.setState({numInstances:n.instanceCount,startIndices:n.vertexStarts}),e.dataChanged||this.getAttributeManager().invalidateAll()}}_getModels(){const{id:t,filled:e,extruded:n}=this.props;let i,s,r;if(e){const e=this.getShaders("top");e.defines.NON_INSTANCED_MODEL=1;const n=this.getAttributeManager().getBufferLayouts({isInstanced:!1});i=new ol(this.context.device,{...e,id:`${t}-top`,topology:"triangle-list",bufferLayout:n,isIndexed:!0,userData:{excludeAttributes:{instanceVertexValid:!0}}})}if(n){const e=this.getAttributeManager().getBufferLayouts({isInstanced:!0});s=new ol(this.context.device,{...this.getShaders("side"),id:`${t}-side`,bufferLayout:e,geometry:new ll({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array([1,0,0,0,1,1,0,1])}}}),isInstanced:!0,userData:{excludeAttributes:{indices:!0}}}),r=new ol(this.context.device,{...this.getShaders("side"),id:`${t}-wireframe`,bufferLayout:e,geometry:new ll({topology:"line-strip",attributes:{positions:{size:2,value:new Float32Array([1,0,0,0,0,1,1,1])}}}),isInstanced:!0,userData:{excludeAttributes:{indices:!0}}})}return{models:[s,r,i].filter(Boolean),topModel:i,sideModel:s,wireframeModel:r}}calculateIndices(t){const{polygonTesselator:e}=this.state;t.startIndices=e.indexStarts,t.value=e.get("indices")}calculatePositions(t){const{polygonTesselator:e}=this.state;t.startIndices=e.vertexStarts,t.value=e.get("positions")}calculateVertexValid(t){t.value=this.state.polygonTesselator.get("vertexValid")}}function lg({data:t,getIndex:e,dataRange:n,replace:i}){const{startRow:s=0,endRow:r=1/0}=n,o=t.length;let a=o,c=o;for(let n=0;n<o;n++){const i=e(t[n]);if(a>n&&i>=s&&(a=n),i>=r){c=n;break}}let l=a;const h=c-a!==i.length?t.slice(c):void 0;for(let e=0;e<i.length;e++)t[l++]=i[e];if(h){for(let e=0;e<h.length;e++)t[l++]=h[e];t.length=l}return{startRow:a,endRow:a+i.length}}cg.defaultProps=og,cg.layerName="SolidPolygonLayer";const hg="uniform sdfUniforms {\n float gamma;\n bool enabled;\n float buffer;\n float outlineBuffer;\n vec4 outlineColor;\n} sdf;\n",ug={name:"sdf",vs:hg,fs:hg,uniformTypes:{gamma:"f32",enabled:"f32",buffer:"f32",outlineBuffer:"f32",outlineColor:"vec4<f32>"}},fg=.75,dg=[];class pg extends rp{getShaders(){const t=super.getShaders();return{...t,modules:[...t.modules,ug],fs:"#version 300 es\n#define SHADER_NAME multi-icon-layer-fragment-shader\nprecision highp float;\nuniform sampler2D iconsTexture;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nif (!bool(picking.isActive)) {\nfloat alpha = texture(iconsTexture, vTextureCoords).a;\nvec4 color = vColor;\nif (sdf.enabled) {\nfloat distance = alpha;\nalpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\nif (sdf.outlineBuffer > 0.0) {\nfloat inFill = alpha;\nfloat inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\ncolor = mix(sdf.outlineColor, vColor, inFill);\nalpha = inBorder;\n}\n}\nfloat a = alpha * color.a;\nif (a < icon.alphaCutoff) {\ndiscard;\n}\nfragColor = vec4(color.rgb, a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n"}}initializeState(){super.initializeState(),this.getAttributeManager().addInstanced({instanceOffsets:{size:2,accessor:"getIconOffsets"},instancePickingColors:{type:"uint8",size:3,accessor:(t,{index:e,target:n})=>this.encodePickingColor(e,n)}})}updateState(t){super.updateState(t);const{props:e,oldProps:n}=t,{outlineColor:i}=e;i!==n.outlineColor&&this.setState({outlineColor:[i[0]/255,i[1]/255,i[2]/255,(i[3]??255)/255]}),!e.sdf&&e.outlineWidth&&F.warn(`${this.id}: fontSettings.sdf is required to render outline`)()}draw(t){const{sdf:e,smoothing:n,outlineWidth:i}=this.props,{outlineColor:s}=this.state,r=i?Math.max(n,fg*(1-i)):-1,o=this.state.model,a={buffer:fg,outlineBuffer:r,gamma:n,enabled:Boolean(e),outlineColor:s};if(o.shaderInputs.setProps({sdf:a}),super.draw(t),e&&i){const{iconManager:t}=this.state;t.getTexture()&&(o.shaderInputs.setProps({sdf:{...a,outlineBuffer:fg}}),o.draw(this.context.renderPass))}}getInstanceOffset(t){return t?Array.from(t).flatMap((t=>super.getInstanceOffset(t))):dg}getInstanceColorMode(t){return 1}getInstanceIconFrame(t){return t?Array.from(t).flatMap((t=>super.getInstanceIconFrame(t))):dg}}pg.defaultProps={getIconOffsets:{type:"accessor",value:t=>t.offsets},alphaCutoff:.001,smoothing:.1,outlineWidth:0,outlineColor:{type:"color",value:[0,0,0,255]}},pg.layerName="MultiIconLayer";const gg=1e20;class mg{constructor({fontSize:t=24,buffer:e=3,radius:n=8,cutoff:i=.25,fontFamily:s="sans-serif",fontWeight:r="normal",fontStyle:o="normal",lang:a=null}={}){this.buffer=e,this.cutoff=i,this.radius=n,this.lang=a;const c=this.size=t+4*e,l=this._createCanvas(c),h=this.ctx=l.getContext("2d",{willReadFrequently:!0});h.font=`${o} ${r} ${t}px ${s}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(c*c),this.gridInner=new Float64Array(c*c),this.f=new Float64Array(c),this.z=new Float64Array(c+1),this.v=new Uint16Array(c)}_createCanvas(t){const e=document.createElement("canvas");return e.width=e.height=t,e}draw(t){const{width:e,actualBoundingBoxAscent:n,actualBoundingBoxDescent:i,actualBoundingBoxLeft:s,actualBoundingBoxRight:r}=this.ctx.measureText(t),o=Math.ceil(n),a=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(r-s))),c=Math.min(this.size-this.buffer,o+Math.ceil(i)),l=a+2*this.buffer,h=c+2*this.buffer,u=Math.max(l*h,0),f=new Uint8ClampedArray(u),d={data:f,width:l,height:h,glyphWidth:a,glyphHeight:c,glyphTop:o,glyphLeft:0,glyphAdvance:e};if(0===a||0===c)return d;const{ctx:p,buffer:g,gridInner:m,gridOuter:_}=this;this.lang&&(p.lang=this.lang),p.clearRect(g,g,a,c),p.fillText(t,g,g+o);const v=p.getImageData(g,g,a,c);_.fill(gg,0,u),m.fill(0,0,u);for(let t=0;t<c;t++)for(let e=0;e<a;e++){const n=v.data[4*(t*a+e)+3]/255;if(0===n)continue;const i=(t+g)*l+e+g;if(1===n)_[i]=0,m[i]=gg;else{const t=.5-n;_[i]=t>0?t*t:0,m[i]=t<0?t*t:0}}_g(_,0,0,l,h,l,this.f,this.v,this.z),_g(m,g,g,a,c,l,this.f,this.v,this.z);for(let t=0;t<u;t++){const e=Math.sqrt(_[t])-Math.sqrt(m[t]);f[t]=Math.round(255-255*(e/this.radius+this.cutoff))}return d}}function _g(t,e,n,i,s,r,o,a,c){for(let l=e;l<e+i;l++)vg(t,n*r+l,r,s,o,a,c);for(let l=n;l<n+s;l++)vg(t,l*r+e,1,i,o,a,c)}function vg(t,e,n,i,s,r,o){r[0]=0,o[0]=-gg,o[1]=gg,s[0]=t[e];for(let a=1,c=0,l=0;a<i;a++){s[a]=t[e+a*n];const i=a*a;do{const t=r[c];l=(s[a]-s[t]+i-t*t)/(a-t)/2}while(l<=o[c]&&--c>-1);c++,r[c]=a,o[c]=l,o[c+1]=gg}for(let a=0,c=0;a<i;a++){for(;o[c+1]<a;)c++;const i=r[c],l=a-i;t[e+a*n]=s[i]+l*l}}const bg=[];function yg(t,e,n,i){let s=0;for(let r=e;r<n;r++){const e=t[r];s+=i[e]?.layoutWidth||0}return s}function wg(t,e,n,i,s,r){let o=e,a=0;for(let c=e;c<n;c++){const e=yg(t,c,c+1,s);a+e>i&&(o<c&&r.push(c),o=c,a=0),a+=e}return a}function xg(t,e,n,i,s=0,r){void 0===r&&(r=t.length);const o=[];return"break-all"===e?wg(t,s,r,n,i,o):function(t,e,n,i,s,r){let o=e,a=e,c=e,l=0;for(let h=e;h<n;h++)if(" "===t[h]?c=h+1:" "!==t[h+1]&&h+1!==n||(c=h+1),c>a){let e=yg(t,a,c,s);l+e>i&&(o<a&&(r.push(a),o=a,l=0),e>i&&(e=wg(t,a,c,i,s,r),o=r[r.length-1])),a=c,l+=e}}(t,s,r,n,i,o),o}function Eg(t,e,n,i,s,r){let o=0,a=0;for(let r=e;r<n;r++){const e=t[r],n=i[e];n?(a||(a=n.layoutHeight),s[r]=o+n.layoutWidth/2,o+=n.layoutWidth):(F.warn(`Missing character: ${e} (${e.codePointAt(0)})`)(),s[r]=o,o+=32)}r[0]=o,r[1]=a}class Tg{constructor(t=5){this._cache={},this._order=[],this.limit=t}get(t){const e=this._cache[t];return e&&(this._deleteOrder(t),this._appendOrder(t)),e}set(t,e){this._cache[t]?(this.delete(t),this._cache[t]=e,this._appendOrder(t)):(Object.keys(this._cache).length===this.limit&&this.delete(this._order[0]),this._cache[t]=e,this._appendOrder(t))}delete(t){this._cache[t]&&(delete this._cache[t],this._deleteOrder(t))}_deleteOrder(t){const e=this._order.indexOf(t);e>=0&&this._order.splice(e,1)}_appendOrder(t){this._order.push(t)}}const Ag={fontFamily:"Monaco, monospace",fontWeight:"normal",characterSet:function(){const t=[];for(let e=32;e<128;e++)t.push(String.fromCharCode(e));return t}(),fontSize:64,buffer:4,sdf:!1,cutoff:.25,radius:12,smoothing:.1};let Sg=new Tg(3);function Cg(t,e){for(let n=0;n<t.length;n++)e.data[4*n+3]=t[n]}function Pg(t,e,n,i){t.font=`${i} ${n}px ${e}`,t.fillStyle="#000",t.textBaseline="alphabetic",t.textAlign="left"}class Mg{constructor(){this.props={...Ag}}get atlas(){return this._atlas}get mapping(){return this._atlas&&this._atlas.mapping}get scale(){const{fontSize:t,buffer:e}=this.props;return(1.2*t+2*e)/t}setProps(t={}){Object.assign(this.props,t),this._key=this._getKey();const e=function(t,e){let n;n="string"==typeof e?new Set(Array.from(e)):new Set(e);const i=Sg.get(t);if(!i)return n;for(const t in i.mapping)n.has(t)&&n.delete(t);return n}(this._key,this.props.characterSet),n=Sg.get(this._key);if(n&&0===e.size)return void(this._atlas!==n&&(this._atlas=n));const i=this._generateFontAtlas(e,n);this._atlas=i,Sg.set(this._key,i)}_generateFontAtlas(t,e){const{fontFamily:n,fontWeight:i,fontSize:s,buffer:r,sdf:o,radius:a,cutoff:c}=this.props;let l=e&&e.data;l||(l=document.createElement("canvas"),l.width=1024);const h=l.getContext("2d",{willReadFrequently:!0});Pg(h,n,s,i);const{mapping:u,canvasHeight:f,xOffset:d,yOffset:p}=function({characterSet:t,getFontWidth:e,fontHeight:n,buffer:i,maxCanvasWidth:s,mapping:r={},xOffset:o=0,yOffset:a=0}){let c=0,l=o;const h=n+2*i;for(const o of t)if(!r[o]){const t=e(o);l+t+2*i>s&&(l=0,c++),r[o]={x:l+i,y:a+c*h+i,width:t,height:h,layoutWidth:t,layoutHeight:n},l+=t+2*i}return{mapping:r,xOffset:l,yOffset:a+c*h,canvasHeight:(u=a+(c+1)*h,Math.pow(2,Math.ceil(Math.log2(u))))};var u}({getFontWidth:t=>h.measureText(t).width,fontHeight:1.2*s,buffer:r,characterSet:t,maxCanvasWidth:1024,...e&&{mapping:e.mapping,xOffset:e.xOffset,yOffset:e.yOffset}});if(l.height!==f){const t=h.getImageData(0,0,l.width,l.height);l.height=f,h.putImageData(t,0,0)}if(Pg(h,n,s,i),o){const e=new mg({fontSize:s,buffer:r,radius:a,cutoff:c,fontFamily:n,fontWeight:`${i}`});for(const n of t){const{data:t,width:i,height:r,glyphTop:o}=e.draw(n);u[n].width=i,u[n].layoutOffsetY=.9*s-o;const a=h.createImageData(i,r);Cg(t,a),h.putImageData(a,u[n].x,u[n].y)}}else for(const e of t)h.fillText(e,u[e].x,u[e].y+r+.9*s);return{xOffset:d,yOffset:p,mapping:u,data:l,width:l.width,height:l.height}}_getKey(){const{fontFamily:t,fontWeight:e,fontSize:n,buffer:i,sdf:s,radius:r,cutoff:o}=this.props;return s?`${t} ${e} ${n} ${i} ${r} ${o}`:`${t} ${e} ${n} ${i}`}}const Rg="uniform textBackgroundUniforms {\n bool billboard;\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n vec4 borderRadius;\n vec4 padding;\n highp int sizeUnits;\n bool stroked;\n} textBackground;\n",Lg={name:"textBackground",vs:Rg,fs:Rg,uniformTypes:{billboard:"f32",sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",borderRadius:"vec4<f32>",padding:"vec4<f32>",sizeUnits:"i32",stroked:"f32"}},Og={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,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]},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:[0,0,0,255]},getLineWidth:{type:"accessor",value:1}};class Ig extends Fd{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME text-background-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceRects;\nin float instanceSizes;\nin float instanceAngles;\nin vec2 instancePixelOffsets;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin vec3 instancePickingColors;\nout vec4 vFillColor;\nout vec4 vLineColor;\nout float vLineWidth;\nout vec2 uv;\nout vec2 dimensions;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = radians(angle);\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\ngeometry.pickingColor = instancePickingColors;\nuv = positions;\nvLineWidth = instanceLineWidths;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits),\ntextBackground.sizeMinPixels, textBackground.sizeMaxPixels\n);\ndimensions = instanceRects.zw * sizePixels + textBackground.padding.xy + textBackground.padding.zw;\nvec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * sizePixels + mix(-textBackground.padding.xy, textBackground.padding.zw, positions);\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\npixelOffset += instancePixelOffsets;\npixelOffset.y *= -1.0;\nif (textBackground.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nDECKGL_FILTER_SIZE(offset_common, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vFillColor, geometry);\nvLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME text-background-layer-fragment-shader\nprecision highp float;\nin vec4 vFillColor;\nin vec4 vLineColor;\nin float vLineWidth;\nin vec2 uv;\nin vec2 dimensions;\nout vec4 fragColor;\nfloat round_rect(vec2 p, vec2 size, vec4 radii) {\nvec2 pixelPositionCB = (p - 0.5) * size;\nvec2 sizeCB = size * 0.5;\nfloat maxBorderRadius = min(size.x, size.y) * 0.5;\nvec4 borderRadius = vec4(min(radii, maxBorderRadius));\nborderRadius.xy =\n(pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw;\nborderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y;\nvec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x;\nreturn -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x);\n}\nfloat rect(vec2 p, vec2 size) {\nvec2 pixelPosition = p * size;\nreturn min(min(pixelPosition.x, size.x - pixelPosition.x),\nmin(pixelPosition.y, size.y - pixelPosition.y));\n}\nvec4 get_stroked_fragColor(float dist) {\nfloat isBorder = smoothedge(dist, vLineWidth);\nreturn mix(vFillColor, vLineColor, isBorder);\n}\nvoid main(void) {\ngeometry.uv = uv;\nif (textBackground.borderRadius != vec4(0.0)) {\nfloat distToEdge = round_rect(uv, dimensions, textBackground.borderRadius);\nif (textBackground.stroked) {\nfragColor = get_stroked_fragColor(distToEdge);\n} else {\nfragColor = vFillColor;\n}\nfloat shapeAlpha = smoothedge(-distToEdge, 0.0);\nfragColor.a *= shapeAlpha;\n} else {\nif (textBackground.stroked) {\nfloat distToEdge = rect(uv, dimensions);\nfragColor = get_stroked_fragColor(distToEdge);\n} else {\nfragColor = vFillColor;\n}\n}\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",modules:[_a,Qa,Lg]})}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"},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(t){super.updateState(t);const{changeFlags:e}=t;e.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({}){const{billboard:t,sizeScale:e,sizeUnits:n,sizeMinPixels:i,sizeMaxPixels:s,getLineWidth:r}=this.props;let{padding:o,borderRadius:a}=this.props;o.length<4&&(o=[o[0],o[1],o[0],o[1]]),Array.isArray(a)||(a=[a,a,a,a]);const c=this.state.model,l={billboard:t,stroked:Boolean(r),borderRadius:a,padding:o,sizeUnits:Yo[n],sizeScale:e,sizeMinPixels:i,sizeMaxPixels:s};c.shaderInputs.setProps({textBackground:l}),c.draw(this.context.renderPass)}_getModel(){return new ol(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new ll({topology:"triangle-strip",vertexCount:4,attributes:{positions:{size:2,value:new Float32Array([0,0,1,0,0,1,1,1])}}}),isInstanced:!0})}}Ig.defaultProps=Og,Ig.layerName="TextBackgroundLayer";const kg={start:1,middle:0,end:-1},Dg={top:1,center:0,bottom:-1},Ng=[0,0,0,255],Fg={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:Ng},getBorderWidth:{type:"accessor",value:0},backgroundBorderRadius:{type:"object",value:0},backgroundPadding:{type:"array",value:[0,0,0,0]},characterSet:{type:"object",value:Ag.characterSet},fontFamily:Ag.fontFamily,fontWeight:Ag.fontWeight,lineHeight:1,outlineWidth:{type:"number",value:0,min:0},outlineColor:{type:"color",value:Ng},fontSettings:{type:"object",value:{},compare:1},wordBreak:"break-word",maxWidth:{type:"number",value:-1},getText:{type:"accessor",value:t=>t.text},getPosition:{type:"accessor",value:t=>t.position},getColor:{type:"accessor",value:Ng},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]},backgroundColor:{deprecatedFor:["background","getBackgroundColor"]}};class Bg extends Bd{constructor(){super(...arguments),this.getBoundingRect=(t,e)=>{let{size:[n,i]}=this.transformParagraph(t,e);const{fontSize:s}=this.state.fontAtlasManager.props;n/=s,i/=s;const{getTextAnchor:r,getAlignmentBaseline:o}=this.props;return[(kg["function"==typeof r?r(t,e):r]-1)*n/2,(Dg["function"==typeof o?o(t,e):o]-1)*i/2,n,i]},this.getIconOffsets=(t,e)=>{const{getTextAnchor:n,getAlignmentBaseline:i}=this.props,{x:s,y:r,rowWidth:o,size:[a,c]}=this.transformParagraph(t,e),l=kg["function"==typeof n?n(t,e):n],h=Dg["function"==typeof i?i(t,e):i],u=s.length,f=new Array(2*u);let d=0;for(let t=0;t<u;t++)f[d++]=(l-1)*a/2+(1-l)*(a-o[t])/2+s[t],f[d++]=(h-1)*c/2+r[t];return f}}initializeState(){this.state={styleVersion:0,fontAtlasManager:new Mg},this.props.maxWidth>0&&F.once(1,"v8.9 breaking change: TextLayer maxWidth is now relative to text size")()}updateState(t){const{props:e,oldProps:n,changeFlags:i}=t;(i.dataChanged||i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getText))&&this._updateText(),(this._updateFontAtlas()||e.lineHeight!==n.lineHeight||e.wordBreak!==n.wordBreak||e.maxWidth!==n.maxWidth)&&this.setState({styleVersion:this.state.styleVersion+1})}getPickingInfo({info:t}){return t.object=t.index>=0?this.props.data[t.index]:null,t}_updateFontAtlas(){const{fontSettings:t,fontFamily:e,fontWeight:n}=this.props,{fontAtlasManager:i,characterSet:s}=this.state,r={...t,characterSet:s,fontFamily:e,fontWeight:n};if(!i.mapping)return i.setProps(r),!0;for(const t in r)if(r[t]!==i.props[t])return i.setProps(r),!0;return!1}_updateText(){const{data:t,characterSet:e}=this.props,n=t.attributes?.getText;let i,{getText:s}=this.props,r=t.startIndices;const o="auto"===e&&new Set;if(n&&r){const{texts:e,characterCount:a}=function({value:t,length:e,stride:n,offset:i,startIndices:s,characterSet:r}){const o=t.BYTES_PER_ELEMENT,a=n?n/o:1,c=i?i/o:0,l=s[e]||Math.ceil((t.length-c)/a),h=r&&new Set,u=new Array(e);let f=t;if(a>1||c>0){f=new(0,t.constructor)(l);for(let e=0;e<l;e++)f[e]=t[e*a+c]}for(let t=0;t<e;t++){const e=f.subarray(s[t],s[t+1]||l);u[t]=String.fromCodePoint.apply(null,e),h&&e.forEach(h.add,h)}if(h)for(const t of h)r.add(String.fromCodePoint(t));return{texts:u,characterCount:l}}({...ArrayBuffer.isView(n)?{value:n}:n,length:t.length,startIndices:r,characterSet:o});i=a,s=(t,{index:n})=>e[n]}else{const{iterable:e,objectInfo:n}=Nf(t);r=[0],i=0;for(const t of e){n.index++;const e=Array.from(s(t,n)||"");o&&e.forEach(o.add,o),i+=e.length,r.push(i)}}this.setState({getText:s,startIndices:r,numInstances:i,characterSet:o||e})}transformParagraph(t,e){const{fontAtlasManager:n}=this.state,i=n.mapping,s=this.state.getText,{wordBreak:r,lineHeight:o,maxWidth:a}=this.props;return function(t,e,n,i,s){const r=Array.from(t),o=r.length,a=new Array(o),c=new Array(o),l=new Array(o),h=("break-word"===n||"break-all"===n)&&isFinite(i)&&i>0,u=[0,0],f=[0,0];let d=0,p=0,g=0;for(let t=0;t<=o;t++){const m=r[t];if("\n"!==m&&t!==o||(g=t),g>p){const t=h?xg(r,n,i,s,p,g):bg;for(let n=0;n<=t.length;n++){const i=0===n?p:t[n-1],o=n<t.length?t[n]:g;Eg(r,i,o,s,a,f);for(let t=i;t<o;t++){const e=r[t];c[t]=d+f[1]/2+(s[e]?.layoutOffsetY||0),l[t]=f[0]}d+=f[1]*e,u[0]=Math.max(u[0],f[0])}p=g}"\n"===m&&(a[p]=0,c[p]=0,l[p]=0,p++)}return u[1]=d,{x:a,y:c,rowWidth:l,size:u}}(s(t,e)||"",o,r,a*n.props.fontSize,i)}renderLayers(){const{startIndices:t,numInstances:e,getText:n,fontAtlasManager:{scale:i,atlas:s,mapping:r},styleVersion:o}=this.state,{data:a,_dataDiff:c,getPosition:l,getColor:h,getSize:u,getAngle:f,getPixelOffset:d,getBackgroundColor:p,getBorderColor:g,getBorderWidth:m,backgroundBorderRadius:_,backgroundPadding:v,background:b,billboard:y,fontSettings:w,outlineWidth:x,outlineColor:E,sizeScale:T,sizeUnits:A,sizeMinPixels:S,sizeMaxPixels:C,transitions:P,updateTriggers:M}=this.props,R=this.getSubLayerClass("characters",pg),L=this.getSubLayerClass("background",Ig);return[b&&new L({getFillColor:p,getLineColor:g,getLineWidth:m,borderRadius:_,padding:v,getPosition:l,getSize:u,getAngle:f,getPixelOffset:d,billboard:y,sizeScale:T,sizeUnits:A,sizeMinPixels:S,sizeMaxPixels:C,transitions:P&&{getPosition:P.getPosition,getAngle:P.getAngle,getSize:P.getSize,getFillColor:P.getBackgroundColor,getLineColor:P.getBorderColor,getLineWidth:P.getBorderWidth,getPixelOffset:P.getPixelOffset}},this.getSubLayerProps({id:"background",updateTriggers:{getPosition:M.getPosition,getAngle:M.getAngle,getSize:M.getSize,getFillColor:M.getBackgroundColor,getLineColor:M.getBorderColor,getLineWidth:M.getBorderWidth,getPixelOffset:M.getPixelOffset,getBoundingRect:{getText:M.getText,getTextAnchor:M.getTextAnchor,getAlignmentBaseline:M.getAlignmentBaseline,styleVersion:o}}}),{data:a.attributes&&a.attributes.background?{length:a.length,attributes:a.attributes.background}:a,_dataDiff:c,autoHighlight:!1,getBoundingRect:this.getBoundingRect}),new R({sdf:w.sdf,smoothing:Number.isFinite(w.smoothing)?w.smoothing:Ag.smoothing,outlineWidth:x/(w.radius||Ag.radius),outlineColor:E,iconAtlas:s,iconMapping:r,getPosition:l,getColor:h,getSize:u,getAngle:f,getPixelOffset:d,billboard:y,sizeScale:T*i,sizeUnits:A,sizeMinPixels:S*i,sizeMaxPixels:C*i,transitions:P&&{getPosition:P.getPosition,getAngle:P.getAngle,getColor:P.getColor,getSize:P.getSize,getPixelOffset:P.getPixelOffset}},this.getSubLayerProps({id:"characters",updateTriggers:{all:M.getText,getPosition:M.getPosition,getAngle:M.getAngle,getColor:M.getColor,getSize:M.getSize,getPixelOffset:M.getPixelOffset,getIconOffsets:{getTextAnchor:M.getTextAnchor,getAlignmentBaseline:M.getAlignmentBaseline,styleVersion:o}}}),{data:a,_dataDiff:c,startIndices:t,numInstances:e,getIconOffsets:this.getIconOffsets,getIcon:n})]}static set fontAtlasCacheLimit(t){!function(t){F.assert(Number.isFinite(t)&&t>=3,"Invalid cache limit"),Sg=new Tg(t)}(t)}}Bg.defaultProps=Fg,Bg.layerName="TextLayer";const $g={circle:{type:hp,props:{filled:"filled",stroked:"stroked",lineWidthMaxPixels:"lineWidthMaxPixels",lineWidthMinPixels:"lineWidthMinPixels",lineWidthScale:"lineWidthScale",lineWidthUnits:"lineWidthUnits",pointRadiusMaxPixels:"radiusMaxPixels",pointRadiusMinPixels:"radiusMinPixels",pointRadiusScale:"radiusScale",pointRadiusUnits:"radiusUnits",pointAntialiasing:"antialiasing",pointBillboard:"billboard",getFillColor:"getFillColor",getLineColor:"getLineColor",getLineWidth:"getLineWidth",getPointRadius:"getRadius"}},icon:{type:rp,props:{iconAtlas:"iconAtlas",iconMapping:"iconMapping",iconSizeMaxPixels:"sizeMaxPixels",iconSizeMinPixels:"sizeMinPixels",iconSizeScale:"sizeScale",iconSizeUnits:"sizeUnits",iconAlphaCutoff:"alphaCutoff",iconBillboard:"billboard",getIcon:"getIcon",getIconAngle:"getAngle",getIconColor:"getColor",getIconPixelOffset:"getPixelOffset",getIconSize:"getSize"}},text:{type:Bg,props:{textSizeMaxPixels:"sizeMaxPixels",textSizeMinPixels:"sizeMinPixels",textSizeScale:"sizeScale",textSizeUnits:"sizeUnits",textBackground:"background",textBackgroundPadding:"backgroundPadding",textFontFamily:"fontFamily",textFontWeight:"fontWeight",textLineHeight:"lineHeight",textMaxWidth:"maxWidth",textOutlineColor:"outlineColor",textOutlineWidth:"outlineWidth",textWordBreak:"wordBreak",textCharacterSet:"characterSet",textBillboard:"billboard",textFontSettings:"fontSettings",getText:"getText",getTextAngle:"getAngle",getTextColor:"getColor",getTextPixelOffset:"getPixelOffset",getTextSize:"getSize",getTextAnchor:"getTextAnchor",getTextAlignmentBaseline:"getAlignmentBaseline",getTextBackgroundColor:"getBackgroundColor",getTextBorderColor:"getBorderColor",getTextBorderWidth:"getBorderWidth"}}},Ug={type:Fp,props:{lineWidthUnits:"widthUnits",lineWidthScale:"widthScale",lineWidthMinPixels:"widthMinPixels",lineWidthMaxPixels:"widthMaxPixels",lineJointRounded:"jointRounded",lineCapRounded:"capRounded",lineMiterLimit:"miterLimit",lineBillboard:"billboard",getLineColor:"getColor",getLineWidth:"getWidth"}},zg={type:cg,props:{extruded:"extruded",filled:"filled",wireframe:"wireframe",elevationScale:"elevationScale",material:"material",_full3d:"_full3d",getElevation:"getElevation",getFillColor:"getFillColor",getLineColor:"getLineColor"}};function jg({type:t,props:e}){const n={};for(const i in e)n[i]=t.defaultProps[e[i]];return n}function Gg(t,e){const{transitions:n,updateTriggers:i}=t.props,s={updateTriggers:{},transitions:n&&{getPosition:n.geometry}};for(const r in e){const o=e[r];let a=t.props[r];r.startsWith("get")&&(a=t.getSubLayerAccessor(a),s.updateTriggers[o]=i[r],n&&(s.transitions[o]=n[r])),s[o]=a}return s}function Wg(t,e,n={}){const i={pointFeatures:[],lineFeatures:[],polygonFeatures:[],polygonOutlineFeatures:[]},{startRow:s=0,endRow:r=t.length}=n;for(let n=s;n<r;n++){const s=t[n],{geometry:r}=s;if(r)if("GeometryCollection"===r.type){F.assert(Array.isArray(r.geometries),"GeoJSON does not have geometries array");const{geometries:t}=r;for(let r=0;r<t.length;r++)Vg(t[r],i,e,s,n)}else Vg(r,i,e,s,n)}return i}function Vg(t,e,n,i,s){const{type:r,coordinates:o}=t,{pointFeatures:a,lineFeatures:c,polygonFeatures:l,polygonOutlineFeatures:h}=e;if(function(t,e){let n=Hg[t];for(F.assert(n,`Unknown GeoJSON type ${t}`);e&&--n>0;)e=e[0];return e&&Number.isFinite(e[0])}(r,o))switch(r){case"Point":a.push(n({geometry:t},i,s));break;case"MultiPoint":o.forEach((t=>{a.push(n({geometry:{type:"Point",coordinates:t}},i,s))}));break;case"LineString":c.push(n({geometry:t},i,s));break;case"MultiLineString":o.forEach((t=>{c.push(n({geometry:{type:"LineString",coordinates:t}},i,s))}));break;case"Polygon":l.push(n({geometry:t},i,s)),o.forEach((t=>{h.push(n({geometry:{type:"LineString",coordinates:t}},i,s))}));break;case"MultiPolygon":o.forEach((t=>{l.push(n({geometry:{type:"Polygon",coordinates:t}},i,s)),t.forEach((t=>{h.push(n({geometry:{type:"LineString",coordinates:t}},i,s))}))}))}else F.warn(`${r} coordinates are malformed`)()}const Hg={Point:1,MultiPoint:2,LineString:2,MultiLineString:3,Polygon:3,MultiPolygon:4};function Xg(t){return t.geometry.coordinates}const Zg=["points","linestrings","polygons"],Kg={...jg($g.circle),...jg($g.icon),...jg($g.text),...jg(Ug),...jg(zg),stroked:!0,filled:!0,extruded:!1,wireframe:!1,_full3d:!1,iconAtlas:{type:"object",value:null},iconMapping:{type:"object",value:{}},getIcon:{type:"accessor",value:t=>t.properties.icon},getText:{type:"accessor",value:t=>t.properties.text},pointType:"circle",getRadius:{deprecatedFor:"getPointRadius"}};class qg extends Bd{initializeState(){this.state={layerProps:{},features:{},featuresDiff:{}}}updateState({props:t,changeFlags:e}){if(!e.dataChanged)return;const{data:n}=this.props,i=n&&"points"in n&&"polygons"in n&&"lines"in n;this.setState({binary:i}),i?this._updateStateBinary({props:t,changeFlags:e}):this._updateStateJSON({props:t,changeFlags:e})}_updateStateBinary({props:t}){const e=function(t,e){const n={points:{},lines:{},polygons:{},polygonsOutline:{}},{points:i,lines:s,polygons:r}=t,o=function(t,e){const n={points:null,lines:null,polygons:null};for(const i in n){const s=t[i].globalFeatureIds.value;n[i]=new Uint8ClampedArray(4*s.length);const r=[];for(let t=0;t<s.length;t++)e(s[t],r),n[i][4*t+0]=r[0],n[i][4*t+1]=r[1],n[i][4*t+2]=r[2],n[i][4*t+3]=255}return n}(t,e);n.points.data={length:i.positions.value.length/i.positions.size,attributes:{...i.attributes,getPosition:i.positions,instancePickingColors:{size:4,value:o.points}},properties:i.properties,numericProps:i.numericProps,featureIds:i.featureIds},n.lines.data={length:s.pathIndices.value.length-1,startIndices:s.pathIndices.value,attributes:{...s.attributes,getPath:s.positions,instancePickingColors:{size:4,value:o.lines}},properties:s.properties,numericProps:s.numericProps,featureIds:s.featureIds},n.lines._pathType="open";const a=Array(r.positions.value.length/r.positions.size).fill(1);for(const t of r.primitivePolygonIndices.value)a[t-1]=0;return n.polygons.data={length:r.polygonIndices.value.length-1,startIndices:r.polygonIndices.value,attributes:{...r.attributes,getPolygon:r.positions,instanceVertexValid:{size:1,value:new Uint16Array(a)},pickingColors:{size:4,value:o.polygons}},properties:r.properties,numericProps:r.numericProps,featureIds:r.featureIds},n.polygons._normalize=!1,r.triangles&&(n.polygons.data.attributes.indices=r.triangles.value),n.polygonsOutline.data={length:r.primitivePolygonIndices.value.length-1,startIndices:r.primitivePolygonIndices.value,attributes:{...r.attributes,getPath:r.positions,instancePickingColors:{size:4,value:o.polygons}},properties:r.properties,numericProps:r.numericProps,featureIds:r.featureIds},n.polygonsOutline._pathType="open",n}(t.data,this.encodePickingColor);this.setState({layerProps:e})}_updateStateJSON({props:t,changeFlags:e}){const n=function(t){if(Array.isArray(t))return t;switch(F.assert(t.type,"GeoJSON does not have type"),t.type){case"Feature":return[t];case"FeatureCollection":return F.assert(Array.isArray(t.features),"GeoJSON does not have features array"),t.features;default:return[{geometry:t}]}}(t.data),i=this.getSubLayerRow.bind(this);let s={};const r={};if(Array.isArray(e.dataChanged)){const t=this.state.features;for(const e in t)s[e]=t[e].slice(),r[e]=[];for(const o of e.dataChanged){const e=Wg(n,i,o);for(const n in t)r[n].push(lg({data:s[n],getIndex:t=>t.__source.index,dataRange:o,replace:e[n]}))}}else s=Wg(n,i);const o=function(t,e){const n={points:{},lines:{},polygons:{},polygonsOutline:{}},{pointFeatures:i,lineFeatures:s,polygonFeatures:r,polygonOutlineFeatures:o}=t;return n.points.data=i,n.points._dataDiff=e.pointFeatures&&(()=>e.pointFeatures),n.points.getPosition=Xg,n.lines.data=s,n.lines._dataDiff=e.lineFeatures&&(()=>e.lineFeatures),n.lines.getPath=Xg,n.polygons.data=r,n.polygons._dataDiff=e.polygonFeatures&&(()=>e.polygonFeatures),n.polygons.getPolygon=Xg,n.polygonsOutline.data=o,n.polygonsOutline._dataDiff=e.polygonOutlineFeatures&&(()=>e.polygonOutlineFeatures),n.polygonsOutline.getPath=Xg,n}(s,r);this.setState({features:s,featuresDiff:r,layerProps:o})}getPickingInfo(t){const e=super.getPickingInfo(t),{index:n,sourceLayer:i}=e;return e.featureType=Zg.find((t=>i.id.startsWith(`${this.id}-${t}-`))),n>=0&&i.id.startsWith(`${this.id}-points-text`)&&this.state.binary&&(e.index=this.props.data.points.globalFeatureIds.value[n]),e}_updateAutoHighlight(t){const e=`${this.id}-points-`,n="points"===t.featureType;for(const i of this.getSubLayers())i.id.startsWith(e)===n&&i.updateAutoHighlight(t)}_renderPolygonLayer(){const{extruded:t,wireframe:e}=this.props,{layerProps:n}=this.state,i="polygons-fill",s=this.shouldRenderSubLayer(i,n.polygons?.data)&&this.getSubLayerClass(i,zg.type);if(s){const r=Gg(this,zg.props),o=t&&e;return o||delete r.getLineColor,r.updateTriggers.lineColors=o,new s(r,this.getSubLayerProps({id:i,updateTriggers:r.updateTriggers}),n.polygons)}return null}_renderLineLayers(){const{extruded:t,stroked:e}=this.props,{layerProps:n}=this.state,i="polygons-stroke",s="linestrings",r=!t&&e&&this.shouldRenderSubLayer(i,n.polygonsOutline?.data)&&this.getSubLayerClass(i,Ug.type),o=this.shouldRenderSubLayer(s,n.lines?.data)&&this.getSubLayerClass(s,Ug.type);if(r||o){const t=Gg(this,Ug.props);return[r&&new r(t,this.getSubLayerProps({id:i,updateTriggers:t.updateTriggers}),n.polygonsOutline),o&&new o(t,this.getSubLayerProps({id:s,updateTriggers:t.updateTriggers}),n.lines)]}return null}_renderPointLayers(){const{pointType:t}=this.props,{layerProps:e,binary:n}=this.state;let{highlightedObjectIndex:i}=this.props;!n&&Number.isFinite(i)&&(i=e.points.data.findIndex((t=>t.__source.index===i)));const s=new Set(t.split("+")),r=[];for(const t of s){const s=`points-${t}`,o=$g[t],a=o&&this.shouldRenderSubLayer(s,e.points?.data)&&this.getSubLayerClass(s,o.type);if(a){const c=Gg(this,o.props);let l=e.points;if("text"===t&&n){const{instancePickingColors:t,...e}=l.data.attributes;l={...l,data:{...l.data,attributes:e}}}r.push(new a(c,this.getSubLayerProps({id:s,updateTriggers:c.updateTriggers,highlightedObjectIndex:i}),l))}}return r}renderLayers(){const{extruded:t}=this.props,e=this._renderPolygonLayer();return[!t&&e,this._renderLineLayers(),this._renderPointLayers(),t&&e]}getSubLayerAccessor(t){const{binary:e}=this.state;return e&&"function"==typeof t?(e,n)=>{const{data:i,index:s}=n,r=function(t,e){if(!t)return null;const n="startIndices"in t?t.startIndices[e]:e;return-1!==n?function(t,e,n){const i={properties:{...t.properties[e]}};for(const e in t.numericProps)i.properties[e]=t.numericProps[e].value[n];return i}(t,t.featureIds.value[n],n):null}(i,s);return t(r,n)}:super.getSubLayerAccessor(t)}}qg.layerName="GeoJsonLayer",qg.defaultProps=Kg;class Yg{constructor(t){this.index=t,this.isVisible=!1,this.isSelected=!1,this.parent=null,this.children=[],this.content=null,this._loader=void 0,this._abortController=null,this._loaderId=0,this._isLoaded=!1,this._isCancelled=!1,this._needsReload=!1}get bbox(){return this._bbox}set bbox(t){this._bbox||(this._bbox=t,this.boundingBox="west"in t?[[t.west,t.south],[t.east,t.north]]:[[t.left,t.top],[t.right,t.bottom]])}get data(){return this.isLoading&&this._loader?this._loader.then((()=>this.data)):this.content}get isLoaded(){return this._isLoaded&&!this._needsReload}get isLoading(){return Boolean(this._loader)&&!this._isCancelled}get needsReload(){return this._needsReload||this._isCancelled}get byteLength(){const t=this.content?this.content.byteLength:0;return Number.isFinite(t)||console.error("byteLength not defined in tile data"),t}async _loadData({getData:t,requestScheduler:e,onLoad:n,onError:i}){const{index:s,id:r,bbox:o,userData:a,zoom:c}=this,l=this._loaderId;this._abortController=new AbortController;const{signal:h}=this._abortController,u=await e.scheduleRequest(this,(t=>t.isSelected?1:-1));if(!u)return void(this._isCancelled=!0);if(this._isCancelled)return void u.done();let f,d=null;try{d=await t({index:s,id:r,bbox:o,userData:a,zoom:c,signal:h})}catch(t){f=t||!0}finally{u.done()}l===this._loaderId&&(this._loader=void 0,this.content=d,!this._isCancelled||d?(this._isLoaded=!0,this._isCancelled=!1,f?i(f,this):n(this)):this._isLoaded=!1)}loadData(t){return this._isLoaded=!1,this._isCancelled=!1,this._needsReload=!1,this._loaderId++,this._loader=this._loadData(t),this._loader}setNeedsReload(){this.isLoading&&(this.abort(),this._loader=void 0),this._needsReload=!0}abort(){this.isLoaded||(this._isCancelled=!0,this._abortController?.abort())}}const Jg=-1,Qg=new Js,tm=new Js;class em{constructor(t=[0,0,0],e=[0,0,0],n){n=n||Qg.copy(t).add(e).scale(.5),this.center=new Js(n),this.halfDiagonal=new Js(e).subtract(this.center),this.minimum=new Js(t),this.maximum=new Js(e)}clone(){return new em(this.minimum,this.maximum,this.center)}equals(t){return this===t||Boolean(t)&&this.minimum.equals(t.minimum)&&this.maximum.equals(t.maximum)}transform(t){return this.center.transformAsPoint(t),this.halfDiagonal.transform(t),this.minimum.transform(t),this.maximum.transform(t),this}intersectPlane(t){const{halfDiagonal:e}=this,n=tm.from(t.normal),i=e.x*Math.abs(n.x)+e.y*Math.abs(n.y)+e.z*Math.abs(n.z),s=this.center.dot(n)+t.distance;return s-i>0?1:s+i<0?Jg:0}distanceTo(t){return Math.sqrt(this.distanceSquaredTo(t))}distanceSquaredTo(t){const e=Qg.from(t).subtract(this.center),{halfDiagonal:n}=this;let i,s=0;return i=Math.abs(e.x)-n.x,i>0&&(s+=i*i),i=Math.abs(e.y)-n.y,i>0&&(s+=i*i),i=Math.abs(e.z)-n.z,i>0&&(s+=i*i),s}}const nm=new Js,im=new Js;class sm{constructor(t=[0,0,0],e=0){this.radius=-0,this.center=new Js,this.fromCenterRadius(t,e)}fromCenterRadius(t,e){return this.center.from(t),this.radius=e,this}fromCornerPoints(t,e){return e=nm.from(e),this.center=(new Js).from(t).add(e).scale(.5),this.radius=this.center.distance(e),this}equals(t){return this===t||Boolean(t)&&this.center.equals(t.center)&&this.radius===t.radius}clone(){return new sm(this.center,this.radius)}union(t){const e=this.center,n=this.radius,i=t.radius,s=nm.copy(t.center).subtract(e),r=s.magnitude();if(n>=r+i)return this.clone();if(i>=r+n)return t.clone();const o=.5*(n+r+i);return im.copy(s).scale((-n+o)/r).add(e),this.center.copy(im),this.radius=o,this}expand(t){const e=nm.from(t).subtract(this.center).magnitude();return e>this.radius&&(this.radius=e),this}transform(t){this.center.transform(t);const e=function(t,e){const n=e[0],i=e[1],s=e[2],r=e[4],o=e[5],a=e[6],c=e[8],l=e[9],h=e[10];return t[0]=Math.sqrt(n*n+i*i+s*s),t[1]=Math.sqrt(r*r+o*o+a*a),t[2]=Math.sqrt(c*c+l*l+h*h),t}(nm,t);return this.radius=Math.max(e[0],Math.max(e[1],e[2]))*this.radius,this}distanceSquaredTo(t){const e=this.distanceTo(t);return e*e}distanceTo(t){const e=nm.from(t).subtract(this.center);return Math.max(0,e.len()-this.radius)}intersectPlane(t){const e=this.radius,n=t.normal.dot(this.center)+t.distance;return n<-e?Jg:n<e?0:1}}const rm=new Js,om=new Js,am=new Js,cm=new Js,lm=new Js,hm=new Js,um=new Js;class fm{constructor(t=[0,0,0],e=[0,0,0,0,0,0,0,0,0]){this.center=(new Js).from(t),this.halfAxes=new rr(e)}get halfSize(){const t=this.halfAxes.getColumn(0),e=this.halfAxes.getColumn(1),n=this.halfAxes.getColumn(2);return[new Js(t).len(),new Js(e).len(),new Js(n).len()]}get quaternion(){const t=this.halfAxes.getColumn(0),e=this.halfAxes.getColumn(1),n=this.halfAxes.getColumn(2),i=new Js(t).normalize(),s=new Js(e).normalize(),r=new Js(n).normalize();return(new Or).fromMatrix3(new rr([...i,...s,...r]))}fromCenterHalfSizeQuaternion(t,e,n){const i=new Or(n),s=(new rr).fromQuaternion(i);return s[0]=s[0]*e[0],s[1]=s[1]*e[0],s[2]=s[2]*e[0],s[3]=s[3]*e[1],s[4]=s[4]*e[1],s[5]=s[5]*e[1],s[6]=s[6]*e[2],s[7]=s[7]*e[2],s[8]=s[8]*e[2],this.center=(new Js).from(t),this.halfAxes=s,this}clone(){return new fm(this.center,this.halfAxes)}equals(t){return this===t||Boolean(t)&&this.center.equals(t.center)&&this.halfAxes.equals(t.halfAxes)}getBoundingSphere(t=new sm){const e=this.halfAxes,n=e.getColumn(0,am),i=e.getColumn(1,cm),s=e.getColumn(2,lm),r=rm.copy(n).add(i).add(s);return t.center.copy(this.center),t.radius=r.magnitude(),t}intersectPlane(t){const e=this.center,n=t.normal,i=this.halfAxes,s=n.x,r=n.y,o=n.z,a=Math.abs(s*i[0]+r*i[1]+o*i[2])+Math.abs(s*i[3]+r*i[4]+o*i[5])+Math.abs(s*i[6]+r*i[7]+o*i[8]),c=n.dot(e)+t.distance;return c<=-a?Jg:c>=a?1:0}distanceTo(t){return Math.sqrt(this.distanceSquaredTo(t))}distanceSquaredTo(t){const e=om.from(t).subtract(this.center),n=this.halfAxes,i=n.getColumn(0,am),s=n.getColumn(1,cm),r=n.getColumn(2,lm),o=i.magnitude(),a=s.magnitude(),c=r.magnitude();i.normalize(),s.normalize(),r.normalize();let l,h=0;return l=Math.abs(e.dot(i))-o,l>0&&(h+=l*l),l=Math.abs(e.dot(s))-a,l>0&&(h+=l*l),l=Math.abs(e.dot(r))-c,l>0&&(h+=l*l),h}computePlaneDistances(t,e,n=[-0,-0]){let i=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;const r=this.center,o=this.halfAxes,a=o.getColumn(0,am),c=o.getColumn(1,cm),l=o.getColumn(2,lm),h=hm.copy(a).add(c).add(l).add(r),u=um.copy(h).subtract(t);let f=e.dot(u);return i=Math.min(f,i),s=Math.max(f,s),h.copy(r).add(a).add(c).subtract(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),h.copy(r).add(a).subtract(c).add(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),h.copy(r).add(a).subtract(c).subtract(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),r.copy(h).subtract(a).add(c).add(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),r.copy(h).subtract(a).add(c).subtract(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),r.copy(h).subtract(a).subtract(c).add(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),r.copy(h).subtract(a).subtract(c).subtract(l),u.copy(h).subtract(t),f=e.dot(u),i=Math.min(f,i),s=Math.max(f,s),n[0]=i,n[1]=s,n}transform(t){this.center.transformAsPoint(t);const e=this.halfAxes.getColumn(0,am);e.transformAsPoint(t);const n=this.halfAxes.getColumn(1,cm);n.transformAsPoint(t);const i=this.halfAxes.getColumn(2,lm);return i.transformAsPoint(t),this.halfAxes=new rr([...e,...n,...i]),this}getTransform(){throw new Error("not implemented")}}const dm=new Js,pm=new Js;class gm{constructor(t=[0,0,1],e=0){this.normal=new Js,this.distance=-0,this.fromNormalDistance(t,e)}fromNormalDistance(t,e){return Ss(Number.isFinite(e)),this.normal.from(t).normalize(),this.distance=e,this}fromPointNormal(t,e){t=dm.from(t),this.normal.from(e).normalize();const n=-this.normal.dot(t);return this.distance=n,this}fromCoefficients(t,e,n,i){return this.normal.set(t,e,n),Ss(ws(this.normal.len(),1)),this.distance=i,this}clone(){return new gm(this.normal,this.distance)}equals(t){return ws(this.distance,t.distance)&&ws(this.normal,t.normal)}getPointDistance(t){return this.normal.dot(t)+this.distance}transform(t){const e=pm.copy(this.normal).transformAsVector(t).normalize(),n=this.normal.scale(-this.distance).transform(t);return this.fromPointNormal(n,e)}projectPointOntoPlane(t,e=[0,0,0]){const n=dm.from(t),i=this.getPointDistance(n),s=pm.copy(this.normal).scale(i);return n.subtract(s).to(e)}}const mm=[new Js([1,0,0]),new Js([0,1,0]),new Js([0,0,1])],_m=new Js,vm=new Js;class bm{constructor(t=[]){this.planes=t}fromBoundingSphere(t){this.planes.length=2*mm.length;const e=t.center,n=t.radius;let i=0;for(const t of mm){let s=this.planes[i],r=this.planes[i+1];s||(s=this.planes[i]=new gm),r||(r=this.planes[i+1]=new gm);const o=_m.copy(t).scale(-n).add(e);s.fromPointNormal(o,t);const a=_m.copy(t).scale(n).add(e),c=vm.copy(t).negate();r.fromPointNormal(a,c),i+=2}return this}computeVisibility(t){let e=1;for(const n of this.planes)switch(t.intersectPlane(n)){case Jg:return Jg;case 0:e=0}return e}computeVisibilityWithPlaneMask(t,e){if(Ss(Number.isFinite(e),"parentPlaneMask is required."),e===bm.MASK_OUTSIDE||e===bm.MASK_INSIDE)return e;let n=bm.MASK_INSIDE;const i=this.planes;for(let s=0;s<this.planes.length;++s){const r=s<31?1<<s:0;if(s<31&&!(e&r))continue;const o=t.intersectPlane(i[s]);if(o===Jg)return bm.MASK_OUTSIDE;0===o&&(n|=r)}return n}}bm.MASK_OUTSIDE=4294967295,bm.MASK_INSIDE=0,bm.MASK_INDETERMINATE=2147483647,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js,new Js;const ym=new rr,wm=new rr,xm=new rr,Em=new rr,Tm=new rr;const Am=[1,0,0],Sm=[2,2,1];function Cm(t){let e=0;for(let n=0;n<3;++n){const i=t[ym.getElementIndex(Sm[n],Am[n])];e+=2*i*i}return Math.sqrt(e)}function Pm(t,e){let n=0,i=1;for(let e=0;e<3;++e){const s=Math.abs(t[ym.getElementIndex(Sm[e],Am[e])]);s>n&&(i=e,n=s)}const s=Am[i],r=Sm[i];let o=1,a=0;if(Math.abs(t[ym.getElementIndex(r,s)])>1e-15){const e=(t[ym.getElementIndex(r,r)]-t[ym.getElementIndex(s,s)])/2/t[ym.getElementIndex(r,s)];let n;n=e<0?-1/(-e+Math.sqrt(1+e*e)):1/(e+Math.sqrt(1+e*e)),o=1/Math.sqrt(1+n*n),a=n*o}return rr.IDENTITY.to(e),e[ym.getElementIndex(s,s)]=e[ym.getElementIndex(r,r)]=o,e[ym.getElementIndex(r,s)]=a,e[ym.getElementIndex(s,r)]=-a,e}const Mm=new Js,Rm=new Js,Lm=new Js,Om=new Js,Im=new Js,km=new rr,Dm={diagonal:new rr,unitary:new rr},Nm=512,Fm=[[.5,.5],[0,0],[0,1],[1,0],[1,1]],Bm=Fm.concat([[0,.5],[.5,0],[1,.5],[.5,1]]),$m=Bm.concat([[.25,.5],[.75,.5]]);class Um{constructor(t,e,n){this.x=t,this.y=e,this.z=n}get children(){if(!this._children){const t=2*this.x,e=2*this.y,n=this.z+1;this._children=[new Um(t,e,n),new Um(t,e+1,n),new Um(t+1,e,n),new Um(t+1,e+1,n)]}return this._children}update(t){const{viewport:e,cullingVolume:n,elevationBounds:i,minZ:s,maxZ:r,bounds:o,offset:a,project:c}=t,l=this.getBoundingVolume(i,a,c);if(o&&!this.insideBounds(o))return!1;if(n.computeVisibility(l)<0)return!1;if(!this.childVisible){let{z:t}=this;if(t<r&&t>=s){const n=l.distanceTo(e.cameraPosition)*e.scale/e.height;t+=Math.floor(Math.log2(n))}if(t>=r)return this.selected=!0,!0}this.selected=!1,this.childVisible=!0;for(const e of this.children)e.update(t);return!0}getSelected(t=[]){if(this.selected&&t.push(this),this._children)for(const e of this._children)e.getSelected(t);return t}insideBounds([t,e,n,i]){const s=Math.pow(2,this.z),r=Nm/s;return this.x*r<n&&this.y*r<i&&(this.x+1)*r>t&&(this.y+1)*r>e}getBoundingVolume(t,e,n){if(n){const e=this.z<1?$m:this.z<2?Bm:Fm,i=[];for(const s of e){const e=Km(this.x+s[0],this.y+s[1],this.z);e[2]=t[0],i.push(n(e)),t[0]!==t[1]&&(e[2]=t[1],i.push(n(e)))}return function(t,e=new fm){if(!t||0===t.length)return e.halfAxes=new rr([0,0,0,0,0,0,0,0,0]),e.center=new Js,e;const n=t.length,i=new Js(0,0,0);for(const e of t)i.add(e);const s=1/n;i.multiplyByScalar(s);let r=0,o=0,a=0,c=0,l=0,h=0;for(const e of t){const t=Mm.copy(e).subtract(i);r+=t.x*t.x,o+=t.x*t.y,a+=t.x*t.z,c+=t.y*t.y,l+=t.y*t.z,h+=t.z*t.z}r*=s,o*=s,a*=s,c*=s,l*=s,h*=s;const u=km;u[0]=r,u[1]=o,u[2]=a,u[3]=o,u[4]=c,u[5]=l,u[6]=a,u[7]=l,u[8]=h;const{unitary:f}=function(t,e={}){let n=0,i=0;const s=wm,r=xm;s.identity(),r.copy(t);const o=1e-20*function(t){let e=0;for(let n=0;n<9;++n){const i=t[n];e+=i*i}return Math.sqrt(e)}(r);for(;i<10&&Cm(r)>o;)Pm(r,Em),Tm.copy(Em).transpose(),r.multiplyRight(Em),r.multiplyLeft(Tm),s.multiplyRight(Em),++n>2&&(++i,n=0);return e.unitary=s.toTarget(e.unitary),e.diagonal=r.toTarget(e.diagonal),e}(u,Dm),d=e.halfAxes.copy(f);let p=d.getColumn(0,Lm),g=d.getColumn(1,Om),m=d.getColumn(2,Im),_=-Number.MAX_VALUE,v=-Number.MAX_VALUE,b=-Number.MAX_VALUE,y=Number.MAX_VALUE,w=Number.MAX_VALUE,x=Number.MAX_VALUE;for(const e of t)Mm.copy(e),_=Math.max(Mm.dot(p),_),v=Math.max(Mm.dot(g),v),b=Math.max(Mm.dot(m),b),y=Math.min(Mm.dot(p),y),w=Math.min(Mm.dot(g),w),x=Math.min(Mm.dot(m),x);p=p.multiplyByScalar(.5*(y+_)),g=g.multiplyByScalar(.5*(w+v)),m=m.multiplyByScalar(.5*(x+b)),e.center.copy(p).add(g).add(m);const E=Rm.set(_-y,v-w,b-x).multiplyByScalar(.5),T=new rr([E[0],0,0,0,E[1],0,0,0,E[2]]);return e.halfAxes.multiplyRight(T),e}(i)}const i=Math.pow(2,this.z),s=Nm/i,r=this.x*s+e*Nm,o=Nm-(this.y+1)*s;return new em([r,o,t[0]],[r+s,o+s,t[1]])}}const zm=512,jm=[-1/0,-1/0,1/0,1/0],Gm={type:"object",value:null,validate:(t,e)=>e.optional&&null===t||"string"==typeof t||Array.isArray(t)&&t.every((t=>"string"==typeof t)),equal:(t,e)=>{if(t===e)return!0;if(!Array.isArray(t)||!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}};function Wm(t,e){const n=[e.transformAsPoint([t[0],t[1]]),e.transformAsPoint([t[2],t[1]]),e.transformAsPoint([t[0],t[3]]),e.transformAsPoint([t[2],t[3]])],i=[Math.min(...n.map((t=>t[0]))),Math.min(...n.map((t=>t[1]))),Math.max(...n.map((t=>t[0]))),Math.max(...n.map((t=>t[1])))];return i}function Vm(t,e){if(!t||!t.length)return null;const{index:n,id:i}=e;if(Array.isArray(t)){const e=function(t){return Math.abs(t.split("").reduce(((t,e)=>(t<<5)-t+e.charCodeAt(0)|0),0))}(i)%t.length;t=t[e]}let s=t;for(const t of Object.keys(n)){const e=new RegExp(`{${t}}`,"g");s=s.replace(e,String(n[t]))}return Number.isInteger(n.y)&&Number.isInteger(n.z)&&(s=s.replace(/\{-y\}/g,String(Math.pow(2,n.z)-n.y-1))),s}function Hm({viewport:t,z:e,cullRect:n}){return(t.subViewports||[t]).map((t=>Xm(t,e||0,n)))}function Xm(t,e,n){if(!Array.isArray(e)){const i=n.x-t.x,s=n.y-t.y,{width:r,height:o}=n,a={targetZ:e},c=t.unproject([i,s],a),l=t.unproject([i+r,s],a),h=t.unproject([i,s+o],a),u=t.unproject([i+r,s+o],a);return[Math.min(c[0],l[0],h[0],u[0]),Math.min(c[1],l[1],h[1],u[1]),Math.max(c[0],l[0],h[0],u[0]),Math.max(c[1],l[1],h[1],u[1])]}const i=Xm(t,e[0],n),s=Xm(t,e[1],n);return[Math.min(i[0],s[0]),Math.min(i[1],s[1]),Math.max(i[2],s[2]),Math.max(i[3],s[3])]}function Zm(t,e){return Math.pow(2,t)*zm/e}function Km(t,e,n){const i=Zm(n,zm),s=Math.PI-2*Math.PI*e/i;return[t/i*360-180,180/Math.PI*Math.atan(.5*(Math.exp(s)-Math.exp(-s)))]}function qm(t,e,n,i){const s=Zm(n,i);return[t/s*zm,e/s*zm]}function Ym(t,e,n,i,s=zm){if(t.isGeospatial){const[t,s]=Km(e,n,i),[r,o]=Km(e+1,n+1,i);return{west:t,north:s,east:r,south:o}}const[r,o]=qm(e,n,i,s),[a,c]=qm(e+1,n+1,i,s);return{left:r,top:o,right:a,bottom:c}}function Jm({viewport:t,maxZoom:e,minZoom:n,zRange:i,extent:s,tileSize:r=zm,modelMatrix:o,modelMatrixInverse:a,zoomOffset:c=0}){let l=t.isGeospatial?Math.round(t.zoom+Math.log2(zm/r))+c:Math.ceil(t.zoom)+c;if("number"==typeof n&&Number.isFinite(n)&&l<n){if(!s)return[];l=n}"number"==typeof e&&Number.isFinite(e)&&l>e&&(l=e);let h=s;return o&&a&&s&&!t.isGeospatial&&(h=Wm(s,o)),t.isGeospatial?function(t,e,n,i){const s=t instanceof Kl&&t.resolution?t.projectPosition:null,r=Object.values(t.getFrustumPlanes()).map((({normal:t,distance:e})=>new gm(t.clone().negate(),e))),o=new bm(r),a=t.distanceScales.unitsPerMeter[2],c=n&&n[0]*a||0,l=n&&n[1]*a||0,h=t instanceof Dc&&t.pitch<=60?e:0;if(i){const[t,e,n,s]=i,r=Ia([t,s]),o=Ia([n,e]);i=[r[0],Nm-r[1],o[0],Nm-o[1]]}const u=new Um(0,0,0),f={viewport:t,project:s,cullingVolume:o,elevationBounds:[c,l],minZ:h,maxZ:e,bounds:i,offset:0};if(u.update(f),t instanceof Dc&&t.subViewports&&t.subViewports.length>1){for(f.offset=-1;u.update(f)&&!(--f.offset<-3););for(f.offset=1;u.update(f)&&!(++f.offset>3););}return u.getSelected()}(t,l,i,s):function(t,e,n,i,s){const r=function(t,e,n){let i;return i=t.getBounds(),t.isGeospatial?[Math.max(i[0],n[0]),Math.max(i[1],n[1]),Math.min(i[2],n[2]),Math.min(i[3],n[3])]:[Math.max(Math.min(i[0],n[2]),n[0]),Math.max(Math.min(i[1],n[3]),n[1]),Math.min(Math.max(i[2],n[0]),n[2]),Math.min(Math.max(i[3],n[1]),n[3])]}(t,0,i),o=Zm(e,n),[a,c,l,h]=function(t,e,n){if(n){const i=Wm(t,n).map((t=>t*e/zm));return i}return t.map((t=>t*e/zm))}(r,o,s),u=[];for(let t=Math.floor(a);t<l;t++)for(let n=Math.floor(c);n<h;n++)u.push({x:t,y:n,z:e});return u}(t,l,r,h||jm,a)}function Qm(t){return/(?=.*{z})(?=.*{x})(?=.*({y}|{-y}))/.test(t)}function t_(t){return Number.isFinite(t.west)&&Number.isFinite(t.north)&&Number.isFinite(t.east)&&Number.isFinite(t.south)}function e_(t,e){if(t===e)return!0;if(Array.isArray(t)){const n=t.length;if(!e||e.length!==n)return!1;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}return!1}const n_="never",i_="no-overlap",s_="best-available",r_={[s_]:function(t){for(const e of t)e.state=0;for(const e of t)e.isSelected&&!c_(e)&&l_(e);for(const e of t)e.isVisible=Boolean(2&e.state)},[i_]:function(t){for(const e of t)e.state=0;for(const e of t)e.isSelected&&c_(e);const e=Array.from(t).sort(((t,e)=>t.zoom-e.zoom));for(const t of e)if(t.isVisible=Boolean(2&t.state),t.children&&(t.isVisible||1&t.state))for(const e of t.children)e.state=1;else t.isSelected&&l_(t)},[n_]:()=>{}},o_={extent:null,tileSize:512,maxZoom:null,minZoom:null,maxCacheSize:null,maxCacheByteSize:null,refinementStrategy:"best-available",zRange:null,maxRequests:6,debounceTime:0,zoomOffset:0,onTileLoad:()=>{},onTileUnload:()=>{},onTileError:()=>{}};class a_{constructor(t){this._getCullBounds=function(t){let e,n={};return i=>{for(const s in i)if(!e_(i[s],n[s])){e=t(i),n=i;break}return e}}(Hm),this.opts={...o_,...t},this.setOptions(this.opts),this.onTileLoad=t=>{this.opts.onTileLoad?.(t),null!==this.opts.maxCacheByteSize&&(this._cacheByteSize+=t.byteLength,this._resizeCache())},this._requestScheduler=new d({throttleRequests:this.opts.maxRequests>0||this.opts.debounceTime>0,maxRequests:this.opts.maxRequests,debounceTime:this.opts.debounceTime}),this._cache=new Map,this._tiles=[],this._dirty=!1,this._cacheByteSize=0,this._viewport=null,this._zRange=null,this._selectedTiles=null,this._frameNumber=0,this._modelMatrix=new xr,this._modelMatrixInverse=new xr}get tiles(){return this._tiles}get selectedTiles(){return this._selectedTiles}get isLoaded(){return null!==this._selectedTiles&&this._selectedTiles.every((t=>t.isLoaded))}get needsReload(){return null!==this._selectedTiles&&this._selectedTiles.some((t=>t.needsReload))}setOptions(t){Object.assign(this.opts,t),Number.isFinite(t.maxZoom)&&(this._maxZoom=Math.floor(t.maxZoom)),Number.isFinite(t.minZoom)&&(this._minZoom=Math.ceil(t.minZoom))}finalize(){for(const t of this._cache.values())t.isLoading&&t.abort();this._cache.clear(),this._tiles=[],this._selectedTiles=null}reloadAll(){for(const t of this._cache.keys()){const e=this._cache.get(t);this._selectedTiles&&this._selectedTiles.includes(e)?e.setNeedsReload():this._cache.delete(t)}}update(t,{zRange:e,modelMatrix:n}={zRange:null,modelMatrix:null}){const i=n?new xr(n):new xr,s=!i.equals(this._modelMatrix);if(this._viewport&&t.equals(this._viewport)&&ws(this._zRange,e)&&!s)this.needsReload&&(this._selectedTiles=this._selectedTiles.map((t=>this._getTile(t.index,!0))));else{s&&(this._modelMatrixInverse=i.clone().invert(),this._modelMatrix=i),this._viewport=t,this._zRange=e;const n=this.getTileIndices({viewport:t,maxZoom:this._maxZoom,minZoom:this._minZoom,zRange:e,modelMatrix:this._modelMatrix,modelMatrixInverse:this._modelMatrixInverse});this._selectedTiles=n.map((t=>this._getTile(t,!0))),this._dirty&&this._rebuildTree()}const r=this.updateTileStates();return this._pruneRequests(),this._dirty&&this._resizeCache(),r&&this._frameNumber++,this._frameNumber}isTileVisible(t,e,n){if(!t.isVisible)return!1;if(e&&this._viewport){const i=this._getCullBounds({viewport:this._viewport,z:this._zRange,cullRect:e});let{bbox:s}=t;for(const[t,e,r,o]of i){let i;if("west"in s)i=s.west<r&&s.east>t&&s.south<o&&s.north>e;else{if(n&&!xr.IDENTITY.equals(n)){const[t,e,i,r]=Wm([s.left,s.top,s.right,s.bottom],n);s={left:t,top:e,right:i,bottom:r}}const a=Math.min(s.top,s.bottom),c=Math.max(s.top,s.bottom);i=s.left<r&&s.right>t&&a<o&&c>e}if(i)return!0}return!1}return!0}getTileIndices({viewport:t,maxZoom:e,minZoom:n,zRange:i,modelMatrix:s,modelMatrixInverse:r}){const{tileSize:o,extent:a,zoomOffset:c}=this.opts;return Jm({viewport:t,maxZoom:e,minZoom:n,zRange:i,tileSize:o,extent:a,modelMatrix:s,modelMatrixInverse:r,zoomOffset:c})}getTileId(t){return`${t.x}-${t.y}-${t.z}`}getTileZoom(t){return t.z}getTileMetadata(t){const{tileSize:e}=this.opts;return{bbox:Ym(this._viewport,t.x,t.y,t.z,e)}}getParentIndex(t){return{x:Math.floor(t.x/2),y:Math.floor(t.y/2),z:t.z-1}}updateTileStates(){const t=this.opts.refinementStrategy||s_,e=new Array(this._cache.size);let n=0;for(const t of this._cache.values())e[n++]=t.isVisible,t.isSelected=!1,t.isVisible=!1;for(const t of this._selectedTiles)t.isSelected=!0,t.isVisible=!0;("function"==typeof t?t:r_[t])(Array.from(this._cache.values())),n=0;for(const t of this._cache.values())if(e[n++]!==t.isVisible)return!0;return!1}_pruneRequests(){const{maxRequests:t=0}=this.opts,e=[];let n=0;for(const t of this._cache.values())t.isLoading&&(n++,t.isSelected||t.isVisible||e.push(t));for(;t>0&&n>t&&e.length>0;)e.shift().abort(),n--}_rebuildTree(){const{_cache:t}=this;for(const e of t.values())e.parent=null,e.children&&(e.children.length=0);for(const e of t.values()){const t=this._getNearestAncestor(e);e.parent=t,t?.children&&t.children.push(e)}}_resizeCache(){const{_cache:t,opts:e}=this,n=e.maxCacheSize??(null!==e.maxCacheByteSize?1/0:5*this.selectedTiles.length),i=e.maxCacheByteSize??1/0;if(t.size>n||this._cacheByteSize>i){for(const[s,r]of t)if(r.isVisible||r.isSelected||(this._cacheByteSize-=null!==e.maxCacheByteSize?r.byteLength:0,t.delete(s),this.opts.onTileUnload?.(r)),t.size<=n&&this._cacheByteSize<=i)break;this._rebuildTree(),this._dirty=!0}this._dirty&&(this._tiles=Array.from(this._cache.values()).sort(((t,e)=>t.zoom-e.zoom)),this._dirty=!1)}_getTile(t,e){const n=this.getTileId(t);let i=this._cache.get(n),s=!1;return!i&&e?(i=new Yg(t),Object.assign(i,this.getTileMetadata(i.index)),Object.assign(i,{id:n,zoom:this.getTileZoom(i.index)}),s=!0,this._cache.set(n,i),this._dirty=!0):i&&i.needsReload&&(s=!0),i&&s&&i.loadData({getData:this.opts.getTileData,requestScheduler:this._requestScheduler,onLoad:this.onTileLoad,onError:this.opts.onTileError}),i}_getNearestAncestor(t){const{_minZoom:e=0}=this;let n=t.index;for(;this.getTileZoom(n)>e;){n=this.getParentIndex(n);const t=this._getTile(n);if(t)return t}return null}}function c_(t){let e=t;for(;e;){if(e.isLoaded||e.content)return e.state|=2,!0;e=e.parent}return!1}function l_(t){for(const e of t.children)e.isLoaded||e.content?e.state|=2:l_(e)}const h_={TilesetClass:a_,data:{type:"data",value:[]},dataComparator:Gm.equal,renderSubLayers:{type:"function",value:t=>new qg(t)},getTileData:{type:"function",optional:!0,value:null},onViewportLoad:{type:"function",optional:!0,value:null},onTileLoad:{type:"function",value:()=>{}},onTileUnload:{type:"function",value:()=>{}},onTileError:{type:"function",value:t=>console.error(t)},extent:{type:"array",optional:!0,value:null,compare:!0},tileSize:512,maxZoom:null,minZoom:0,maxCacheSize:null,maxCacheByteSize:null,refinementStrategy:s_,zRange:null,maxRequests:6,debounceTime:0,zoomOffset:0};class u_ extends Bd{initializeState(){this.state={tileset:null,isLoaded:!1}}finalizeState(){this.state?.tileset?.finalize()}get isLoaded(){return Boolean(this.state?.tileset?.selectedTiles?.every((t=>t.isLoaded&&t.layers&&t.layers.every((t=>t.isLoaded)))))}shouldUpdateState({changeFlags:t}){return t.somethingChanged}updateState({changeFlags:t}){let{tileset:e}=this.state;const n=t.dataChanged||t.updateTriggersChanged&&(t.updateTriggersChanged.all||t.updateTriggersChanged.getTileData);e?(t.propsOrDataChanged||t.updateTriggersChanged)&&(e.setOptions(this._getTilesetOptions()),n?e.reloadAll():e.tiles.forEach((t=>{t.layers=null}))):(e=new this.props.TilesetClass(this._getTilesetOptions()),this.setState({tileset:e})),this._updateTileset()}_getTilesetOptions(){const{tileSize:t,maxCacheSize:e,maxCacheByteSize:n,refinementStrategy:i,extent:s,maxZoom:r,minZoom:o,maxRequests:a,debounceTime:c,zoomOffset:l}=this.props;return{maxCacheSize:e,maxCacheByteSize:n,maxZoom:r,minZoom:o,tileSize:t,refinementStrategy:i,extent:s,maxRequests:a,debounceTime:c,zoomOffset:l,getTileData:this.getTileData.bind(this),onTileLoad:this._onTileLoad.bind(this),onTileError:this._onTileError.bind(this),onTileUnload:this._onTileUnload.bind(this)}}_updateTileset(){const t=this.state.tileset,{zRange:e,modelMatrix:n}=this.props,i=t.update(this.context.viewport,{zRange:e,modelMatrix:n}),{isLoaded:s}=t,r=this.state.frameNumber!==i;s&&(this.state.isLoaded!==s||r)&&this._onViewportLoad(),r&&this.setState({frameNumber:i}),this.state.isLoaded=s}_onViewportLoad(){const{tileset:t}=this.state,{onViewportLoad:e}=this.props;e&&e(t.selectedTiles)}_onTileLoad(t){this.props.onTileLoad(t),t.layers=null,this.setNeedsUpdate()}_onTileError(t,e){this.props.onTileError(t),e.layers=null,this.setNeedsUpdate()}_onTileUnload(t){this.props.onTileUnload(t)}getTileData(t){const{data:e,getTileData:n,fetch:i}=this.props,{signal:s}=t;return t.url="string"==typeof e||Array.isArray(e)?Vm(e,t):null,n?n(t):i&&t.url?i(t.url,{propName:"data",layer:this,signal:s}):null}renderSubLayers(t){return this.props.renderSubLayers(t)}getSubLayerPropsByTile(t){return null}getPickingInfo(t){const e=t.sourceLayer,n=e.props.tile,i=t.info;return i.picked&&(i.tile=n),i.sourceTile=n,i.sourceTileSubLayer=e,i}_updateAutoHighlight(t){t.sourceTileSubLayer.updateAutoHighlight(t)}renderLayers(){return this.state.tileset.tiles.map((t=>{const e=this.getSubLayerPropsByTile(t);if(t.isLoaded||t.content)if(t.layers)e&&t.layers[0]&&Object.keys(e).some((n=>t.layers[0].props[n]!==e[n]))&&(t.layers=t.layers.map((t=>t.clone(e))));else{const n=this.renderSubLayers({...this.props,...this.getSubLayerProps({id:t.id,updateTriggers:this.props.updateTriggers}),data:t.content,_offset:0,tile:t});t.layers=bl(n,Boolean).map((n=>n.clone({tile:t,...e})))}return t.layers}))}filterSubLayer({layer:t,cullRect:e}){const{tile:n}=t.props,{modelMatrix:i}=this.props;return this.state.tileset.isTileVisible(n,e,i?new xr(i):null)}}u_.defaultProps=h_,u_.layerName="TileLayer";const f_=Math.PI/180,d_=new Float32Array(16),p_=new Float32Array(12);function g_(t,e,n){const i=e[0]*f_,s=e[1]*f_,r=e[2]*f_,o=Math.sin(r),a=Math.sin(i),c=Math.sin(s),l=Math.cos(r),h=Math.cos(i),u=Math.cos(s),f=n[0],d=n[1],p=n[2];t[0]=f*u*h,t[1]=f*c*h,t[2]=f*-a,t[3]=d*(-c*l+u*a*o),t[4]=d*(u*l+c*a*o),t[5]=d*h*o,t[6]=p*(c*o+u*a*l),t[7]=p*(-u*o+c*a*l),t[8]=p*h*l}function m_(t){return t[0]=t[0],t[1]=t[1],t[2]=t[2],t[3]=t[4],t[4]=t[5],t[5]=t[6],t[6]=t[8],t[7]=t[9],t[8]=t[10],t[9]=t[12],t[10]=t[13],t[11]=t[14],t.subarray(0,12)}const __={size:12,accessor:["getOrientation","getScale","getTranslation","getTransformMatrix"],shaderAttributes:{instanceModelMatrixCol0:{size:3,elementOffset:0},instanceModelMatrixCol1:{size:3,elementOffset:3},instanceModelMatrixCol2:{size:3,elementOffset:6},instanceTranslation:{size:3,elementOffset:9}},update(t,{startRow:e,endRow:n}){const{data:i,getOrientation:s,getScale:r,getTranslation:o,getTransformMatrix:a}=this.props,c=Array.isArray(a),l=c&&16===a.length,h=Array.isArray(r),u=Array.isArray(s),f=Array.isArray(o),d=l||!c&&Boolean(a(i[0]));t.constant=d?l:u&&h&&f;const p=t.value;if(t.constant){let e;d?(d_.set(a),e=m_(d_)):(e=p_,g_(e,s,r),e.set(o,9)),t.value=new Float32Array(e)}else{let c=e*t.size;const{iterable:g,objectInfo:m}=Nf(i,e,n);for(const t of g){let e;m.index++,d?(d_.set(l?a:a(t,m)),e=m_(d_)):(e=p_,g_(e,u?s:s(t,m),h?r:r(t,m)),e.set(f?o:o(t,m),9)),p[c++]=e[0],p[c++]=e[1],p[c++]=e[2],p[c++]=e[3],p[c++]=e[4],p[c++]=e[5],p[c++]=e[6],p[c++]=e[7],p[c++]=e[8],p[c++]=e[9],p[c++]=e[10],p[c++]=e[11]}}}};function v_(t,e){return e===Ko.CARTESIAN||e===Ko.METER_OFFSETS||e===Ko.DEFAULT&&!t.isGeospatial}const b_="uniform simpleMeshUniforms {\n float sizeScale;\n bool composeModelMatrix;\n bool hasTexture;\n bool flatShading;\n} simpleMesh;\n",y_={name:"simpleMesh",vs:b_,fs:b_,uniformTypes:{sizeScale:"f32",composeModelMatrix:"f32",hasTexture:"f32",flatShading:"f32"}};function w_(t){const e=t.positions||t.POSITION;F.assert(e,'no "postions" or "POSITION" attribute in mesh');const n=e.value.length/e.size;let i=t.COLOR_0||t.colors;i||(i={size:3,value:new Float32Array(3*n).fill(1)});let s=t.NORMAL||t.normals;s||(s={size:3,value:new Float32Array(3*n).fill(0)});let r=t.TEXCOORD_0||t.texCoords;return r||(r={size:2,value:new Float32Array(2*n).fill(0)}),{positions:e,colors:i,normals:s,texCoords:r}}function x_(t){return t instanceof ll?(t.attributes=w_(t.attributes),t):new ll(t.attributes?{...t,topology:"triangle-list",attributes:w_(t.attributes)}:{topology:"triangle-list",attributes:w_(t)})}class E_ extends Fd{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME simple-mesh-layer-vs\nin vec3 positions;\nin vec3 normals;\nin vec3 colors;\nin vec2 texCoords;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec3 instanceModelMatrixCol0;\nin vec3 instanceModelMatrixCol1;\nin vec3 instanceModelMatrixCol2;\nin vec3 instanceTranslation;\nout vec2 vTexCoord;\nout vec3 cameraPosition;\nout vec3 normals_commonspace;\nout vec4 position_commonspace;\nout vec4 vColor;\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = texCoords;\ngeometry.pickingColor = instancePickingColors;\nvTexCoord = texCoords;\ncameraPosition = project.cameraPosition;\nvColor = vec4(colors * instanceColors.rgb, instanceColors.a);\nmat3 instanceModelMatrix = mat3(instanceModelMatrixCol0, instanceModelMatrixCol1, instanceModelMatrixCol2);\nvec3 pos = (instanceModelMatrix * positions) * simpleMesh.sizeScale + instanceTranslation;\nif (simpleMesh.composeModelMatrix) {\nDECKGL_FILTER_SIZE(pos, geometry);\nnormals_commonspace = project_normal(instanceModelMatrix * normals);\ngeometry.worldPosition += pos;\ngl_Position = project_position_to_clipspace(pos + instancePositions, instancePositions64Low, vec3(0.0), position_commonspace);\ngeometry.position = position_commonspace;\n}\nelse {\npos = project_size(pos);\nDECKGL_FILTER_SIZE(pos, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, pos, position_commonspace);\ngeometry.position = position_commonspace;\nnormals_commonspace = project_normal(instanceModelMatrix * normals);\n}\ngeometry.normal = normals_commonspace;\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME simple-mesh-layer-fs\nprecision highp float;\nuniform sampler2D sampler;\nin vec2 vTexCoord;\nin vec3 cameraPosition;\nin vec3 normals_commonspace;\nin vec4 position_commonspace;\nin vec4 vColor;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = vTexCoord;\nvec3 normal;\nif (simpleMesh.flatShading) {\nnormal = normalize(cross(dFdx(position_commonspace.xyz), dFdy(position_commonspace.xyz)));\n} else {\nnormal = normals_commonspace;\n}\nvec4 color = simpleMesh.hasTexture ? texture(sampler, vTexCoord) : vColor;\nDECKGL_FILTER_COLOR(color, geometry);\nvec3 lightColor = lighting_getLightColor(color.rgb, cameraPosition, position_commonspace.xyz, normal);\nfragColor = vec4(lightColor, color.a * layer.opacity);\n}\n",modules:[_a,Hr,Qa,y_]})}getBounds(){if(this.props._instanced)return super.getBounds();let t=this.state.positionBounds;if(t)return t;const{mesh:e}=this.props;if(!e)return null;if(t=e.header?.boundingBox,!t){const{attributes:n}=x_(e);n.POSITION=n.POSITION||n.positions,t=m(n)}return this.state.positionBounds=t,t}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{transition:!0,type:"float64",fp64:this.use64bitPositions(),size:3,accessor:"getPosition"},instanceColors:{type:"unorm8",transition:!0,size:this.props.colorFormat.length,accessor:"getColor",defaultValue:[0,0,0,255]},instanceModelMatrix:__}),this.setState({emptyTexture:this.context.device.createTexture({data:new Uint8Array(4),width:1,height:1})})}updateState(t){super.updateState(t);const{props:e,oldProps:n,changeFlags:i}=t;if(e.mesh!==n.mesh||i.extensionsChanged){if(this.state.positionBounds=null,this.state.model?.destroy(),e.mesh){this.state.model=this.getModel(e.mesh);const t=e.mesh.attributes||e.mesh;this.setState({hasNormals:Boolean(t.NORMAL||t.normals)})}this.getAttributeManager().invalidateAll()}e.texture!==n.texture&&e.texture instanceof ye&&this.setTexture(e.texture),this.state.model&&this.state.model.setTopology(this.props.wireframe?"line-strip":"triangle-list")}finalizeState(t){super.finalizeState(t),this.state.emptyTexture.delete()}draw({}){const{model:t}=this.state;if(!t)return;const{viewport:e,renderPass:n}=this.context,{sizeScale:i,coordinateSystem:s,_instanced:r}=this.props,o={sizeScale:i,composeModelMatrix:!r||v_(e,s),flatShading:!this.state.hasNormals};t.shaderInputs.setProps({simpleMesh:o}),t.draw(n)}get isLoaded(){return Boolean(this.state?.model&&super.isLoaded)}getModel(t){const e=new ol(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:x_(t),isInstanced:!0}),{texture:n}=this.props,{emptyTexture:i}=this.state,s={sampler:n||i,hasTexture:Boolean(n)};return e.shaderInputs.setProps({simpleMesh:s}),e}setTexture(t){const{emptyTexture:e,model:n}=this.state;if(n){const i={sampler:t||e,hasTexture:Boolean(t)};n.shaderInputs.setProps({simpleMesh:i})}}}E_.defaultProps={mesh:{type:"object",value:null,async:!0},texture:{type:"image",value:null,async:!0},sizeScale:{type:"number",value:1,min:0},_instanced:!0,wireframe:!1,material:!0,getPosition:{type:"accessor",value:t=>t.position},getColor:{type:"accessor",value:[0,0,0,255]},getOrientation:{type:"accessor",value:[0,0,0]},getScale:{type:"accessor",value:[1,1,1]},getTranslation:{type:"accessor",value:[0,0,0]},getTransformMatrix:{type:"accessor",value:[]},textureParameters:{type:"object",ignore:!0,value:null}},E_.layerName="SimpleMeshLayer";const T_=[1],A_={...u_.defaultProps,elevationData:Gm,texture:{...Gm,optional:!0},meshMaxError:{type:"number",value:4},bounds:{type:"array",value:null,optional:!0,compare:!0},color:{type:"color",value:[255,255,255]},elevationDecoder:{type:"object",value:{rScaler:1,gScaler:0,bScaler:0,offset:0}},workerUrl:"",wireframe:!1,material:!0,loaders:[g]};function S_(t){return Array.isArray(t)?t.join(";"):t||""}class C_ extends Bd{updateState({props:t,oldProps:e}){const n=t.elevationData!==e.elevationData;if(n){const{elevationData:e}=t,n=e&&(Array.isArray(e)||P_(e));this.setState({isTiled:n})}if(!this.state.isTiled&&(n||t.meshMaxError!==e.meshMaxError||t.elevationDecoder!==e.elevationDecoder||t.bounds!==e.bounds)){const e=this.loadTerrain(t);this.setState({terrain:e})}t.workerUrl&&F.removed("workerUrl","loadOptions.terrain.workerUrl")()}loadTerrain({elevationData:t,bounds:e,elevationDecoder:n,meshMaxError:i,signal:s}){if(!t)return null;let r=this.getLoadOptions();r={...r,terrain:{skirtHeight:this.state.isTiled?2*i:0,...r?.terrain,bounds:e,meshMaxError:i,elevationDecoder:n}};const{fetch:o}=this.props;return o(t,{propName:"elevationData",layer:this,loadOptions:r,signal:s})}getTiledTerrainData(t){const{elevationData:e,fetch:n,texture:i,elevationDecoder:s,meshMaxError:r}=this.props,{viewport:o}=this.context,a=Vm(e,t),c=i&&Vm(i,t),{signal:l}=t;let h=[0,0],u=[0,0];if(o.isGeospatial){const e=t.bbox;h=o.projectFlat([e.west,e.south]),u=o.projectFlat([e.east,e.north])}else{const e=t.bbox;h=[e.left,e.bottom],u=[e.right,e.top]}const f=this.loadTerrain({elevationData:a,bounds:[h[0],h[1],u[0],u[1]],elevationDecoder:s,meshMaxError:r,signal:l}),d=c?n(c,{propName:"texture",layer:this,loaders:[],signal:l}).catch((()=>null)):Promise.resolve(null);return Promise.all([f,d])}renderSubLayers(t){const e=this.getSubLayerClass("mesh",E_),{color:n,wireframe:i,material:s}=this.props,{data:r}=t;if(!r)return null;const[o,a]=r;return new e(t,{data:T_,mesh:o,texture:a,_instanced:!1,coordinateSystem:Ko.CARTESIAN,getPosition:()=>[0,0,0],getColor:n,wireframe:i,material:s})}onViewportLoad(t){if(!t)return;const{zRange:e}=this.state,n=t.map((t=>t.content)).filter(Boolean).map((t=>t[0].header.boundingBox.map((t=>t[2]))));if(0===n.length)return;const i=Math.min(...n.map((t=>t[0]))),s=Math.max(...n.map((t=>t[1])));(!e||i<e[0]||s>e[1])&&this.setState({zRange:[i,s]})}renderLayers(){const{color:t,material:e,elevationData:n,texture:i,wireframe:s,meshMaxError:r,elevationDecoder:o,tileSize:a,maxZoom:c,minZoom:l,extent:h,maxRequests:u,onTileLoad:f,onTileUnload:d,onTileError:p,maxCacheSize:g,maxCacheByteSize:m,refinementStrategy:_}=this.props;return this.state.isTiled?new u_(this.getSubLayerProps({id:"tiles"}),{getTileData:this.getTiledTerrainData.bind(this),renderSubLayers:this.renderSubLayers.bind(this),updateTriggers:{getTileData:{elevationData:S_(n),texture:S_(i),meshMaxError:r,elevationDecoder:o}},onViewportLoad:this.onViewportLoad.bind(this),zRange:this.state.zRange||null,tileSize:a,maxZoom:c,minZoom:l,extent:h,maxRequests:u,onTileLoad:f,onTileUnload:d,onTileError:p,maxCacheSize:g,maxCacheByteSize:m,refinementStrategy:_}):n?new(this.getSubLayerClass("mesh",E_))(this.getSubLayerProps({id:"mesh"}),{data:T_,mesh:this.state.terrain,texture:i,_instanced:!1,getPosition:()=>[0,0,0],getColor:t,material:e,wireframe:s}):null}}C_.defaultProps=A_,C_.layerName="TerrainLayer";const P_=t=>t.includes("{x}")&&(t.includes("{y}")||t.includes("{-y}"));function M_([t,e]){const n=6378137;return[t*Math.PI/180*n,Math.log(Math.tan(Math.PI/4+e*Math.PI/360))*n]}function R_(t){const e=Object.entries(t).filter((([,t])=>null!=t&&""!==t)).map((([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(e))}`)).join("&");return e?`?${e}`:""}class L_{_groups=[];_dirty=!0;_cachedLayers=[];_deck=null;constructor(t={}){if(t.groups?.length){const e=new Set;for(const n of t.groups)n?.id&&!e.has(n.id)&&(e.add(n.id),this._groups.push(n));this._dirty=!0}}get size(){return this._groups.length}get groups(){return[...this._groups]}getGroup(t){return this._groups.find((e=>e.id===t))}hasGroup(t){return this._groups.some((e=>e.id===t))}attachDeck(t){this._deck=t}detachDeck(){this._deck=null}applyToDeck(t={}){if(!this._deck)return;const e=[...this.getLayers(t)].sort(((t,e)=>(t.props.zIndex??0)-(e.props.zIndex??0)));this._deck.setProps({layers:e})}addGroup(t){if(!t?.id)throw new Error("LayerGroup benötigt eine eindeutige id");this.hasGroup(t.id)||(this._groups.push(t),this._dirty=!0)}addGroups(t){t.forEach((t=>this.addGroup(t)))}removeGroup(t,e){const n=this._groups.findIndex((e=>e.id===t));if(n<0)return;const[i]=this._groups.splice(n,1);e?.destroy&&i.destroy?.(),this._dirty=!0}clear(t){t?.destroy&&this._groups.forEach((t=>t.destroy?.())),this._groups=[],this._dirty=!0}replaceGroup(t,e=!0){const n=this._groups.findIndex((e=>e.id===t.id));n<0?this._groups.push(t):e?this._groups[n]=t:(this._groups.splice(n,1),this._groups.push(t)),this._dirty=!0}moveGroup(t,e){const n=this._groups.findIndex((e=>e.id===t));if(n<0)return;const i=Math.max(0,Math.min(this._groups.length-1,e));if(n===i)return;const[s]=this._groups.splice(n,1);this._groups.splice(i,0,s),this._dirty=!0}setGroupVisible(t,e,n={}){const i=this.getGroup(t);if(!i)throw new Error(`LayerGroup mit id "${t}" nicht gefunden`);return i.visible!==e&&(i.visible=e,this._dirty=!0,this.applyToDeck({respectExternalChanges:n.respectExternalChanges}),!0)}removeLayer(t,e={}){let n=!1;for(const i of this._groups){const s=i;if("function"==typeof s.hasLayer&&"function"==typeof s.removeLayer&&s.hasLayer(t)&&(s.removeLayer(t),n=!0,!e.removeFromAll))break}return n&&(this._dirty=!0,this.applyToDeck({respectExternalChanges:e.respectExternalChanges})),n}setModelEnabled(t,e,n,i={apply:!0}){const s=this.getGroup(t);if(!s)throw new Error(`Gruppe "${t}" nicht gefunden`);"function"==typeof s.setModelEnabled&&(s.setModelEnabled(e,n),this._dirty=!0,i.apply&&this.applyToDeck())}withUpdate(t){this._dirty=!0,t(this)}getLayers(t={}){const e=this._groups.some((t=>t.isDirty()));if(!this._dirty&&!e)return this._cachedLayers;const n=[];for(const e of this._groups){const i=e.getLayers(t);i.length&&n.push(...i)}return this._cachedLayers=n,this._dirty=!1,this._cachedLayers}markDirty(){this._dirty=!0}destroy(t){t?.destroyGroups&&this._groups.forEach((t=>t.destroy?.())),this._groups=[],this._cachedLayers=[],this._dirty=!0}}class O_{id;_visible=!0;_syncMode="force-model";_models=new Map;_instances=new Map;_recreateOnNextEmit=!1;_overrides=new Map;_dirty=!0;_cachedLayers=[];_basemap=null;constructor(t){this.id=t.id,this._visible=t.visible??!0,this._syncMode=t.syncMode??"force-model",this._basemap=t.basemap??null,(t.models??[]).forEach((t=>this.addModel(t)))}get visible(){return this._visible}set visible(t){this._visible!==t&&(this._visible=t,t||(this._instances.clear(),this._recreateOnNextEmit=!0),this._dirty=!0)}get syncMode(){return this._syncMode}set syncMode(t){this._syncMode!==t&&(this._syncMode=t,this._dirty=!0)}set basemap(t){this._basemap!==t&&(this._basemap=t,this._instances.clear(),this._recreateOnNextEmit=!0,this._dirty=!0)}get basemap(){return this._basemap}isDirty(){return this._dirty}addModel(t){if(!t?.id)throw new Error("LayerModel benötigt id");this._models.set(t.id,{...t}),this._dirty=!0}addModels(t){t.forEach((t=>this.addModel(t)))}getModel(t){const e=this._models.get(t);return e?{...e}:void 0}removeModel(t){this._models.delete(t)&&(this._instances.delete(t),this._overrides.delete(t),this._dirty=!0)}clear(){this._models.clear(),this._instances.clear(),this._overrides.clear(),this._cachedLayers=[],this._dirty=!0}setModelEnabled(t,e){const n=this._models.get(t);if(!n)throw new Error(`LayerModel "${t}" nicht gefunden`);n.enabled!==e&&(n.enabled=e,e||this._instances.delete(t),this._dirty=!0)}replaceModel(t){const e=this._models.has(t.id);this._models.set(t.id,{...t}),this._dirty=this._dirty||!e}setModelOverrides(t,e){if(!this._models.has(t))throw new Error(`LayerModel "${t}" nicht gefunden`);const n=this._overrides.get(t)??{};this._overrides.set(t,{...n,...e}),this._dirty=!0}clearModelOverrides(t){this._overrides.delete(t)&&(this._dirty=!0)}getLayers(){if(!this._dirty&&this._cachedLayers.length)return this._cachedLayers;if(!this._visible)return this._cachedLayers=[],this._dirty=!1,this._cachedLayers;const t=[];for(const[e,n]of this._models.entries()){let s=this._visible&&n.enabled;if(this._basemap&&n.elementId!==this._basemap&&(s=!1),!s){this._instances.delete(e);continue}let r=this._instances.get(e);if(!r||this._recreateOnNextEmit){i("deck - lgwm - getLayers - model.make()");const t=n.make();r=!0===(t.props.visible??!0)?t:t.clone({visible:!0}),this._instances.set(e,r)}"force-model"===this._syncMode&&(r.props.visible??!0)!==s&&(r=r.clone({visible:s}),this._instances.set(e,r));const o=this._overrides.get(e);if(o&&Object.keys(o).length){const t=Object.entries(o).some((([t,e])=>r.props[t]!==e));t&&(r=r.clone(o),this._instances.set(e,r))}t.push(r)}return this._recreateOnNextEmit=!1,this._cachedLayers=t,this._dirty=!1,this._cachedLayers}destroy(){this._instances.forEach((t=>t.finalize?.())),this.clear()}}var I_=Object.freeze({__proto__:null,DeckProvider:class{deck;target;shadowRoot;injectedStyle;layerGroups=new L_({});layerErrorCallbacks=new Map;async init(t){this.target=t.target,this.shadowRoot=t.shadowRoot,this.injectedStyle=await async function(t){const e=document.createElement("style");return e.textContent="canvas.deckgl-canvas { background:#fff !important; }",t?.appendChild(e),e}(this.shadowRoot);let e={longitude:t.mapInitOptions?.center?.[0]??8.5417,latitude:t.mapInitOptions?.center?.[1]??49.0069,zoom:t.mapInitOptions?.zoom??5,bearing:0,pitch:0};Object.assign(this.target.style,{width:"100%",height:"100%",position:"relative",background:"#fff"}),this.deck=new Pf({parent:this.target,controller:{scrollZoom:!0,dragPan:!0,dragRotate:!0,touchZoom:!0,touchRotate:!0,doubleClickZoom:!0,keyboard:!0},viewState:e,onViewStateChange:({viewState:t})=>{e=t,this.deck.setProps({viewState:e})},layers:[],_typedArrayManagerProps:{overAlloc:1}}),this.layerGroups.attachDeck(this.deck)}ensureModelGroup(t){const e=this.layerGroups.getGroup(t);if(e)return e;const n=new O_({id:t,syncMode:"force-model"});return this.layerGroups.addGroup(n),n}createLayerModel(t,e,n=!0,i=null){return{id:t,elementId:i,enabled:n,make:e,meta:{}}}async buildXyzTileLayer(t,e){return new u_({id:e,data:[t.url],zIndex:100,maxRequests:20,tileSize:t.tileSize??256,minZoom:t.minZoom??0,maxZoom:t.maxZoom??19,opacity:t.opacity,onTileError:t=>{i(`v-map - provider - deck - Tile Error: ${t}`),this.layerErrorCallbacks.get(e)?.({type:"network",message:`Tile load error: ${t}`,cause:t})},renderSubLayers:t=>{const{west:e,south:n,east:i,north:s}=t.tile.bbox,r=[e,n,i,s],{data:o,...a}=t;if(null==o){const e=document.createElement("canvas");e.width=t.tile.width,e.height=t.tile.height;const n=e.getContext("2d");return n?.clearRect(0,0,t.tile.width,t.tile.height),new Hd({id:`dynamic-transparent-bitmap-${t.tile.index.x}-${t.tile.index.y}-${t.tile.index.z}`,image:e,coordinates:"pixel",bounds:[0,0,t.tile.width,t.tile.height]})}return new Hd(a,{image:o,bounds:r,opacity:t.opacity??1})},updateTriggers:{renderSubLayers:["sl.props.opacity"]}})}buildArcgisUrl(t,e,n){const i=new URLSearchParams;e&&Object.entries(e).forEach((([t,e])=>{null!=e&&i.set(t,String(e))})),n&&i.set("token",n);const s=i.toString();return s?`${t}${t.includes("?")?"&":"?"}${s}`:t}async buildArcgisTileLayer(t,e){const n=this.buildArcgisUrl(t.url,t.params,t.token);return this.buildXyzTileLayer({...t,url:n,minZoom:t.minZoom,maxZoom:t.maxZoom,opacity:t.opacity},e)}async buildTerrainLayer(t,e){const n=this.normalizeElevationDecoder(t.elevationDecoder);return new C_({id:e,elevationData:t.elevationData,texture:t.texture,elevationDecoder:n,wireframe:t.wireframe??!1,color:t.color,minZoom:t.minZoom,maxZoom:t.maxZoom,meshMaxError:t.meshMaxError,opacity:t.opacity??1,visible:t.visible??!0,material:!0,pickable:!1})}getModelUrl(t){if(t&&"function"==typeof t.make)try{const e=t.make(),n=e?.props,i=n?.data;return(Array.isArray(i)?i[0]:void 0)??n?.url}catch(t){return void r("Failed to resolve model URL",t)}}normalizeElevationDecoder(t){const e={rScaler:1,gScaler:1,bScaler:1,offset:0};return t?{rScaler:t.rScaler??t.r??e.rScaler,gScaler:t.gScaler??t.g??e.gScaler,bScaler:t.bScaler??t.b??e.bScaler,offset:t.offset??e.offset}:e}createGeostylerDeckGLStyle(t){const e=(t,e)=>null==t||"object"==typeof t&&t.name?e:t,n=[0,100,255,76],i=[0,100,255,255],s=[0,100,255,255];let r=n,o=i,a=s,c=8,l=2;if(t.rules)for(const h of t.rules)if(h.symbolizers)for(const t of h.symbolizers)switch(t.kind){case"Fill":const h=e(t.color,"rgba(0,100,255,0.3)"),u=e(t.opacity,.3);r=this.parseColor(h,n),void 0!==u&&(r=this.applyOpacity(r,u));const f=e(t.outlineColor);f&&(o=this.parseColor(f,i));const d=e(t.outlineWidth,1);void 0!==d&&(l=d);break;case"Line":const p=e(t.color,"rgba(0,100,255,1)");o=this.parseColor(p,i);const g=e(t.width,2);void 0!==g&&(l=g);break;case"Mark":const m=e(t.color,"rgba(0,100,255,1)");a=this.parseColor(m,s);const _=e(t.radius,6);void 0!==_&&(c=_);break;case"Icon":const v=e(t.size,32);void 0!==v&&(c=v/2)}return{getFillColor:()=>r,getLineColor:()=>o,getPointRadius:()=>c,getPointFillColor:()=>a,lineWidthMinPixels:l,pointRadiusMinPixels:2,pointRadiusMaxPixels:100}}parseColor(t,e){if(!t)return e;if(t.startsWith("#")){const e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),255]}const n=t.match(/rgba?\(([^)]+)\)/);if(n){const t=n[1].split(",").map((t=>parseFloat(t.trim())));return[t[0]||0,t[1]||0,t[2]||0,void 0!==t[3]?Math.round(255*t[3]):255]}return e}applyOpacity(t,e){return[t[0],t[1],t[2],Math.round(255*e)]}createDeckGLStyle(t={}){const e=this.parseColor(t.fillColor,[0,100,255,76]),n=this.parseColor(t.strokeColor,[0,100,255,255]),i=this.parseColor(t.pointColor,[0,100,255,255]),s=void 0!==t.fillOpacity?this.applyOpacity(e,t.fillOpacity):e,r=void 0!==t.strokeOpacity?this.applyOpacity(n,t.strokeOpacity):n,o=void 0!==t.pointOpacity?this.applyOpacity(i,t.pointOpacity):i;return{getFillColor:e=>{if(t.styleFunction){const n=t.styleFunction(e);if(n.fillColor){const t=this.parseColor(n.fillColor,s);return void 0!==n.fillOpacity?this.applyOpacity(t,n.fillOpacity):t}}return s},getLineColor:e=>{if(t.styleFunction){const n=t.styleFunction(e);if(n.strokeColor){const t=this.parseColor(n.strokeColor,r);return void 0!==n.strokeOpacity?this.applyOpacity(t,n.strokeOpacity):t}}return r},getPointRadius:e=>{if(t.styleFunction){const n=t.styleFunction(e);if(void 0!==n.pointRadius)return n.pointRadius}return t.pointRadius??8},getPointFillColor:e=>{if(t.styleFunction){const n=t.styleFunction(e);if(n.pointColor){const t=this.parseColor(n.pointColor,o);return void 0!==n.pointOpacity?this.applyOpacity(t,n.pointOpacity):t}}return o},lineWidthMinPixels:t.strokeWidth??2,pointRadiusMinPixels:2,pointRadiusMaxPixels:100}}async buildOsmLayer(t,e){let n="https://tile.openstreetmap.org/{z}/{x}/{y}.png";return t.url&&(n=t.url+"/{z}/{x}/{y}.png"),this.buildXyzTileLayer({...t,url:n},e)}async buildGoogleTileLayer(t,e){if(!t.apiKey)throw new Error("Google-Layer benötigt 'apiKey' (Google Maps Platform).");await this.loadGoogleMapsApi(t.apiKey,{language:t.language,region:t.region,libraries:t.libraries});const n=this.getGoogleMapTypeId(t.mapType||"roadmap");return new u_({id:e,data:["placeholder"],opacity:t.opacity??1,visible:t.visible??!0,minZoom:0,maxZoom:t.maxZoom??19,tileSize:256,getTileData:async({index:e})=>{const{x:i,y:s,z:o}=e,a=((t,e,n)=>{const i=Math.pow(2,n),s=(t+1)/i*360-180;return{west:t/i*360-180,south:180*Math.atan(Math.sinh(Math.PI*(1-2*(e+1)/i)))/Math.PI,east:s,north:180*Math.atan(Math.sinh(Math.PI*(1-2*e/i)))/Math.PI}})(i,s,o),c=new URLSearchParams({center:`${(a.south+a.north)/2},${(a.west+a.east)/2}`,zoom:o.toString(),size:"256x256",scale:"scaleFactor1x"===t.scale?"1":"2",maptype:n,key:t.apiKey,format:"png"});t.language&&c.set("language",t.language),t.region&&c.set("region",t.region);const l=`https://maps.googleapis.com/maps/api/staticmap?${c.toString()}`;try{const t=await fetch(l);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.blob()}catch(t){return r("Failed to load Google tile:",t),null}},renderSubLayers:t=>{const n=t.data,i=t.tile;if(!n)return null;const{west:s,south:r,east:o,north:a}=i.bbox;return new Hd({id:`${e}-bitmap-${i.index.x}-${i.index.y}-${i.index.z}`,image:n,bounds:[s,r,o,a],opacity:t.opacity??1})},onTileLoad:()=>{this.ensureGoogleLogo(this.target)}})}getGoogleMapTypeId(t){switch(t){case"roadmap":default:return"roadmap";case"satellite":return"satellite";case"terrain":return"terrain";case"hybrid":return"hybrid"}}async loadGoogleMapsApi(t,e){const n=window,i=n.__mockGoogleMapsApi;"function"!=typeof i?n.google?.maps||await new Promise(((i,s)=>{const r="___deckGoogleInit___"+Math.random().toString(36).slice(2);n[r]=()=>i();const o=document.createElement("script"),a=new URLSearchParams({key:t,callback:r,v:"weekly"});e?.language&&a.set("language",e.language),e?.region&&a.set("region",e.region),e?.libraries?.length&&a.set("libraries",e.libraries.join(",")),o.src=`https://maps.googleapis.com/maps/api/js?${a.toString()}`,o.async=!0,o.onerror=()=>s(new Error("Google Maps JS API failed to load")),document.head.appendChild(o)})):await i(t,e)}ensureGoogleLogo(t){const e=t;if(e._googleLogoAdded)return;const n=document.createElement("img");n.src="https://developers.google.com/static/maps/documentation/images/google_on_white.png",n.alt="Google",n.style.position="absolute",n.style.bottom="6px",n.style.left="6px",n.style.height="18px",n.style.pointerEvents="none",n.style.zIndex="1000",t.appendChild(n),e._googleLogoAdded=!0}async buildScatterPlot(t,e){const n=t.data,s=new hp({id:e,data:n,getPosition:t=>t.position,getRadius:t=>t.radius,getFillColor:t=>t.color,radiusMinPixels:2,radiusMaxPixels:30,pickable:!0,autoHighlight:!0,highlightColor:[255,255,0,128],onHover:t=>{t.object&&i("v-map - provider - deck - Hover:",t.object)},updateTriggers:{getPosition:n,getRadius:n,getFillColor:n}});return s}async createGeoJSONLayer(e,n){let i=null,s=null;if(s=e.geojson?JSON.parse(e.geojson):e.url,s){let r;if(e.geostylerStyle)r=this.createGeostylerDeckGLStyle(e.geostylerStyle);else{const n=e.style?{...t,...e.style}:t;r=this.createDeckGLStyle(n)}i=new qg({id:n,data:s,filled:!0,stroked:!0,pointType:"circle",pickable:!0,...r,opacity:e.opacity??1,visible:e.visible??!0,updateTriggers:{getFillColor:[e.style,e.geostylerStyle],getLineColor:[e.style,e.geostylerStyle],getPointRadius:[e.style,e.geostylerStyle],data:[e.geojson,e.url]}})}return i}async buildWmsTileLayer(t,e){const n=t.tileSize??256,s=t.version??"1.3.0",r="1.1.1"===s?"SRS":"CRS",o={SERVICE:"WMS",REQUEST:"GetMap",VERSION:s,LAYERS:t.layers,STYLES:t.styles??"",FORMAT:t.format??"image/png",TRANSPARENT:t.transparent??1?"TRUE":"FALSE",[r]:"EPSG:3857",TILED:"true"};return new u_({id:e,data:[t.url],zIndex:100,tileSize:n,minZoom:t.minZoom??0,maxZoom:t.maxZoom??19,opacity:t.opacity,maxRequests:20,getTileData:async i=>{const{west:s,south:r,east:a,north:c}=i.bbox,l=function(t,e,n,i){{const[s,r]=M_([t,e]),[o,a]=M_([n,i]);return`${s},${r},${o},${a}`}}(s,r,a,c),h={...o,BBOX:l,WIDTH:n,HEIGHT:n,TIME:t.time,...t.extraParams},u=`${t.url}${R_(h)}`;try{const t=await fetch(u,{mode:"cors"});if(!t.ok)throw new Error(`HTTP ${t.status}`);const e=await t.blob();return await createImageBitmap(e)}catch(t){this.layerErrorCallbacks.get(e)?.({type:"network",message:`WMS tile fetch error: ${t}`,cause:t});const i=document.createElement("canvas");i.width=n,i.height=n;const s=i.getContext("2d");return s?.clearRect(0,0,i.width,i.height),i}},onTileError:t=>{i(`v-map - provider - deck - WMS Tile Error: ${t}`),this.layerErrorCallbacks.get(e)?.({type:"network",message:`WMS tile error: ${t}`,cause:t})},renderSubLayers:t=>{const{west:n,south:i,east:s,north:r}=t.tile.bbox;return t.data instanceof HTMLCanvasElement?new Hd({id:`${e}-bmp-${t.tile.index.x}-${t.tile.index.y}-${t.tile.index.z}`,image:t.data,coordinates:"pixel",bounds:[0,0,t.tile.width,t.tile.height]}):new Hd({id:`${e}-bmp-${t.tile.index.x}-${t.tile.index.y}-${t.tile.index.z}`,image:t.data,bounds:[n,i,s,r],opacity:t.opacity??1,pickable:!1})},updateTriggers:{getTileData:[t.layers,t.styles,t.format,t.transparent,t.version,t.crs,t.time,JSON.stringify(t.extraParams??{})],renderSubLayers:["sl.props.opacity"]}})}async buildWcsTileLayer(t,e){const n=t.tileSize??256,s=t.version??"2.0.1",r=t.format??"image/tiff",o=t.projection??"EPSG:4326",a={SERVICE:"WCS",REQUEST:"GetCoverage",VERSION:s,FORMAT:r};return new u_({id:e,data:[t.url],zIndex:100,tileSize:n,minZoom:t.minZoom??0,maxZoom:t.maxZoom??19,opacity:t.opacity,maxRequests:20,getTileData:async i=>{const{west:c,south:l,east:h,north:u}=i.bbox;let f;if(s.startsWith("2.0")){f={...a,coverageId:t.coverageName,...t.params},(r.includes("tiff")||r.includes("geotiff"))&&(f["geotiff:compression"]="LZW");const i=R_(f),s=`${t.url}${i}&subset=X(${c},${h})&subset=Y(${l},${u})`;try{const t=await fetch(s,{mode:"cors"});if(!t.ok)throw new Error(`HTTP ${t.status}`);const e=await t.blob();return await createImageBitmap(e)}catch(t){this.layerErrorCallbacks.get(e)?.({type:"network",message:`WCS tile fetch error: ${t}`,cause:t});const i=document.createElement("canvas");i.width=n,i.height=n;const s=i.getContext("2d");return s?.clearRect(0,0,i.width,i.height),i}}else{f={...a,COVERAGE:t.coverageName,BBOX:`${c},${l},${h},${u}`,CRS:o,WIDTH:n,HEIGHT:n,...t.params};const i=`${t.url}${R_(f)}`;try{const t=await fetch(i,{mode:"cors"});if(!t.ok)throw new Error(`HTTP ${t.status}`);const e=await t.blob();return await createImageBitmap(e)}catch(t){this.layerErrorCallbacks.get(e)?.({type:"network",message:`WCS tile fetch error: ${t}`,cause:t});const i=document.createElement("canvas");i.width=n,i.height=n;const s=i.getContext("2d");return s?.clearRect(0,0,i.width,i.height),i}}},onTileError:t=>{i(`v-map - provider - deck - WCS Tile Error: ${t}`),this.layerErrorCallbacks.get(e)?.({type:"network",message:`WCS tile error: ${t}`,cause:t})},renderSubLayers:t=>{const{west:n,south:i,east:s,north:r}=t.tile.bbox;return t.data instanceof HTMLCanvasElement?new Hd({id:`${e}-bmp-${t.tile.index.x}-${t.tile.index.y}-${t.tile.index.z}`,image:t.data,coordinates:"pixel",bounds:[0,0,t.tile.width,t.tile.height]}):new Hd({id:`${e}-bmp-${t.tile.index.x}-${t.tile.index.y}-${t.tile.index.z}`,image:t.data,bounds:[n,i,s,r],opacity:t.opacity??1,pickable:!1})},updateTriggers:{getTileData:[t.coverageName,t.format,t.version,t.projection,JSON.stringify(t.params??{})],renderSubLayers:["sl.props.opacity"]}})}async createLayer(t,e){switch(t.type){case"geojson":return this.createGeoJSONLayer(t,e);case"osm":return this.buildOsmLayer(t,e);case"google":return this.buildGoogleTileLayer(t,e);case"wms":return this.buildWmsTileLayer(t,e);case"wcs":return this.buildWcsTileLayer(t,e);case"wfs":return this.createWFSLayer(t,e);case"arcgis":return this.buildArcgisTileLayer(t,e);case"terrain":return this.buildTerrainLayer(t,e);case"terrain-geotiff":return this.createGeoTIFFTerrainLayer(t,e);case"xyz":return this.buildXyzTileLayer(t,e);case"scatterplot":return this.buildScatterPlot(t,e);case"wkt":return this.createWKTLayer(t,e);case"geotiff":return this.createGeoTIFFLayer(t,e);default:return i(`v-map - provider - deck - Unsupported layer type: ${t.type}`),null}}async addLayerToGroup(t){const e=this.ensureModelGroup(t.groupId),n=crypto.randomUUID(),i=await this.createLayer(t,n);if(!i)return null;const s=this.createLayerModel(n,(()=>i.clone({})),t.visible??!0);void 0!==typeof t.groupVisible&&(e.visible=t.groupVisible),e.addModel(s);const r={};return void 0!==t.opacity&&(r.opacity=t.opacity),void 0!==t.zIndex&&(r.zIndex=t.zIndex),!0===t.visible&&(r.visible=!0),!1===t.visible&&(r.visible=!1),Object.keys(r).length&&e.setModelOverrides(n,r),this.layerGroups.applyToDeck(),n}async addBaseLayer(t,e,n){if(!n||!e)return i("ol - addBaseLayer - ids missing"),null;const s=this.ensureModelGroup(t.groupId??"basemap");s.basemap=e;const r=crypto.randomUUID(),o=await this.createLayer(t,r);if(!o)return null;const a=this.createLayerModel(r,(()=>o),!0,n);s.addModel(a);const c={};return void 0!==t.opacity&&(c.opacity=t.opacity),void 0!==t.zIndex&&(c.zIndex=t.zIndex),!0===t.visible&&(c.visible=!0),!1===t.visible&&(c.visible=!1),Object.keys(c).length&&s.setModelOverrides(r,c),this.layerGroups.applyToDeck(),r}async setBaseLayer(t,e){this.ensureModelGroup(t).basemap=e??null,this.layerGroups.applyToDeck()}async ensureGroup(t,e,n){await this._ensureGroup(t,e,n)}async _ensureGroup(t,e,n){const i=this.layerGroups.hasGroup(t),s=this.ensureModelGroup(t);return"boolean"==typeof e&&s.visible!==e&&(s.visible=e),void 0!==n?.basemapid&&s.basemap!==n.basemapid&&(s.basemap=n.basemapid??null),i&&"boolean"!=typeof e&&void 0===n?.basemapid||this.layerGroups.applyToDeck(),s}async updateLayer(t,e){const n=this.layerGroups.groups.find((e=>e.getModel?.(t)));if(n){switch(e.type){case"geojson":{const i=e.data?.geojson?JSON.parse(e.data.geojson):e.data?.url;i&&n.setModelOverrides(t,{data:i});break}case"osm":e.data?.url&&n.setModelOverrides(t,{url:`${e.data.url}/{z}/{x}/{y}.png`});break;case"google":(e.data?.mapType||e.data?.apiKey)&&r("Google Maps layer updates require full layer recreation");break;case"wms":{const i={};e.data?.url&&(i.url=e.data.url),e.data?.layers&&(i.layers=e.data.layers),void 0!==e.data?.styles&&(i.styles=e.data.styles),e.data?.format&&(i.format=e.data.format),void 0!==e.data?.transparent&&(i.transparent=e.data.transparent),e.data?.version&&(i.version=e.data.version),e.data?.crs&&(i.crs=e.data.crs),void 0!==e.data?.time&&(i.time=e.data.time),e.data?.extraParams&&(i.extraParams=e.data.extraParams),Object.keys(i).length&&n.setModelOverrides(t,i);break}case"wcs":{const i={};e.data?.url&&(i.url=e.data.url),e.data?.coverageName&&(i.coverageName=e.data.coverageName),e.data?.format&&(i.format=e.data.format),e.data?.version&&(i.version=e.data.version),e.data?.projection&&(i.projection=e.data.projection),e.data?.params&&(i.params=e.data.params),void 0!==e.data?.tileSize&&(i.tileSize=e.data.tileSize),void 0!==e.data?.minZoom&&(i.minZoom=e.data.minZoom),void 0!==e.data?.maxZoom&&(i.maxZoom=e.data.maxZoom),Object.keys(i).length&&n.setModelOverrides(t,i);break}case"arcgis":{const i={},s=n.getModel?.(t),r=this.getModelUrl(s),o=e.data?.url??r??null;if(o){const t=this.buildArcgisUrl(o,e.data?.params,e.data?.token);i.data=[t],i.url=t}void 0!==e.data?.minZoom&&(i.minZoom=e.data.minZoom),void 0!==e.data?.maxZoom&&(i.maxZoom=e.data.maxZoom),Object.keys(i).length&&n.setModelOverrides(t,i);break}case"terrain":{const i={};e.data?.elevationData&&(i.elevationData=e.data.elevationData),void 0!==e.data?.texture&&(i.texture=e.data.texture),void 0!==e.data?.elevationDecoder&&(i.elevationDecoder=e.data.elevationDecoder),void 0!==e.data?.wireframe&&(i.wireframe=e.data.wireframe),void 0!==e.data?.color&&(i.color=e.data.color),void 0!==e.data?.meshMaxError&&(i.meshMaxError=e.data.meshMaxError),Object.keys(i).length&&n.setModelOverrides(t,i);break}case"wkt":if(e.data?.wkt){const i=await this.wktToGeoJSON(e.data.wkt);n.setModelOverrides(t,{data:i})}else e.data?.url&&n.setModelOverrides(t,{data:e.data.url});break;case"geotiff":{const i=e.data??{},s={};"url"in i&&(s.url=i.url),"nodata"in i&&(s.noDataValue=i.nodata),"colorMap"in i&&(s.colorMap=i.colorMap),"valueRange"in i&&(s.valueRange=i.valueRange),"resolution"in i&&(s.resolution=i.resolution),"resampleMethod"in i&&(s.resampleMethod=i.resampleMethod),Object.keys(s).length&&n.setModelOverrides(t,s);break}case"terrain-geotiff":{const i=e.data??{},s={};"url"in i&&(s.url=i.url),"projection"in i&&(s.projection=i.projection),"forceProjection"in i&&(s.forceProjection=i.forceProjection),"nodata"in i&&(s.noDataValue=i.nodata),"meshMaxError"in i&&(s.meshMaxError=i.meshMaxError),"wireframe"in i&&(s.wireframe=i.wireframe),"texture"in i&&(s.texture=i.texture),"color"in i&&(s.color=i.color),"colorMap"in i&&(s.colorMap=i.colorMap),"valueRange"in i&&(s.valueRange=i.valueRange),"elevationScale"in i&&(s.elevationScale=i.elevationScale),"renderMode"in i&&(s.renderMode=i.renderMode),Object.keys(s).length&&n.setModelOverrides(t,s);break}case"wfs":{const i=await this.fetchWFSFromUrl(e.data);n.setModelOverrides(t,{data:i});break}}this.layerGroups.applyToDeck()}}onLayerError(t,e){this.layerErrorCallbacks.set(t,e)}offLayerError(t){this.layerErrorCallbacks.delete(t)}async removeLayer(t){this.offLayerError(t);for(const e of this.layerGroups.groups){const n=e,i=n.removeModel?.bind(n),s=n.getModel?.bind(n);if("function"==typeof s&&s(t))return i(t),void this.layerGroups.applyToDeck()}this.layerGroups.removeLayer(t,{removeFromAll:!0})}async setOpacity(t,e){const n=this.layerGroups.groups.find((e=>e.getModel?.(t)));n&&(n.setModelOverrides(t,{opacity:e}),this.layerGroups.applyToDeck())}async setZIndex(t,e){const n=this.layerGroups.groups.find((e=>e.getModel?.(t)));n&&(n.setModelOverrides(t,{zIndex:e}),this.layerGroups.applyToDeck())}async setVisible(t,e){const n=this.layerGroups.groups.find((e=>e.getModel?.(t)));n&&(n.setModelEnabled(t,e),n.setModelOverrides(t,{visible:e}),this.layerGroups.applyToDeck())}async setGroupVisible(t,e){this.layerGroups.setGroupVisible(t,e)}async setView([t,e],n){this.deck?.setProps({viewState:{longitude:t,latitude:e,zoom:n,bearing:0,pitch:0}})}async createWKTLayer(e,n){const i=await this.resolveWktToGeoJSON(e);let s;if(e.geostylerStyle)s=this.createGeostylerDeckGLStyle(e.geostylerStyle);else{const n=e.style?{...t,...e.style}:t;s=this.createDeckGLStyle(n)}return new qg({id:n,data:i,filled:!0,stroked:!0,pointType:"circle",pickable:!0,...s,opacity:e.opacity??1,visible:e.visible??!0,updateTriggers:{getFillColor:[e.style,e.geostylerStyle],getLineColor:[e.style,e.geostylerStyle],getPointRadius:[e.style,e.geostylerStyle],data:[e.wkt,e.url]}})}async resolveWktToGeoJSON(t){try{const e=await this.resolveWktText(t);return await this.wktToGeoJSON(e)}catch(t){return i("v-map - provider - deck - Failed to parse WKT:",t),{type:"FeatureCollection",features:[]}}}async resolveWktText(t){if(t.wkt)return t.wkt;if(t.url){const e=await fetch(t.url);if(!e.ok)throw new Error(`Failed to fetch WKT: ${e.status}`);return await e.text()}throw new Error("Either wkt or url must be provided")}async wktToGeoJSON(t){const e="function"==typeof n.wellknownModule.default?n.wellknownModule.default:n.wellknownModule.parse;if("function"!=typeof e)throw new Error("wellknown parser not available");const i=e(t);if(!i)throw new Error("Failed to parse WKT");return{type:"FeatureCollection",features:[{type:"Feature",geometry:i,properties:{}}]}}async createGeoTIFFLayer(t,e){if(!t.url)throw new Error("GeoTIFF layer requires a URL");try{return await async function(t){const[{CompositeLayer:e},{TileLayer:n},{BitmapLayer:h},{default:u},f,d]=await Promise.all([import("./index7.js"),import("./index8.js"),import("./index6.js"),import("./index4.js"),import("./geotiff.js").then((function(t){return t.g})),import("./main-dist.js").then((function(t){return t.m}))]);return new class extends e{static layerName="DeckGLGeoTIFFLayer";static defaultProps={minZoom:0,maxZoom:24,tileSize:256,noDataValue:0,nullColor:[0,0,0,0],resolution:1,resampleMethod:"bilinear",forceProjection:!1,colorMap:"grayscale"};tiff;image;fromProjection="EPSG:4326";viewProjection="EPSG:3857";sourceBounds=[0,0,0,0];tileProcessor;activeLoad;loadedSignature;loadToken=0;storeRuntimeState(){this.setState({runtime:{tiff:this.tiff,image:this.image,fromProjection:this.fromProjection,sourceBounds:this.sourceBounds,tileProcessor:this.tileProcessor}})}restoreRuntimeState(){const t=this.state.runtime;t&&(this.tiff??=t.tiff,this.image??=t.image,this.tileProcessor??=t.tileProcessor,this.fromProjection=t.fromProjection??this.fromProjection,this.sourceBounds=t.sourceBounds??this.sourceBounds)}constructor(t){super(t)}getLoadSignature(t=this.props){return JSON.stringify({url:t.url??null,projection:t.projection??null,forceProjection:t.forceProjection??!1,noDataValue:t.noDataValue??null})}scheduleLoad(t){const e=this.getLoadSignature();if(this.activeLoad?.signature===e)return void i(`${_}skip duplicate load: ${t}`);if(this.loadedSignature===e&&this.state.init)return void i(`${_}skip already-loaded source: ${t}`);const n=++this.loadToken;this.activeLoad={signature:e,token:n},this.setState({init:!1}),this._loadAsync(n,e,t)}async _loadAsync(t,e,n){try{if(!await this.loadGeoTIFF(t)||this.activeLoad?.token!==t)return;this.loadedSignature=e,this.setState({init:!0}),i(`${_}load complete: ${n}`),i(this.state)}finally{this.activeLoad?.token===t&&(this.activeLoad=void 0)}}async initializeState(t){i(this.state),this.scheduleLoad("initializeState"),i(this.state)}shouldUpdateState({changeFlags:t}){return Boolean(t.propsOrDataChanged||t.updateTriggersChanged)}updateState({props:t,oldProps:e,changeFlags:n}){this.restoreRuntimeState();const s=t.url!==e.url||t.projection!==e.projection||t.forceProjection!==e.forceProjection||t.noDataValue!==e.noDataValue,r=!(!Array.isArray(t.valueRange)&&!Array.isArray(e.valueRange)||Array.isArray(t.valueRange)&&Array.isArray(e.valueRange)&&t.valueRange.length===e.valueRange.length&&t.valueRange.every(((t,n)=>t===e.valueRange[n]))),o=t.colorMap!==e.colorMap||r||t.resolution!==e.resolution||t.resampleMethod!==e.resampleMethod||t.opacity!==e.opacity||t.visible!==e.visible||n.updateTriggersChanged;n.dataChanged||t.data!==e.data||s?this.scheduleLoad("updateState"):(o&&this.triggerLayerUpdate(),i(this.state))}finalizeState(t){this.tiff&&(this.tiff=null),this.image=null}async loadGeoTIFF(t){const{url:e,projection:n,forceProjection:r}=this.props;if(!e)return this.tiff=void 0,this.image=void 0,this.tileProcessor=void 0,this.sourceBounds=[0,0,0,0],this.storeRuntimeState(),i(`${_}no URL provided, skipping GeoTIFF loading`),this.triggerLayerUpdate(),this.loadedSignature=this.getLoadSignature(),!0;i(`${_}loadGeoTIFF: init=${this.state.init}, token=${t}`);try{const s=await o(e,{projection:n,forceProjection:r,nodata:this.props.noDataValue},{geotiff:f,proj4:u,geokeysToProj4:d});if(this.activeLoad?.token!==t)return i(`${_}ignore stale source load result: token=${t}`),!1;this.tiff=s.tiff,this.image=s.baseImage,this.fromProjection=s.fromProjection,this.sourceBounds=s.sourceBounds;const l=await a(s,this.viewProjection);return this.activeLoad?.token!==t?(i(`${_}ignore stale tile processor result: token=${t}`),!1):(this.tileProcessor=new c(l),this.tileProcessor.createGlobalTriangulation(),this.storeRuntimeState(),i(`v-map - deck - geotiff - loaded: projection=${s.fromProjection}→${this.viewProjection}, bounds=[${s.sourceBounds.map((t=>t.toFixed(0))).join(",")}], wgs84=[${s.wgs84Bounds.map((t=>t.toFixed(4))).join(",")}], size=${s.width}x${s.height}, bands=${s.samplesPerPixel}`),this.triggerLayerUpdate(),!0)}catch(t){return s(`${_}failed to load GeoTIFF:`,t),this.raiseError(t,"Failed to load GeoTIFF"),!1}}getViewExtent(){if(!this.sourceBounds||!this.tileProcessor)return null;const[t,e,n,i]=this.sourceBounds,s=85.05112878,o=-85.05112878;try{const a=t=>u(this.fromProjection,"EPSG:4326",t),c=t=>t&&2===t.length&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&!Number.isNaN(t[0])&&!Number.isNaN(t[1]),l=t=>Math.max(-180,Math.min(180,t)),h=t=>Math.max(o,Math.min(s,t)),f=a([t,e]),d=a([n,e]),p=a([t,i]),g=a([n,i]);if(!(c(f)&&c(d)&&c(p)&&c(g)))return r(`${_}invalid coordinates after transformation:`,{sw:f,se:d,nw:p,ne:g}),null;let m=Math.min(f[0],d[0],p[0],g[0]),v=Math.max(f[0],d[0],p[0],g[0]),b=Math.min(f[1],d[1],p[1],g[1]),y=Math.max(f[1],d[1],p[1],g[1]);return m=l(m),v=l(v),b=h(b),y=h(y),Number.isFinite(m)&&Number.isFinite(v)&&Number.isFinite(b)&&Number.isFinite(y)?((-180===m||180===v||b===o||y===s)&&r(`${_}extent exceeds valid bounds, clamped to valid range`),[m,b,v,y]):(r(`${_}invalid extent calculated:`,{minLng:m,minLat:b,maxLng:v,maxLat:y}),null)}catch(t){return r(`${_}failed to calculate extent from source bounds:`,t),null}}async getTileData(t){if(this.restoreRuntimeState(),i(`v-map - deck - geotiff - getTileData ENTER(${t.index.x},${t.index.y},${t.index.z}): image=${!!this.image}, processor=${!!this.tileProcessor}`),!this.image||!this.tileProcessor)return null;const e=t.index.x,n=t.index.y,s=t.index.z;try{const{tileSize:t,resolution:r,resampleMethod:o,colorMap:a,valueRange:c}=this.props;let h;a&&(h=l(a,c).stops);const u=await this.tileProcessor.getTileData({x:e,y:n,z:s,tileSize:t,resolution:r,resampleMethod:o,colorStops:h});if(!u)return i(`v-map - deck - geotiff - getTileData(${e},${n},${s}): no data returned`),null;let f=0;for(let t=3;t<u.length;t+=4)if(u[t]>0){f++;break}return i(`v-map - deck - geotiff - getTileData(${e},${n},${s}): rgba ${u.length} bytes, tileSize=${t}, hasContent=${f>0}`),{data:u,width:t,height:t}}catch(t){return r(`${_}tile [${s}/${e}/${n}] failed:`,t),null}}renderLayers(){if(this.restoreRuntimeState(),!this.image||!this.tileProcessor||!1===this.props.visible)return null;const{minZoom:t,maxZoom:e,tileSize:s,opacity:o,visible:a}=this.props,c=this.getViewExtent();c?i(`${_}view extent: [${c.map((t=>t.toFixed(2))).join(", ")}]`):r(`${_}view extent is null, tiles will load globally`);const l={id:`${this.props.id}-tiles`,minZoom:t,maxZoom:e,tileSize:s,opacity:o,visible:a,getTileData:this.getTileData.bind(this),onTileError:t=>{r(`v-map - deck - geotiff - tilelayer - error: ${t.message}`),this.props.onTileLoadError?.(t)},renderSubLayers:t=>{const{tile:e}=t;if(!e?.data)return null;const{data:n,width:s,height:r}=e.data,{west:o,south:a,east:c,north:l}=t.tile.bbox,u=[o,a,c,l],{opacity:f,visible:d}=this.props,p=globalThis.WebGLRenderingContext,g=p?.TEXTURE_MIN_FILTER??10241,m=p?.TEXTURE_MAG_FILTER??10240,_=p?.LINEAR??9729,v=function(t,e,n){const i=globalThis.ImageData;return i?{image:new i(t instanceof Uint8ClampedArray?t:new Uint8ClampedArray(t.buffer,t.byteOffset,t.byteLength),e,n),kind:"ImageData"}:{image:{data:t,width:e,height:n},kind:"raw"}}(n,s,r);return i(`v-map - deck - geotiff - renderSubLayer(${e.index.x},${e.index.y},${e.index.z}): data=${n?.length??"null"}, w=${s}, h=${r}, bounds=[${o?.toFixed(2)},${a?.toFixed(2)},${c?.toFixed(2)},${l?.toFixed(2)}]`),i(`v-map - deck - geotiff - textureSource(${e.index.x},${e.index.y},${e.index.z}): kind=${v.kind}, ctor=${v.image?.constructor?.name??"unknown"}, w=${s}, h=${r}, bytes=${n?.length??"null"}`),new h({...t,id:`${t.id}-bitmap`,opacity:f,visible:d,image:v.image,bounds:u,textureParameters:{[g]:_,[m]:_}})},updateTriggers:{renderSubLayers:[o,a]}};return c&&(l.extent=c),new n(l)}triggerLayerUpdate(){this.setNeedsRedraw()}}(t)}({id:e,url:t.url,opacity:t.opacity??1,visible:t.visible??!0,noDataValue:t.nodata,nullColor:[0,0,0,0],onTileLoadError:t=>{this.layerErrorCallbacks.get(e)?.({type:"network",message:`GeoTIFF tile error: ${t.message}`,cause:t})}})}catch(t){return i("v-map - provider - deck - Failed to create GeoTIFF layer:",t),new qg({id:e,data:{type:"FeatureCollection",features:[]},opacity:0})}}async createGeoTIFFTerrainLayer(t,e){try{const n=await async function(t){const[{CompositeLayer:e},{TileLayer:n},{BitmapLayer:h},{SimpleMeshLayer:u},f,{default:d},p,g]=await Promise.all([import("./index7.js"),import("./index8.js"),import("./index6.js"),import("./index2.js"),import("./index3.js"),import("./index4.js"),import("./geotiff.js").then((function(t){return t.g})),import("./main-dist.js").then((function(t){return t.m}))]),m=f.default??f;return new class extends e{static layerName="DeckGLGeoTIFFTerrainLayer";static defaultProps={minZoom:0,maxZoom:24,tileSize:256,noDataValue:0,forceProjection:!1,meshMaxError:4,wireframe:!1,elevationScale:1,colorMap:"terrain",renderMode:"terrain"};tiff;image;fromProjection="EPSG:4326";viewProjection="EPSG:3857";sourceBounds=[0,0,0,0];tileProcessor;activeLoad;loadedSignature;loadToken=0;storeRuntimeState(){this.setState({runtime:{tiff:this.tiff,image:this.image,fromProjection:this.fromProjection,sourceBounds:this.sourceBounds,tileProcessor:this.tileProcessor}})}restoreRuntimeState(){const t=this.state.runtime;t&&(this.tiff??=t.tiff,this.image??=t.image,this.tileProcessor??=t.tileProcessor,this.fromProjection=t.fromProjection??this.fromProjection,this.sourceBounds=t.sourceBounds??this.sourceBounds)}constructor(t){super(t)}getLoadSignature(t=this.props){return JSON.stringify({url:t.url??null,projection:t.projection??null,forceProjection:t.forceProjection??!1,noDataValue:t.noDataValue??null})}scheduleLoad(t){const e=this.getLoadSignature();if(this.activeLoad?.signature===e)return void i(`${v}skip duplicate load: ${t}`);if(this.loadedSignature===e&&this.state.init)return void i(`${v}skip already-loaded source: ${t}`);const n=++this.loadToken;this.activeLoad={signature:e,token:n},this.setState({init:!1}),this._loadAsync(n,e,t)}async _loadAsync(t,e,n){try{if(!await this.loadGeoTIFF(t)||this.activeLoad?.token!==t)return;this.loadedSignature=e,this.setState({init:!0}),i(`${v}load complete: ${n}`)}finally{this.activeLoad?.token===t&&(this.activeLoad=void 0)}}async initializeState(t){this.scheduleLoad("initializeState")}shouldUpdateState({changeFlags:t}){return Boolean(t.propsOrDataChanged||t.updateTriggersChanged)}updateState({props:t,oldProps:e,changeFlags:n}){this.restoreRuntimeState();const i=t.meshMaxError!==e.meshMaxError||t.wireframe!==e.wireframe||t.texture!==e.texture||t.color!==e.color||t.colorMap!==e.colorMap||t.valueRange!==e.valueRange||t.elevationScale!==e.elevationScale||t.opacity!==e.opacity||t.visible!==e.visible||t.renderMode!==e.renderMode||n.updateTriggersChanged;n.dataChanged||t.data!==e.data||t.url!==e.url||t.projection!==e.projection||t.forceProjection!==e.forceProjection||t.noDataValue!==e.noDataValue?this.scheduleLoad("updateState"):i&&this.setNeedsRedraw()}finalizeState(t){this.tiff&&(this.tiff=null),this.image=null}async loadGeoTIFF(t){const{url:e,projection:n,forceProjection:r}=this.props;if(!e)return this.tiff=void 0,this.image=void 0,this.tileProcessor=void 0,this.sourceBounds=[0,0,0,0],this.storeRuntimeState(),i(`${v}no URL provided, skipping GeoTIFF loading`),this.loadedSignature=this.getLoadSignature(),!0;i(`${v}loadGeoTIFF: url=${e}, token=${t}`);try{const s=await o(e,{projection:n,forceProjection:r,nodata:this.props.noDataValue},{geotiff:p,proj4:d,geokeysToProj4:g});if(this.activeLoad?.token!==t)return i(`${v}ignore stale source load result: token=${t}`),!1;this.tiff=s.tiff,this.image=s.baseImage,this.fromProjection=s.fromProjection,this.sourceBounds=s.sourceBounds;const l=await a(s,this.viewProjection);return this.activeLoad?.token!==t?(i(`${v}ignore stale tile processor result: token=${t}`),!1):(this.tileProcessor=new c(l),this.tileProcessor.createGlobalTriangulation(),this.storeRuntimeState(),i(`${v}loaded: projection=${this.fromProjection}→${this.viewProjection}, bounds=[${this.sourceBounds.map((t=>t.toFixed(0))).join(",")}]`),this.setNeedsRedraw(),!0)}catch(t){return s(`${v}failed to load GeoTIFF:`,t),this.raiseError(t,"Failed to load GeoTIFF"),!1}}getViewExtent(){if(!this.tileProcessor)return null;const[t,e,n,i]=this.sourceBounds,s=85.05112878,o=t=>Math.max(-180,Math.min(180,Number.isFinite(t)?t:0)),a=t=>Math.max(-s,Math.min(s,Number.isFinite(t)?t:0)),c=t=>{if("EPSG:4326"===this.fromProjection)return t;const e=d(this.fromProjection,"EPSG:4326",t);return[Number(e[0]),Number(e[1])]};try{const s=[c([t,e]),c([n,e]),c([n,i]),c([t,i])],l=o(Math.min(...s.map((t=>t[0])))),h=o(Math.max(...s.map((t=>t[0])))),u=a(Math.min(...s.map((t=>t[1])))),f=a(Math.max(...s.map((t=>t[1]))));return l>h||u>f?(r(`${v}invalid extent calculated from source bounds`),null):[l,u,h,f]}catch(t){return r(`${v}failed to calculate extent from source bounds:`,t),null}}async getTileData(t){if(!this.image||!this.tileProcessor)return null;const{x:e,y:n,z:i}=t.index,{tileSize:s,renderMode:o}=this.props;try{return"colormap"===o?this._getTileDataColormap(e,n,i,s):this._getTileDataTerrain(e,n,i,s)}catch(t){return r(`${v}tile [${i}/${e}/${n}] failed:`,t),null}}async _getTileDataColormap(t,e,n,i){const{colorMap:s,valueRange:r}=this.props;let o;s&&(o=l(s,r).stops);const a=await this.tileProcessor.getTileData({x:t,y:e,z:n,tileSize:i,resolution:1,resampleMethod:"bilinear",colorStops:o});return a?{data:a,width:i,height:i}:null}async _getTileDataTerrain(t,e,n,i){const s=await this.tileProcessor.getElevationData({x:t,y:e,z:n,tileSize:i});return s?{elevationData:s,gridSize:i+1}:null}renderLayers(){if(this.restoreRuntimeState(),!this.image||!this.tileProcessor||!1===this.props.visible)return null;const{minZoom:t,maxZoom:e,tileSize:i,renderMode:s,opacity:o}=this.props,a=this.getViewExtent(),c={id:`${this.props.id}-tiles`,minZoom:t,maxZoom:e,tileSize:i,opacity:o,visible:this.props.visible,getTileData:this.getTileData.bind(this),onTileError:t=>{r(`v-map - deck - terrain-geotiff - tilelayer - error: ${t.message}`),this.props.onTileLoadError?.(t)},renderSubLayers:"colormap"===s?this._renderColormapSubLayer.bind(this):this._renderTerrainSubLayer.bind(this)};return a&&(c.extent=a),new n(c)}_renderColormapSubLayer(t){const{tile:e}=t;if(!e?.data)return null;const{data:n,width:i,height:s}=e.data,{west:r,south:o,east:a,north:c}=t.tile.bbox,l=[r,o,a,c],{opacity:u,visible:f}=this.props,d=globalThis.WebGLRenderingContext,p=d?.TEXTURE_MIN_FILTER??10241,g=d?.TEXTURE_MAG_FILTER??10240,m=d?.LINEAR??9729;return new h({...t,id:`${t.id}-bitmap`,opacity:u,visible:f,image:{data:n,width:i,height:s},bounds:l,textureParameters:{[p]:m,[g]:m}})}_renderTerrainSubLayer(t){const{tile:e}=t;if(!e?.data)return null;const{elevationData:n,gridSize:i}=e.data,{west:s,south:r,east:o,north:a}=t.tile.bbox,{meshMaxError:c,wireframe:l,color:h,elevationScale:f,texture:d,opacity:p,visible:g}=this.props,_=new m(i).createTile(n),{vertices:v,triangles:b}=_.getMesh(c??4),y=i-1,w=v.length/2,x=new Float32Array(3*w),E=new Float32Array(2*w),T=o-s,A=a-r,S=f??1;for(let t=0;t<w;t++){const e=v[2*t],r=v[2*t+1],o=n[r*i+e];x[3*t+0]=s+e/y*T,x[3*t+1]=a-r/y*A,x[3*t+2]=o*S,E[2*t+0]=e/y,E[2*t+1]=r/y}const C={attributes:{POSITION:{value:x,size:3},TEXCOORD_0:{value:E,size:2}},indices:{value:Uint32Array.from(b),size:1},mode:4},P=t.tile?.index,M="string"==typeof d?d.replaceAll("{x}",String(P?.x??"{x}")).replaceAll("{y}",String(P?.y??"{y}")).replaceAll("{z}",String(P?.z??"{z}")):void 0;return new u({...t,id:`${t.id}-mesh`,opacity:p,visible:g,mesh:C,data:[[0,0,0]],getPosition:t=>t,getColor:M?[255,255,255]:h??[200,200,200],texture:M??null,wireframe:l??!1})}}(t)}({id:e,url:t.url,projection:t.projection,forceProjection:t.forceProjection,noDataValue:t.nodata,minZoom:t.minZoom,maxZoom:t.maxZoom,tileSize:t.tileSize,meshMaxError:t.meshMaxError,wireframe:t.wireframe,texture:t.texture,color:t.color,colorMap:t.colorMap,valueRange:t.valueRange,elevationScale:t.elevationScale,renderMode:t.renderMode,opacity:t.opacity??1,visible:t.visible??!0,onTileLoadError:t=>{this.layerErrorCallbacks.get(e)?.({type:"network",message:`GeoTIFF terrain tile error: ${t.message}`,cause:t})}});return n}catch(t){return i("v-map - provider - deck - Failed to create GeoTIFF Terrain layer:",t),null}}onPointerMove(t){const e=e=>{const n=this.target.getBoundingClientRect(),i=[e.clientX-n.left,e.clientY-n.top];try{const e=this.deck?.getViewports()?.[0];if(e){const[n,s]=e.unproject(i);t([n,s],i)}else t(null,i)}catch{t(null,i)}};return this.target.addEventListener("pointermove",e),()=>this.target.removeEventListener("pointermove",e)}async destroy(){try{this.layerGroups.clear({destroy:!0}),this.shadowRoot&&this.injectedStyle?.remove(),this.deck?.finalize()}catch{}}async createWFSLayer(e,n){const i=await this.fetchWFSFromUrl(e);let s;if(e.geostylerStyle)s=this.createGeostylerDeckGLStyle(e.geostylerStyle);else{const n=e.style?{...t,...e.style}:t;s=this.createDeckGLStyle(n)}return new qg({id:n,data:i,filled:!0,stroked:!0,pointType:"circle",...s,pickable:!0,autoHighlight:!0})}async fetchWFSFromUrl(t){const n={service:"WFS",request:"GetFeature",version:t.version??"1.1.0",typeName:t.typeName,outputFormat:t.outputFormat??"application/json",srsName:t.srsName??"EPSG:4326",...t.params??{}},i=this.appendParams(t.url,n),s=await fetch(i);if(!s.ok)throw new Error(`WFS request failed (${s.status} ${s.statusText})`);const r=(t.outputFormat??"application/json").toLowerCase();if(r.includes("json")||r.includes("geojson")||"application/json"===r)return await s.json();if(r.includes("gml")||r.includes("xml")){const t=await s.text(),n=new e;return await n.parse(t)}return await s.json()}appendParams(t,e){const n=new URLSearchParams;return Object.entries(e).forEach((([t,e])=>{null!=e&&n.set(t,String(e))})),n.toString()?`${t}${t.includes("?")?"&":"?"}${n.toString()}`:t}getMap(){return this.deck}}});export{ja as $,Rs as A,Hd as B,Bd as C,ka as D,Ia as E,Ds as F,ll as G,Oa as H,rp as I,Os as J,La as K,Fd as L,ol as M,$c as N,Ko as O,Fp as P,ha as Q,fc as R,E_ as S,Bg as T,Yo as U,Js as V,up as W,dc as X,nt as Y,kc as Z,Ua as _,Qa as a,xr as a0,Is as a1,Da as a2,hh as a3,th as a4,uh as a5,Ec as a6,Dl as a7,fh as a8,Ma as a9,bl as aA,pd as aB,na as aC,gd as aD,hd as aE,Rh as aF,Lh as aG,Oh as aH,Pd as aI,Rd as aJ,Br as aK,Mt as aL,Or as aM,__ as aN,v_ as aO,u_ as aP,Qm as aQ,Vm as aR,t_ as aS,Gm as aT,C_ as aU,a_ as aV,Yg as aW,I_ as aX,ql as aa,Dc as ab,Kl as ac,Gl as ad,ys as ae,j as af,ic as ag,ta as ah,wc as ai,ac as aj,pc as ak,ul as al,Pf as am,Tl as an,Gf as ao,id as ap,vh as aq,ma as ar,Ja as as,ph as at,dh as au,Bl as av,jl as aw,Sc as ax,$d as ay,wl as az,hp as b,Kr as c,Al as d,qg as e,cg as f,pg as g,Ig as h,Vr as i,F as j,Hr as k,Nf as l,fp as m,Kp as n,ps as o,_a as p,gs as q,lg as r,ws as s,vs as t,Hc as u,_s as v,$s as w,bs as x,ya as y,Ls as z}
|