{"version":3,"file":"SuitabilityIcon-BXWUHzrE.js","sources":["../../../node_modules/react-transition-group/node_modules/prop-types/lib/ReactPropTypesSecret.js","../../../node_modules/react-transition-group/node_modules/prop-types/factoryWithThrowingShims.js","../../../node_modules/react-transition-group/node_modules/prop-types/index.js","../../../node_modules/@babel/runtime/helpers/interopRequireDefault.js","../../../node_modules/dom-helpers/class/hasClass.js","../../../node_modules/dom-helpers/class/addClass.js","../../../node_modules/dom-helpers/class/removeClass.js","../../../node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js","../../../node_modules/react-transition-group/Transition.js","../../../node_modules/react-transition-group/CSSTransition.js","../../../node_modules/react-transition-group/utils/ChildMapping.js","../../../node_modules/react-transition-group/TransitionGroup.js","../../../node_modules/react-transition-group/ReplaceTransition.js","../../../node_modules/react-transition-group/index.js","../../../node_modules/quickselect/index.js","../../../node_modules/rbush/index.js","../../../node_modules/@turf/boolean-within/dist/esm/index.js","../../../node_modules/tinyqueue/index.js","../../../node_modules/point-in-polygon/flat.js","../../../node_modules/point-in-polygon/nested.js","../../../node_modules/point-in-polygon/index.js","../../../node_modules/robust-predicates/umd/orient2d.min.js","../../../node_modules/concaveman/index.js","../../../node_modules/@turf/convex/dist/esm/index.js","../../../node_modules/@turf/center-of-mass/dist/esm/index.js","../../../node_modules/@turf/point-grid/dist/esm/index.js","../../../node_modules/@turf/kinks/dist/esm/index.js","../../../node_modules/earcut/src/earcut.js","../../../node_modules/@turf/unkink-polygon/dist/esm/index.js","../../../node_modules/posthog-js/dist/module.js","../../../node_modules/@fullstory/browser/dist/index.esm.js","../../../app/javascript/utils/analytics.ts","../../../app/javascript/components/layout/Content.jsx","../../../app/javascript/constants/errors.ts","../../../app/javascript/views/ErrorBoundaryView.jsx","../../../node_modules/tinycolor2/tinycolor.js","../../../app/javascript/utils/colors.js","../../../node_modules/mapbox-gl/dist/mapbox-gl.js","../../../node_modules/property-expr/index.js","../../../node_modules/tiny-case/index.js","../../../node_modules/toposort/index.js","../../../node_modules/yup/index.esm.js","../../../app/javascript/utils/geojson.js","../../../app/javascript/utils/map.js","../../../node_modules/twgl.js/dist/5.x/twgl-full.module.js","../../../app/javascript/utils/webgl/RasterLayerWithClipping/shaders/raster.vert","../../../app/javascript/utils/webgl/RasterLayerWithClipping/shaders/raster.frag","../../../app/javascript/utils/webgl/RasterLayerWithClipping/shaders/mask.vert","../../../app/javascript/utils/webgl/RasterLayerWithClipping/shaders/mask.frag","../../../app/javascript/utils/webgl/RasterLayerWithClipping/helpers.js","../../../app/javascript/utils/webgl/RasterLayerWithClipping/index.js","../../../app/javascript/utils/webgl/suitability-calculations/constants.js","../../../app/javascript/utils/webgl/suitability-calculations/helpers.js","../../../app/javascript/constants/tilesets.js","../../../app/javascript/utils/tilesets.js","../../../app/javascript/hooks/useAddClippableTilesetLayers.js","../../../node_modules/@babel/runtime/helpers/esm/extends.js","../../../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../../../node_modules/reactstrap/node_modules/prop-types/lib/ReactPropTypesSecret.js","../../../node_modules/reactstrap/node_modules/prop-types/factoryWithThrowingShims.js","../../../node_modules/reactstrap/node_modules/prop-types/index.js","../../../node_modules/reactstrap/node_modules/classnames/index.js","../../../node_modules/reactstrap/es/utils.js","../../../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../../../node_modules/reactstrap/es/Button.js","../../../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../../node_modules/reactstrap/es/Fade.js","../../../node_modules/reactstrap/es/Portal.js","../../../node_modules/reactstrap/es/Modal.js","../../../node_modules/reactstrap/es/ModalBody.js","../../../node_modules/reactstrap/es/Input.js","../../../node_modules/reactstrap/es/Spinner.js","../../../app/javascript/components/icons/Logo.tsx","../../../node_modules/react-fast-compare/index.js","../../../node_modules/deepmerge/dist/es.js","../../../node_modules/lodash-es/_freeGlobal.js","../../../node_modules/lodash-es/_root.js","../../../node_modules/lodash-es/_Symbol.js","../../../node_modules/lodash-es/_getRawTag.js","../../../node_modules/lodash-es/_objectToString.js","../../../node_modules/lodash-es/_baseGetTag.js","../../../node_modules/lodash-es/_overArg.js","../../../node_modules/lodash-es/_getPrototype.js","../../../node_modules/lodash-es/isObjectLike.js","../../../node_modules/lodash-es/isPlainObject.js","../../../node_modules/lodash-es/_listCacheClear.js","../../../node_modules/lodash-es/eq.js","../../../node_modules/lodash-es/_assocIndexOf.js","../../../node_modules/lodash-es/_listCacheDelete.js","../../../node_modules/lodash-es/_listCacheGet.js","../../../node_modules/lodash-es/_listCacheHas.js","../../../node_modules/lodash-es/_listCacheSet.js","../../../node_modules/lodash-es/_ListCache.js","../../../node_modules/lodash-es/_stackClear.js","../../../node_modules/lodash-es/_stackDelete.js","../../../node_modules/lodash-es/_stackGet.js","../../../node_modules/lodash-es/_stackHas.js","../../../node_modules/lodash-es/isObject.js","../../../node_modules/lodash-es/isFunction.js","../../../node_modules/lodash-es/_coreJsData.js","../../../node_modules/lodash-es/_isMasked.js","../../../node_modules/lodash-es/_toSource.js","../../../node_modules/lodash-es/_baseIsNative.js","../../../node_modules/lodash-es/_getValue.js","../../../node_modules/lodash-es/_getNative.js","../../../node_modules/lodash-es/_Map.js","../../../node_modules/lodash-es/_nativeCreate.js","../../../node_modules/lodash-es/_hashClear.js","../../../node_modules/lodash-es/_hashDelete.js","../../../node_modules/lodash-es/_hashGet.js","../../../node_modules/lodash-es/_hashHas.js","../../../node_modules/lodash-es/_hashSet.js","../../../node_modules/lodash-es/_Hash.js","../../../node_modules/lodash-es/_mapCacheClear.js","../../../node_modules/lodash-es/_isKeyable.js","../../../node_modules/lodash-es/_getMapData.js","../../../node_modules/lodash-es/_mapCacheDelete.js","../../../node_modules/lodash-es/_mapCacheGet.js","../../../node_modules/lodash-es/_mapCacheHas.js","../../../node_modules/lodash-es/_mapCacheSet.js","../../../node_modules/lodash-es/_MapCache.js","../../../node_modules/lodash-es/_stackSet.js","../../../node_modules/lodash-es/_Stack.js","../../../node_modules/lodash-es/_arrayEach.js","../../../node_modules/lodash-es/_defineProperty.js","../../../node_modules/lodash-es/_baseAssignValue.js","../../../node_modules/lodash-es/_assignValue.js","../../../node_modules/lodash-es/_copyObject.js","../../../node_modules/lodash-es/_baseTimes.js","../../../node_modules/lodash-es/_baseIsArguments.js","../../../node_modules/lodash-es/isArguments.js","../../../node_modules/lodash-es/isArray.js","../../../node_modules/lodash-es/stubFalse.js","../../../node_modules/lodash-es/isBuffer.js","../../../node_modules/lodash-es/_isIndex.js","../../../node_modules/lodash-es/isLength.js","../../../node_modules/lodash-es/_baseIsTypedArray.js","../../../node_modules/lodash-es/_baseUnary.js","../../../node_modules/lodash-es/_nodeUtil.js","../../../node_modules/lodash-es/isTypedArray.js","../../../node_modules/lodash-es/_arrayLikeKeys.js","../../../node_modules/lodash-es/_isPrototype.js","../../../node_modules/lodash-es/_nativeKeys.js","../../../node_modules/lodash-es/_baseKeys.js","../../../node_modules/lodash-es/isArrayLike.js","../../../node_modules/lodash-es/keys.js","../../../node_modules/lodash-es/_baseAssign.js","../../../node_modules/lodash-es/_nativeKeysIn.js","../../../node_modules/lodash-es/_baseKeysIn.js","../../../node_modules/lodash-es/keysIn.js","../../../node_modules/lodash-es/_baseAssignIn.js","../../../node_modules/lodash-es/_cloneBuffer.js","../../../node_modules/lodash-es/_copyArray.js","../../../node_modules/lodash-es/_arrayFilter.js","../../../node_modules/lodash-es/stubArray.js","../../../node_modules/lodash-es/_getSymbols.js","../../../node_modules/lodash-es/_copySymbols.js","../../../node_modules/lodash-es/_arrayPush.js","../../../node_modules/lodash-es/_getSymbolsIn.js","../../../node_modules/lodash-es/_copySymbolsIn.js","../../../node_modules/lodash-es/_baseGetAllKeys.js","../../../node_modules/lodash-es/_getAllKeys.js","../../../node_modules/lodash-es/_getAllKeysIn.js","../../../node_modules/lodash-es/_DataView.js","../../../node_modules/lodash-es/_Promise.js","../../../node_modules/lodash-es/_Set.js","../../../node_modules/lodash-es/_WeakMap.js","../../../node_modules/lodash-es/_getTag.js","../../../node_modules/lodash-es/_initCloneArray.js","../../../node_modules/lodash-es/_Uint8Array.js","../../../node_modules/lodash-es/_cloneArrayBuffer.js","../../../node_modules/lodash-es/_cloneDataView.js","../../../node_modules/lodash-es/_cloneRegExp.js","../../../node_modules/lodash-es/_cloneSymbol.js","../../../node_modules/lodash-es/_cloneTypedArray.js","../../../node_modules/lodash-es/_initCloneByTag.js","../../../node_modules/lodash-es/_baseCreate.js","../../../node_modules/lodash-es/_initCloneObject.js","../../../node_modules/lodash-es/_baseIsMap.js","../../../node_modules/lodash-es/isMap.js","../../../node_modules/lodash-es/_baseIsSet.js","../../../node_modules/lodash-es/isSet.js","../../../node_modules/lodash-es/_baseClone.js","../../../node_modules/lodash-es/clone.js","../../../node_modules/lodash-es/_arrayMap.js","../../../node_modules/lodash-es/isSymbol.js","../../../node_modules/lodash-es/memoize.js","../../../node_modules/lodash-es/_memoizeCapped.js","../../../node_modules/lodash-es/_stringToPath.js","../../../node_modules/lodash-es/_toKey.js","../../../node_modules/lodash-es/_baseToString.js","../../../node_modules/lodash-es/toString.js","../../../node_modules/lodash-es/toPath.js","../../../node_modules/use-context-selector/dist/index.modern.js","../../../node_modules/lodash-es/cloneDeep.js","../../../node_modules/formik/dist/formik.esm.js","../../../app/javascript/components/icons/ChevronIcon.tsx","../../../node_modules/@mapbox/search-js-core/dist/index-esm.js","../../../node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs","../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs","../../../node_modules/no-scroll/index.js","../../../node_modules/tabbable/dist/index.esm.js","../../../node_modules/focus-trap/dist/focus-trap.esm.js","../../../node_modules/subtag/subtag.js","../../../node_modules/@mapbox/sphericalmercator/sphericalmercator.js","../../../node_modules/@mapbox/search-js-web/dist/index-esm.js","../../../node_modules/@mapbox/search-js-react/dist/index-esm.js","../../../app/javascript/components/icons/SectionsIcon.tsx","../../../app/javascript/utils/async.js","../../../node_modules/@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.js","../../../app/javascript/components/map/NaipLayer.jsx","../../../app/javascript/components/map/MapContainer.jsx","../../../app/javascript/hooks/useInitializeMapEffect.js","../../../app/javascript/utils/getMapBounds.ts","../../../app/javascript/utils/loadCluBoundaries.js","../../../app/javascript/utils/geocode.js","../../../app/javascript/components/public-suitability-tool/components/AddressSearch.jsx","../../../app/javascript/hooks/useToggleMap.js","../../../app/javascript/components/icons/CropIcon.tsx","../../../app/javascript/components/basics/PositionedOverMap.jsx","../../../app/javascript/components/icons/SuitabilityIcon.tsx"],"sourcesContent":["/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","\"use strict\";\n\nexports.__esModule = true;\nexports.default = hasClass;\n\nfunction hasClass(element, className) {\n if (element.classList) return !!className && element.classList.contains(className);else return (\" \" + (element.className.baseVal || element.className) + \" \").indexOf(\" \" + className + \" \") !== -1;\n}\n\nmodule.exports = exports[\"default\"];","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nexports.__esModule = true;\nexports.default = addClass;\n\nvar _hasClass = _interopRequireDefault(require(\"./hasClass\"));\n\nfunction addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!(0, _hasClass.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + ' ' + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + ' ' + className);\n}\n\nmodule.exports = exports[\"default\"];","'use strict';\n\nfunction replaceClassName(origClass, classToRemove) {\n return origClass.replace(new RegExp('(^|\\\\s)' + classToRemove + '(?:\\\\s|$)', 'g'), '$1').replace(/\\s+/g, ' ').replace(/^\\s*|\\s*$/g, '');\n}\n\nmodule.exports = function removeClass(element, className) {\n if (element.classList) element.classList.remove(className);else if (typeof element.className === 'string') element.className = replaceClassName(element.className, className);else element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n};","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nfunction componentWillMount() {\n // Call this.constructor.gDSFP to support sub-classes.\n var state = this.constructor.getDerivedStateFromProps(this.props, this.state);\n if (state !== null && state !== undefined) {\n this.setState(state);\n }\n}\n\nfunction componentWillReceiveProps(nextProps) {\n // Call this.constructor.gDSFP to support sub-classes.\n // Use the setState() updater to ensure state isn't stale in certain edge cases.\n function updater(prevState) {\n var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);\n return state !== null && state !== undefined ? state : null;\n }\n // Binding \"this\" is important for shallow renderer support.\n this.setState(updater.bind(this));\n}\n\nfunction componentWillUpdate(nextProps, nextState) {\n try {\n var prevProps = this.props;\n var prevState = this.state;\n this.props = nextProps;\n this.state = nextState;\n this.__reactInternalSnapshotFlag = true;\n this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(\n prevProps,\n prevState\n );\n } finally {\n this.props = prevProps;\n this.state = prevState;\n }\n}\n\n// React may warn about cWM/cWRP/cWU methods being deprecated.\n// Add a flag to suppress these warnings for this special case.\ncomponentWillMount.__suppressDeprecationWarning = true;\ncomponentWillReceiveProps.__suppressDeprecationWarning = true;\ncomponentWillUpdate.__suppressDeprecationWarning = true;\n\nfunction polyfill(Component) {\n var prototype = Component.prototype;\n\n if (!prototype || !prototype.isReactComponent) {\n throw new Error('Can only polyfill class components');\n }\n\n if (\n typeof Component.getDerivedStateFromProps !== 'function' &&\n typeof prototype.getSnapshotBeforeUpdate !== 'function'\n ) {\n return Component;\n }\n\n // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Error if any of these lifecycles are present,\n // Because they would work differently between older and newer (16.3+) versions of React.\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n if (typeof prototype.componentWillMount === 'function') {\n foundWillMountName = 'componentWillMount';\n } else if (typeof prototype.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n if (typeof prototype.componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n if (typeof prototype.componentWillUpdate === 'function') {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n if (\n foundWillMountName !== null ||\n foundWillReceivePropsName !== null ||\n foundWillUpdateName !== null\n ) {\n var componentName = Component.displayName || Component.name;\n var newApiName =\n typeof Component.getDerivedStateFromProps === 'function'\n ? 'getDerivedStateFromProps()'\n : 'getSnapshotBeforeUpdate()';\n\n throw Error(\n 'Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' +\n componentName +\n ' uses ' +\n newApiName +\n ' but also contains the following legacy lifecycles:' +\n (foundWillMountName !== null ? '\\n ' + foundWillMountName : '') +\n (foundWillReceivePropsName !== null\n ? '\\n ' + foundWillReceivePropsName\n : '') +\n (foundWillUpdateName !== null ? '\\n ' + foundWillUpdateName : '') +\n '\\n\\nThe above lifecycles should be removed. Learn more about this warning here:\\n' +\n 'https://fb.me/react-async-component-lifecycle-hooks'\n );\n }\n\n // React <= 16.2 does not support static getDerivedStateFromProps.\n // As a workaround, use cWM and cWRP to invoke the new static lifecycle.\n // Newer versions of React will ignore these lifecycles if gDSFP exists.\n if (typeof Component.getDerivedStateFromProps === 'function') {\n prototype.componentWillMount = componentWillMount;\n prototype.componentWillReceiveProps = componentWillReceiveProps;\n }\n\n // React <= 16.2 does not support getSnapshotBeforeUpdate.\n // As a workaround, use cWU to invoke the new lifecycle.\n // Newer versions of React will ignore that lifecycle if gSBU exists.\n if (typeof prototype.getSnapshotBeforeUpdate === 'function') {\n if (typeof prototype.componentDidUpdate !== 'function') {\n throw new Error(\n 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'\n );\n }\n\n prototype.componentWillUpdate = componentWillUpdate;\n\n var componentDidUpdate = prototype.componentDidUpdate;\n\n prototype.componentDidUpdate = function componentDidUpdatePolyfill(\n prevProps,\n prevState,\n maybeSnapshot\n ) {\n // 16.3+ will not execute our will-update method;\n // It will pass a snapshot value to did-update though.\n // Older versions will require our polyfilled will-update value.\n // We need to handle both cases, but can't just check for the presence of \"maybeSnapshot\",\n // Because for <= 15.x versions this might be a \"prevContext\" object.\n // We also can't just check \"__reactInternalSnapshot\",\n // Because get-snapshot might return a falsy value.\n // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.\n var snapshot = this.__reactInternalSnapshotFlag\n ? this.__reactInternalSnapshot\n : maybeSnapshot;\n\n componentDidUpdate.call(this, prevProps, prevState, snapshot);\n };\n }\n\n return Component;\n}\n\nexport { polyfill };\n","\"use strict\";\n\nexports.__esModule = true;\nexports.default = exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = void 0;\n\nvar PropTypes = _interopRequireWildcard(require(\"prop-types\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _reactDom = _interopRequireDefault(require(\"react-dom\"));\n\nvar _reactLifecyclesCompat = require(\"react-lifecycles-compat\");\n\nvar _PropTypes = require(\"./utils/PropTypes\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar UNMOUNTED = 'unmounted';\nexports.UNMOUNTED = UNMOUNTED;\nvar EXITED = 'exited';\nexports.EXITED = EXITED;\nvar ENTERING = 'entering';\nexports.ENTERING = ENTERING;\nvar ENTERED = 'entered';\nexports.ENTERED = ENTERED;\nvar EXITING = 'exiting';\n/**\n * The Transition component lets you describe a transition from one component\n * state to another _over time_ with a simple declarative API. Most commonly\n * it's used to animate the mounting and unmounting of a component, but can also\n * be used to describe in-place transition states as well.\n *\n * ---\n *\n * **Note**: `Transition` is a platform-agnostic base component. If you're using\n * transitions in CSS, you'll probably want to use\n * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)\n * instead. It inherits all the features of `Transition`, but contains\n * additional features necessary to play nice with CSS transitions (hence the\n * name of the component).\n *\n * ---\n *\n * By default the `Transition` component does not alter the behavior of the\n * component it renders, it only tracks \"enter\" and \"exit\" states for the\n * components. It's up to you to give meaning and effect to those states. For\n * example we can add styles to a component when it enters or exits:\n *\n * ```jsx\n * import { Transition } from 'react-transition-group';\n *\n * const duration = 300;\n *\n * const defaultStyle = {\n * transition: `opacity ${duration}ms ease-in-out`,\n * opacity: 0,\n * }\n *\n * const transitionStyles = {\n * entering: { opacity: 0 },\n * entered: { opacity: 1 },\n * };\n *\n * const Fade = ({ in: inProp }) => (\n * \n * {state => (\n *
\n * I'm a fade Transition!\n *
\n * )}\n *
\n * );\n * ```\n *\n * There are 4 main states a Transition can be in:\n * - `'entering'`\n * - `'entered'`\n * - `'exiting'`\n * - `'exited'`\n *\n * Transition state is toggled via the `in` prop. When `true` the component\n * begins the \"Enter\" stage. During this stage, the component will shift from\n * its current transition state, to `'entering'` for the duration of the\n * transition and then to the `'entered'` stage once it's complete. Let's take\n * the following example (we'll use the\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n *
\n * \n * {state => (\n * // ...\n * )}\n * \n * \n *
\n * );\n * }\n * ```\n *\n * When the button is clicked the component will shift to the `'entering'` state\n * and stay there for 500ms (the value of `timeout`) before it finally switches\n * to `'entered'`.\n *\n * When `in` is `false` the same thing happens except the state moves from\n * `'exiting'` to `'exited'`.\n */\n\nexports.EXITING = EXITING;\n\nvar Transition =\n/*#__PURE__*/\nfunction (_React$Component) {\n _inheritsLoose(Transition, _React$Component);\n\n function Transition(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n var parentGroup = context.transitionGroup; // In the context of a TransitionGroup all enters are really appears\n\n var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;\n var initialStatus;\n _this.appearStatus = null;\n\n if (props.in) {\n if (appear) {\n initialStatus = EXITED;\n _this.appearStatus = ENTERING;\n } else {\n initialStatus = ENTERED;\n }\n } else {\n if (props.unmountOnExit || props.mountOnEnter) {\n initialStatus = UNMOUNTED;\n } else {\n initialStatus = EXITED;\n }\n }\n\n _this.state = {\n status: initialStatus\n };\n _this.nextCallback = null;\n return _this;\n }\n\n var _proto = Transition.prototype;\n\n _proto.getChildContext = function getChildContext() {\n return {\n transitionGroup: null // allows for nested Transitions\n\n };\n };\n\n Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {\n var nextIn = _ref.in;\n\n if (nextIn && prevState.status === UNMOUNTED) {\n return {\n status: EXITED\n };\n }\n\n return null;\n }; // getSnapshotBeforeUpdate(prevProps) {\n // let nextStatus = null\n // if (prevProps !== this.props) {\n // const { status } = this.state\n // if (this.props.in) {\n // if (status !== ENTERING && status !== ENTERED) {\n // nextStatus = ENTERING\n // }\n // } else {\n // if (status === ENTERING || status === ENTERED) {\n // nextStatus = EXITING\n // }\n // }\n // }\n // return { nextStatus }\n // }\n\n\n _proto.componentDidMount = function componentDidMount() {\n this.updateStatus(true, this.appearStatus);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n var nextStatus = null;\n\n if (prevProps !== this.props) {\n var status = this.state.status;\n\n if (this.props.in) {\n if (status !== ENTERING && status !== ENTERED) {\n nextStatus = ENTERING;\n }\n } else {\n if (status === ENTERING || status === ENTERED) {\n nextStatus = EXITING;\n }\n }\n }\n\n this.updateStatus(false, nextStatus);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.cancelNextCallback();\n };\n\n _proto.getTimeouts = function getTimeouts() {\n var timeout = this.props.timeout;\n var exit, enter, appear;\n exit = enter = appear = timeout;\n\n if (timeout != null && typeof timeout !== 'number') {\n exit = timeout.exit;\n enter = timeout.enter; // TODO: remove fallback for next major\n\n appear = timeout.appear !== undefined ? timeout.appear : enter;\n }\n\n return {\n exit: exit,\n enter: enter,\n appear: appear\n };\n };\n\n _proto.updateStatus = function updateStatus(mounting, nextStatus) {\n if (mounting === void 0) {\n mounting = false;\n }\n\n if (nextStatus !== null) {\n // nextStatus will always be ENTERING or EXITING.\n this.cancelNextCallback();\n\n var node = _reactDom.default.findDOMNode(this);\n\n if (nextStatus === ENTERING) {\n this.performEnter(node, mounting);\n } else {\n this.performExit(node);\n }\n } else if (this.props.unmountOnExit && this.state.status === EXITED) {\n this.setState({\n status: UNMOUNTED\n });\n }\n };\n\n _proto.performEnter = function performEnter(node, mounting) {\n var _this2 = this;\n\n var enter = this.props.enter;\n var appearing = this.context.transitionGroup ? this.context.transitionGroup.isMounting : mounting;\n var timeouts = this.getTimeouts();\n var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED\n // if we are mounting and running this it means appear _must_ be set\n\n if (!mounting && !enter) {\n this.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(node);\n });\n return;\n }\n\n this.props.onEnter(node, appearing);\n this.safeSetState({\n status: ENTERING\n }, function () {\n _this2.props.onEntering(node, appearing);\n\n _this2.onTransitionEnd(node, enterTimeout, function () {\n _this2.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(node, appearing);\n });\n });\n });\n };\n\n _proto.performExit = function performExit(node) {\n var _this3 = this;\n\n var exit = this.props.exit;\n var timeouts = this.getTimeouts(); // no exit animation skip right to EXITED\n\n if (!exit) {\n this.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(node);\n });\n return;\n }\n\n this.props.onExit(node);\n this.safeSetState({\n status: EXITING\n }, function () {\n _this3.props.onExiting(node);\n\n _this3.onTransitionEnd(node, timeouts.exit, function () {\n _this3.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(node);\n });\n });\n });\n };\n\n _proto.cancelNextCallback = function cancelNextCallback() {\n if (this.nextCallback !== null) {\n this.nextCallback.cancel();\n this.nextCallback = null;\n }\n };\n\n _proto.safeSetState = function safeSetState(nextState, callback) {\n // This shouldn't be necessary, but there are weird race conditions with\n // setState callbacks and unmounting in testing, so always make sure that\n // we can cancel any pending setState callbacks after we unmount.\n callback = this.setNextCallback(callback);\n this.setState(nextState, callback);\n };\n\n _proto.setNextCallback = function setNextCallback(callback) {\n var _this4 = this;\n\n var active = true;\n\n this.nextCallback = function (event) {\n if (active) {\n active = false;\n _this4.nextCallback = null;\n callback(event);\n }\n };\n\n this.nextCallback.cancel = function () {\n active = false;\n };\n\n return this.nextCallback;\n };\n\n _proto.onTransitionEnd = function onTransitionEnd(node, timeout, handler) {\n this.setNextCallback(handler);\n var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;\n\n if (!node || doesNotHaveTimeoutOrListener) {\n setTimeout(this.nextCallback, 0);\n return;\n }\n\n if (this.props.addEndListener) {\n this.props.addEndListener(node, this.nextCallback);\n }\n\n if (timeout != null) {\n setTimeout(this.nextCallback, timeout);\n }\n };\n\n _proto.render = function render() {\n var status = this.state.status;\n\n if (status === UNMOUNTED) {\n return null;\n }\n\n var _this$props = this.props,\n children = _this$props.children,\n childProps = _objectWithoutPropertiesLoose(_this$props, [\"children\"]); // filter props for Transtition\n\n\n delete childProps.in;\n delete childProps.mountOnEnter;\n delete childProps.unmountOnExit;\n delete childProps.appear;\n delete childProps.enter;\n delete childProps.exit;\n delete childProps.timeout;\n delete childProps.addEndListener;\n delete childProps.onEnter;\n delete childProps.onEntering;\n delete childProps.onEntered;\n delete childProps.onExit;\n delete childProps.onExiting;\n delete childProps.onExited;\n\n if (typeof children === 'function') {\n return children(status, childProps);\n }\n\n var child = _react.default.Children.only(children);\n\n return _react.default.cloneElement(child, childProps);\n };\n\n return Transition;\n}(_react.default.Component);\n\nTransition.contextTypes = {\n transitionGroup: PropTypes.object\n};\nTransition.childContextTypes = {\n transitionGroup: function transitionGroup() {}\n};\nTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * A `function` child can be used instead of a React element. This function is\n * called with the current transition status (`'entering'`, `'entered'`,\n * `'exiting'`, `'exited'`, `'unmounted'`), which can be used to apply context\n * specific props to a component.\n *\n * ```jsx\n * \n * {state => (\n * \n * )}\n * \n * ```\n */\n children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,\n\n /**\n * Show the component; triggers the enter or exit states\n */\n in: PropTypes.bool,\n\n /**\n * By default the child component is mounted immediately along with\n * the parent `Transition` component. If you want to \"lazy mount\" the component on the\n * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay\n * mounted, even on \"exited\", unless you also specify `unmountOnExit`.\n */\n mountOnEnter: PropTypes.bool,\n\n /**\n * By default the child component stays mounted after it reaches the `'exited'` state.\n * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.\n */\n unmountOnExit: PropTypes.bool,\n\n /**\n * Normally a component is not transitioned if it is shown when the `` component mounts.\n * If you want to transition on the first mount set `appear` to `true`, and the\n * component will transition in as soon as the `` mounts.\n *\n * > Note: there are no specific \"appear\" states. `appear` only adds an additional `enter` transition.\n */\n appear: PropTypes.bool,\n\n /**\n * Enable or disable enter transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * Enable or disable exit transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * The duration of the transition, in milliseconds.\n * Required unless `addEndListener` is provided.\n *\n * You may specify a single timeout for all transitions:\n *\n * ```jsx\n * timeout={500}\n * ```\n *\n * or individually:\n *\n * ```jsx\n * timeout={{\n * appear: 500,\n * enter: 300,\n * exit: 500,\n * }}\n * ```\n *\n * - `appear` defaults to the value of `enter`\n * - `enter` defaults to `0`\n * - `exit` defaults to `0`\n *\n * @type {number | { enter?: number, exit?: number, appear?: number }}\n */\n timeout: function timeout(props) {\n var pt = _PropTypes.timeoutsShape;\n if (!props.addEndListener) pt = pt.isRequired;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return pt.apply(void 0, [props].concat(args));\n },\n\n /**\n * Add a custom transition end trigger. Called with the transitioning\n * DOM node and a `done` callback. Allows for more fine grained transition end\n * logic. **Note:** Timeouts are still used as a fallback if provided.\n *\n * ```jsx\n * addEndListener={(node, done) => {\n * // use the css transitionend event to mark the finish of a transition\n * node.addEventListener('transitionend', done, false);\n * }}\n * ```\n */\n addEndListener: PropTypes.func,\n\n /**\n * Callback fired before the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired after the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired after the \"entered\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired before the \"exiting\" status is applied.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired after the \"exiting\" status is applied.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExiting: PropTypes.func,\n\n /**\n * Callback fired after the \"exited\" status is applied.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExited: PropTypes.func // Name the function so it is clearer in the documentation\n\n} : {};\n\nfunction noop() {}\n\nTransition.defaultProps = {\n in: false,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n enter: true,\n exit: true,\n onEnter: noop,\n onEntering: noop,\n onEntered: noop,\n onExit: noop,\n onExiting: noop,\n onExited: noop\n};\nTransition.UNMOUNTED = 0;\nTransition.EXITED = 1;\nTransition.ENTERING = 2;\nTransition.ENTERED = 3;\nTransition.EXITING = 4;\n\nvar _default = (0, _reactLifecyclesCompat.polyfill)(Transition);\n\nexports.default = _default;","\"use strict\";\n\nexports.__esModule = true;\nexports.default = void 0;\n\nvar PropTypes = _interopRequireWildcard(require(\"prop-types\"));\n\nvar _addClass = _interopRequireDefault(require(\"dom-helpers/class/addClass\"));\n\nvar _removeClass = _interopRequireDefault(require(\"dom-helpers/class/removeClass\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _Transition = _interopRequireDefault(require(\"./Transition\"));\n\nvar _PropTypes = require(\"./utils/PropTypes\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar addClass = function addClass(node, classes) {\n return node && classes && classes.split(' ').forEach(function (c) {\n return (0, _addClass.default)(node, c);\n });\n};\n\nvar removeClass = function removeClass(node, classes) {\n return node && classes && classes.split(' ').forEach(function (c) {\n return (0, _removeClass.default)(node, c);\n });\n};\n/**\n * A transition component inspired by the excellent\n * [ng-animate](http://www.nganimate.org/) library, you should use it if you're\n * using CSS transitions or animations. It's built upon the\n * [`Transition`](https://reactcommunity.org/react-transition-group/transition)\n * component, so it inherits all of its props.\n *\n * `CSSTransition` applies a pair of class names during the `appear`, `enter`,\n * and `exit` states of the transition. The first class is applied and then a\n * second `*-active` class in order to activate the CSSS transition. After the\n * transition, matching `*-done` class names are applied to persist the\n * transition state.\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n *
\n * \n *
\n * {\"I'll receive my-node-* classes\"}\n *
\n *
\n * \n *
\n * );\n * }\n * ```\n *\n * When the `in` prop is set to `true`, the child component will first receive\n * the class `example-enter`, then the `example-enter-active` will be added in\n * the next tick. `CSSTransition` [forces a\n * reflow](https://github.com/reactjs/react-transition-group/blob/5007303e729a74be66a21c3e2205e4916821524b/src/CSSTransition.js#L208-L215)\n * between before adding the `example-enter-active`. This is an important trick\n * because it allows us to transition between `example-enter` and\n * `example-enter-active` even though they were added immediately one after\n * another. Most notably, this is what makes it possible for us to animate\n * _appearance_.\n *\n * ```css\n * .my-node-enter {\n * opacity: 0;\n * }\n * .my-node-enter-active {\n * opacity: 1;\n * transition: opacity 200ms;\n * }\n * .my-node-exit {\n * opacity: 1;\n * }\n * .my-node-exit-active {\n * opacity: 0;\n * transition: opacity: 200ms;\n * }\n * ```\n *\n * `*-active` classes represent which styles you want to animate **to**.\n */\n\n\nvar CSSTransition =\n/*#__PURE__*/\nfunction (_React$Component) {\n _inheritsLoose(CSSTransition, _React$Component);\n\n function CSSTransition() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n\n _this.onEnter = function (node, appearing) {\n var _this$getClassNames = _this.getClassNames(appearing ? 'appear' : 'enter'),\n className = _this$getClassNames.className;\n\n _this.removeClasses(node, 'exit');\n\n addClass(node, className);\n\n if (_this.props.onEnter) {\n _this.props.onEnter(node, appearing);\n }\n };\n\n _this.onEntering = function (node, appearing) {\n var _this$getClassNames2 = _this.getClassNames(appearing ? 'appear' : 'enter'),\n activeClassName = _this$getClassNames2.activeClassName;\n\n _this.reflowAndAddClass(node, activeClassName);\n\n if (_this.props.onEntering) {\n _this.props.onEntering(node, appearing);\n }\n };\n\n _this.onEntered = function (node, appearing) {\n var appearClassName = _this.getClassNames('appear').doneClassName;\n\n var enterClassName = _this.getClassNames('enter').doneClassName;\n\n var doneClassName = appearing ? appearClassName + \" \" + enterClassName : enterClassName;\n\n _this.removeClasses(node, appearing ? 'appear' : 'enter');\n\n addClass(node, doneClassName);\n\n if (_this.props.onEntered) {\n _this.props.onEntered(node, appearing);\n }\n };\n\n _this.onExit = function (node) {\n var _this$getClassNames3 = _this.getClassNames('exit'),\n className = _this$getClassNames3.className;\n\n _this.removeClasses(node, 'appear');\n\n _this.removeClasses(node, 'enter');\n\n addClass(node, className);\n\n if (_this.props.onExit) {\n _this.props.onExit(node);\n }\n };\n\n _this.onExiting = function (node) {\n var _this$getClassNames4 = _this.getClassNames('exit'),\n activeClassName = _this$getClassNames4.activeClassName;\n\n _this.reflowAndAddClass(node, activeClassName);\n\n if (_this.props.onExiting) {\n _this.props.onExiting(node);\n }\n };\n\n _this.onExited = function (node) {\n var _this$getClassNames5 = _this.getClassNames('exit'),\n doneClassName = _this$getClassNames5.doneClassName;\n\n _this.removeClasses(node, 'exit');\n\n addClass(node, doneClassName);\n\n if (_this.props.onExited) {\n _this.props.onExited(node);\n }\n };\n\n _this.getClassNames = function (type) {\n var classNames = _this.props.classNames;\n var isStringClassNames = typeof classNames === 'string';\n var prefix = isStringClassNames && classNames ? classNames + '-' : '';\n var className = isStringClassNames ? prefix + type : classNames[type];\n var activeClassName = isStringClassNames ? className + '-active' : classNames[type + 'Active'];\n var doneClassName = isStringClassNames ? className + '-done' : classNames[type + 'Done'];\n return {\n className: className,\n activeClassName: activeClassName,\n doneClassName: doneClassName\n };\n };\n\n return _this;\n }\n\n var _proto = CSSTransition.prototype;\n\n _proto.removeClasses = function removeClasses(node, type) {\n var _this$getClassNames6 = this.getClassNames(type),\n className = _this$getClassNames6.className,\n activeClassName = _this$getClassNames6.activeClassName,\n doneClassName = _this$getClassNames6.doneClassName;\n\n className && removeClass(node, className);\n activeClassName && removeClass(node, activeClassName);\n doneClassName && removeClass(node, doneClassName);\n };\n\n _proto.reflowAndAddClass = function reflowAndAddClass(node, className) {\n // This is for to force a repaint,\n // which is necessary in order to transition styles when adding a class name.\n if (className) {\n /* eslint-disable no-unused-expressions */\n node && node.scrollTop;\n /* eslint-enable no-unused-expressions */\n\n addClass(node, className);\n }\n };\n\n _proto.render = function render() {\n var props = _extends({}, this.props);\n\n delete props.classNames;\n return _react.default.createElement(_Transition.default, _extends({}, props, {\n onEnter: this.onEnter,\n onEntered: this.onEntered,\n onEntering: this.onEntering,\n onExit: this.onExit,\n onExiting: this.onExiting,\n onExited: this.onExited\n }));\n };\n\n return CSSTransition;\n}(_react.default.Component);\n\nCSSTransition.defaultProps = {\n classNames: ''\n};\nCSSTransition.propTypes = process.env.NODE_ENV !== \"production\" ? _extends({}, _Transition.default.propTypes, {\n /**\n * The animation classNames applied to the component as it enters, exits or\n * has finished the transition. A single name can be provided and it will be\n * suffixed for each stage: e.g.\n *\n * `classNames=\"fade\"` applies `fade-enter`, `fade-enter-active`,\n * `fade-enter-done`, `fade-exit`, `fade-exit-active`, `fade-exit-done`,\n * `fade-appear`, `fade-appear-active`, and `fade-appear-done`.\n *\n * **Note**: `fade-appear-done` and `fade-enter-done` will _both_ be applied.\n * This allows you to define different behavior for when appearing is done and\n * when regular entering is done, using selectors like\n * `.fade-enter-done:not(.fade-appear-done)`. For example, you could apply an\n * epic entrance animation when element first appears in the DOM using\n * [Animate.css](https://daneden.github.io/animate.css/). Otherwise you can\n * simply use `fade-enter-done` for defining both cases.\n *\n * Each individual classNames can also be specified independently like:\n *\n * ```js\n * classNames={{\n * appear: 'my-appear',\n * appearActive: 'my-active-appear',\n * appearDone: 'my-done-appear',\n * enter: 'my-enter',\n * enterActive: 'my-active-enter',\n * enterDone: 'my-done-enter',\n * exit: 'my-exit',\n * exitActive: 'my-active-exit',\n * exitDone: 'my-done-exit',\n * }}\n * ```\n *\n * If you want to set these classes using CSS Modules:\n *\n * ```js\n * import styles from './styles.css';\n * ```\n *\n * you might want to use camelCase in your CSS file, that way could simply\n * spread them instead of listing them one by one:\n *\n * ```js\n * classNames={{ ...styles }}\n * ```\n *\n * @type {string | {\n * appear?: string,\n * appearActive?: string,\n * appearDone?: string,\n * enter?: string,\n * enterActive?: string,\n * enterDone?: string,\n * exit?: string,\n * exitActive?: string,\n * exitDone?: string,\n * }}\n */\n classNames: _PropTypes.classNamesShape,\n\n /**\n * A `` callback fired immediately after the 'enter' or 'appear' class is\n * applied.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEnter: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'enter-active' or\n * 'appear-active' class is applied.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'enter' or\n * 'appear' classes are **removed** and the `done` class is added to the DOM node.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntered: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit' class is\n * applied.\n *\n * @type Function(node: HtmlElement)\n */\n onExit: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit-active' is applied.\n *\n * @type Function(node: HtmlElement)\n */\n onExiting: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit' classes\n * are **removed** and the `exit-done` class is added to the DOM node.\n *\n * @type Function(node: HtmlElement)\n */\n onExited: PropTypes.func\n}) : {};\nvar _default = CSSTransition;\nexports.default = _default;\nmodule.exports = exports[\"default\"];","\"use strict\";\n\nexports.__esModule = true;\nexports.getChildMapping = getChildMapping;\nexports.mergeChildMappings = mergeChildMappings;\nexports.getInitialChildMapping = getInitialChildMapping;\nexports.getNextChildMapping = getNextChildMapping;\n\nvar _react = require(\"react\");\n\n/**\n * Given `this.props.children`, return an object mapping key to child.\n *\n * @param {*} children `this.props.children`\n * @return {object} Mapping of key to child\n */\nfunction getChildMapping(children, mapFn) {\n var mapper = function mapper(child) {\n return mapFn && (0, _react.isValidElement)(child) ? mapFn(child) : child;\n };\n\n var result = Object.create(null);\n if (children) _react.Children.map(children, function (c) {\n return c;\n }).forEach(function (child) {\n // run the map function here instead so that the key is the computed one\n result[child.key] = mapper(child);\n });\n return result;\n}\n/**\n * When you're adding or removing children some may be added or removed in the\n * same render pass. We want to show *both* since we want to simultaneously\n * animate elements in and out. This function takes a previous set of keys\n * and a new set of keys and merges them with its best guess of the correct\n * ordering. In the future we may expose some of the utilities in\n * ReactMultiChild to make this easy, but for now React itself does not\n * directly have this concept of the union of prevChildren and nextChildren\n * so we implement it here.\n *\n * @param {object} prev prev children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @param {object} next next children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @return {object} a key set that contains all keys in `prev` and all keys\n * in `next` in a reasonable order.\n */\n\n\nfunction mergeChildMappings(prev, next) {\n prev = prev || {};\n next = next || {};\n\n function getValueForKey(key) {\n return key in next ? next[key] : prev[key];\n } // For each key of `next`, the list of keys to insert before that key in\n // the combined list\n\n\n var nextKeysPending = Object.create(null);\n var pendingKeys = [];\n\n for (var prevKey in prev) {\n if (prevKey in next) {\n if (pendingKeys.length) {\n nextKeysPending[prevKey] = pendingKeys;\n pendingKeys = [];\n }\n } else {\n pendingKeys.push(prevKey);\n }\n }\n\n var i;\n var childMapping = {};\n\n for (var nextKey in next) {\n if (nextKeysPending[nextKey]) {\n for (i = 0; i < nextKeysPending[nextKey].length; i++) {\n var pendingNextKey = nextKeysPending[nextKey][i];\n childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);\n }\n }\n\n childMapping[nextKey] = getValueForKey(nextKey);\n } // Finally, add the keys which didn't appear before any key in `next`\n\n\n for (i = 0; i < pendingKeys.length; i++) {\n childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);\n }\n\n return childMapping;\n}\n\nfunction getProp(child, prop, props) {\n return props[prop] != null ? props[prop] : child.props[prop];\n}\n\nfunction getInitialChildMapping(props, onExited) {\n return getChildMapping(props.children, function (child) {\n return (0, _react.cloneElement)(child, {\n onExited: onExited.bind(null, child),\n in: true,\n appear: getProp(child, 'appear', props),\n enter: getProp(child, 'enter', props),\n exit: getProp(child, 'exit', props)\n });\n });\n}\n\nfunction getNextChildMapping(nextProps, prevChildMapping, onExited) {\n var nextChildMapping = getChildMapping(nextProps.children);\n var children = mergeChildMappings(prevChildMapping, nextChildMapping);\n Object.keys(children).forEach(function (key) {\n var child = children[key];\n if (!(0, _react.isValidElement)(child)) return;\n var hasPrev = key in prevChildMapping;\n var hasNext = key in nextChildMapping;\n var prevChild = prevChildMapping[key];\n var isLeaving = (0, _react.isValidElement)(prevChild) && !prevChild.props.in; // item is new (entering)\n\n if (hasNext && (!hasPrev || isLeaving)) {\n // console.log('entering', key)\n children[key] = (0, _react.cloneElement)(child, {\n onExited: onExited.bind(null, child),\n in: true,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n } else if (!hasNext && hasPrev && !isLeaving) {\n // item is old (exiting)\n // console.log('leaving', key)\n children[key] = (0, _react.cloneElement)(child, {\n in: false\n });\n } else if (hasNext && hasPrev && (0, _react.isValidElement)(prevChild)) {\n // item hasn't changed transition states\n // copy over the last transition props;\n // console.log('unchanged', key)\n children[key] = (0, _react.cloneElement)(child, {\n onExited: onExited.bind(null, child),\n in: prevChild.props.in,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n }\n });\n return children;\n}","\"use strict\";\n\nexports.__esModule = true;\nexports.default = void 0;\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _reactLifecyclesCompat = require(\"react-lifecycles-compat\");\n\nvar _ChildMapping = require(\"./utils/ChildMapping\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nvar values = Object.values || function (obj) {\n return Object.keys(obj).map(function (k) {\n return obj[k];\n });\n};\n\nvar defaultProps = {\n component: 'div',\n childFactory: function childFactory(child) {\n return child;\n }\n /**\n * The `` component manages a set of transition components\n * (`` and ``) in a list. Like with the transition\n * components, `` is a state machine for managing the mounting\n * and unmounting of components over time.\n *\n * Consider the example below. As items are removed or added to the TodoList the\n * `in` prop is toggled automatically by the ``.\n *\n * Note that `` does not define any animation behavior!\n * Exactly _how_ a list item animates is up to the individual transition\n * component. This means you can mix and match animations across different list\n * items.\n */\n\n};\n\nvar TransitionGroup =\n/*#__PURE__*/\nfunction (_React$Component) {\n _inheritsLoose(TransitionGroup, _React$Component);\n\n function TransitionGroup(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n\n var handleExited = _this.handleExited.bind(_assertThisInitialized(_assertThisInitialized(_this))); // Initial children should all be entering, dependent on appear\n\n\n _this.state = {\n handleExited: handleExited,\n firstRender: true\n };\n return _this;\n }\n\n var _proto = TransitionGroup.prototype;\n\n _proto.getChildContext = function getChildContext() {\n return {\n transitionGroup: {\n isMounting: !this.appeared\n }\n };\n };\n\n _proto.componentDidMount = function componentDidMount() {\n this.appeared = true;\n this.mounted = true;\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.mounted = false;\n };\n\n TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {\n var prevChildMapping = _ref.children,\n handleExited = _ref.handleExited,\n firstRender = _ref.firstRender;\n return {\n children: firstRender ? (0, _ChildMapping.getInitialChildMapping)(nextProps, handleExited) : (0, _ChildMapping.getNextChildMapping)(nextProps, prevChildMapping, handleExited),\n firstRender: false\n };\n };\n\n _proto.handleExited = function handleExited(child, node) {\n var currentChildMapping = (0, _ChildMapping.getChildMapping)(this.props.children);\n if (child.key in currentChildMapping) return;\n\n if (child.props.onExited) {\n child.props.onExited(node);\n }\n\n if (this.mounted) {\n this.setState(function (state) {\n var children = _extends({}, state.children);\n\n delete children[child.key];\n return {\n children: children\n };\n });\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n Component = _this$props.component,\n childFactory = _this$props.childFactory,\n props = _objectWithoutPropertiesLoose(_this$props, [\"component\", \"childFactory\"]);\n\n var children = values(this.state.children).map(childFactory);\n delete props.appear;\n delete props.enter;\n delete props.exit;\n\n if (Component === null) {\n return children;\n }\n\n return _react.default.createElement(Component, props, children);\n };\n\n return TransitionGroup;\n}(_react.default.Component);\n\nTransitionGroup.childContextTypes = {\n transitionGroup: _propTypes.default.object.isRequired\n};\nTransitionGroup.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * `` renders a `
` by default. You can change this\n * behavior by providing a `component` prop.\n * If you use React v16+ and would like to avoid a wrapping `
` element\n * you can pass in `component={null}`. This is useful if the wrapping div\n * borks your css styles.\n */\n component: _propTypes.default.any,\n\n /**\n * A set of `` components, that are toggled `in` and out as they\n * leave. the `` will inject specific transition props, so\n * remember to spread them through if you are wrapping the `` as\n * with our `` example.\n *\n * While this component is meant for multiple `Transition` or `CSSTransition`\n * children, sometimes you may want to have a single transition child with\n * content that you want to be transitioned out and in when you change it\n * (e.g. routes, images etc.) In that case you can change the `key` prop of\n * the transition child as you change its content, this will cause\n * `TransitionGroup` to transition the child out and back in.\n */\n children: _propTypes.default.node,\n\n /**\n * A convenience prop that enables or disables appear animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n appear: _propTypes.default.bool,\n\n /**\n * A convenience prop that enables or disables enter animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n enter: _propTypes.default.bool,\n\n /**\n * A convenience prop that enables or disables exit animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n exit: _propTypes.default.bool,\n\n /**\n * You may need to apply reactive updates to a child as it is exiting.\n * This is generally done by using `cloneElement` however in the case of an exiting\n * child the element has already been removed and not accessible to the consumer.\n *\n * If you do need to update a child as it leaves you can provide a `childFactory`\n * to wrap every child, even the ones that are leaving.\n *\n * @type Function(child: ReactElement) -> ReactElement\n */\n childFactory: _propTypes.default.func\n} : {};\nTransitionGroup.defaultProps = defaultProps;\n\nvar _default = (0, _reactLifecyclesCompat.polyfill)(TransitionGroup);\n\nexports.default = _default;\nmodule.exports = exports[\"default\"];","\"use strict\";\n\nexports.__esModule = true;\nexports.default = void 0;\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _reactDom = require(\"react-dom\");\n\nvar _TransitionGroup = _interopRequireDefault(require(\"./TransitionGroup\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\n/**\n * The `` component is a specialized `Transition` component\n * that animates between two children.\n *\n * ```jsx\n * \n *
I appear first
\n *
I replace the above
\n *
\n * ```\n */\nvar ReplaceTransition =\n/*#__PURE__*/\nfunction (_React$Component) {\n _inheritsLoose(ReplaceTransition, _React$Component);\n\n function ReplaceTransition() {\n var _this;\n\n for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {\n _args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;\n\n _this.handleEnter = function () {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return _this.handleLifecycle('onEnter', 0, args);\n };\n\n _this.handleEntering = function () {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n\n return _this.handleLifecycle('onEntering', 0, args);\n };\n\n _this.handleEntered = function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n\n return _this.handleLifecycle('onEntered', 0, args);\n };\n\n _this.handleExit = function () {\n for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n args[_key5] = arguments[_key5];\n }\n\n return _this.handleLifecycle('onExit', 1, args);\n };\n\n _this.handleExiting = function () {\n for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n args[_key6] = arguments[_key6];\n }\n\n return _this.handleLifecycle('onExiting', 1, args);\n };\n\n _this.handleExited = function () {\n for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {\n args[_key7] = arguments[_key7];\n }\n\n return _this.handleLifecycle('onExited', 1, args);\n };\n\n return _this;\n }\n\n var _proto = ReplaceTransition.prototype;\n\n _proto.handleLifecycle = function handleLifecycle(handler, idx, originalArgs) {\n var _child$props;\n\n var children = this.props.children;\n\n var child = _react.default.Children.toArray(children)[idx];\n\n if (child.props[handler]) (_child$props = child.props)[handler].apply(_child$props, originalArgs);\n if (this.props[handler]) this.props[handler]((0, _reactDom.findDOMNode)(this));\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n children = _this$props.children,\n inProp = _this$props.in,\n props = _objectWithoutPropertiesLoose(_this$props, [\"children\", \"in\"]);\n\n var _React$Children$toArr = _react.default.Children.toArray(children),\n first = _React$Children$toArr[0],\n second = _React$Children$toArr[1];\n\n delete props.onEnter;\n delete props.onEntering;\n delete props.onEntered;\n delete props.onExit;\n delete props.onExiting;\n delete props.onExited;\n return _react.default.createElement(_TransitionGroup.default, props, inProp ? _react.default.cloneElement(first, {\n key: 'first',\n onEnter: this.handleEnter,\n onEntering: this.handleEntering,\n onEntered: this.handleEntered\n }) : _react.default.cloneElement(second, {\n key: 'second',\n onEnter: this.handleExit,\n onEntering: this.handleExiting,\n onEntered: this.handleExited\n }));\n };\n\n return ReplaceTransition;\n}(_react.default.Component);\n\nReplaceTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n in: _propTypes.default.bool.isRequired,\n children: function children(props, propName) {\n if (_react.default.Children.count(props[propName]) !== 2) return new Error(\"\\\"\" + propName + \"\\\" must be exactly two transition components.\");\n return null;\n }\n} : {};\nvar _default = ReplaceTransition;\nexports.default = _default;\nmodule.exports = exports[\"default\"];","\"use strict\";\n\nvar _CSSTransition = _interopRequireDefault(require(\"./CSSTransition\"));\n\nvar _ReplaceTransition = _interopRequireDefault(require(\"./ReplaceTransition\"));\n\nvar _TransitionGroup = _interopRequireDefault(require(\"./TransitionGroup\"));\n\nvar _Transition = _interopRequireDefault(require(\"./Transition\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nmodule.exports = {\n Transition: _Transition.default,\n TransitionGroup: _TransitionGroup.default,\n ReplaceTransition: _ReplaceTransition.default,\n CSSTransition: _CSSTransition.default\n};","\nexport default function quickselect(arr, k, left, right, compare) {\n quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);\n}\n\nfunction quickselectStep(arr, k, left, right, compare) {\n\n while (right > left) {\n if (right - left > 600) {\n var n = right - left + 1;\n var m = k - left + 1;\n var z = Math.log(n);\n var s = 0.5 * Math.exp(2 * z / 3);\n var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselectStep(arr, k, newLeft, newRight, compare);\n }\n\n var t = arr[k];\n var i = left;\n var j = right;\n\n swap(arr, left, k);\n if (compare(arr[right], t) > 0) swap(arr, left, right);\n\n while (i < j) {\n swap(arr, i, j);\n i++;\n j--;\n while (compare(arr[i], t) < 0) i++;\n while (compare(arr[j], t) > 0) j--;\n }\n\n if (compare(arr[left], t) === 0) swap(arr, left, j);\n else {\n j++;\n swap(arr, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\nfunction swap(arr, i, j) {\n var tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","import quickselect from 'quickselect';\n\nexport default class RBush {\n constructor(maxEntries = 9) {\n // max entries in a node is 9 by default; min node fill is 40% for best performance\n this._maxEntries = Math.max(4, maxEntries);\n this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));\n this.clear();\n }\n\n all() {\n return this._all(this.data, []);\n }\n\n search(bbox) {\n let node = this.data;\n const result = [];\n\n if (!intersects(bbox, node)) return result;\n\n const toBBox = this.toBBox;\n const nodesToSearch = [];\n\n while (node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const childBBox = node.leaf ? toBBox(child) : child;\n\n if (intersects(bbox, childBBox)) {\n if (node.leaf) result.push(child);\n else if (contains(bbox, childBBox)) this._all(child, result);\n else nodesToSearch.push(child);\n }\n }\n node = nodesToSearch.pop();\n }\n\n return result;\n }\n\n collides(bbox) {\n let node = this.data;\n\n if (!intersects(bbox, node)) return false;\n\n const nodesToSearch = [];\n while (node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const childBBox = node.leaf ? this.toBBox(child) : child;\n\n if (intersects(bbox, childBBox)) {\n if (node.leaf || contains(bbox, childBBox)) return true;\n nodesToSearch.push(child);\n }\n }\n node = nodesToSearch.pop();\n }\n\n return false;\n }\n\n load(data) {\n if (!(data && data.length)) return this;\n\n if (data.length < this._minEntries) {\n for (let i = 0; i < data.length; i++) {\n this.insert(data[i]);\n }\n return this;\n }\n\n // recursively build the tree with the given data from scratch using OMT algorithm\n let node = this._build(data.slice(), 0, data.length - 1, 0);\n\n if (!this.data.children.length) {\n // save as is if tree is empty\n this.data = node;\n\n } else if (this.data.height === node.height) {\n // split root if trees have the same height\n this._splitRoot(this.data, node);\n\n } else {\n if (this.data.height < node.height) {\n // swap trees if inserted one is bigger\n const tmpNode = this.data;\n this.data = node;\n node = tmpNode;\n }\n\n // insert the small tree into the large tree at appropriate level\n this._insert(node, this.data.height - node.height - 1, true);\n }\n\n return this;\n }\n\n insert(item) {\n if (item) this._insert(item, this.data.height - 1);\n return this;\n }\n\n clear() {\n this.data = createNode([]);\n return this;\n }\n\n remove(item, equalsFn) {\n if (!item) return this;\n\n let node = this.data;\n const bbox = this.toBBox(item);\n const path = [];\n const indexes = [];\n let i, parent, goingUp;\n\n // depth-first iterative tree traversal\n while (node || path.length) {\n\n if (!node) { // go up\n node = path.pop();\n parent = path[path.length - 1];\n i = indexes.pop();\n goingUp = true;\n }\n\n if (node.leaf) { // check current node\n const index = findItem(item, node.children, equalsFn);\n\n if (index !== -1) {\n // item found, remove the item and condense tree upwards\n node.children.splice(index, 1);\n path.push(node);\n this._condense(path);\n return this;\n }\n }\n\n if (!goingUp && !node.leaf && contains(node, bbox)) { // go down\n path.push(node);\n indexes.push(i);\n i = 0;\n parent = node;\n node = node.children[0];\n\n } else if (parent) { // go right\n i++;\n node = parent.children[i];\n goingUp = false;\n\n } else node = null; // nothing found\n }\n\n return this;\n }\n\n toBBox(item) { return item; }\n\n compareMinX(a, b) { return a.minX - b.minX; }\n compareMinY(a, b) { return a.minY - b.minY; }\n\n toJSON() { return this.data; }\n\n fromJSON(data) {\n this.data = data;\n return this;\n }\n\n _all(node, result) {\n const nodesToSearch = [];\n while (node) {\n if (node.leaf) result.push(...node.children);\n else nodesToSearch.push(...node.children);\n\n node = nodesToSearch.pop();\n }\n return result;\n }\n\n _build(items, left, right, height) {\n\n const N = right - left + 1;\n let M = this._maxEntries;\n let node;\n\n if (N <= M) {\n // reached leaf level; return leaf\n node = createNode(items.slice(left, right + 1));\n calcBBox(node, this.toBBox);\n return node;\n }\n\n if (!height) {\n // target height of the bulk-loaded tree\n height = Math.ceil(Math.log(N) / Math.log(M));\n\n // target number of root entries to maximize storage utilization\n M = Math.ceil(N / Math.pow(M, height - 1));\n }\n\n node = createNode([]);\n node.leaf = false;\n node.height = height;\n\n // split the items into M mostly square tiles\n\n const N2 = Math.ceil(N / M);\n const N1 = N2 * Math.ceil(Math.sqrt(M));\n\n multiSelect(items, left, right, N1, this.compareMinX);\n\n for (let i = left; i <= right; i += N1) {\n\n const right2 = Math.min(i + N1 - 1, right);\n\n multiSelect(items, i, right2, N2, this.compareMinY);\n\n for (let j = i; j <= right2; j += N2) {\n\n const right3 = Math.min(j + N2 - 1, right2);\n\n // pack each entry recursively\n node.children.push(this._build(items, j, right3, height - 1));\n }\n }\n\n calcBBox(node, this.toBBox);\n\n return node;\n }\n\n _chooseSubtree(bbox, node, level, path) {\n while (true) {\n path.push(node);\n\n if (node.leaf || path.length - 1 === level) break;\n\n let minArea = Infinity;\n let minEnlargement = Infinity;\n let targetNode;\n\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const area = bboxArea(child);\n const enlargement = enlargedArea(bbox, child) - area;\n\n // choose entry with the least area enlargement\n if (enlargement < minEnlargement) {\n minEnlargement = enlargement;\n minArea = area < minArea ? area : minArea;\n targetNode = child;\n\n } else if (enlargement === minEnlargement) {\n // otherwise choose one with the smallest area\n if (area < minArea) {\n minArea = area;\n targetNode = child;\n }\n }\n }\n\n node = targetNode || node.children[0];\n }\n\n return node;\n }\n\n _insert(item, level, isNode) {\n const bbox = isNode ? item : this.toBBox(item);\n const insertPath = [];\n\n // find the best node for accommodating the item, saving all nodes along the path too\n const node = this._chooseSubtree(bbox, this.data, level, insertPath);\n\n // put the item into the node\n node.children.push(item);\n extend(node, bbox);\n\n // split on node overflow; propagate upwards if necessary\n while (level >= 0) {\n if (insertPath[level].children.length > this._maxEntries) {\n this._split(insertPath, level);\n level--;\n } else break;\n }\n\n // adjust bboxes along the insertion path\n this._adjustParentBBoxes(bbox, insertPath, level);\n }\n\n // split overflowed node into two\n _split(insertPath, level) {\n const node = insertPath[level];\n const M = node.children.length;\n const m = this._minEntries;\n\n this._chooseSplitAxis(node, m, M);\n\n const splitIndex = this._chooseSplitIndex(node, m, M);\n\n const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));\n newNode.height = node.height;\n newNode.leaf = node.leaf;\n\n calcBBox(node, this.toBBox);\n calcBBox(newNode, this.toBBox);\n\n if (level) insertPath[level - 1].children.push(newNode);\n else this._splitRoot(node, newNode);\n }\n\n _splitRoot(node, newNode) {\n // split root node\n this.data = createNode([node, newNode]);\n this.data.height = node.height + 1;\n this.data.leaf = false;\n calcBBox(this.data, this.toBBox);\n }\n\n _chooseSplitIndex(node, m, M) {\n let index;\n let minOverlap = Infinity;\n let minArea = Infinity;\n\n for (let i = m; i <= M - m; i++) {\n const bbox1 = distBBox(node, 0, i, this.toBBox);\n const bbox2 = distBBox(node, i, M, this.toBBox);\n\n const overlap = intersectionArea(bbox1, bbox2);\n const area = bboxArea(bbox1) + bboxArea(bbox2);\n\n // choose distribution with minimum overlap\n if (overlap < minOverlap) {\n minOverlap = overlap;\n index = i;\n\n minArea = area < minArea ? area : minArea;\n\n } else if (overlap === minOverlap) {\n // otherwise choose distribution with minimum area\n if (area < minArea) {\n minArea = area;\n index = i;\n }\n }\n }\n\n return index || M - m;\n }\n\n // sorts node children by the best axis for split\n _chooseSplitAxis(node, m, M) {\n const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;\n const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;\n const xMargin = this._allDistMargin(node, m, M, compareMinX);\n const yMargin = this._allDistMargin(node, m, M, compareMinY);\n\n // if total distributions margin value is minimal for x, sort by minX,\n // otherwise it's already sorted by minY\n if (xMargin < yMargin) node.children.sort(compareMinX);\n }\n\n // total margin of all possible split distributions where each node is at least m full\n _allDistMargin(node, m, M, compare) {\n node.children.sort(compare);\n\n const toBBox = this.toBBox;\n const leftBBox = distBBox(node, 0, m, toBBox);\n const rightBBox = distBBox(node, M - m, M, toBBox);\n let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);\n\n for (let i = m; i < M - m; i++) {\n const child = node.children[i];\n extend(leftBBox, node.leaf ? toBBox(child) : child);\n margin += bboxMargin(leftBBox);\n }\n\n for (let i = M - m - 1; i >= m; i--) {\n const child = node.children[i];\n extend(rightBBox, node.leaf ? toBBox(child) : child);\n margin += bboxMargin(rightBBox);\n }\n\n return margin;\n }\n\n _adjustParentBBoxes(bbox, path, level) {\n // adjust bboxes along the given tree path\n for (let i = level; i >= 0; i--) {\n extend(path[i], bbox);\n }\n }\n\n _condense(path) {\n // go through the path, removing empty nodes and updating bboxes\n for (let i = path.length - 1, siblings; i >= 0; i--) {\n if (path[i].children.length === 0) {\n if (i > 0) {\n siblings = path[i - 1].children;\n siblings.splice(siblings.indexOf(path[i]), 1);\n\n } else this.clear();\n\n } else calcBBox(path[i], this.toBBox);\n }\n }\n}\n\nfunction findItem(item, items, equalsFn) {\n if (!equalsFn) return items.indexOf(item);\n\n for (let i = 0; i < items.length; i++) {\n if (equalsFn(item, items[i])) return i;\n }\n return -1;\n}\n\n// calculate node's bbox from bboxes of its children\nfunction calcBBox(node, toBBox) {\n distBBox(node, 0, node.children.length, toBBox, node);\n}\n\n// min bounding rectangle of node children from k to p-1\nfunction distBBox(node, k, p, toBBox, destNode) {\n if (!destNode) destNode = createNode(null);\n destNode.minX = Infinity;\n destNode.minY = Infinity;\n destNode.maxX = -Infinity;\n destNode.maxY = -Infinity;\n\n for (let i = k; i < p; i++) {\n const child = node.children[i];\n extend(destNode, node.leaf ? toBBox(child) : child);\n }\n\n return destNode;\n}\n\nfunction extend(a, b) {\n a.minX = Math.min(a.minX, b.minX);\n a.minY = Math.min(a.minY, b.minY);\n a.maxX = Math.max(a.maxX, b.maxX);\n a.maxY = Math.max(a.maxY, b.maxY);\n return a;\n}\n\nfunction compareNodeMinX(a, b) { return a.minX - b.minX; }\nfunction compareNodeMinY(a, b) { return a.minY - b.minY; }\n\nfunction bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }\nfunction bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }\n\nfunction enlargedArea(a, b) {\n return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *\n (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));\n}\n\nfunction intersectionArea(a, b) {\n const minX = Math.max(a.minX, b.minX);\n const minY = Math.max(a.minY, b.minY);\n const maxX = Math.min(a.maxX, b.maxX);\n const maxY = Math.min(a.maxY, b.maxY);\n\n return Math.max(0, maxX - minX) *\n Math.max(0, maxY - minY);\n}\n\nfunction contains(a, b) {\n return a.minX <= b.minX &&\n a.minY <= b.minY &&\n b.maxX <= a.maxX &&\n b.maxY <= a.maxY;\n}\n\nfunction intersects(a, b) {\n return b.minX <= a.maxX &&\n b.minY <= a.maxY &&\n b.maxX >= a.minX &&\n b.maxY >= a.minY;\n}\n\nfunction createNode(children) {\n return {\n children,\n height: 1,\n leaf: true,\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity\n };\n}\n\n// sort an array so that items come in groups of n unsorted items, with groups sorted between each other;\n// combines selection algorithm with binary divide & conquer approach\n\nfunction multiSelect(arr, left, right, n, compare) {\n const stack = [left, right];\n\n while (stack.length) {\n right = stack.pop();\n left = stack.pop();\n\n if (right - left <= n) continue;\n\n const mid = left + Math.ceil((right - left) / n / 2) * n;\n quickselect(arr, mid, left, right, compare);\n\n stack.push(left, mid, mid, right);\n }\n}\n","// index.ts\nimport { bbox as calcBbox } from \"@turf/bbox\";\nimport { booleanPointOnLine } from \"@turf/boolean-point-on-line\";\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { getGeom } from \"@turf/invariant\";\nfunction booleanWithin(feature1, feature2) {\n var geom1 = getGeom(feature1);\n var geom2 = getGeom(feature2);\n var type1 = geom1.type;\n var type2 = geom2.type;\n switch (type1) {\n case \"Point\":\n switch (type2) {\n case \"MultiPoint\":\n return isPointInMultiPoint(geom1, geom2);\n case \"LineString\":\n return booleanPointOnLine(geom1, geom2, { ignoreEndVertices: true });\n case \"Polygon\":\n case \"MultiPolygon\":\n return booleanPointInPolygon(geom1, geom2, { ignoreBoundary: true });\n default:\n throw new Error(\"feature2 \" + type2 + \" geometry not supported\");\n }\n case \"MultiPoint\":\n switch (type2) {\n case \"MultiPoint\":\n return isMultiPointInMultiPoint(geom1, geom2);\n case \"LineString\":\n return isMultiPointOnLine(geom1, geom2);\n case \"Polygon\":\n case \"MultiPolygon\":\n return isMultiPointInPoly(geom1, geom2);\n default:\n throw new Error(\"feature2 \" + type2 + \" geometry not supported\");\n }\n case \"LineString\":\n switch (type2) {\n case \"LineString\":\n return isLineOnLine(geom1, geom2);\n case \"Polygon\":\n case \"MultiPolygon\":\n return isLineInPoly(geom1, geom2);\n default:\n throw new Error(\"feature2 \" + type2 + \" geometry not supported\");\n }\n case \"Polygon\":\n switch (type2) {\n case \"Polygon\":\n case \"MultiPolygon\":\n return isPolyInPoly(geom1, geom2);\n default:\n throw new Error(\"feature2 \" + type2 + \" geometry not supported\");\n }\n default:\n throw new Error(\"feature1 \" + type1 + \" geometry not supported\");\n }\n}\nfunction isPointInMultiPoint(point, multiPoint) {\n var i;\n var output = false;\n for (i = 0; i < multiPoint.coordinates.length; i++) {\n if (compareCoords(multiPoint.coordinates[i], point.coordinates)) {\n output = true;\n break;\n }\n }\n return output;\n}\nfunction isMultiPointInMultiPoint(multiPoint1, multiPoint2) {\n for (var i = 0; i < multiPoint1.coordinates.length; i++) {\n var anyMatch = false;\n for (var i2 = 0; i2 < multiPoint2.coordinates.length; i2++) {\n if (compareCoords(multiPoint1.coordinates[i], multiPoint2.coordinates[i2])) {\n anyMatch = true;\n }\n }\n if (!anyMatch) {\n return false;\n }\n }\n return true;\n}\nfunction isMultiPointOnLine(multiPoint, lineString) {\n var foundInsidePoint = false;\n for (var i = 0; i < multiPoint.coordinates.length; i++) {\n if (!booleanPointOnLine(multiPoint.coordinates[i], lineString)) {\n return false;\n }\n if (!foundInsidePoint) {\n foundInsidePoint = booleanPointOnLine(\n multiPoint.coordinates[i],\n lineString,\n { ignoreEndVertices: true }\n );\n }\n }\n return foundInsidePoint;\n}\nfunction isMultiPointInPoly(multiPoint, polygon) {\n var output = true;\n var oneInside = false;\n var isInside = false;\n for (var i = 0; i < multiPoint.coordinates.length; i++) {\n isInside = booleanPointInPolygon(multiPoint.coordinates[i], polygon);\n if (!isInside) {\n output = false;\n break;\n }\n if (!oneInside) {\n isInside = booleanPointInPolygon(multiPoint.coordinates[i], polygon, {\n ignoreBoundary: true\n });\n }\n }\n return output && isInside;\n}\nfunction isLineOnLine(lineString1, lineString2) {\n for (var i = 0; i < lineString1.coordinates.length; i++) {\n if (!booleanPointOnLine(lineString1.coordinates[i], lineString2)) {\n return false;\n }\n }\n return true;\n}\nfunction isLineInPoly(linestring, polygon) {\n var polyBbox = calcBbox(polygon);\n var lineBbox = calcBbox(linestring);\n if (!doBBoxOverlap(polyBbox, lineBbox)) {\n return false;\n }\n var foundInsidePoint = false;\n for (var i = 0; i < linestring.coordinates.length; i++) {\n if (!booleanPointInPolygon(linestring.coordinates[i], polygon)) {\n return false;\n }\n if (!foundInsidePoint) {\n foundInsidePoint = booleanPointInPolygon(\n linestring.coordinates[i],\n polygon,\n { ignoreBoundary: true }\n );\n }\n if (!foundInsidePoint && i < linestring.coordinates.length - 1) {\n var midpoint = getMidpoint(\n linestring.coordinates[i],\n linestring.coordinates[i + 1]\n );\n foundInsidePoint = booleanPointInPolygon(midpoint, polygon, {\n ignoreBoundary: true\n });\n }\n }\n return foundInsidePoint;\n}\nfunction isPolyInPoly(geometry1, geometry2) {\n var poly1Bbox = calcBbox(geometry1);\n var poly2Bbox = calcBbox(geometry2);\n if (!doBBoxOverlap(poly2Bbox, poly1Bbox)) {\n return false;\n }\n for (var i = 0; i < geometry1.coordinates[0].length; i++) {\n if (!booleanPointInPolygon(geometry1.coordinates[0][i], geometry2)) {\n return false;\n }\n }\n return true;\n}\nfunction doBBoxOverlap(bbox1, bbox2) {\n if (bbox1[0] > bbox2[0])\n return false;\n if (bbox1[2] < bbox2[2])\n return false;\n if (bbox1[1] > bbox2[1])\n return false;\n if (bbox1[3] < bbox2[3])\n return false;\n return true;\n}\nfunction compareCoords(pair1, pair2) {\n return pair1[0] === pair2[0] && pair1[1] === pair2[1];\n}\nfunction getMidpoint(pair1, pair2) {\n return [(pair1[0] + pair2[0]) / 2, (pair1[1] + pair2[1]) / 2];\n}\nvar turf_boolean_within_default = booleanWithin;\nexport {\n booleanWithin,\n turf_boolean_within_default as default\n};\n//# sourceMappingURL=index.js.map","\nexport default class TinyQueue {\n constructor(data = [], compare = defaultCompare) {\n this.data = data;\n this.length = this.data.length;\n this.compare = compare;\n\n if (this.length > 0) {\n for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);\n }\n }\n\n push(item) {\n this.data.push(item);\n this.length++;\n this._up(this.length - 1);\n }\n\n pop() {\n if (this.length === 0) return undefined;\n\n const top = this.data[0];\n const bottom = this.data.pop();\n this.length--;\n\n if (this.length > 0) {\n this.data[0] = bottom;\n this._down(0);\n }\n\n return top;\n }\n\n peek() {\n return this.data[0];\n }\n\n _up(pos) {\n const {data, compare} = this;\n const item = data[pos];\n\n while (pos > 0) {\n const parent = (pos - 1) >> 1;\n const current = data[parent];\n if (compare(item, current) >= 0) break;\n data[pos] = current;\n pos = parent;\n }\n\n data[pos] = item;\n }\n\n _down(pos) {\n const {data, compare} = this;\n const halfLength = this.length >> 1;\n const item = data[pos];\n\n while (pos < halfLength) {\n let left = (pos << 1) + 1;\n let best = data[left];\n const right = left + 1;\n\n if (right < this.length && compare(data[right], best) < 0) {\n left = right;\n best = data[right];\n }\n if (compare(best, item) >= 0) break;\n\n data[pos] = best;\n pos = left;\n }\n\n data[pos] = item;\n }\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","module.exports = function pointInPolygonFlat (point, vs, start, end) {\n var x = point[0], y = point[1];\n var inside = false;\n if (start === undefined) start = 0;\n if (end === undefined) end = vs.length;\n var len = (end-start)/2;\n for (var i = 0, j = len - 1; i < len; j = i++) {\n var xi = vs[start+i*2+0], yi = vs[start+i*2+1];\n var xj = vs[start+j*2+0], yj = vs[start+j*2+1];\n var intersect = ((yi > y) !== (yj > y))\n && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);\n if (intersect) inside = !inside;\n }\n return inside;\n};\n","// ray-casting algorithm based on\n// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html\n\nmodule.exports = function pointInPolygonNested (point, vs, start, end) {\n var x = point[0], y = point[1];\n var inside = false;\n if (start === undefined) start = 0;\n if (end === undefined) end = vs.length;\n var len = end - start;\n for (var i = 0, j = len - 1; i < len; j = i++) {\n var xi = vs[i+start][0], yi = vs[i+start][1];\n var xj = vs[j+start][0], yj = vs[j+start][1];\n var intersect = ((yi > y) !== (yj > y))\n && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);\n if (intersect) inside = !inside;\n }\n return inside;\n};\n","var pointInPolygonFlat = require('./flat.js')\nvar pointInPolygonNested = require('./nested.js')\n\nmodule.exports = function pointInPolygon (point, vs, start, end) {\n if (vs.length > 0 && Array.isArray(vs[0])) {\n return pointInPolygonNested(point, vs, start, end);\n } else {\n return pointInPolygonFlat(point, vs, start, end);\n }\n}\nmodule.exports.nested = pointInPolygonNested\nmodule.exports.flat = pointInPolygonFlat\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?e(exports):\"function\"==typeof define&&define.amd?define([\"exports\"],e):e((t=t||self).predicates={})}(this,function(t){\"use strict\";const e=134217729,n=33306690738754706e-32;function r(t,e,n,r,o){let f,i,u,c,s=e[0],a=r[0],d=0,l=0;a>s==a>-s?(f=s,s=e[++d]):(f=a,a=r[++l]);let p=0;if(ds==a>-s?(u=f-((i=s+f)-s),s=e[++d]):(u=f-((i=a+f)-a),a=r[++l]),f=i,0!==u&&(o[p++]=u);ds==a>-s?(u=f-((i=f+s)-(c=i-f))+(s-c),s=e[++d]):(u=f-((i=f+a)-(c=i-f))+(a-c),a=r[++l]),f=i,0!==u&&(o[p++]=u);for(;d0!=x>0)return j;const m=Math.abs(M+x);return Math.abs(j)>=f*m?j:-function(t,o,f,p,b,y,h){let M,x,j,m,_,v,w,A,F,O,P,g,k,q,z,B,C,D;const E=t-b,G=f-b,H=o-y,I=p-y;_=(z=(A=E-(w=(v=e*E)-(v-E)))*(O=I-(F=(v=e*I)-(v-I)))-((q=E*I)-w*F-A*F-w*O))-(P=z-(C=(A=H-(w=(v=e*H)-(v-H)))*(O=G-(F=(v=e*G)-(v-G)))-((B=H*G)-w*F-A*F-w*O))),c[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),c[1]=k-(P+_)+(_-B),_=(D=g+P)-g,c[2]=g-(D-_)+(P-_),c[3]=D;let J=function(t,e){let n=e[0];for(let r=1;r=K||-J>=K)return J;if(M=t-(E+(_=t-E))+(_-b),j=f-(G+(_=f-G))+(_-b),x=o-(H+(_=o-H))+(_-y),m=p-(I+(_=p-I))+(_-y),0===M&&0===x&&0===j&&0===m)return J;if(K=u*h+n*Math.abs(J),(J+=E*m+I*M-(H*j+G*x))>=K||-J>=K)return J;_=(z=(A=M-(w=(v=e*M)-(v-M)))*(O=I-(F=(v=e*I)-(v-I)))-((q=M*I)-w*F-A*F-w*O))-(P=z-(C=(A=x-(w=(v=e*x)-(v-x)))*(O=G-(F=(v=e*G)-(v-G)))-((B=x*G)-w*F-A*F-w*O))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),l[1]=k-(P+_)+(_-B),_=(D=g+P)-g,l[2]=g-(D-_)+(P-_),l[3]=D;const L=r(4,c,4,l,s);_=(z=(A=E-(w=(v=e*E)-(v-E)))*(O=m-(F=(v=e*m)-(v-m)))-((q=E*m)-w*F-A*F-w*O))-(P=z-(C=(A=H-(w=(v=e*H)-(v-H)))*(O=j-(F=(v=e*j)-(v-j)))-((B=H*j)-w*F-A*F-w*O))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),l[1]=k-(P+_)+(_-B),_=(D=g+P)-g,l[2]=g-(D-_)+(P-_),l[3]=D;const N=r(L,s,4,l,a);_=(z=(A=M-(w=(v=e*M)-(v-M)))*(O=m-(F=(v=e*m)-(v-m)))-((q=M*m)-w*F-A*F-w*O))-(P=z-(C=(A=x-(w=(v=e*x)-(v-x)))*(O=j-(F=(v=e*j)-(v-j)))-((B=x*j)-w*F-A*F-w*O))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),l[1]=k-(P+_)+(_-B),_=(D=g+P)-g,l[2]=g-(D-_)+(P-_),l[3]=D;const Q=r(N,a,4,l,d);return d[Q-1]}(t,o,p,b,y,h,m)},t.orient2dfast=function(t,e,n,r,o,f){return(e-f)*(n-o)-(t-o)*(r-f)},Object.defineProperty(t,\"__esModule\",{value:!0})});\n","'use strict';\n\nvar RBush = require('rbush');\nvar Queue = require('tinyqueue');\nvar pointInPolygon = require('point-in-polygon');\nvar orient = require('robust-predicates/umd/orient2d.min.js').orient2d;\n\n// Fix for require issue in webpack https://github.com/mapbox/concaveman/issues/18\nif (Queue.default) {\n Queue = Queue.default;\n}\n\nmodule.exports = concaveman;\nmodule.exports.default = concaveman;\n\nfunction concaveman(points, concavity, lengthThreshold) {\n // a relative measure of concavity; higher value means simpler hull\n concavity = Math.max(0, concavity === undefined ? 2 : concavity);\n\n // when a segment goes below this length threshold, it won't be drilled down further\n lengthThreshold = lengthThreshold || 0;\n\n // start with a convex hull of the points\n var hull = fastConvexHull(points);\n\n // index the points with an R-tree\n var tree = new RBush(16);\n tree.toBBox = function (a) {\n return {\n minX: a[0],\n minY: a[1],\n maxX: a[0],\n maxY: a[1]\n };\n };\n tree.compareMinX = function (a, b) { return a[0] - b[0]; };\n tree.compareMinY = function (a, b) { return a[1] - b[1]; };\n\n tree.load(points);\n\n // turn the convex hull into a linked list and populate the initial edge queue with the nodes\n var queue = [];\n for (var i = 0, last; i < hull.length; i++) {\n var p = hull[i];\n tree.remove(p);\n last = insertNode(p, last);\n queue.push(last);\n }\n\n // index the segments with an R-tree (for intersection checks)\n var segTree = new RBush(16);\n for (i = 0; i < queue.length; i++) segTree.insert(updateBBox(queue[i]));\n\n var sqConcavity = concavity * concavity;\n var sqLenThreshold = lengthThreshold * lengthThreshold;\n\n // process edges one by one\n while (queue.length) {\n var node = queue.shift();\n var a = node.p;\n var b = node.next.p;\n\n // skip the edge if it's already short enough\n var sqLen = getSqDist(a, b);\n if (sqLen < sqLenThreshold) continue;\n\n var maxSqLen = sqLen / sqConcavity;\n\n // find the best connection point for the current edge to flex inward to\n p = findCandidate(tree, node.prev.p, a, b, node.next.next.p, maxSqLen, segTree);\n\n // if we found a connection and it satisfies our concavity measure\n if (p && Math.min(getSqDist(p, a), getSqDist(p, b)) <= maxSqLen) {\n // connect the edge endpoints through this point and add 2 new edges to the queue\n queue.push(node);\n queue.push(insertNode(p, node));\n\n // update point and segment indexes\n tree.remove(p);\n segTree.remove(node);\n segTree.insert(updateBBox(node));\n segTree.insert(updateBBox(node.next));\n }\n }\n\n // convert the resulting hull linked list to an array of points\n node = last;\n var concave = [];\n do {\n concave.push(node.p);\n node = node.next;\n } while (node !== last);\n\n concave.push(node.p);\n\n return concave;\n}\n\nfunction findCandidate(tree, a, b, c, d, maxDist, segTree) {\n var queue = new Queue([], compareDist);\n var node = tree.data;\n\n // search through the point R-tree with a depth-first search using a priority queue\n // in the order of distance to the edge (b, c)\n while (node) {\n for (var i = 0; i < node.children.length; i++) {\n var child = node.children[i];\n\n var dist = node.leaf ? sqSegDist(child, b, c) : sqSegBoxDist(b, c, child);\n if (dist > maxDist) continue; // skip the node if it's farther than we ever need\n\n queue.push({\n node: child,\n dist: dist\n });\n }\n\n while (queue.length && !queue.peek().node.children) {\n var item = queue.pop();\n var p = item.node;\n\n // skip all points that are as close to adjacent edges (a,b) and (c,d),\n // and points that would introduce self-intersections when connected\n var d0 = sqSegDist(p, a, b);\n var d1 = sqSegDist(p, c, d);\n if (item.dist < d0 && item.dist < d1 &&\n noIntersections(b, p, segTree) &&\n noIntersections(c, p, segTree)) return p;\n }\n\n node = queue.pop();\n if (node) node = node.node;\n }\n\n return null;\n}\n\nfunction compareDist(a, b) {\n return a.dist - b.dist;\n}\n\n// square distance from a segment bounding box to the given one\nfunction sqSegBoxDist(a, b, bbox) {\n if (inside(a, bbox) || inside(b, bbox)) return 0;\n var d1 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.maxX, bbox.minY);\n if (d1 === 0) return 0;\n var d2 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.minX, bbox.maxY);\n if (d2 === 0) return 0;\n var d3 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.maxX, bbox.minY, bbox.maxX, bbox.maxY);\n if (d3 === 0) return 0;\n var d4 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.maxY, bbox.maxX, bbox.maxY);\n if (d4 === 0) return 0;\n return Math.min(d1, d2, d3, d4);\n}\n\nfunction inside(a, bbox) {\n return a[0] >= bbox.minX &&\n a[0] <= bbox.maxX &&\n a[1] >= bbox.minY &&\n a[1] <= bbox.maxY;\n}\n\n// check if the edge (a,b) doesn't intersect any other edges\nfunction noIntersections(a, b, segTree) {\n var minX = Math.min(a[0], b[0]);\n var minY = Math.min(a[1], b[1]);\n var maxX = Math.max(a[0], b[0]);\n var maxY = Math.max(a[1], b[1]);\n\n var edges = segTree.search({minX: minX, minY: minY, maxX: maxX, maxY: maxY});\n for (var i = 0; i < edges.length; i++) {\n if (intersects(edges[i].p, edges[i].next.p, a, b)) return false;\n }\n return true;\n}\n\nfunction cross(p1, p2, p3) {\n return orient(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);\n}\n\n// check if the edges (p1,q1) and (p2,q2) intersect\nfunction intersects(p1, q1, p2, q2) {\n return p1 !== q2 && q1 !== p2 &&\n cross(p1, q1, p2) > 0 !== cross(p1, q1, q2) > 0 &&\n cross(p2, q2, p1) > 0 !== cross(p2, q2, q1) > 0;\n}\n\n// update the bounding box of a node's edge\nfunction updateBBox(node) {\n var p1 = node.p;\n var p2 = node.next.p;\n node.minX = Math.min(p1[0], p2[0]);\n node.minY = Math.min(p1[1], p2[1]);\n node.maxX = Math.max(p1[0], p2[0]);\n node.maxY = Math.max(p1[1], p2[1]);\n return node;\n}\n\n// speed up convex hull by filtering out points inside quadrilateral formed by 4 extreme points\nfunction fastConvexHull(points) {\n var left = points[0];\n var top = points[0];\n var right = points[0];\n var bottom = points[0];\n\n // find the leftmost, rightmost, topmost and bottommost points\n for (var i = 0; i < points.length; i++) {\n var p = points[i];\n if (p[0] < left[0]) left = p;\n if (p[0] > right[0]) right = p;\n if (p[1] < top[1]) top = p;\n if (p[1] > bottom[1]) bottom = p;\n }\n\n // filter out points that are inside the resulting quadrilateral\n var cull = [left, top, right, bottom];\n var filtered = cull.slice();\n for (i = 0; i < points.length; i++) {\n if (!pointInPolygon(points[i], cull)) filtered.push(points[i]);\n }\n\n // get convex hull around the filtered points\n return convexHull(filtered);\n}\n\n// create a new node in a doubly linked list\nfunction insertNode(p, prev) {\n var node = {\n p: p,\n prev: null,\n next: null,\n minX: 0,\n minY: 0,\n maxX: 0,\n maxY: 0\n };\n\n if (!prev) {\n node.prev = node;\n node.next = node;\n\n } else {\n node.next = prev.next;\n node.prev = prev;\n prev.next.prev = node;\n prev.next = node;\n }\n return node;\n}\n\n// square distance between 2 points\nfunction getSqDist(p1, p2) {\n\n var dx = p1[0] - p2[0],\n dy = p1[1] - p2[1];\n\n return dx * dx + dy * dy;\n}\n\n// square distance from a point to a segment\nfunction sqSegDist(p, p1, p2) {\n\n var x = p1[0],\n y = p1[1],\n dx = p2[0] - x,\n dy = p2[1] - y;\n\n if (dx !== 0 || dy !== 0) {\n\n var t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);\n\n if (t > 1) {\n x = p2[0];\n y = p2[1];\n\n } else if (t > 0) {\n x += dx * t;\n y += dy * t;\n }\n }\n\n dx = p[0] - x;\n dy = p[1] - y;\n\n return dx * dx + dy * dy;\n}\n\n// segment to segment distance, ported from http://geomalgorithms.com/a07-_distance.html by Dan Sunday\nfunction sqSegSegDist(x0, y0, x1, y1, x2, y2, x3, y3) {\n var ux = x1 - x0;\n var uy = y1 - y0;\n var vx = x3 - x2;\n var vy = y3 - y2;\n var wx = x0 - x2;\n var wy = y0 - y2;\n var a = ux * ux + uy * uy;\n var b = ux * vx + uy * vy;\n var c = vx * vx + vy * vy;\n var d = ux * wx + uy * wy;\n var e = vx * wx + vy * wy;\n var D = a * c - b * b;\n\n var sc, sN, tc, tN;\n var sD = D;\n var tD = D;\n\n if (D === 0) {\n sN = 0;\n sD = 1;\n tN = e;\n tD = c;\n } else {\n sN = b * e - c * d;\n tN = a * e - b * d;\n if (sN < 0) {\n sN = 0;\n tN = e;\n tD = c;\n } else if (sN > sD) {\n sN = sD;\n tN = e + b;\n tD = c;\n }\n }\n\n if (tN < 0.0) {\n tN = 0.0;\n if (-d < 0.0) sN = 0.0;\n else if (-d > a) sN = sD;\n else {\n sN = -d;\n sD = a;\n }\n } else if (tN > tD) {\n tN = tD;\n if ((-d + b) < 0.0) sN = 0;\n else if (-d + b > a) sN = sD;\n else {\n sN = -d + b;\n sD = a;\n }\n }\n\n sc = sN === 0 ? 0 : sN / sD;\n tc = tN === 0 ? 0 : tN / tD;\n\n var cx = (1 - sc) * x0 + sc * x1;\n var cy = (1 - sc) * y0 + sc * y1;\n var cx2 = (1 - tc) * x2 + tc * x3;\n var cy2 = (1 - tc) * y2 + tc * y3;\n var dx = cx2 - cx;\n var dy = cy2 - cy;\n\n return dx * dx + dy * dy;\n}\n\nfunction compareByX(a, b) {\n return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0];\n}\n\nfunction convexHull(points) {\n points.sort(compareByX);\n\n var lower = [];\n for (var i = 0; i < points.length; i++) {\n while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) {\n lower.pop();\n }\n lower.push(points[i]);\n }\n\n var upper = [];\n for (var ii = points.length - 1; ii >= 0; ii--) {\n while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[ii]) <= 0) {\n upper.pop();\n }\n upper.push(points[ii]);\n }\n\n upper.pop();\n lower.pop();\n return lower.concat(upper);\n}\n","// index.ts\nimport { polygon } from \"@turf/helpers\";\nimport { coordEach } from \"@turf/meta\";\nimport concaveman from \"concaveman\";\nfunction convex(geojson, options = {}) {\n options.concavity = options.concavity || Infinity;\n const points = [];\n coordEach(geojson, (coord) => {\n points.push([coord[0], coord[1]]);\n });\n if (!points.length) {\n return null;\n }\n const convexHull = concaveman(points, options.concavity);\n if (convexHull.length > 3) {\n return polygon([convexHull]);\n }\n return null;\n}\nvar turf_convex_default = convex;\nexport {\n convex,\n turf_convex_default as default\n};\n//# sourceMappingURL=index.js.map","// index.ts\nimport { convex } from \"@turf/convex\";\nimport { centroid } from \"@turf/centroid\";\nimport { point } from \"@turf/helpers\";\nimport { getType, getCoord } from \"@turf/invariant\";\nimport { coordEach } from \"@turf/meta\";\nfunction centerOfMass(geojson, options = {}) {\n switch (getType(geojson)) {\n case \"Point\":\n return point(getCoord(geojson), options.properties);\n case \"Polygon\":\n var coords = [];\n coordEach(geojson, function(coord) {\n coords.push(coord);\n });\n var centre = centroid(geojson, { properties: options.properties });\n var translation = centre.geometry.coordinates;\n var sx = 0;\n var sy = 0;\n var sArea = 0;\n var i, pi, pj, xi, xj, yi, yj, a;\n var neutralizedPoints = coords.map(function(point2) {\n return [point2[0] - translation[0], point2[1] - translation[1]];\n });\n for (i = 0; i < coords.length - 1; i++) {\n pi = neutralizedPoints[i];\n xi = pi[0];\n yi = pi[1];\n pj = neutralizedPoints[i + 1];\n xj = pj[0];\n yj = pj[1];\n a = xi * yj - xj * yi;\n sArea += a;\n sx += (xi + xj) * a;\n sy += (yi + yj) * a;\n }\n if (sArea === 0) {\n return centre;\n } else {\n var area = sArea * 0.5;\n var areaFactor = 1 / (6 * area);\n return point(\n [translation[0] + areaFactor * sx, translation[1] + areaFactor * sy],\n options.properties\n );\n }\n default:\n var hull = convex(geojson);\n if (hull)\n return centerOfMass(hull, { properties: options.properties });\n else\n return centroid(geojson, { properties: options.properties });\n }\n}\nvar turf_center_of_mass_default = centerOfMass;\nexport {\n centerOfMass,\n turf_center_of_mass_default as default\n};\n//# sourceMappingURL=index.js.map","// index.ts\nimport { booleanWithin as within } from \"@turf/boolean-within\";\nimport { distance } from \"@turf/distance\";\nimport { point, featureCollection } from \"@turf/helpers\";\nfunction pointGrid(bbox, cellSide, options = {}) {\n if (options.mask && !options.units)\n options.units = \"kilometers\";\n var results = [];\n var west = bbox[0];\n var south = bbox[1];\n var east = bbox[2];\n var north = bbox[3];\n var xFraction = cellSide / distance([west, south], [east, south], options);\n var cellWidth = xFraction * (east - west);\n var yFraction = cellSide / distance([west, south], [west, north], options);\n var cellHeight = yFraction * (north - south);\n var bboxWidth = east - west;\n var bboxHeight = north - south;\n var columns = Math.floor(bboxWidth / cellWidth);\n var rows = Math.floor(bboxHeight / cellHeight);\n var deltaX = (bboxWidth - columns * cellWidth) / 2;\n var deltaY = (bboxHeight - rows * cellHeight) / 2;\n var currentX = west + deltaX;\n while (currentX <= east) {\n var currentY = south + deltaY;\n while (currentY <= north) {\n var cellPt = point([currentX, currentY], options.properties);\n if (options.mask) {\n if (within(cellPt, options.mask))\n results.push(cellPt);\n } else {\n results.push(cellPt);\n }\n currentY += cellHeight;\n }\n currentX += cellWidth;\n }\n return featureCollection(results);\n}\nvar turf_point_grid_default = pointGrid;\nexport {\n turf_point_grid_default as default,\n pointGrid\n};\n//# sourceMappingURL=index.js.map","// index.ts\nimport { point } from \"@turf/helpers\";\nfunction kinks(featureIn) {\n let coordinates;\n let feature;\n const results = {\n type: \"FeatureCollection\",\n features: []\n };\n if (featureIn.type === \"Feature\") {\n feature = featureIn.geometry;\n } else {\n feature = featureIn;\n }\n if (feature.type === \"LineString\") {\n coordinates = [feature.coordinates];\n } else if (feature.type === \"MultiLineString\") {\n coordinates = feature.coordinates;\n } else if (feature.type === \"MultiPolygon\") {\n coordinates = [].concat(...feature.coordinates);\n } else if (feature.type === \"Polygon\") {\n coordinates = feature.coordinates;\n } else {\n throw new Error(\n \"Input must be a LineString, MultiLineString, Polygon, or MultiPolygon Feature or Geometry\"\n );\n }\n coordinates.forEach((line1) => {\n coordinates.forEach((line2) => {\n for (let i = 0; i < line1.length - 1; i++) {\n for (let k = i; k < line2.length - 1; k++) {\n if (line1 === line2) {\n if (Math.abs(i - k) === 1) {\n continue;\n }\n if (\n // segments are first and last segment of lineString\n i === 0 && k === line1.length - 2 && // lineString is closed\n line1[i][0] === line1[line1.length - 1][0] && line1[i][1] === line1[line1.length - 1][1]\n ) {\n continue;\n }\n }\n const intersection = lineIntersects(\n line1[i][0],\n line1[i][1],\n line1[i + 1][0],\n line1[i + 1][1],\n line2[k][0],\n line2[k][1],\n line2[k + 1][0],\n line2[k + 1][1]\n );\n if (intersection) {\n results.features.push(point([intersection[0], intersection[1]]));\n }\n }\n }\n });\n });\n return results;\n}\nfunction lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) {\n let denominator;\n let a;\n let b;\n let numerator1;\n let numerator2;\n const result = {\n x: null,\n y: null,\n onLine1: false,\n onLine2: false\n };\n denominator = (line2EndY - line2StartY) * (line1EndX - line1StartX) - (line2EndX - line2StartX) * (line1EndY - line1StartY);\n if (denominator === 0) {\n if (result.x !== null && result.y !== null) {\n return result;\n } else {\n return false;\n }\n }\n a = line1StartY - line2StartY;\n b = line1StartX - line2StartX;\n numerator1 = (line2EndX - line2StartX) * a - (line2EndY - line2StartY) * b;\n numerator2 = (line1EndX - line1StartX) * a - (line1EndY - line1StartY) * b;\n a = numerator1 / denominator;\n b = numerator2 / denominator;\n result.x = line1StartX + a * (line1EndX - line1StartX);\n result.y = line1StartY + a * (line1EndY - line1StartY);\n if (a >= 0 && a <= 1) {\n result.onLine1 = true;\n }\n if (b >= 0 && b <= 1) {\n result.onLine2 = true;\n }\n if (result.onLine1 && result.onLine2) {\n return [result.x, result.y];\n } else {\n return false;\n }\n}\nvar turf_kinks_default = kinks;\nexport {\n turf_kinks_default as default,\n kinks\n};\n//# sourceMappingURL=index.js.map","'use strict';\n\nmodule.exports = earcut;\nmodule.exports.default = earcut;\n\nfunction earcut(data, holeIndices, dim) {\n\n dim = dim || 2;\n\n var hasHoles = holeIndices && holeIndices.length,\n outerLen = hasHoles ? holeIndices[0] * dim : data.length,\n outerNode = linkedList(data, 0, outerLen, dim, true),\n triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n var minX, minY, maxX, maxY, x, y, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = maxX = data[0];\n minY = maxY = data[1];\n\n for (var i = dim; i < outerLen; i += dim) {\n x = data[i];\n y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n var i, last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);\n } else {\n for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n var p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n var stop = ear,\n prev, next;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n prev = ear.prev;\n next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n // cut off the triangle\n triangles.push(prev.i / dim | 0);\n triangles.push(ear.i / dim | 0);\n triangles.push(next.i / dim | 0);\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles, dim);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n var a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox; min & max are calculated like this for speed\n var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),\n y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),\n x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),\n y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);\n\n var p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n var a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox; min & max are calculated like this for speed\n var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),\n y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),\n x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),\n y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);\n\n // z-order range for the current triangle bbox;\n var minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n var p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles, dim) {\n var p = start;\n do {\n var a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i / dim | 0);\n triangles.push(p.i / dim | 0);\n triangles.push(b.i / dim | 0);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n var a = start;\n do {\n var b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n var c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n var queue = [],\n i, len, start, end, list;\n\n for (i = 0, len = holeIndices.length; i < len; i++) {\n start = holeIndices[i] * dim;\n end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareX);\n\n // process holes from left to right\n for (i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareX(a, b) {\n return a.x - b.x;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and and link it\nfunction eliminateHole(hole, outerNode) {\n var bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n var bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n var p = outerNode,\n hx = hole.x,\n hy = hole.y,\n qx = -Infinity,\n m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n do {\n if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n var stop = m,\n mx = m.x,\n my = m.y,\n tanMin = Infinity,\n tan;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n var p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n var i, p, q, e, tail, numMerges, pSize, qSize,\n inSize = 1;\n\n do {\n p = list;\n list = null;\n tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n q = p;\n pSize = 0;\n for (i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n var p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n var o1 = sign(area(p1, q1, p2));\n var o2 = sign(area(p1, q1, q2));\n var o3 = sign(area(p2, q2, p1));\n var o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n var p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n var p = a,\n inside = false,\n px = (a.x + b.x) / 2,\n py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n var a2 = new Node(a.i, a.x, a.y),\n b2 = new Node(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n var p = new Node(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction Node(i, x, y) {\n // vertex index in coordinates array\n this.i = i;\n\n // vertex coordinates\n this.x = x;\n this.y = y;\n\n // previous and next vertex nodes in a polygon ring\n this.prev = null;\n this.next = null;\n\n // z-order curve value\n this.z = 0;\n\n // previous and next nodes in z-order\n this.prevZ = null;\n this.nextZ = null;\n\n // indicates whether this is a steiner point\n this.steiner = false;\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nearcut.deviation = function (data, holeIndices, dim, triangles) {\n var hasHoles = holeIndices && holeIndices.length;\n var outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (var i = 0, len = holeIndices.length; i < len; i++) {\n var start = holeIndices[i] * dim;\n var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n var trianglesArea = 0;\n for (i = 0; i < triangles.length; i += 3) {\n var a = triangles[i] * dim;\n var b = triangles[i + 1] * dim;\n var c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n};\n\nfunction signedArea(data, start, end, dim) {\n var sum = 0;\n for (var i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nearcut.flatten = function (data) {\n var dim = data[0][0].length,\n result = {vertices: [], holes: [], dimensions: dim},\n holeIndex = 0;\n\n for (var i = 0; i < data.length; i++) {\n for (var j = 0; j < data[i].length; j++) {\n for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);\n }\n if (i > 0) {\n holeIndex += data[i - 1].length;\n result.holes.push(holeIndex);\n }\n }\n return result;\n};\n","// index.ts\nimport { flattenEach, featureEach } from \"@turf/meta\";\nimport { polygon as polygon2, featureCollection as featureCollection2 } from \"@turf/helpers\";\n\n// lib/geojson-polygon-self-intersections.js\nimport rbush from \"rbush\";\nfunction geojsonPolygonSelfIntersections(feature, filterFn, useSpatialIndex) {\n if (feature.geometry.type !== \"Polygon\")\n throw new Error(\"The input feature must be a Polygon\");\n if (useSpatialIndex === void 0)\n useSpatialIndex = 1;\n var coord = feature.geometry.coordinates;\n var output = [];\n var seen = {};\n if (useSpatialIndex) {\n var allEdgesAsRbushTreeItems = [];\n for (var ring0 = 0; ring0 < coord.length; ring0++) {\n for (var edge0 = 0; edge0 < coord[ring0].length - 1; edge0++) {\n allEdgesAsRbushTreeItems.push(rbushTreeItem(ring0, edge0));\n }\n }\n var tree = new rbush();\n tree.load(allEdgesAsRbushTreeItems);\n }\n for (var ringA = 0; ringA < coord.length; ringA++) {\n for (var edgeA = 0; edgeA < coord[ringA].length - 1; edgeA++) {\n if (useSpatialIndex) {\n var bboxOverlaps = tree.search(rbushTreeItem(ringA, edgeA));\n bboxOverlaps.forEach(function(bboxIsect) {\n var ring12 = bboxIsect.ring;\n var edge12 = bboxIsect.edge;\n ifIsectAddToOutput(ringA, edgeA, ring12, edge12);\n });\n } else {\n for (var ring1 = 0; ring1 < coord.length; ring1++) {\n for (var edge1 = 0; edge1 < coord[ring1].length - 1; edge1++) {\n ifIsectAddToOutput(ringA, edgeA, ring1, edge1);\n }\n }\n }\n }\n }\n if (!filterFn)\n output = {\n type: \"Feature\",\n geometry: { type: \"MultiPoint\", coordinates: output }\n };\n return output;\n function ifIsectAddToOutput(ring02, edge02, ring12, edge12) {\n var start0 = coord[ring02][edge02];\n var end0 = coord[ring02][edge02 + 1];\n var start1 = coord[ring12][edge12];\n var end1 = coord[ring12][edge12 + 1];\n var isect = intersect(start0, end0, start1, end1);\n if (isect === null)\n return;\n var frac0;\n var frac1;\n if (end0[0] !== start0[0]) {\n frac0 = (isect[0] - start0[0]) / (end0[0] - start0[0]);\n } else {\n frac0 = (isect[1] - start0[1]) / (end0[1] - start0[1]);\n }\n if (end1[0] !== start1[0]) {\n frac1 = (isect[0] - start1[0]) / (end1[0] - start1[0]);\n } else {\n frac1 = (isect[1] - start1[1]) / (end1[1] - start1[1]);\n }\n if (frac0 >= 1 || frac0 <= 0 || frac1 >= 1 || frac1 <= 0)\n return;\n var key = isect;\n var unique = !seen[key];\n if (unique) {\n seen[key] = true;\n }\n if (filterFn) {\n output.push(\n filterFn(\n isect,\n ring02,\n edge02,\n start0,\n end0,\n frac0,\n ring12,\n edge12,\n start1,\n end1,\n frac1,\n unique\n )\n );\n } else {\n output.push(isect);\n }\n }\n function rbushTreeItem(ring, edge) {\n var start = coord[ring][edge];\n var end = coord[ring][edge + 1];\n var minX;\n var maxX;\n var minY;\n var maxY;\n if (start[0] < end[0]) {\n minX = start[0];\n maxX = end[0];\n } else {\n minX = end[0];\n maxX = start[0];\n }\n if (start[1] < end[1]) {\n minY = start[1];\n maxY = end[1];\n } else {\n minY = end[1];\n maxY = start[1];\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n ring,\n edge\n };\n }\n}\nfunction intersect(start0, end0, start1, end1) {\n if (equalArrays(start0, start1) || equalArrays(start0, end1) || equalArrays(end0, start1) || equalArrays(end1, start1))\n return null;\n var x0 = start0[0], y0 = start0[1], x1 = end0[0], y1 = end0[1], x2 = start1[0], y2 = start1[1], x3 = end1[0], y3 = end1[1];\n var denom = (x0 - x1) * (y2 - y3) - (y0 - y1) * (x2 - x3);\n if (denom === 0)\n return null;\n var x4 = ((x0 * y1 - y0 * x1) * (x2 - x3) - (x0 - x1) * (x2 * y3 - y2 * x3)) / denom;\n var y4 = ((x0 * y1 - y0 * x1) * (y2 - y3) - (y0 - y1) * (x2 * y3 - y2 * x3)) / denom;\n return [x4, y4];\n}\nfunction equalArrays(array1, array2) {\n if (!array1 || !array2)\n return false;\n if (array1.length !== array2.length)\n return false;\n for (var i = 0, l = array1.length; i < l; i++) {\n if (array1[i] instanceof Array && array2[i] instanceof Array) {\n if (!equalArrays(array1[i], array2[i]))\n return false;\n } else if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\n// lib/simplepolygon.js\nimport { area } from \"@turf/area\";\nimport { featureCollection, polygon } from \"@turf/helpers\";\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport rbush2 from \"rbush\";\nfunction simplepolygon(feature) {\n if (feature.type != \"Feature\")\n throw new Error(\"The input must a geojson object of type Feature\");\n if (feature.geometry === void 0 || feature.geometry == null)\n throw new Error(\n \"The input must a geojson object with a non-empty geometry\"\n );\n if (feature.geometry.type != \"Polygon\")\n throw new Error(\"The input must be a geojson Polygon\");\n var numRings = feature.geometry.coordinates.length;\n var vertices = [];\n for (var i = 0; i < numRings; i++) {\n var ring = feature.geometry.coordinates[i];\n if (!equalArrays2(ring[0], ring[ring.length - 1])) {\n ring.push(ring[0]);\n }\n for (var j = 0; j < ring.length - 1; j++) {\n vertices.push(ring[j]);\n }\n }\n if (!isUnique(vertices))\n throw new Error(\n \"The input polygon may not have duplicate vertices (except for the first and last vertex of each ring)\"\n );\n var numvertices = vertices.length;\n var selfIsectsData = geojsonPolygonSelfIntersections(\n feature,\n function filterFn(isect, ring0, edge0, start0, end0, frac0, ring1, edge1, start1, end1, frac1, unique) {\n return [\n isect,\n ring0,\n edge0,\n start0,\n end0,\n frac0,\n ring1,\n edge1,\n start1,\n end1,\n frac1,\n unique\n ];\n }\n );\n var numSelfIsect = selfIsectsData.length;\n if (numSelfIsect == 0) {\n var outputFeatureArray = [];\n for (var i = 0; i < numRings; i++) {\n outputFeatureArray.push(\n polygon([feature.geometry.coordinates[i]], {\n parent: -1,\n winding: windingOfRing(feature.geometry.coordinates[i])\n })\n );\n }\n var output = featureCollection(outputFeatureArray);\n determineParents();\n setNetWinding();\n return output;\n }\n var pseudoVtxListByRingAndEdge = [];\n var isectList = [];\n for (var i = 0; i < numRings; i++) {\n pseudoVtxListByRingAndEdge.push([]);\n for (var j = 0; j < feature.geometry.coordinates[i].length - 1; j++) {\n pseudoVtxListByRingAndEdge[i].push([\n new PseudoVtx(\n feature.geometry.coordinates[i][modulo(j + 1, feature.geometry.coordinates[i].length - 1)],\n 1,\n [i, j],\n [i, modulo(j + 1, feature.geometry.coordinates[i].length - 1)],\n void 0\n )\n ]);\n isectList.push(\n new Isect(\n feature.geometry.coordinates[i][j],\n [i, modulo(j - 1, feature.geometry.coordinates[i].length - 1)],\n [i, j],\n void 0,\n void 0,\n false,\n true\n )\n );\n }\n }\n for (var i = 0; i < numSelfIsect; i++) {\n pseudoVtxListByRingAndEdge[selfIsectsData[i][1]][selfIsectsData[i][2]].push(\n new PseudoVtx(\n selfIsectsData[i][0],\n selfIsectsData[i][5],\n [selfIsectsData[i][1], selfIsectsData[i][2]],\n [selfIsectsData[i][6], selfIsectsData[i][7]],\n void 0\n )\n );\n if (selfIsectsData[i][11])\n isectList.push(\n new Isect(\n selfIsectsData[i][0],\n [selfIsectsData[i][1], selfIsectsData[i][2]],\n [selfIsectsData[i][6], selfIsectsData[i][7]],\n void 0,\n void 0,\n true,\n true\n )\n );\n }\n var numIsect = isectList.length;\n for (var i = 0; i < pseudoVtxListByRingAndEdge.length; i++) {\n for (var j = 0; j < pseudoVtxListByRingAndEdge[i].length; j++) {\n pseudoVtxListByRingAndEdge[i][j].sort(function(a, b) {\n return a.param < b.param ? -1 : 1;\n });\n }\n }\n var allIsectsAsIsectRbushTreeItem = [];\n for (var i = 0; i < numIsect; i++) {\n allIsectsAsIsectRbushTreeItem.push({\n minX: isectList[i].coord[0],\n minY: isectList[i].coord[1],\n maxX: isectList[i].coord[0],\n maxY: isectList[i].coord[1],\n index: i\n });\n }\n var isectRbushTree = new rbush2();\n isectRbushTree.load(allIsectsAsIsectRbushTreeItem);\n for (var i = 0; i < pseudoVtxListByRingAndEdge.length; i++) {\n for (var j = 0; j < pseudoVtxListByRingAndEdge[i].length; j++) {\n for (var k = 0; k < pseudoVtxListByRingAndEdge[i][j].length; k++) {\n var coordToFind;\n if (k == pseudoVtxListByRingAndEdge[i][j].length - 1) {\n coordToFind = pseudoVtxListByRingAndEdge[i][modulo(j + 1, feature.geometry.coordinates[i].length - 1)][0].coord;\n } else {\n coordToFind = pseudoVtxListByRingAndEdge[i][j][k + 1].coord;\n }\n var IsectRbushTreeItemFound = isectRbushTree.search({\n minX: coordToFind[0],\n minY: coordToFind[1],\n maxX: coordToFind[0],\n maxY: coordToFind[1]\n })[0];\n pseudoVtxListByRingAndEdge[i][j][k].nxtIsectAlongEdgeIn = IsectRbushTreeItemFound.index;\n }\n }\n }\n for (var i = 0; i < pseudoVtxListByRingAndEdge.length; i++) {\n for (var j = 0; j < pseudoVtxListByRingAndEdge[i].length; j++) {\n for (var k = 0; k < pseudoVtxListByRingAndEdge[i][j].length; k++) {\n var coordToFind = pseudoVtxListByRingAndEdge[i][j][k].coord;\n var IsectRbushTreeItemFound = isectRbushTree.search({\n minX: coordToFind[0],\n minY: coordToFind[1],\n maxX: coordToFind[0],\n maxY: coordToFind[1]\n })[0];\n var l = IsectRbushTreeItemFound.index;\n if (l < numvertices) {\n isectList[l].nxtIsectAlongRingAndEdge2 = pseudoVtxListByRingAndEdge[i][j][k].nxtIsectAlongEdgeIn;\n } else {\n if (equalArrays2(\n isectList[l].ringAndEdge1,\n pseudoVtxListByRingAndEdge[i][j][k].ringAndEdgeIn\n )) {\n isectList[l].nxtIsectAlongRingAndEdge1 = pseudoVtxListByRingAndEdge[i][j][k].nxtIsectAlongEdgeIn;\n } else {\n isectList[l].nxtIsectAlongRingAndEdge2 = pseudoVtxListByRingAndEdge[i][j][k].nxtIsectAlongEdgeIn;\n }\n }\n }\n }\n }\n var queue = [];\n var i = 0;\n for (var j = 0; j < numRings; j++) {\n var leftIsect = i;\n for (var k = 0; k < feature.geometry.coordinates[j].length - 1; k++) {\n if (isectList[i].coord[0] < isectList[leftIsect].coord[0]) {\n leftIsect = i;\n }\n i++;\n }\n var isectAfterLeftIsect = isectList[leftIsect].nxtIsectAlongRingAndEdge2;\n for (var k = 0; k < isectList.length; k++) {\n if (isectList[k].nxtIsectAlongRingAndEdge1 == leftIsect || isectList[k].nxtIsectAlongRingAndEdge2 == leftIsect) {\n var isectBeforeLeftIsect = k;\n break;\n }\n }\n var windingAtIsect = isConvex(\n [\n isectList[isectBeforeLeftIsect].coord,\n isectList[leftIsect].coord,\n isectList[isectAfterLeftIsect].coord\n ],\n true\n ) ? 1 : -1;\n queue.push({ isect: leftIsect, parent: -1, winding: windingAtIsect });\n }\n queue.sort(function(a, b) {\n return isectList[a.isect].coord > isectList[b.isect].coord ? -1 : 1;\n });\n var outputFeatureArray = [];\n while (queue.length > 0) {\n var popped = queue.pop();\n var startIsect = popped.isect;\n var currentOutputRingParent = popped.parent;\n var currentOutputRingWinding = popped.winding;\n var currentOutputRing = outputFeatureArray.length;\n var currentOutputRingCoords = [isectList[startIsect].coord];\n var currentIsect = startIsect;\n if (isectList[startIsect].ringAndEdge1Walkable) {\n var walkingRingAndEdge = isectList[startIsect].ringAndEdge1;\n var nxtIsect = isectList[startIsect].nxtIsectAlongRingAndEdge1;\n } else {\n var walkingRingAndEdge = isectList[startIsect].ringAndEdge2;\n var nxtIsect = isectList[startIsect].nxtIsectAlongRingAndEdge2;\n }\n while (!equalArrays2(isectList[startIsect].coord, isectList[nxtIsect].coord)) {\n currentOutputRingCoords.push(isectList[nxtIsect].coord);\n var nxtIsectInQueue = void 0;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].isect == nxtIsect) {\n nxtIsectInQueue = i;\n break;\n }\n }\n if (nxtIsectInQueue != void 0) {\n queue.splice(nxtIsectInQueue, 1);\n }\n if (equalArrays2(walkingRingAndEdge, isectList[nxtIsect].ringAndEdge1)) {\n walkingRingAndEdge = isectList[nxtIsect].ringAndEdge2;\n isectList[nxtIsect].ringAndEdge2Walkable = false;\n if (isectList[nxtIsect].ringAndEdge1Walkable) {\n var pushing = { isect: nxtIsect };\n if (isConvex(\n [\n isectList[currentIsect].coord,\n isectList[nxtIsect].coord,\n isectList[isectList[nxtIsect].nxtIsectAlongRingAndEdge2].coord\n ],\n currentOutputRingWinding == 1\n )) {\n pushing.parent = currentOutputRingParent;\n pushing.winding = -currentOutputRingWinding;\n } else {\n pushing.parent = currentOutputRing;\n pushing.winding = currentOutputRingWinding;\n }\n queue.push(pushing);\n }\n currentIsect = nxtIsect;\n nxtIsect = isectList[nxtIsect].nxtIsectAlongRingAndEdge2;\n } else {\n walkingRingAndEdge = isectList[nxtIsect].ringAndEdge1;\n isectList[nxtIsect].ringAndEdge1Walkable = false;\n if (isectList[nxtIsect].ringAndEdge2Walkable) {\n var pushing = { isect: nxtIsect };\n if (isConvex(\n [\n isectList[currentIsect].coord,\n isectList[nxtIsect].coord,\n isectList[isectList[nxtIsect].nxtIsectAlongRingAndEdge1].coord\n ],\n currentOutputRingWinding == 1\n )) {\n pushing.parent = currentOutputRingParent;\n pushing.winding = -currentOutputRingWinding;\n } else {\n pushing.parent = currentOutputRing;\n pushing.winding = currentOutputRingWinding;\n }\n queue.push(pushing);\n }\n currentIsect = nxtIsect;\n nxtIsect = isectList[nxtIsect].nxtIsectAlongRingAndEdge1;\n }\n }\n currentOutputRingCoords.push(isectList[nxtIsect].coord);\n outputFeatureArray.push(\n polygon([currentOutputRingCoords], {\n index: currentOutputRing,\n parent: currentOutputRingParent,\n winding: currentOutputRingWinding,\n netWinding: void 0\n })\n );\n }\n var output = featureCollection(outputFeatureArray);\n determineParents();\n setNetWinding();\n function determineParents() {\n var featuresWithoutParent = [];\n for (var i2 = 0; i2 < output.features.length; i2++) {\n if (output.features[i2].properties.parent == -1)\n featuresWithoutParent.push(i2);\n }\n if (featuresWithoutParent.length > 1) {\n for (var i2 = 0; i2 < featuresWithoutParent.length; i2++) {\n var parent = -1;\n var parentArea = Infinity;\n for (var j2 = 0; j2 < output.features.length; j2++) {\n if (featuresWithoutParent[i2] == j2)\n continue;\n if (booleanPointInPolygon(\n output.features[featuresWithoutParent[i2]].geometry.coordinates[0][0],\n output.features[j2],\n { ignoreBoundary: true }\n )) {\n if (area(output.features[j2]) < parentArea) {\n parent = j2;\n }\n }\n }\n output.features[featuresWithoutParent[i2]].properties.parent = parent;\n }\n }\n }\n function setNetWinding() {\n for (var i2 = 0; i2 < output.features.length; i2++) {\n if (output.features[i2].properties.parent == -1) {\n var netWinding = output.features[i2].properties.winding;\n output.features[i2].properties.netWinding = netWinding;\n setNetWindingOfChildren(i2, netWinding);\n }\n }\n }\n function setNetWindingOfChildren(parent, ParentNetWinding) {\n for (var i2 = 0; i2 < output.features.length; i2++) {\n if (output.features[i2].properties.parent == parent) {\n var netWinding = ParentNetWinding + output.features[i2].properties.winding;\n output.features[i2].properties.netWinding = netWinding;\n setNetWindingOfChildren(i2, netWinding);\n }\n }\n }\n return output;\n}\nvar PseudoVtx = function(coord, param, ringAndEdgeIn, ringAndEdgeOut, nxtIsectAlongEdgeIn) {\n this.coord = coord;\n this.param = param;\n this.ringAndEdgeIn = ringAndEdgeIn;\n this.ringAndEdgeOut = ringAndEdgeOut;\n this.nxtIsectAlongEdgeIn = nxtIsectAlongEdgeIn;\n};\nvar Isect = function(coord, ringAndEdge1, ringAndEdge2, nxtIsectAlongRingAndEdge1, nxtIsectAlongRingAndEdge2, ringAndEdge1Walkable, ringAndEdge2Walkable) {\n this.coord = coord;\n this.ringAndEdge1 = ringAndEdge1;\n this.ringAndEdge2 = ringAndEdge2;\n this.nxtIsectAlongRingAndEdge1 = nxtIsectAlongRingAndEdge1;\n this.nxtIsectAlongRingAndEdge2 = nxtIsectAlongRingAndEdge2;\n this.ringAndEdge1Walkable = ringAndEdge1Walkable;\n this.ringAndEdge2Walkable = ringAndEdge2Walkable;\n};\nfunction isConvex(pts, righthanded) {\n if (typeof righthanded === \"undefined\")\n righthanded = true;\n if (pts.length != 3)\n throw new Error(\"This function requires an array of three points [x,y]\");\n var d = (pts[1][0] - pts[0][0]) * (pts[2][1] - pts[0][1]) - (pts[1][1] - pts[0][1]) * (pts[2][0] - pts[0][0]);\n return d >= 0 == righthanded;\n}\nfunction windingOfRing(ring) {\n var leftVtx = 0;\n for (var i = 0; i < ring.length - 1; i++) {\n if (ring[i][0] < ring[leftVtx][0])\n leftVtx = i;\n }\n if (isConvex(\n [\n ring[modulo(leftVtx - 1, ring.length - 1)],\n ring[leftVtx],\n ring[modulo(leftVtx + 1, ring.length - 1)]\n ],\n true\n )) {\n var winding = 1;\n } else {\n var winding = -1;\n }\n return winding;\n}\nfunction equalArrays2(array1, array2) {\n if (!array1 || !array2)\n return false;\n if (array1.length != array2.length)\n return false;\n for (var i = 0, l = array1.length; i < l; i++) {\n if (array1[i] instanceof Array && array2[i] instanceof Array) {\n if (!equalArrays2(array1[i], array2[i]))\n return false;\n } else if (array1[i] != array2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction modulo(n, m) {\n return (n % m + m) % m;\n}\nfunction isUnique(array) {\n var u = {};\n var isUnique2 = 1;\n for (var i = 0, l = array.length; i < l; ++i) {\n if (Object.prototype.hasOwnProperty.call(u, array[i])) {\n isUnique2 = 0;\n break;\n }\n u[array[i]] = 1;\n }\n return isUnique2;\n}\n\n// index.ts\nfunction unkinkPolygon(geojson) {\n var features = [];\n flattenEach(geojson, function(feature) {\n if (feature.geometry.type !== \"Polygon\")\n return;\n featureEach(simplepolygon(feature), function(poly) {\n features.push(polygon2(poly.geometry.coordinates, feature.properties));\n });\n });\n return featureCollection2(features);\n}\nvar turf_unkink_polygon_default = unkinkPolygon;\nexport {\n turf_unkink_polygon_default as default,\n unkinkPolygon\n};\n//# sourceMappingURL=index.js.map","var e,t=\"undefined\"!=typeof window?window:void 0,i=\"undefined\"!=typeof globalThis?globalThis:t,r=Array.prototype,n=r.forEach,s=r.indexOf,o=null==i?void 0:i.navigator,a=null==i?void 0:i.document,l=null==i?void 0:i.location,u=null==i?void 0:i.fetch,c=null!=i&&i.XMLHttpRequest&&\"withCredentials\"in new i.XMLHttpRequest?i.XMLHttpRequest:void 0,d=null==i?void 0:i.AbortController,h=null==o?void 0:o.userAgent,_=null!=t?t:{},p={DEBUG:!1,LIB_VERSION:\"1.207.0\"},v=\"$copy_autocapture\",g=[\"$snapshot\",\"$pageview\",\"$pageleave\",\"$set\",\"survey dismissed\",\"survey sent\",\"survey shown\",\"$identify\",\"$groupidentify\",\"$create_alias\",\"$$client_ingestion_warning\",\"$web_experiment_applied\",\"$feature_enrollment_update\",\"$feature_flag_called\"];!function(e){e.GZipJS=\"gzip-js\",e.Base64=\"base64\"}(e||(e={}));var f=[\"fatal\",\"error\",\"warning\",\"log\",\"info\",\"debug\"];function m(e,t){return-1!==e.indexOf(t)}var b=function(e){return e.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g,\"\")},y=function(e){return e.replace(/^\\$/,\"\")};var w=Array.isArray,S=Object.prototype,E=S.hasOwnProperty,k=S.toString,x=w||function(e){return\"[object Array]\"===k.call(e)},I=e=>\"function\"==typeof e,C=e=>e===Object(e)&&!x(e),P=e=>{if(C(e)){for(var t in e)if(E.call(e,t))return!1;return!0}return!1},F=e=>void 0===e,R=e=>\"[object String]\"==k.call(e),T=e=>R(e)&&0===e.trim().length,$=e=>null===e,O=e=>F(e)||$(e),M=e=>\"[object Number]\"==k.call(e),L=e=>\"[object Boolean]\"===k.call(e),A=e=>e instanceof FormData,D=e=>m(g,e),N=e=>{var i={_log:function(i){if(t&&(p.DEBUG||_.POSTHOG_DEBUG)&&!F(t.console)&&t.console){for(var r=(\"__rrweb_original__\"in t.console[i]?t.console[i].__rrweb_original__:t.console[i]),n=arguments.length,s=new Array(n>1?n-1:0),o=1;o{i.error(\"You must initialize PostHog before calling \".concat(e))},createLogger:t=>N(\"\".concat(e,\" \").concat(t))};return i},q=N(\"[PostHog.js]\"),B=q.createLogger,H=B(\"[ExternalScriptsLoader]\"),U=(e,t,i)=>{if(e.config.disable_external_dependency_loading)return H.warn(\"\".concat(t,\" was requested but loading of external scripts is disabled.\")),i(\"Loading of external scripts is disabled\");var r=()=>{if(!a)return i(\"document not found\");var r=a.createElement(\"script\");if(r.type=\"text/javascript\",r.crossOrigin=\"anonymous\",r.src=t,r.onload=e=>i(void 0,e),r.onerror=e=>i(e),e.config.prepare_external_dependency_script&&(r=e.config.prepare_external_dependency_script(r)),!r)return i(\"prepare_external_dependency_script returned null\");var n,s=a.querySelectorAll(\"body > script\");s.length>0?null===(n=s[0].parentNode)||void 0===n||n.insertBefore(r,s[0]):a.body.appendChild(r)};null!=a&&a.body?r():null==a||a.addEventListener(\"DOMContentLoaded\",r)};function z(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function j(e){for(var t=1;t=0||(n[i]=e[i]);return n}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}_.__PosthogExtensions__=_.__PosthogExtensions__||{},_.__PosthogExtensions__.loadExternalDependency=(e,t,i)=>{var r=\"/static/\".concat(t,\".js\")+\"?v=\".concat(e.version);if(\"remote-config\"===t&&(r=\"/array/\".concat(e.config.token,\"/config.js\")),\"toolbar\"===t){var n=3e5,s=Math.floor(Date.now()/n)*n;r=\"\".concat(r,\"&t=\").concat(s)}var o=e.requestRouter.endpointFor(\"assets\",r);U(e,o,i)},_.__PosthogExtensions__.loadSiteApp=(e,t,i)=>{var r=e.requestRouter.endpointFor(\"api\",t);U(e,r,i)};var G={};function J(e,t,i){if(x(e))if(n&&e.forEach===n)e.forEach(t,i);else if(\"length\"in e&&e.length===+e.length)for(var r=0,s=e.length;r1?t-1:0),r=1;r1?t-1:0),r=1;r0&&(t[i]=e)})),t};function ie(e,t){return i=e,r=e=>R(e)&&!$(t)?e.slice(0,t):e,n=new Set,function e(t,i){return t!==Object(t)?r?r(t,i):t:n.has(t)?void 0:(n.add(t),x(t)?(s=[],J(t,(t=>{s.push(e(t))}))):(s={},Y(t,((t,i)=>{n.has(t)||(s[i]=e(t,i))}))),s);var s}(i);var i,r,n}var re=function(){function e(t){return t&&(t.preventDefault=e.preventDefault,t.stopPropagation=e.stopPropagation),t}return e.preventDefault=function(){this.returnValue=!1},e.stopPropagation=function(){this.cancelBubble=!0},function(i,r,n,s,o){if(i)if(i.addEventListener&&!s)i.addEventListener(r,n,!!o);else{var a=\"on\"+r,l=i[a];i[a]=function(i,r,n){return function(s){if(s=s||e(null==t?void 0:t.event)){var o,a=!0;I(n)&&(o=n(s));var l=r.call(i,s);return!1!==o&&!1!==l||(a=!1),a}}}(i,n,l)}else q.error(\"No valid element provided to register_event\")}}();function ne(e,t){for(var i=0;i{var t={};for(var[i,r]of Q(e||{}))r&&(t[i]=r);return t};class Ge{constructor(e){W(this,\"_override_warning\",!1),W(this,\"_hasLoadedFlags\",!1),W(this,\"_requestInFlight\",!1),W(this,\"_reloadingDisabled\",!1),W(this,\"_additionalReloadRequested\",!1),W(this,\"_decideCalled\",!1),W(this,\"_flagsLoadedFromRemote\",!1),this.instance=e,this.featureFlagEventHandlers=[]}decide(){if(this.instance.config.__preview_remote_config)this._decideCalled=!0;else{var e=!this._reloadDebouncer&&(this.instance.config.advanced_disable_feature_flags||this.instance.config.advanced_disable_feature_flags_on_first_load);this._callDecideEndpoint({disableFlags:e})}}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagVariants(){var e=this.instance.get_property(xe),t=this.instance.get_property(je);if(!t)return e||{};for(var i=K({},e),r=Object.keys(t),n=0;n{this._callDecideEndpoint()}),5))}clearDebouncer(){clearTimeout(this._reloadDebouncer),this._reloadDebouncer=void 0}ensureFlagsLoaded(){this._hasLoadedFlags||this._requestInFlight||this._reloadDebouncer||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this._reloadingDisabled=e}_callDecideEndpoint(t){if(this.clearDebouncer(),!this.instance.config.advanced_disable_decide)if(this._requestInFlight)this._additionalReloadRequested=!0;else{var i={token:this.instance.config.token,distinct_id:this.instance.get_distinct_id(),groups:this.instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:this.instance.get_property(Ce),group_properties:this.instance.get_property(Pe)};(null!=t&&t.disableFlags||this.instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this._requestInFlight=!0,this.instance._send_request({method:\"POST\",url:this.instance.requestRouter.endpointFor(\"api\",\"/decide/?v=3\"),data:i,compression:this.instance.config.disable_compression?void 0:e.Base64,timeout:this.instance.config.feature_flag_request_timeout_ms,callback:e=>{var t,r,n=!0;(200===e.statusCode&&(this.$anon_distinct_id=void 0,n=!1),this._requestInFlight=!1,this._decideCalled)||(this._decideCalled=!0,this.instance._onRemoteConfig(null!==(r=e.json)&&void 0!==r?r:{}));i.disable_flags||(this._flagsLoadedFromRemote=!n,this.receivedFeatureFlags(null!==(t=e.json)&&void 0!==t?t:{},n),this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callDecideEndpoint()))}})}}getFeatureFlag(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){var i,r,n,s,o,a=this.getFlagVariants()[e],l=\"\".concat(a),u=this.instance.get_property(Te)||{};if(t.send_event||!(\"send_event\"in t))if(!(e in u)||!u[e].includes(l))x(u[e])?u[e].push(l):u[e]=[l],null===(i=this.instance.persistence)||void 0===i||i.register({[Te]:u}),this.instance.capture(\"$feature_flag_called\",{$feature_flag:e,$feature_flag_response:a,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_bootstrapped_response:(null===(r=this.instance.config.bootstrap)||void 0===r||null===(n=r.featureFlags)||void 0===n?void 0:n[e])||null,$feature_flag_bootstrapped_payload:(null===(s=this.instance.config.bootstrap)||void 0===s||null===(o=s.featureFlagPayloads)||void 0===o?void 0:o[e])||null,$used_bootstrap_value:!this._flagsLoadedFromRemote});return a}Ue.warn('getFeatureFlag for key \"'+e+\"\\\" failed. Feature flags didn't load in time.\")}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}isFeatureEnabled(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0)return!!this.getFeatureFlag(e,t);Ue.warn('isFeatureEnabled for key \"'+e+\"\\\" failed. Feature flags didn't load in time.\")}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((t=>t!==e))}receivedFeatureFlags(e,t){if(this.instance.persistence){this._hasLoadedFlags=!0;var i=this.getFlagVariants(),r=this.getFlagPayloads();!function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.featureFlags,s=e.featureFlagPayloads;if(n)if(x(n)){var o={};if(n)for(var a=0;a1&&void 0!==arguments[1]&&arguments[1];if(!this.instance.__loaded||!this.instance.persistence)return Ue.uninitializedWarning(\"posthog.feature_flags.override\");if(this._override_warning=t,!1===e)this.instance.persistence.unregister(je);else if(x(e)){for(var i={},r=0;rthis.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t){var i,r=(this.instance.get_property(Ie)||[]).find((t=>t.flagKey===e)),n={[\"$feature_enrollment/\".concat(e)]:t},s={$feature_flag:e,$feature_enrollment:t,$set:n};r&&(s.$early_access_feature_name=r.name),this.instance.capture(\"$feature_enrollment_update\",s),this.setPersonPropertiesForFlags(n,!1);var o=j(j({},this.getFlagVariants()),{},{[e]:t});null===(i=this.instance.persistence)||void 0===i||i.register({[ze]:Object.keys(Ve(o)),[xe]:o}),this._fireFeatureFlagsCallbacks()}getEarlyAccessFeatures(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.instance.get_property(Ie);if(i&&!t)return e(i);this.instance._send_request({url:this.instance.requestRouter.endpointFor(\"api\",\"/api/early_access_features/?token=\".concat(this.instance.config.token)),method:\"GET\",callback:t=>{var i;if(t.json){var r=t.json.earlyAccessFeatures;return null===(i=this.instance.persistence)||void 0===i||i.register({[Ie]:r}),e(r)}}})}_prepareFeatureFlagsForCallbacks(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter((e=>t[e])),flagVariants:Object.keys(t).filter((e=>t[e])).reduce(((e,i)=>(e[i]=t[i],e)),{})}}_fireFeatureFlagsCallbacks(e){var{flags:t,flagVariants:i}=this._prepareFeatureFlagsForCallbacks();this.featureFlagEventHandlers.forEach((r=>r(t,i,{errorsLoading:e})))}setPersonPropertiesForFlags(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this.instance.get_property(Ce)||{};this.instance.register({[Ce]:j(j({},i),e)}),t&&this.instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this.instance.unregister(Ce)}setGroupPropertiesForFlags(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this.instance.get_property(Pe)||{};0!==Object.keys(i).length&&Object.keys(i).forEach((t=>{i[t]=j(j({},i[t]),e[t]),delete e[t]})),this.instance.register({[Pe]:j(j({},i),e)}),t&&this.instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this.instance.get_property(Pe)||{};this.instance.register({[Pe]:j(j({},t),{},{[e]:{}})})}else this.instance.unregister(Pe)}}Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return M(e)&&isFinite(e)&&Math.floor(e)===e});var Je=\"0123456789abcdef\";class Ye{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError(\"not 128-bit length\")}static fromFieldsV7(e,t,i,r){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(r)||e<0||t<0||i<0||r<0||e>0xffffffffffff||t>4095||i>1073741823||r>4294967295)throw new RangeError(\"invalid field value\");var n=new Uint8Array(16);return n[0]=e/Math.pow(2,40),n[1]=e/Math.pow(2,32),n[2]=e/Math.pow(2,24),n[3]=e/Math.pow(2,16),n[4]=e/Math.pow(2,8),n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|i>>>24,n[9]=i>>>16,n[10]=i>>>8,n[11]=i,n[12]=r>>>24,n[13]=r>>>16,n[14]=r>>>8,n[15]=r,new Ye(n)}toString(){for(var e=\"\",t=0;t>>4)+Je.charAt(15&this.bytes[t]),3!==t&&5!==t&&7!==t&&9!==t||(e+=\"-\");if(36!==e.length)throw new Error(\"Invalid UUIDv7 was generated\");return e}clone(){return new Ye(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var t=0;t<16;t++){var i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}}class Ke{constructor(){W(this,\"timestamp\",0),W(this,\"counter\",0),W(this,\"random\",new Ze)}generate(){var e=this.generateOrAbort();if(F(e)){this.timestamp=0;var t=this.generateOrAbort();if(F(t))throw new Error(\"Could not generate UUID after timestamp reset\");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+1e4>this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Ye.fromFieldsV7(this.timestamp,Math.trunc(this.counter/Math.pow(2,30)),this.counter&Math.pow(2,30)-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}}var Xe,Qe=e=>{if(\"undefined\"!=typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error(\"no cryptographically strong RNG available\");for(var t=0;tcrypto.getRandomValues(e));class Ze{constructor(){W(this,\"buffer\",new Uint32Array(8)),W(this,\"cursor\",1/0)}nextUint32(){return this.cursor>=this.buffer.length&&(Qe(this.buffer),this.cursor=0),this.buffer[this.cursor++]}}var et=()=>tt().toString(),tt=()=>(Xe||(Xe=new Ke)).generate(),it=\"Thu, 01 Jan 1970 00:00:00 GMT\",rt=\"\";var nt=/[a-z0-9][a-z0-9-]+\\.[a-z]{2,}$/i;function st(e,t){if(t){var i=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a;if(rt)return rt;if(!t)return\"\";if([\"localhost\",\"127.0.0.1\"].includes(e))return\"\";for(var i=e.split(\".\"),r=Math.min(i.length,8),n=\"dmn_chk_\"+et(),s=new RegExp(\"(^|;)\\\\s*\"+n+\"=1\");!rt&&r--;){var o=i.slice(r).join(\".\"),l=n+\"=1;domain=.\"+o;t.cookie=l,s.test(t.cookie)&&(t.cookie=l+\";expires=\"+it,rt=o)}return rt}(e);if(!i){var r=(e=>{var t=e.match(nt);return t?t[0]:\"\"})(e);r!==i&&q.info(\"Warning: cookie subdomain discovery mismatch\",r,i),i=r}return i?\"; domain=.\"+i:\"\"}return\"\"}var ot={is_supported:()=>!!a,error:function(e){q.error(\"cookieStore error: \"+e)},get:function(e){if(a){try{for(var t=e+\"=\",i=a.cookie.split(\";\").filter((e=>e.length)),r=0;r3686.4&&q.warn(\"cookieStore warning: large cookie, len=\"+c.length),a.cookie=c,c}catch(e){return}},remove:function(e,t){try{ot.set(e,\"\",-1,t)}catch(e){return}}},at=null,lt={is_supported:function(){if(!$(at))return at;var e=!0;if(F(t))e=!1;else try{var i=\"__mplssupport__\";lt.set(i,\"xyz\"),'\"xyz\"'!==lt.get(i)&&(e=!1),lt.remove(i)}catch(t){e=!1}return e||q.error(\"localStorage unsupported; falling back to cookie store\"),at=e,e},error:function(e){q.error(\"localStorage error: \"+e)},get:function(e){try{return null==t?void 0:t.localStorage.getItem(e)}catch(e){lt.error(e)}return null},parse:function(e){try{return JSON.parse(lt.get(e))||{}}catch(e){}return null},set:function(e,i){try{null==t||t.localStorage.setItem(e,JSON.stringify(i))}catch(e){lt.error(e)}},remove:function(e){try{null==t||t.localStorage.removeItem(e)}catch(e){lt.error(e)}}},ut=[\"distinct_id\",we,Se,Ne,De],ct=j(j({},lt),{},{parse:function(e){try{var t={};try{t=ot.parse(e)||{}}catch(e){}var i=K(t,JSON.parse(lt.get(e)||\"{}\"));return lt.set(e,i),i}catch(e){}return null},set:function(e,t,i,r,n,s){try{lt.set(e,t,void 0,void 0,s);var o={};ut.forEach((e=>{t[e]&&(o[e]=t[e])})),Object.keys(o).length&&ot.set(e,o,i,r,n,s)}catch(e){lt.error(e)}},remove:function(e,i){try{null==t||t.localStorage.removeItem(e),ot.remove(e,i)}catch(e){lt.error(e)}}}),dt={},ht={is_supported:function(){return!0},error:function(e){q.error(\"memoryStorage error: \"+e)},get:function(e){return dt[e]||null},parse:function(e){return dt[e]||null},set:function(e,t){dt[e]=t},remove:function(e){delete dt[e]}},_t=null,pt={is_supported:function(){if(!$(_t))return _t;if(_t=!0,F(t))_t=!1;else try{var e=\"__support__\";pt.set(e,\"xyz\"),'\"xyz\"'!==pt.get(e)&&(_t=!1),pt.remove(e)}catch(e){_t=!1}return _t},error:function(e){q.error(\"sessionStorage error: \",e)},get:function(e){try{return null==t?void 0:t.sessionStorage.getItem(e)}catch(e){pt.error(e)}return null},parse:function(e){try{return JSON.parse(pt.get(e))||null}catch(e){}return null},set:function(e,i){try{null==t||t.sessionStorage.setItem(e,JSON.stringify(i))}catch(e){pt.error(e)}},remove:function(e){try{null==t||t.sessionStorage.removeItem(e)}catch(e){pt.error(e)}}},vt=[\"localhost\",\"127.0.0.1\"],gt=e=>{var t=null==a?void 0:a.createElement(\"a\");return F(t)?null:(t.href=e,t)},ft=function(e,t){return!!function(e){try{new RegExp(e)}catch(e){return!1}return!0}(t)&&new RegExp(t).test(e)},mt=function(e){var t,i,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"&\",n=[];return Y(e,(function(e,r){F(e)||F(r)||\"undefined\"===r||(t=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),i=encodeURIComponent(r),n[n.length]=i+\"=\"+t)})),n.join(r)},bt=function(e,t){for(var i,r=((e.split(\"#\")[0]||\"\").split(\"?\")[1]||\"\").split(\"&\"),n=0;nt&&m(t,Pt)||function(e){return m(e,Rt)&&!m(e,Lt)&&!m(e,kt)}(e),_i=function(e,t){return t=t||\"\",m(e,\" OPR/\")&&m(e,\"Mini\")?Ht:m(e,\" OPR/\")?Bt:ci.test(e)?Tt:m(e,\"IE\"+St)||m(e,\"WPDesktop\")?qt:m(e,Ot)?Mt:m(e,Ut)||m(e,\"Edg/\")?zt:m(e,\"FBIOS\")?\"Facebook \"+St:m(e,\"UCWEB\")||m(e,\"UCBrowser\")?\"UC Browser\":m(e,\"CriOS\")?Dt:m(e,\"CrMo\")||m(e,Lt)?Lt:m(e,kt)&&m(e,Rt)?Yt:m(e,\"FxiOS\")?Wt:m(e.toLowerCase(),ni.toLowerCase())?ni:hi(e,t)?m(e,St)?Kt:Rt:m(e,jt)?jt:m(e,\"MSIE\")||m(e,\"Trident/\")?Nt:m(e,\"Gecko\")?jt:\"\"},pi={[qt]:[new RegExp(\"rv:\"+si)],[zt]:[new RegExp(Ut+\"?\\\\/\"+si)],[Lt]:[new RegExp(\"(\"+Lt+\"|CrMo)\\\\/\"+si)],[Dt]:[new RegExp(\"CriOS\\\\/\"+si)],\"UC Browser\":[new RegExp(\"(UCBrowser|UCWEB)\\\\/\"+si)],[Rt]:[oi],[Kt]:[oi],[Bt]:[new RegExp(\"(Opera|OPR)\\\\/\"+si)],[jt]:[new RegExp(jt+\"\\\\/\"+si)],[Wt]:[new RegExp(\"FxiOS\\\\/\"+si)],[ni]:[new RegExp(\"Konqueror[:/]?\"+si,\"i\")],[Tt]:[new RegExp(Tt+\" \"+si),oi],[Yt]:[new RegExp(\"android\\\\s\"+si,\"i\")],[Mt]:[new RegExp(Ot+\"\\\\/\"+si)],[Nt]:[new RegExp(\"(rv:|MSIE )\"+si)],Mozilla:[new RegExp(\"rv:\"+si)]},vi=[[new RegExp(Jt+\"; \"+Jt+\" (.*?)[);]\",\"i\"),e=>[Jt,e&&e[1]||\"\"]],[new RegExp(Vt,\"i\"),[Vt,\"\"]],[new RegExp(Gt,\"i\"),[Gt,\"\"]],[ci,[Tt,\"\"]],[new RegExp(Xt,\"i\"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Qt,\"\"];if(new RegExp(St).test(t)&&!/IEMobile\\b/.test(t))return[Xt+\" \"+St,\"\"];var i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){var r=i[1],n=di[r]||\"\";return/arm/i.test(t)&&(n=\"RT\"),[Xt,n]}return[Xt,\"\"]}],[/((iPhone|iPad|iPod).*?OS (\\d+)_(\\d+)_?(\\d+)?|iPhone)/,e=>{if(e&&e[3]){var t=[e[3],e[4],e[5]||\"0\"];return[Et,t.join(\".\")]}return[Et,\"\"]}],[/(watch.*\\/(\\d+\\.\\d+\\.\\d+)|watch os,(\\d+\\.\\d+),)/i,e=>{var t=\"\";return e&&e.length>=3&&(t=F(e[2])?e[3]:e[2]),[\"watchOS\",t]}],[new RegExp(\"(\"+kt+\" (\\\\d+)\\\\.(\\\\d+)\\\\.?(\\\\d+)?|\"+kt+\")\",\"i\"),e=>{if(e&&e[2]){var t=[e[2],e[3],e[4]||\"0\"];return[kt,t.join(\".\")]}return[kt,\"\"]}],[/Mac OS X (\\d+)[_.](\\d+)[_.]?(\\d+)?/i,e=>{var t=[\"Mac OS X\",\"\"];if(e&&e[1]){var i=[e[1],e[2],e[3]||\"0\"];t[1]=i.join(\".\")}return t}],[/Mac/i,[\"Mac OS X\",\"\"]],[/CrOS/,[At,\"\"]],[/Linux|debian/i,[\"Linux\",\"\"]]],gi=function(e){return ui.test(e)?Vt:li.test(e)?Gt:ai.test(e)?Jt:new RegExp(ei,\"i\").test(e)?ei:new RegExp(\"(\"+Qt+\"|WPDesktop)\",\"i\").test(e)?Qt:/iPad/.test(e)?Ct:/iPod/.test(e)?\"iPod Touch\":/iPhone/.test(e)?\"iPhone\":/(watch)(?: ?os[,/]|\\d,\\d\\/)[\\d.]+/i.test(e)?Ft:ci.test(e)?Tt:/(kobo)\\s(ereader|touch)/i.test(e)?\"Kobo\":new RegExp(Zt,\"i\").test(e)?Zt:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\\))/i.test(e)||/(kf[a-z]+)( bui|\\)).+silk\\//i.test(e)?\"Kindle Fire\":/(Android|ZTE)/i.test(e)?!new RegExp(St).test(e)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)?/pixel[\\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?kt:It:kt:new RegExp(\"(pda|\"+St+\")\",\"i\").test(e)?ii:new RegExp(xt,\"i\").test(e)&&!new RegExp(xt+\" pc\",\"i\").test(e)?ri:\"\"},fi=\"https?://(.*)\",mi=[\"gclid\",\"gclsrc\",\"dclid\",\"gbraid\",\"wbraid\",\"fbclid\",\"msclkid\",\"twclid\",\"li_fat_id\",\"igshid\",\"ttclid\",\"rdt_cid\",\"irclid\",\"_kx\"],bi=X([\"utm_source\",\"utm_medium\",\"utm_campaign\",\"utm_content\",\"utm_term\",\"gad_source\",\"mc_cid\"],mi),yi=\"\",wi={campaignParams:function(){var{customTrackedParams:e,maskPersonalDataProperties:t,customPersonalDataProperties:i}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a)return{};var r=t?X([],mi,i||[]):[];return this._campaignParamsFromUrl(yt(a.URL,r,yi),e)},_campaignParamsFromUrl:function(e,t){var i=bi.concat(t||[]),r={};return Y(i,(function(t){var i=bt(e,t);r[t]=i||null})),r},_searchEngine:function(e){return e?0===e.search(fi+\"google.([^/?]*)\")?\"google\":0===e.search(fi+\"bing.com\")?\"bing\":0===e.search(fi+\"yahoo.com\")?\"yahoo\":0===e.search(fi+\"duckduckgo.com\")?\"duckduckgo\":null:null},_searchInfoFromReferrer:function(e){var t=wi._searchEngine(e),i=\"yahoo\"!=t?\"q\":\"p\",r={};if(!$(t)){r.$search_engine=t;var n=a?bt(a.referrer,i):\"\";n.length&&(r.ph_keyword=n)}return r},searchInfo:function(){var e=null==a?void 0:a.referrer;return e?this._searchInfoFromReferrer(e):{}},browser:_i,browserVersion:function(e,t){var i=_i(e,t),r=pi[i];if(F(r))return null;for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};if(!h)return{};var r=e?X([],mi,i||[]):[],[n,s]=wi.os(h);return K(te({$os:n,$os_version:s,$browser:wi.browser(h,navigator.vendor),$device:wi.device(h),$device_type:wi.deviceType(h),$timezone:wi.timezone(),$timezone_offset:wi.timezoneOffset()}),{$current_url:yt(null==l?void 0:l.href,r,yi),$host:null==l?void 0:l.host,$pathname:null==l?void 0:l.pathname,$raw_user_agent:h.length>1e3?h.substring(0,997)+\"...\":h,$browser_version:wi.browserVersion(h,navigator.vendor),$browser_language:wi.browserLanguage(),$browser_language_prefix:wi.browserLanguagePrefix(),$screen_height:null==t?void 0:t.screen.height,$screen_width:null==t?void 0:t.screen.width,$viewport_height:null==t?void 0:t.innerHeight,$viewport_width:null==t?void 0:t.innerWidth,$lib:\"web\",$lib_version:p.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})},people_properties:function(){if(!h)return{};var[e,t]=wi.os(h);return K(te({$os:e,$os_version:t,$browser:wi.browser(h,navigator.vendor)}),{$browser_version:wi.browserVersion(h,navigator.vendor)})}},Si=[\"cookie\",\"localstorage\",\"localstorage+cookie\",\"sessionstorage\",\"memory\"];class Ei{constructor(e){this.config=e,this.props={},this.campaign_params_saved=!1,this.name=(e=>{var t=\"\";return e.token&&(t=e.token.replace(/\\+/g,\"PL\").replace(/\\//g,\"SL\").replace(/=/g,\"EQ\")),e.persistence_name?\"ph_\"+e.persistence_name:\"ph_\"+t+\"_posthog\"})(e),this.storage=this.buildStorage(e),this.load(),e.debug&&q.info(\"Persistence loaded\",e.persistence,j({},this.props)),this.update_config(e,e),this.save()}buildStorage(e){-1===Si.indexOf(e.persistence.toLowerCase())&&(q.critical(\"Unknown persistence type \"+e.persistence+\"; falling back to localStorage+cookie\"),e.persistence=\"localStorage+cookie\");var t=e.persistence.toLowerCase();return\"localstorage\"===t&<.is_supported()?lt:\"localstorage+cookie\"===t&&ct.is_supported()?ct:\"sessionstorage\"===t&&pt.is_supported()?pt:\"memory\"===t?ht:\"cookie\"===t?ot:ct.is_supported()?ct:ot}properties(){var e={};return Y(this.props,(function(t,i){if(i===xe&&C(t))for(var r=Object.keys(t),n=0;n{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this.props[i]=e,r=!0)})),r)return this.save(),!0}return!1}register(e,t){if(C(e)){this.expire_days=F(t)?this.default_expiry:t;var i=!1;if(Y(e,((t,r)=>{e.hasOwnProperty(r)&&this.props[r]!==t&&(this.props[r]=t,i=!0)})),i)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.campaign_params_saved){var e=wi.campaignParams({customTrackedParams:this.config.custom_campaign_params,maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties});P(te(e))||this.register(e),this.campaign_params_saved=!0}}update_search_keyword(){this.register(wi.searchInfo())}update_referrer_info(){this.register_once(wi.referrerInfo(),void 0)}set_initial_person_info(){this.props[Le]||this.props[Ae]||this.register_once({[De]:wi.initialPersonInfo()},void 0)}get_referrer_info(){return te({$referrer:this.props.$referrer,$referring_domain:this.props.$referring_domain})}get_initial_props(){var e={};Y([Ae,Le],(t=>{var i=this.props[t];i&&Y(i,(function(t,i){e[\"$initial_\"+y(i)]=t}))}));var t=this.props[De];if(t){var i=wi.initialPersonPropsFromInfo(t);K(e,i)}return e}safe_merge(e){return Y(this.props,(function(t,i){i in e||(e[i]=t)})),e}update_config(e,t){if(this.default_expiry=this.expire_days=e.cookie_expiration,this.set_disabled(e.disable_persistence),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence){var i=this.buildStorage(e),r=this.props;this.clear(),this.storage=i,this.props=r,this.save()}}set_disabled(e){this.disabled=e,this.disabled?this.remove():this.save()}set_cross_subdomain(e){e!==this.cross_subdomain&&(this.cross_subdomain=e,this.remove(),this.save())}get_cross_subdomain(){return!!this.cross_subdomain}set_secure(e){e!==this.secure&&(this.secure=e,this.remove(),this.save())}set_event_timer(e,t){var i=this.props[ae]||{};i[e]=t,this.props[ae]=i,this.save()}remove_event_timer(e){var t=(this.props[ae]||{})[e];return F(t)||(delete this.props[ae][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}}function ki(e){var t,i;return(null===(t=JSON.stringify(e,(i=[],function(e,t){if(C(t)){for(;i.length>0&&i[i.length-1]!==this;)i.pop();return i.includes(t)?\"[Circular]\":(i.push(t),t)}return t})))||void 0===t?void 0:t.length)||0}function xi(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6606028.8;if(e.size>=t&&e.data.length>1){var i=Math.floor(e.data.length/2),r=e.data.slice(0,i),n=e.data.slice(i);return[xi({size:ki(r),data:r,sessionId:e.sessionId,windowId:e.windowId}),xi({size:ki(n),data:n,sessionId:e.sessionId,windowId:e.windowId})].flatMap((e=>e))}return[e]}var Ii=(e=>(e[e.DomContentLoaded=0]=\"DomContentLoaded\",e[e.Load=1]=\"Load\",e[e.FullSnapshot=2]=\"FullSnapshot\",e[e.IncrementalSnapshot=3]=\"IncrementalSnapshot\",e[e.Meta=4]=\"Meta\",e[e.Custom=5]=\"Custom\",e[e.Plugin=6]=\"Plugin\",e))(Ii||{}),Ci=(e=>(e[e.Mutation=0]=\"Mutation\",e[e.MouseMove=1]=\"MouseMove\",e[e.MouseInteraction=2]=\"MouseInteraction\",e[e.Scroll=3]=\"Scroll\",e[e.ViewportResize=4]=\"ViewportResize\",e[e.Input=5]=\"Input\",e[e.TouchMove=6]=\"TouchMove\",e[e.MediaInteraction=7]=\"MediaInteraction\",e[e.StyleSheetRule=8]=\"StyleSheetRule\",e[e.CanvasMutation=9]=\"CanvasMutation\",e[e.Font=10]=\"Font\",e[e.Log=11]=\"Log\",e[e.Drag=12]=\"Drag\",e[e.StyleDeclaration=13]=\"StyleDeclaration\",e[e.Selection=14]=\"Selection\",e[e.AdoptedStyleSheet=15]=\"AdoptedStyleSheet\",e[e.CustomElement=16]=\"CustomElement\",e))(Ci||{});function Pi(e){var t;return e instanceof Element&&(e.id===qe||!(null===(t=e.closest)||void 0===t||!t.call(e,\".toolbar-global-fade-container\")))}function Fi(e){return!!e&&1===e.nodeType}function Ri(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Ti(e){return!!e&&3===e.nodeType}function $i(e){return!!e&&11===e.nodeType}function Oi(e){return e?b(e).split(/\\s+/):[]}function Mi(e){var i=null==t?void 0:t.location.href;return!!(i&&e&&e.some((e=>i.match(e))))}function Li(e){var t=\"\";switch(typeof e.className){case\"string\":t=e.className;break;case\"object\":t=(e.className&&\"baseVal\"in e.className?e.className.baseVal:null)||e.getAttribute(\"class\")||\"\";break;default:t=\"\"}return Oi(t)}function Ai(e){return O(e)?null:b(e).split(/(\\s+)/).filter((e=>Ki(e))).join(\"\").replace(/[\\r\\n]/g,\" \").replace(/[ ]+/g,\" \").substring(0,255)}function Di(e){var t=\"\";return Ui(e)&&!zi(e)&&e.childNodes&&e.childNodes.length&&Y(e.childNodes,(function(e){var i;Ti(e)&&e.textContent&&(t+=null!==(i=Ai(e.textContent))&&void 0!==i?i:\"\")})),b(t)}function Ni(e){return F(e.target)?e.srcElement||null:null!==(t=e.target)&&void 0!==t&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var qi=[\"a\",\"button\",\"form\",\"input\",\"select\",\"textarea\",\"label\"];function Bi(e){var t=e.parentNode;return!(!t||!Fi(t))&&t}function Hi(e,i){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;if(!t||!e||Ri(e,\"html\")||!Fi(e))return!1;if(null!=r&&r.url_allowlist&&!Mi(r.url_allowlist))return!1;if(null!=r&&r.url_ignorelist&&Mi(r.url_ignorelist))return!1;if(null!=r&&r.dom_event_allowlist){var o=r.dom_event_allowlist;if(o&&!o.some((e=>i.type===e)))return!1}for(var a=!1,l=[e],u=!0,c=e;c.parentNode&&!Ri(c,\"body\");)if($i(c.parentNode))l.push(c.parentNode.host),c=c.parentNode.host;else{if(!(u=Bi(c)))break;if(n||qi.indexOf(u.tagName.toLowerCase())>-1)a=!0;else{var d=t.getComputedStyle(u);d&&\"pointer\"===d.getPropertyValue(\"cursor\")&&(a=!0)}l.push(u),c=u}if(!function(e,t){var i=null==t?void 0:t.element_allowlist;if(F(i))return!0;var r=function(e){if(i.some((t=>e.tagName.toLowerCase()===t)))return{v:!0}};for(var n of e){var s=r(n);if(\"object\"==typeof s)return s.v}return!1}(l,r))return!1;if(!function(e,t){var i=null==t?void 0:t.css_selector_allowlist;if(F(i))return!0;var r=function(e){if(i.some((t=>e.matches(t))))return{v:!0}};for(var n of e){var s=r(n);if(\"object\"==typeof s)return s.v}return!1}(l,r))return!1;var h=t.getComputedStyle(e);if(h&&\"pointer\"===h.getPropertyValue(\"cursor\")&&\"click\"===i.type)return!0;var _=e.tagName.toLowerCase();switch(_){case\"html\":return!1;case\"form\":return(s||[\"submit\"]).indexOf(i.type)>=0;case\"input\":case\"select\":case\"textarea\":return(s||[\"change\",\"click\"]).indexOf(i.type)>=0;default:return a?(s||[\"click\"]).indexOf(i.type)>=0:(s||[\"click\"]).indexOf(i.type)>=0&&(qi.indexOf(_)>-1||\"true\"===e.getAttribute(\"contenteditable\"))}}function Ui(e){for(var t=e;t.parentNode&&!Ri(t,\"body\");t=t.parentNode){var i=Li(t);if(m(i,\"ph-sensitive\")||m(i,\"ph-no-capture\"))return!1}if(m(Li(e),\"ph-include\"))return!0;var r=e.type||\"\";if(R(r))switch(r.toLowerCase()){case\"hidden\":case\"password\":return!1}var n=e.name||e.id||\"\";if(R(n)){if(/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(n.replace(/[^a-zA-Z0-9]/g,\"\")))return!1}return!0}function zi(e){return!!(Ri(e,\"input\")&&![\"button\",\"checkbox\",\"submit\",\"reset\"].includes(e.type)||Ri(e,\"select\")||Ri(e,\"textarea\")||\"true\"===e.getAttribute(\"contenteditable\"))}var ji=\"(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})\",Wi=new RegExp(\"^(?:\".concat(ji,\")$\")),Vi=new RegExp(ji),Gi=\"\\\\d{3}-?\\\\d{2}-?\\\\d{4}\",Ji=new RegExp(\"^(\".concat(Gi,\")$\")),Yi=new RegExp(\"(\".concat(Gi,\")\"));function Ki(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(O(e))return!1;if(R(e)){if(e=b(e),(t?Wi:Vi).test((e||\"\").replace(/[- ]/g,\"\")))return!1;if((t?Ji:Yi).test(e))return!1}return!0}function Xi(e){var t=Di(e);return Ki(t=\"\".concat(t,\" \").concat(Qi(e)).trim())?t:\"\"}function Qi(e){var t=\"\";return e&&e.childNodes&&e.childNodes.length&&Y(e.childNodes,(function(e){var i;if(e&&\"span\"===(null===(i=e.tagName)||void 0===i?void 0:i.toLowerCase()))try{var r=Di(e);t=\"\".concat(t,\" \").concat(r).trim(),e.childNodes&&e.childNodes.length&&(t=\"\".concat(t,\" \").concat(Qi(e)).trim())}catch(e){q.error(\"[AutoCapture]\",e)}})),t}function Zi(e){return function(e){var t=e.map((e=>{var t,i,r=\"\";if(e.tag_name&&(r+=e.tag_name),e.attr_class)for(var n of(e.attr_class.sort(),e.attr_class))r+=\".\".concat(n.replace(/\"/g,\"\"));var s=j(j(j(j({},e.text?{text:e.text}:{}),{},{\"nth-child\":null!==(t=e.nth_child)&&void 0!==t?t:0,\"nth-of-type\":null!==(i=e.nth_of_type)&&void 0!==i?i:0},e.href?{href:e.href}:{}),e.attr_id?{attr_id:e.attr_id}:{}),e.attributes),o={};return Q(s).sort(((e,t)=>{var[i]=e,[r]=t;return i.localeCompare(r)})).forEach((e=>{var[t,i]=e;return o[er(t.toString())]=er(i.toString())})),r+=\":\",r+=Q(s).map((e=>{var[t,i]=e;return\"\".concat(t,'=\"').concat(i,'\"')})).join(\"\")}));return t.join(\";\")}(function(e){return e.map((e=>{var t,i,r={text:null===(t=e.$el_text)||void 0===t?void 0:t.slice(0,400),tag_name:e.tag_name,href:null===(i=e.attr__href)||void 0===i?void 0:i.slice(0,2048),attr_class:tr(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Q(e).filter((e=>{var[t]=e;return 0===t.indexOf(\"attr__\")})).forEach((e=>{var[t,i]=e;return r.attributes[t]=i})),r}))}(e))}function er(e){return e.replace(/\"|\\\\\"/g,'\\\\\"')}function tr(e){var t=e.attr__class;return t?x(t)?t:Oi(t):void 0}var ir=\"[SessionRecording]\",rr=\"redacted\",nr={initiatorTypes:[\"audio\",\"beacon\",\"body\",\"css\",\"early-hint\",\"embed\",\"fetch\",\"frame\",\"iframe\",\"icon\",\"image\",\"img\",\"input\",\"link\",\"navigation\",\"object\",\"ping\",\"script\",\"track\",\"video\",\"xmlhttprequest\"],maskRequestFn:e=>e,recordHeaders:!1,recordBody:!1,recordInitialRequests:!1,recordPerformance:!1,performanceEntryTypeToObserve:[\"first-input\",\"navigation\",\"paint\",\"resource\"],payloadSizeLimitBytes:1e6,payloadHostDenyList:[\".lr-ingest.io\",\".ingest.sentry.io\",\".clarity.ms\",\"analytics.google.com\"]},sr=[\"authorization\",\"x-forwarded-for\",\"authorization\",\"cookie\",\"set-cookie\",\"x-api-key\",\"x-real-ip\",\"remote-addr\",\"forwarded\",\"proxy-authorization\",\"x-csrf-token\",\"x-csrftoken\",\"x-xsrf-token\"],or=[\"password\",\"secret\",\"passwd\",\"api_key\",\"apikey\",\"auth\",\"credentials\",\"mysql_pwd\",\"privatekey\",\"private_key\",\"token\"],ar=[\"/s/\",\"/e/\",\"/i/\"];function lr(e,t,i,r){if(O(e))return e;var n=(null==t?void 0:t[\"content-length\"])||function(e){return new Blob([e]).size}(e);return R(n)&&(n=parseInt(n)),n>i?ir+\" \".concat(r,\" body too large to record (\").concat(n,\" bytes)\"):e}function ur(e,t){if(O(e))return e;var i=e;return Ki(i,!1)||(i=ir+\" \"+t+\" body \"+rr),Y(or,(e=>{var r,n;null!==(r=i)&&void 0!==r&&r.length&&-1!==(null===(n=i)||void 0===n?void 0:n.indexOf(e))&&(i=ir+\" \"+t+\" body \"+rr+\" as might contain: \"+e)})),i}var cr=(e,t)=>{var i,r,n,s={payloadSizeLimitBytes:nr.payloadSizeLimitBytes,performanceEntryTypeToObserve:[...nr.performanceEntryTypeToObserve],payloadHostDenyList:[...t.payloadHostDenyList||[],...nr.payloadHostDenyList]},o=!1!==e.session_recording.recordHeaders&&t.recordHeaders,a=!1!==e.session_recording.recordBody&&t.recordBody,l=!1!==e.capture_performance&&t.recordPerformance,u=(i=s,n=Math.min(1e6,null!==(r=i.payloadSizeLimitBytes)&&void 0!==r?r:1e6),e=>(null!=e&&e.requestBody&&(e.requestBody=lr(e.requestBody,e.requestHeaders,n,\"Request\")),null!=e&&e.responseBody&&(e.responseBody=lr(e.responseBody,e.responseHeaders,n,\"Response\")),e)),c=t=>{return u(((e,t)=>{var i,r=gt(e.name),n=0===t.indexOf(\"http\")?null===(i=gt(t))||void 0===i?void 0:i.pathname:t;\"/\"===n&&(n=\"\");var s=null==r?void 0:r.pathname.replace(n||\"\",\"\");if(!(r&&s&&ar.some((e=>0===s.indexOf(e)))))return e})((r=(i=t).requestHeaders,O(r)||Y(Object.keys(null!=r?r:{}),(e=>{sr.includes(e.toLowerCase())&&(r[e]=rr)})),i),e.api_host));var i,r},d=I(e.session_recording.maskNetworkRequestFn);return d&&I(e.session_recording.maskCapturedNetworkRequestFn)&&q.warn(\"Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.\"),d&&(e.session_recording.maskCapturedNetworkRequestFn=t=>{var i=e.session_recording.maskNetworkRequestFn({url:t.name});return j(j({},t),{},{name:null==i?void 0:i.url})}),s.maskRequestFn=I(e.session_recording.maskCapturedNetworkRequestFn)?t=>{var i,r,n,s=c(t);return s&&null!==(i=null===(r=(n=e.session_recording).maskCapturedNetworkRequestFn)||void 0===r?void 0:r.call(n,s))&&void 0!==i?i:void 0}:e=>function(e){if(!F(e))return e.requestBody=ur(e.requestBody,\"Request\"),e.responseBody=ur(e.responseBody,\"Response\"),e}(c(e)),j(j(j({},nr),s),{},{recordHeaders:o,recordBody:a,recordPerformance:l,recordInitialRequests:l})};function dr(e,t,i,r,n){return t>i&&(q.warn(\"min cannot be greater than max.\"),t=i),M(e)?e>i?(r&&q.warn(r+\" cannot be greater than max: \"+i+\". Using max value instead.\"),i):e1&&void 0!==arguments[1]?arguments[1]:{};W(this,\"bucketSize\",100),W(this,\"refillRate\",10),W(this,\"mutationBuckets\",{}),W(this,\"loggedTracker\",{}),W(this,\"refillBuckets\",(()=>{Object.keys(this.mutationBuckets).forEach((e=>{this.mutationBuckets[e]=this.mutationBuckets[e]+this.refillRate,this.mutationBuckets[e]>=this.bucketSize&&delete this.mutationBuckets[e]}))})),W(this,\"getNodeOrRelevantParent\",(e=>{var t=this.rrweb.mirror.getNode(e);if(\"svg\"!==(null==t?void 0:t.nodeName)&&t instanceof Element){var i=t.closest(\"svg\");if(i)return[this.rrweb.mirror.getId(i),i]}return[e,t]})),W(this,\"numberOfChanges\",(e=>{var t,i,r,n,s,o,a,l;return(null!==(t=null===(i=e.removes)||void 0===i?void 0:i.length)&&void 0!==t?t:0)+(null!==(r=null===(n=e.attributes)||void 0===n?void 0:n.length)&&void 0!==r?r:0)+(null!==(s=null===(o=e.texts)||void 0===o?void 0:o.length)&&void 0!==s?s:0)+(null!==(a=null===(l=e.adds)||void 0===l?void 0:l.length)&&void 0!==a?a:0)})),W(this,\"throttleMutations\",(e=>{if(3!==e.type||0!==e.data.source)return e;var t=e.data,i=this.numberOfChanges(t);t.attributes&&(t.attributes=t.attributes.filter((e=>{var t,i,r,[n,s]=this.getNodeOrRelevantParent(e.id);if(0===this.mutationBuckets[n])return!1;(this.mutationBuckets[n]=null!==(t=this.mutationBuckets[n])&&void 0!==t?t:this.bucketSize,this.mutationBuckets[n]=Math.max(this.mutationBuckets[n]-1,0),0===this.mutationBuckets[n])&&(this.loggedTracker[n]||(this.loggedTracker[n]=!0,null===(i=(r=this.options).onBlockedNode)||void 0===i||i.call(r,n,s)));return e})));var r=this.numberOfChanges(t);return 0!==r||i===r?e:void 0})),this.rrweb=e,this.options=r,this.refillRate=dr(null!==(t=this.options.refillRate)&&void 0!==t?t:this.refillRate,0,100,\"mutation throttling refill rate\"),this.bucketSize=dr(null!==(i=this.options.bucketSize)&&void 0!==i?i:this.bucketSize,0,100,\"mutation throttling bucket size\"),setInterval((()=>{this.refillBuckets()}),1e3)}}var _r=Uint8Array,pr=Uint16Array,vr=Uint32Array,gr=new _r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fr=new _r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),mr=new _r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),br=function(e,t){for(var i=new pr(31),r=0;r<31;++r)i[r]=t+=1<>>1|(21845&xr)<<1;Ir=(61680&(Ir=(52428&Ir)>>>2|(13107&Ir)<<2))>>>4|(3855&Ir)<<4,kr[xr]=((65280&Ir)>>>8|(255&Ir)<<8)>>>1}var Cr=function(e,t,i){for(var r=e.length,n=0,s=new pr(t);n>>l]=u}else for(o=new pr(r),n=0;n>>15-e[n];return o},Pr=new _r(288);for(xr=0;xr<144;++xr)Pr[xr]=8;for(xr=144;xr<256;++xr)Pr[xr]=9;for(xr=256;xr<280;++xr)Pr[xr]=7;for(xr=280;xr<288;++xr)Pr[xr]=8;var Fr=new _r(32);for(xr=0;xr<32;++xr)Fr[xr]=5;var Rr=Cr(Pr,9,0),Tr=Cr(Fr,5,0),$r=function(e){return(e/8>>0)+(7&e&&1)},Or=function(e,t,i){(null==i||i>e.length)&&(i=e.length);var r=new(e instanceof pr?pr:e instanceof vr?vr:_r)(i-t);return r.set(e.subarray(t,i)),r},Mr=function(e,t,i){i<<=7&t;var r=t/8>>0;e[r]|=i,e[r+1]|=i>>>8},Lr=function(e,t,i){i<<=7&t;var r=t/8>>0;e[r]|=i,e[r+1]|=i>>>8,e[r+2]|=i>>>16},Ar=function(e,t){for(var i=[],r=0;rh&&(h=s[r].s);var _=new pr(h+1),p=Dr(i[c-1],_,0);if(p>t){r=0;var v=0,g=p-t,f=1<t))break;v+=f-(1<>>=g;v>0;){var b=s[r].s;_[b]=0&&v;--r){var y=s[r].s;_[y]==t&&(--_[y],++v)}p=t}return[new _r(_),p]},Dr=function(e,t,i){return-1==e.s?Math.max(Dr(e.l,t,i+1),Dr(e.r,t,i+1)):t[e.s]=i},Nr=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new pr(++t),r=0,n=e[0],s=1,o=function(e){i[r++]=e},a=1;a<=t;++a)if(e[a]==n&&a!=t)++s;else{if(!n&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(n),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(n);s=1,n=e[a]}return[i.subarray(0,r),t]},qr=function(e,t){for(var i=0,r=0;r>>8,e[n+2]=255^e[n],e[n+3]=255^e[n+1];for(var s=0;s4&&!I[mr[P-1]];--P);var F,R,T,$,O=u+5<<3,M=qr(n,Pr)+qr(s,Fr)+o,L=qr(n,h)+qr(s,v)+o+14+3*P+qr(E,I)+(2*E[16]+3*E[17]+7*E[18]);if(O<=M&&O<=L)return Br(t,c,e.subarray(l,l+u));if(Mr(t,c,1+(L15&&(Mr(t,c,q[k]>>>5&127),c+=q[k]>>>12)}}}else F=Rr,R=Pr,T=Tr,$=Fr;for(k=0;k255){B=r[k]>>>18&31;Lr(t,c,F[B+257]),c+=R[B+257],B>7&&(Mr(t,c,r[k]>>>23&31),c+=gr[B]);var H=31&r[k];Lr(t,c,T[H]),c+=$[H],H>3&&(Lr(t,c,r[k]>>>5&8191),c+=fr[H])}else Lr(t,c,F[r[k]]),c+=R[r[k]];return Lr(t,c,F[256]),c+R[256]},Ur=new vr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),zr=function(){for(var e=new vr(256),t=0;t<256;++t){for(var i=t,r=9;--r;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),jr=function(){var e=4294967295;return{p:function(t){for(var i=e,r=0;r>>8;e=i},d:function(){return 4294967295^e}}},Wr=function(e,t,i,r,n){return function(e,t,i,r,n,s){var o=e.length,a=new _r(r+o+5*(1+Math.floor(o/7e3))+n),l=a.subarray(r,a.length-n),u=0;if(!t||o<8)for(var c=0;c<=o;c+=65535){var d=c+65535;d>>13,p=8191&h,v=(1<7e3||I>24576)&&$>423){u=Hr(e,l,0,w,S,E,x,I,P,c-P,u),I=k=x=0,P=c;for(var O=0;O<286;++O)S[O]=0;for(O=0;O<30;++O)E[O]=0}var M=2,L=0,A=p,D=R-T&32767;if($>2&&F==y(c-D))for(var N=Math.min(_,$)-1,q=Math.min(32767,c),B=Math.min(258,$);D<=q&&--A&&R!=T;){if(e[c+M]==e[c+M-D]){for(var H=0;HM){if(M=H,L=D,H>N)break;var U=Math.min(D,H-2),z=0;for(O=0;Oz&&(z=W,T=j)}}}D+=(R=T)-(T=g[R])+32768&32767}if(L){w[I++]=268435456|Sr[M]<<18|Er[L];var V=31&Sr[M],G=31&Er[L];x+=gr[V]+fr[G],++S[257+V],++E[G],C=c+M,++k}else w[I++]=e[c],++S[e[c]]}}u=Hr(e,l,s,w,S,E,x,I,P,c-P,u)}return Or(a,0,r+$r(u)+n)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,i,r,!n)},Vr=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8},Gr=function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&Vr(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var r=0;r<=i.length;++r)e[r+10]=i.charCodeAt(r)}},Jr=function(e){return 10+(e.filename&&e.filename.length+1||0)};function Yr(e,t){void 0===t&&(t={});var i=jr(),r=e.length;i.p(e);var n=Wr(e,t,Jr(t),8),s=n.length;return Gr(n,t),Vr(n,s-8,i.d()),Vr(n,s-4,r),n}function Kr(e,t){var i=e.length;if(\"undefined\"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var r=new _r(e.length+(e.length>>>1)),n=0,s=function(e){r[n++]=e},o=0;or.length){var a=new _r(n+8+(i-o<<1));a.set(r),r=a}var l=e.charCodeAt(o);l<128||t?s(l):l<2048?(s(192|l>>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),s(128|l>>>12&63),s(128|l>>>6&63),s(128|63&l)):(s(224|l>>>12),s(128|l>>>6&63),s(128|63&l))}return Or(r,0,n)}var Xr=\"[SessionRecording]\",Qr=B(Xr),Zr=3e5,en=[Ci.MouseMove,Ci.MouseInteraction,Ci.Scroll,Ci.ViewportResize,Ci.Input,Ci.TouchMove,Ci.MediaInteraction,Ci.Drag],tn=e=>({rrwebMethod:e,enqueuedAt:Date.now(),attempt:1});function rn(e){return function(e,t){for(var i=\"\",r=0;r>10,56320|1023&n))}return i}(Yr(Kr(JSON.stringify(e))),!0)}function nn(e){return e.type===Ii.Custom&&\"sessionIdle\"===e.data.tag}function sn(e,t){return t.some((t=>\"regex\"===t.matching&&new RegExp(t.url).test(e)))}class on{get sessionIdleThresholdMilliseconds(){return this.instance.config.session_recording.session_idle_threshold_ms||3e5}get rrwebRecord(){var e,t;return null==_||null===(e=_.__PosthogExtensions__)||void 0===e||null===(t=e.rrweb)||void 0===t?void 0:t.record}get started(){return this._captureStarted}get sessionManager(){if(!this.instance.sessionManager)throw new Error(Xr+\" must be started with a valid sessionManager.\");return this.instance.sessionManager}get fullSnapshotIntervalMillis(){var e,t;return\"trigger_pending\"===this.triggerStatus?6e4:null!==(e=null===(t=this.instance.config.session_recording)||void 0===t?void 0:t.full_snapshot_interval_millis)&&void 0!==e?e:Zr}get isSampled(){var e=this.instance.get_property(Se);return L(e)?e:null}get sessionDuration(){var e,t,i=null===(e=this.buffer)||void 0===e?void 0:e.data[(null===(t=this.buffer)||void 0===t?void 0:t.data.length)-1],{sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0);return i?i.timestamp-r:null}get isRecordingEnabled(){var e=!!this.instance.get_property(pe),i=!this.instance.config.disable_session_recording;return t&&e&&i}get isConsoleLogCaptureEnabled(){var e=!!this.instance.get_property(ve),t=this.instance.config.enable_recording_console_log;return null!=t?t:e}get canvasRecording(){var e,t,i,r,n,s,o=this.instance.config.session_recording.captureCanvas,a=this.instance.get_property(fe),l=null!==(e=null!==(t=null==o?void 0:o.recordCanvas)&&void 0!==t?t:null==a?void 0:a.enabled)&&void 0!==e&&e,u=null!==(i=null!==(r=null==o?void 0:o.canvasFps)&&void 0!==r?r:null==a?void 0:a.fps)&&void 0!==i?i:0,c=null!==(n=null!==(s=null==o?void 0:o.canvasQuality)&&void 0!==s?s:null==a?void 0:a.quality)&&void 0!==n?n:0;return{enabled:l,fps:dr(u,0,12,\"canvas recording fps\"),quality:dr(c,0,1,\"canvas recording quality\")}}get networkPayloadCapture(){var e,t,i=this.instance.get_property(ge),r={recordHeaders:null===(e=this.instance.config.session_recording)||void 0===e?void 0:e.recordHeaders,recordBody:null===(t=this.instance.config.session_recording)||void 0===t?void 0:t.recordBody},n=(null==r?void 0:r.recordHeaders)||(null==i?void 0:i.recordHeaders),s=(null==r?void 0:r.recordBody)||(null==i?void 0:i.recordBody),o=C(this.instance.config.capture_performance)?this.instance.config.capture_performance.network_timing:this.instance.config.capture_performance,a=!!(L(o)?o:null==i?void 0:i.capturePerformance);return n||s||a?{recordHeaders:n,recordBody:s,recordPerformance:a}:void 0}get sampleRate(){var e=this.instance.get_property(me);return M(e)?e:null}get minimumDuration(){var e=this.instance.get_property(be);return M(e)?e:null}get status(){return this.receivedDecide?this.isRecordingEnabled?this._urlBlocked?\"paused\":O(this._linkedFlag)||this._linkedFlagSeen?\"trigger_pending\"===this.triggerStatus?\"buffering\":L(this.isSampled)?this.isSampled?\"sampled\":\"disabled\":\"active\":\"buffering\":\"disabled\":\"buffering\"}get urlTriggerStatus(){var e;return 0===this._urlTriggers.length?\"trigger_disabled\":(null===(e=this.instance)||void 0===e?void 0:e.get_property(Ee))===this.sessionId?\"trigger_activated\":\"trigger_pending\"}get eventTriggerStatus(){var e;return 0===this._eventTriggers.length?\"trigger_disabled\":(null===(e=this.instance)||void 0===e?void 0:e.get_property(ke))===this.sessionId?\"trigger_activated\":\"trigger_pending\"}get triggerStatus(){var e=\"trigger_activated\"===this.eventTriggerStatus||\"trigger_activated\"===this.urlTriggerStatus,t=\"trigger_pending\"===this.eventTriggerStatus||\"trigger_pending\"===this.urlTriggerStatus;return e?\"trigger_activated\":t?\"trigger_pending\":\"trigger_disabled\"}constructor(e){if(W(this,\"queuedRRWebEvents\",[]),W(this,\"isIdle\",!1),W(this,\"_linkedFlagSeen\",!1),W(this,\"_lastActivityTimestamp\",Date.now()),W(this,\"_linkedFlag\",null),W(this,\"_removePageViewCaptureHook\",void 0),W(this,\"_onSessionIdListener\",void 0),W(this,\"_persistDecideOnSessionListener\",void 0),W(this,\"_samplingSessionListener\",void 0),W(this,\"_urlTriggers\",[]),W(this,\"_urlBlocklist\",[]),W(this,\"_urlBlocked\",!1),W(this,\"_eventTriggers\",[]),W(this,\"_removeEventTriggerCaptureHook\",void 0),W(this,\"_forceAllowLocalhostNetworkCapture\",!1),W(this,\"_onBeforeUnload\",(()=>{this._flushBuffer()})),W(this,\"_onOffline\",(()=>{this._tryAddCustomEvent(\"browser offline\",{})})),W(this,\"_onOnline\",(()=>{this._tryAddCustomEvent(\"browser online\",{})})),W(this,\"_onVisibilityChange\",(()=>{if(null!=a&&a.visibilityState){var e=\"window \"+a.visibilityState;this._tryAddCustomEvent(e,{})}})),this.instance=e,this._captureStarted=!1,this._endpoint=\"/s/\",this.stopRrweb=void 0,this.receivedDecide=!1,!this.instance.sessionManager)throw Qr.error(\"started without valid sessionManager\"),new Error(Xr+\" started without valid sessionManager. This is a bug.\");if(this.instance.config.__preview_experimental_cookieless_mode)throw new Error(Xr+\" cannot be used with __preview_experimental_cookieless_mode.\");var{sessionId:t,windowId:i}=this.sessionManager.checkAndGetSessionAndWindowId();this.sessionId=t,this.windowId=i,this.buffer=this.clearBuffer(),this.sessionIdleThresholdMilliseconds>=this.sessionManager.sessionTimeoutMs&&Qr.warn(\"session_idle_threshold_ms (\".concat(this.sessionIdleThresholdMilliseconds,\") is greater than the session timeout (\").concat(this.sessionManager.sessionTimeoutMs,\"). Session will never be detected as idle\"))}startIfEnabledOrStop(e){this.isRecordingEnabled?(this._startCapture(e),null==t||t.addEventListener(\"beforeunload\",this._onBeforeUnload),null==t||t.addEventListener(\"offline\",this._onOffline),null==t||t.addEventListener(\"online\",this._onOnline),null==t||t.addEventListener(\"visibilitychange\",this._onVisibilityChange),this._setupSampling(),this._addEventTriggerListener(),O(this._removePageViewCaptureHook)&&(this._removePageViewCaptureHook=this.instance.on(\"eventCaptured\",(e=>{try{if(\"$pageview\"===e.event){var t=null!=e&&e.properties.$current_url?this._maskUrl(null==e?void 0:e.properties.$current_url):\"\";if(!t)return;this._tryAddCustomEvent(\"$pageview\",{href:t})}}catch(e){Qr.error(\"Could not add $pageview to rrweb session\",e)}}))),this._onSessionIdListener||(this._onSessionIdListener=this.sessionManager.onSessionId(((e,t,i)=>{var r,n,s,o;i&&(this._tryAddCustomEvent(\"$session_id_change\",{sessionId:e,windowId:t,changeReason:i}),null===(r=this.instance)||void 0===r||null===(n=r.persistence)||void 0===n||n.unregister(ke),null===(s=this.instance)||void 0===s||null===(o=s.persistence)||void 0===o||o.unregister(Ee))})))):this.stopRecording()}stopRecording(){var e,i,r,n;this._captureStarted&&this.stopRrweb&&(this.stopRrweb(),this.stopRrweb=void 0,this._captureStarted=!1,null==t||t.removeEventListener(\"beforeunload\",this._onBeforeUnload),null==t||t.removeEventListener(\"offline\",this._onOffline),null==t||t.removeEventListener(\"online\",this._onOnline),null==t||t.removeEventListener(\"visibilitychange\",this._onVisibilityChange),this.clearBuffer(),clearInterval(this._fullSnapshotTimer),null===(e=this._removePageViewCaptureHook)||void 0===e||e.call(this),this._removePageViewCaptureHook=void 0,null===(i=this._removeEventTriggerCaptureHook)||void 0===i||i.call(this),this._removeEventTriggerCaptureHook=void 0,null===(r=this._onSessionIdListener)||void 0===r||r.call(this),this._onSessionIdListener=void 0,null===(n=this._samplingSessionListener)||void 0===n||n.call(this),this._samplingSessionListener=void 0,Qr.info(\"stopped\"))}makeSamplingDecision(e){var t,i=this.sessionId!==e,r=this.sampleRate;if(M(r)){var n,s=this.isSampled,o=i||!L(s);if(o)n=Math.random(){var i=C(t)&&a in t,r=l?t[a]===l:i;r&&this._reportStarted(\"linked_flag_matched\",{linkedFlag:a,linkedVariant:l}),this._linkedFlagSeen=r}))}null!==(r=e.sessionRecording)&&void 0!==r&&r.urlTriggers&&(this._urlTriggers=e.sessionRecording.urlTriggers),null!==(n=e.sessionRecording)&&void 0!==n&&n.urlBlocklist&&(this._urlBlocklist=e.sessionRecording.urlBlocklist),null!==(s=e.sessionRecording)&&void 0!==s&&s.eventTriggers&&(this._eventTriggers=e.sessionRecording.eventTriggers),this.receivedDecide=!0,this.startIfEnabledOrStop()}_setupSampling(){M(this.sampleRate)&&O(this._samplingSessionListener)&&(this._samplingSessionListener=this.sessionManager.onSessionId((e=>{this.makeSamplingDecision(e)})))}_persistRemoteConfig(e){if(this.instance.persistence){var t,i=this.instance.persistence,r=()=>{var t,r,n,s,o,a,l,u,c=null===(t=e.sessionRecording)||void 0===t?void 0:t.sampleRate,d=O(c)?null:parseFloat(c),h=null===(r=e.sessionRecording)||void 0===r?void 0:r.minimumDurationMilliseconds;i.register({[pe]:!!e.sessionRecording,[ve]:null===(n=e.sessionRecording)||void 0===n?void 0:n.consoleLogRecordingEnabled,[ge]:j({capturePerformance:e.capturePerformance},null===(s=e.sessionRecording)||void 0===s?void 0:s.networkPayloadCapture),[fe]:{enabled:null===(o=e.sessionRecording)||void 0===o?void 0:o.recordCanvas,fps:null===(a=e.sessionRecording)||void 0===a?void 0:a.canvasFps,quality:null===(l=e.sessionRecording)||void 0===l?void 0:l.canvasQuality},[me]:d,[be]:F(h)?null:h,[ye]:null===(u=e.sessionRecording)||void 0===u?void 0:u.scriptConfig})};r(),null===(t=this._persistDecideOnSessionListener)||void 0===t||t.call(this),this._persistDecideOnSessionListener=this.sessionManager.onSessionId(r)}}log(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"log\";null===(t=this.instance.sessionRecording)||void 0===t||t.onRRwebEmit({type:6,data:{plugin:\"rrweb/console@1\",payload:{level:i,trace:[],payload:[JSON.stringify(e)]}},timestamp:Date.now()})}_startCapture(e){if(!F(Object.assign)&&!F(Array.from)&&!(this._captureStarted||this.instance.config.disable_session_recording||this.instance.consent.isOptedOut())){var t,i;if(this._captureStarted=!0,this.sessionManager.checkAndGetSessionAndWindowId(),this.rrwebRecord)this._onScriptLoaded();else null===(t=_.__PosthogExtensions__)||void 0===t||null===(i=t.loadExternalDependency)||void 0===i||i.call(t,this.instance,this.scriptName,(e=>{if(e)return Qr.error(\"could not load recorder\",e);this._onScriptLoaded()}));Qr.info(\"starting\"),\"active\"===this.status&&this._reportStarted(e||\"recording_initialized\")}}get scriptName(){var e,t,i;return(null===(e=this.instance)||void 0===e||null===(t=e.persistence)||void 0===t||null===(i=t.get_property(ye))||void 0===i?void 0:i.script)||\"recorder\"}isInteractiveEvent(e){var t;return 3===e.type&&-1!==en.indexOf(null===(t=e.data)||void 0===t?void 0:t.source)}_updateWindowAndSessionIds(e){var t=this.isInteractiveEvent(e);t||this.isIdle||e.timestamp-this._lastActivityTimestamp>this.sessionIdleThresholdMilliseconds&&(this.isIdle=!0,clearInterval(this._fullSnapshotTimer),this._tryAddCustomEvent(\"sessionIdle\",{eventTimestamp:e.timestamp,lastActivityTimestamp:this._lastActivityTimestamp,threshold:this.sessionIdleThresholdMilliseconds,bufferLength:this.buffer.data.length,bufferSize:this.buffer.size}),this._flushBuffer());var i=!1;if(t&&(this._lastActivityTimestamp=e.timestamp,this.isIdle&&(this.isIdle=!1,this._tryAddCustomEvent(\"sessionNoLongerIdle\",{reason:\"user activity\",type:e.type}),i=!0)),!this.isIdle){var{windowId:r,sessionId:n}=this.sessionManager.checkAndGetSessionAndWindowId(!t,e.timestamp),s=this.sessionId!==n,o=this.windowId!==r;this.windowId=r,this.sessionId=n,s||o?(this.stopRecording(),this.startIfEnabledOrStop(\"session_id_changed\")):i&&this._scheduleFullSnapshot()}}_tryRRWebMethod(e){try{return e.rrwebMethod(),!0}catch(t){return this.queuedRRWebEvents.length<10?this.queuedRRWebEvents.push({enqueuedAt:e.enqueuedAt||Date.now(),attempt:e.attempt++,rrwebMethod:e.rrwebMethod}):Qr.warn(\"could not emit queued rrweb event.\",t,e),!1}}_tryAddCustomEvent(e,t){return this._tryRRWebMethod(tn((()=>this.rrwebRecord.addCustomEvent(e,t))))}_tryTakeFullSnapshot(){return this._tryRRWebMethod(tn((()=>this.rrwebRecord.takeFullSnapshot())))}_onScriptLoaded(){var e,t={blockClass:\"ph-no-capture\",blockSelector:void 0,ignoreClass:\"ph-ignore-input\",maskTextClass:\"ph-mask\",maskTextSelector:void 0,maskTextFn:void 0,maskAllInputs:!0,maskInputOptions:{password:!0},maskInputFn:void 0,slimDOMOptions:{},collectFonts:!1,inlineStylesheet:!0,recordCrossOriginIframes:!1},i=this.instance.config.session_recording;for(var[r,n]of Object.entries(i||{}))r in t&&(\"maskInputOptions\"===r?t.maskInputOptions=j({password:!0},n):t[r]=n);if(this.canvasRecording&&this.canvasRecording.enabled&&(t.recordCanvas=!0,t.sampling={canvas:this.canvasRecording.fps},t.dataURLOptions={type:\"image/webp\",quality:this.canvasRecording.quality}),this.rrwebRecord){this.mutationRateLimiter=null!==(e=this.mutationRateLimiter)&&void 0!==e?e:new hr(this.rrwebRecord,{refillRate:this.instance.config.session_recording.__mutationRateLimiterRefillRate,bucketSize:this.instance.config.session_recording.__mutationRateLimiterBucketSize,onBlockedNode:(e,t)=>{var i=\"Too many mutations on node '\".concat(e,\"'. Rate limiting. This could be due to SVG animations or something similar\");Qr.info(i,{node:t}),this.log(Xr+\" \"+i,\"warn\")}});var s=this._gatherRRWebPlugins();this.stopRrweb=this.rrwebRecord(j({emit:e=>{this.onRRwebEmit(e)},plugins:s},t)),this._lastActivityTimestamp=Date.now(),this.isIdle=!1,this._tryAddCustomEvent(\"$session_options\",{sessionRecordingOptions:t,activePlugins:s.map((e=>null==e?void 0:e.name))}),this._tryAddCustomEvent(\"$posthog_config\",{config:this.instance.config})}else Qr.error(\"onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.\")}_scheduleFullSnapshot(){if(this._fullSnapshotTimer&&clearInterval(this._fullSnapshotTimer),!this.isIdle){var e=this.fullSnapshotIntervalMillis;e&&(this._fullSnapshotTimer=setInterval((()=>{this._tryTakeFullSnapshot()}),e))}}_gatherRRWebPlugins(){var e,t,i,r,n=[],s=null===(e=_.__PosthogExtensions__)||void 0===e||null===(t=e.rrwebPlugins)||void 0===t?void 0:t.getRecordConsolePlugin;s&&this.isConsoleLogCaptureEnabled&&n.push(s());var o=null===(i=_.__PosthogExtensions__)||void 0===i||null===(r=i.rrwebPlugins)||void 0===r?void 0:r.getRecordNetworkPlugin;this.networkPayloadCapture&&I(o)&&(!vt.includes(location.hostname)||this._forceAllowLocalhostNetworkCapture?n.push(o(cr(this.instance.config,this.networkPayloadCapture))):Qr.info(\"NetworkCapture not started because we are on localhost.\"));return n}onRRwebEmit(e){var t;if(this._processQueuedEvents(),e&&C(e)){if(e.type===Ii.Meta){var i=this._maskUrl(e.data.href);if(this._lastHref=i,!i)return;e.data.href=i}else this._pageViewFallBack();if(this._checkUrlTriggerConditions(),\"paused\"!==this.status||function(e){return e.type===Ii.Custom&&\"recording paused\"===e.data.tag}(e)){e.type===Ii.FullSnapshot&&this._scheduleFullSnapshot(),e.type===Ii.FullSnapshot&&\"trigger_pending\"===this.triggerStatus&&this.clearBuffer();var r=this.mutationRateLimiter?this.mutationRateLimiter.throttleMutations(e):e;if(r){var n=function(e){var t=e;if(t&&C(t)&&6===t.type&&C(t.data)&&\"rrweb/console@1\"===t.data.plugin){t.data.payload.payload.length>10&&(t.data.payload.payload=t.data.payload.payload.slice(0,10),t.data.payload.payload.push(\"...[truncated]\"));for(var i=[],r=0;r2e3?i.push(t.data.payload.payload[r].slice(0,2e3)+\"...[truncated]\"):i.push(t.data.payload.payload[r]);return t.data.payload.payload=i,e}return e}(r);if(this._updateWindowAndSessionIds(n),!this.isIdle||nn(n)){if(nn(n)){var s=n.data.payload;if(s){var o=s.lastActivityTimestamp,a=s.threshold;n.timestamp=o+a}}var l=null===(t=this.instance.config.session_recording.compress_events)||void 0===t||t?function(e){if(ki(e)<1024)return e;try{if(e.type===Ii.FullSnapshot)return j(j({},e),{},{data:rn(e.data),cv:\"2024-10\"});if(e.type===Ii.IncrementalSnapshot&&e.data.source===Ci.Mutation)return j(j({},e),{},{cv:\"2024-10\",data:j(j({},e.data),{},{texts:rn(e.data.texts),attributes:rn(e.data.attributes),removes:rn(e.data.removes),adds:rn(e.data.adds)})});if(e.type===Ii.IncrementalSnapshot&&e.data.source===Ci.StyleSheetRule)return j(j({},e),{},{cv:\"2024-10\",data:j(j({},e.data),{},{adds:rn(e.data.adds),removes:rn(e.data.removes)})})}catch(e){Qr.error(\"could not compress event - will use uncompressed event\",e)}return e}(n):n,u={$snapshot_bytes:ki(l),$snapshot_data:l,$session_id:this.sessionId,$window_id:this.windowId};\"disabled\"!==this.status?this._captureSnapshotBuffered(u):this.clearBuffer()}}}}}_pageViewFallBack(){if(!this.instance.config.capture_pageview&&t){var e=this._maskUrl(t.location.href);this._lastHref!==e&&(this._tryAddCustomEvent(\"$url_changed\",{href:e}),this._lastHref=e)}}_processQueuedEvents(){if(this.queuedRRWebEvents.length){var e=[...this.queuedRRWebEvents];this.queuedRRWebEvents=[],e.forEach((e=>{Date.now()-e.enqueuedAt<=2e3&&this._tryRRWebMethod(e)}))}}_maskUrl(e){var t=this.instance.config.session_recording;if(t.maskNetworkRequestFn){var i,r={url:e};return null===(i=r=t.maskNetworkRequestFn(r))||void 0===i?void 0:i.url}return e}clearBuffer(){return this.buffer={size:0,data:[],sessionId:this.sessionId,windowId:this.windowId},this.buffer}_flushBuffer(){this.flushBufferTimer&&(clearTimeout(this.flushBufferTimer),this.flushBufferTimer=void 0);var e=this.minimumDuration,t=this.sessionDuration,i=M(t)&&t>=0,r=M(e)&&i&&t{this._flushBuffer()}),2e3),this.buffer;this.buffer.data.length>0&&xi(this.buffer).forEach((e=>{this._captureSnapshot({$snapshot_bytes:e.size,$snapshot_data:e.data,$session_id:e.sessionId,$window_id:e.windowId,$lib:\"web\",$lib_version:p.LIB_VERSION})}));return this.clearBuffer()}_captureSnapshotBuffered(e){var t,i=2+((null===(t=this.buffer)||void 0===t?void 0:t.data.length)||0);!this.isIdle&&(this.buffer.size+e.$snapshot_bytes+i>943718.4||this.buffer.sessionId!==this.sessionId)&&(this.buffer=this._flushBuffer()),this.buffer.size+=e.$snapshot_bytes,this.buffer.data.push(e.$snapshot_data),this.flushBufferTimer||this.isIdle||(this.flushBufferTimer=setTimeout((()=>{this._flushBuffer()}),2e3))}_captureSnapshot(e){this.instance.capture(\"$snapshot\",e,{_url:this.instance.requestRouter.endpointFor(\"api\",this._endpoint),_noTruncate:!0,_batchKey:\"recordings\",skip_client_rate_limiting:!0})}_checkUrlTriggerConditions(){if(void 0!==t&&t.location.href){var e=t.location.href,i=\"paused\"===this.status,r=sn(e,this._urlBlocklist);r&&!i?this._pauseRecording():!r&&i&&this._resumeRecording(),sn(e,this._urlTriggers)&&this._activateTrigger(\"url\")}}_activateTrigger(e){var t,i;\"trigger_pending\"===this.triggerStatus&&(null===(t=this.instance)||void 0===t||null===(i=t.persistence)||void 0===i||i.register({[\"url\"===e?Ee:ke]:this.sessionId}),this._flushBuffer(),this._reportStarted(e+\"_trigger_matched\"))}_pauseRecording(){\"paused\"!==this.status&&(this._urlBlocked=!0,clearInterval(this._fullSnapshotTimer),Qr.info(\"recording paused due to URL blocker\"),this._tryAddCustomEvent(\"recording paused\",{reason:\"url blocker\"}))}_resumeRecording(){\"paused\"===this.status&&(this._urlBlocked=!1,this._tryTakeFullSnapshot(),this._scheduleFullSnapshot(),this._tryAddCustomEvent(\"recording resumed\",{reason:\"left blocked url\"}),Qr.info(\"recording resumed\"))}_addEventTriggerListener(){0!==this._eventTriggers.length&&O(this._removeEventTriggerCaptureHook)&&(this._removeEventTriggerCaptureHook=this.instance.on(\"eventCaptured\",(e=>{try{this._eventTriggers.includes(e.event)&&this._activateTrigger(\"event\")}catch(e){Qr.error(\"Could not activate event trigger\",e)}})))}overrideLinkedFlag(){this._linkedFlagSeen=!0,this._tryTakeFullSnapshot(),this._reportStarted(\"linked_flag_overridden\")}overrideSampling(){var e;null===(e=this.instance.persistence)||void 0===e||e.register({[Se]:!0}),this._tryTakeFullSnapshot(),this._reportStarted(\"sampling_overridden\")}overrideTrigger(e){this._activateTrigger(e)}_reportStarted(e,t){this.instance.register_for_session({$session_recording_start_reason:e}),Qr.info(e.replace(\"_\",\" \"),t),m([\"recording_initialized\",\"session_id_changed\"],e)||this._tryAddCustomEvent(e,t)}}var an=B(\"[RemoteConfig]\");class ln{constructor(e){this.instance=e}get remoteConfig(){var e,t;return null===(e=_._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(t=e[this.instance.config.token])||void 0===t?void 0:t.config}_loadRemoteConfigJs(e){var t,i,r;null!==(t=_.__PosthogExtensions__)&&void 0!==t&&t.loadExternalDependency?null===(i=_.__PosthogExtensions__)||void 0===i||null===(r=i.loadExternalDependency)||void 0===r||r.call(i,this.instance,\"remote-config\",(()=>e(this.remoteConfig))):(an.error(\"PostHog Extensions not found. Cannot load remote config.\"),e())}_loadRemoteConfigJSON(e){this.instance._send_request({method:\"GET\",url:this.instance.requestRouter.endpointFor(\"assets\",\"/array/\".concat(this.instance.config.token,\"/config\")),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return an.info(\"Using preloaded remote config\",this.remoteConfig),void this.onRemoteConfig(this.remoteConfig);if(this.instance.config.advanced_disable_decide)return void an.warn(\"Remote config is disabled. Falling back to local config.\");this._loadRemoteConfigJs((e=>{if(!e)return an.info(\"No config found after loading remote JS config. Falling back to JSON.\"),void this._loadRemoteConfigJSON((e=>{this.onRemoteConfig(e)}));this.onRemoteConfig(e)}))}catch(e){an.error(\"Error loading remote config\",e)}}onRemoteConfig(e){e?this.instance.config.__preview_remote_config?(this.instance._onRemoteConfig(e),!1!==e.hasFeatureFlags&&this.instance.featureFlags.ensureFlagsLoaded()):an.info(\"__preview_remote_config is disabled. Logging config instead\",e):an.error(\"Failed to fetch remote config from PostHog.\")}}var un,cn=null!=t&&t.location?wt(t.location.hash,\"__posthog\")||wt(location.hash,\"state\"):null,dn=\"_postHogToolbarParams\",hn=B(\"[Toolbar]\");!function(e){e[e.UNINITIALIZED=0]=\"UNINITIALIZED\",e[e.LOADING=1]=\"LOADING\",e[e.LOADED=2]=\"LOADED\"}(un||(un={}));class _n{constructor(e){this.instance=e}setToolbarState(e){_.ph_toolbar_state=e}getToolbarState(){var e;return null!==(e=_.ph_toolbar_state)&&void 0!==e?e:un.UNINITIALIZED}maybeLoadToolbar(){var e,i,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(!t||!a)return!1;r=null!==(e=r)&&void 0!==e?e:t.location,s=null!==(i=s)&&void 0!==i?i:t.history;try{if(!n){try{t.localStorage.setItem(\"test\",\"test\"),t.localStorage.removeItem(\"test\")}catch(e){return!1}n=null==t?void 0:t.localStorage}var o,l=cn||wt(r.hash,\"__posthog\")||wt(r.hash,\"state\"),u=l?Z((()=>JSON.parse(atob(decodeURIComponent(l)))))||Z((()=>JSON.parse(decodeURIComponent(l)))):null;return u&&\"ph_authorize\"===u.action?((o=u).source=\"url\",o&&Object.keys(o).length>0&&(u.desiredHash?r.hash=u.desiredHash:s?s.replaceState(s.state,\"\",r.pathname+r.search):r.hash=\"\")):((o=JSON.parse(n.getItem(dn)||\"{}\")).source=\"localstorage\",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token)&&(this.loadToolbar(o),!0)}catch(e){return!1}}_callLoadToolbar(e){var t=_.ph_load_toolbar||_.ph_load_editor;!O(t)&&I(t)?t(e,this.instance):hn.warn(\"No toolbar load function found\")}loadToolbar(e){var i=!(null==a||!a.getElementById(qe));if(!t||i)return!1;var r=\"custom\"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,n=j(j({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor(\"ui\")},r?{instrument:!1}:{});if(t.localStorage.setItem(dn,JSON.stringify(j(j({},n),{},{source:void 0}))),this.getToolbarState()===un.LOADED)this._callLoadToolbar(n);else if(this.getToolbarState()===un.UNINITIALIZED){var s,o;this.setToolbarState(un.LOADING),null===(s=_.__PosthogExtensions__)||void 0===s||null===(o=s.loadExternalDependency)||void 0===o||o.call(s,this.instance,\"toolbar\",(e=>{if(e)return hn.error(\"[Toolbar] Failed to load\",e),void this.setToolbarState(un.UNINITIALIZED);this.setToolbarState(un.LOADED),this._callLoadToolbar(n)})),re(t,\"turbolinks:load\",(()=>{this.setToolbarState(un.UNINITIALIZED),this.loadToolbar(n)}))}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return this.maybeLoadToolbar(e,t,i)}}class pn{constructor(e){W(this,\"isPaused\",!0),W(this,\"queue\",[]),W(this,\"flushTimeoutMs\",3e3),this.sendRequest=e}enqueue(e){this.queue.push(e),this.flushTimeout||this.setFlushTimeout()}unload(){this.clearFlushTimeout();var e=this.queue.length>0?this.formatQueue():{},t=Object.values(e),i=[...t.filter((e=>0===e.url.indexOf(\"/e\"))),...t.filter((e=>0!==e.url.indexOf(\"/e\")))];i.map((e=>{this.sendRequest(j(j({},e),{},{transport:\"sendBeacon\"}))}))}enable(){this.isPaused=!1,this.setFlushTimeout()}setFlushTimeout(){var e=this;this.isPaused||(this.flushTimeout=setTimeout((()=>{if(this.clearFlushTimeout(),this.queue.length>0){var t=this.formatQueue(),i=function(i){var r=t[i],n=(new Date).getTime();r.data&&x(r.data)&&Y(r.data,(e=>{e.offset=Math.abs(e.timestamp-n),delete e.timestamp})),e.sendRequest(r)};for(var r in t)i(r)}}),this.flushTimeoutMs))}clearFlushTimeout(){clearTimeout(this.flushTimeout),this.flushTimeout=void 0}formatQueue(){var e={};return Y(this.queue,(t=>{var i,r=t,n=(r?r.batchKey:null)||r.url;F(e[n])&&(e[n]=j(j({},r),{},{data:[]})),null===(i=e[n].data)||void 0===i||i.push(r.data)})),this.queue=[],e}}var vn=function(e){var t,i,r,n,s=\"\";for(t=i=0,r=(e=(e+\"\").replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\")).length,n=0;n127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),$(a)||(i>t&&(s+=e.substring(t,i)),s+=a,t=i=n+1)}return i>t&&(s+=e.substring(t,e.length)),s},gn=!!c||!!u,fn=\"text/plain\",mn=(e,t)=>{var[i,r]=e.split(\"?\"),n=j({},t);null==r||r.split(\"&\").forEach((e=>{var[t]=e.split(\"=\");delete n[t]}));var s=mt(n);return s=s?(r?r+\"&\":\"\")+s:r,\"\".concat(i,\"?\").concat(s)},bn=(e,t)=>JSON.stringify(e,((e,t)=>\"bigint\"==typeof t?t.toString():t),t),yn=t=>{var{data:i,compression:r}=t;if(i){if(r===e.GZipJS){var n=Yr(Kr(bn(i)),{mtime:0}),s=new Blob([n],{type:fn});return{contentType:fn,body:s,estimatedSize:s.size}}if(r===e.Base64){var o=function(e){var t,i,r,n,s,o=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",a=0,l=0,u=\"\",c=[];if(!e)return e;e=vn(e);do{t=(s=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,i=s>>12&63,r=s>>6&63,n=63&s,c[l++]=o.charAt(t)+o.charAt(i)+o.charAt(r)+o.charAt(n)}while(a\"data=\"+encodeURIComponent(\"string\"==typeof e?e:bn(e)))(o);return{contentType:\"application/x-www-form-urlencoded\",body:a,estimatedSize:new Blob([a]).size}}var l=bn(i);return{contentType:\"application/json\",body:l,estimatedSize:new Blob([l]).size}}},wn=[];u&&wn.push({transport:\"fetch\",method:e=>{var t,i,{contentType:r,body:n,estimatedSize:s}=null!==(t=yn(e))&&void 0!==t?t:{},o=new Headers;Y(e.headers,(function(e,t){o.append(t,e)})),r&&o.append(\"Content-Type\",r);var a=e.url,l=null;if(d){var c=new d;l={signal:c.signal,timeout:setTimeout((()=>c.abort()),e.timeout)}}u(a,j({method:(null==e?void 0:e.method)||\"GET\",headers:o,keepalive:\"POST\"===e.method&&(s||0)<52428.8,body:n,signal:null===(i=l)||void 0===i?void 0:i.signal},e.fetchOptions)).then((t=>t.text().then((i=>{var r,n={statusCode:t.status,text:i};if(200===t.status)try{n.json=JSON.parse(i)}catch(e){q.error(e)}null===(r=e.callback)||void 0===r||r.call(e,n)})))).catch((t=>{var i;q.error(t),null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,text:t})})).finally((()=>l?clearTimeout(l.timeout):null))}}),c&&wn.push({transport:\"XHR\",method:e=>{var t,i=new c;i.open(e.method||\"GET\",e.url,!0);var{contentType:r,body:n}=null!==(t=yn(e))&&void 0!==t?t:{};Y(e.headers,(function(e,t){i.setRequestHeader(t,e)})),r&&i.setRequestHeader(\"Content-Type\",r),e.timeout&&(i.timeout=e.timeout),i.withCredentials=!0,i.onreadystatechange=()=>{if(4===i.readyState){var t,r={statusCode:i.status,text:i.responseText};if(200===i.status)try{r.json=JSON.parse(i.responseText)}catch(e){}null===(t=e.callback)||void 0===t||t.call(e,r)}},i.send(n)}}),null!=o&&o.sendBeacon&&wn.push({transport:\"sendBeacon\",method:e=>{var t=mn(e.url,{beacon:\"1\"});try{var i,{contentType:r,body:n}=null!==(i=yn(e))&&void 0!==i?i:{},s=\"string\"==typeof n?new Blob([n],{type:r}):n;o.sendBeacon(t,s)}catch(e){}}});var Sn=[\"retriesPerformedSoFar\"];class En{constructor(e){W(this,\"isPolling\",!1),W(this,\"pollIntervalMs\",3e3),W(this,\"queue\",[]),this.instance=e,this.queue=[],this.areWeOnline=!0,!F(t)&&\"onLine\"in t.navigator&&(this.areWeOnline=t.navigator.onLine,t.addEventListener(\"online\",(()=>{this.areWeOnline=!0,this.flush()})),t.addEventListener(\"offline\",(()=>{this.areWeOnline=!1})))}retriableRequest(e){var{retriesPerformedSoFar:t}=e,i=V(e,Sn);M(t)&&t>0&&(i.url=mn(i.url,{retry_count:t})),this.instance._send_request(j(j({},i),{},{callback:e=>{var r;200!==e.statusCode&&(e.statusCode<400||e.statusCode>=500)&&(null!=t?t:0)<10?this.enqueue(j({retriesPerformedSoFar:t},i)):null===(r=i.callback)||void 0===r||r.call(i,e)}}))}enqueue(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var i=function(e){var t=3e3*Math.pow(2,e),i=t/2,r=Math.min(18e5,t),n=(Math.random()-.5)*(r-i);return Math.ceil(r+n)}(t),r=Date.now()+i;this.queue.push({retryAt:r,requestOptions:e});var n=\"Enqueued failed request for retry in \".concat(i);navigator.onLine||(n+=\" (Browser is offline)\"),q.warn(n),this.isPolling||(this.isPolling=!0,this.poll())}poll(){this.poller&&clearTimeout(this.poller),this.poller=setTimeout((()=>{this.areWeOnline&&this.queue.length>0&&this.flush(),this.poll()}),this.pollIntervalMs)}flush(){var e=Date.now(),t=[],i=this.queue.filter((i=>i.retryAt0)for(var{requestOptions:r}of i)this.retriableRequest(r)}unload(){for(var{requestOptions:e}of(this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.queue))try{this.instance._send_request(j(j({},e),{},{transport:\"sendBeacon\"}))}catch(e){q.error(e)}this.queue=[]}}var kn,xn=B(\"[SessionId]\");class In{constructor(e,t,i){var r;if(W(this,\"_sessionIdChangedHandlers\",[]),!e.persistence)throw new Error(\"SessionIdManager requires a PostHogPersistence instance\");if(e.config.__preview_experimental_cookieless_mode)throw new Error(\"SessionIdManager cannot be used with __preview_experimental_cookieless_mode\");this.config=e.config,this.persistence=e.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this._sessionIdGenerator=t||et,this._windowIdGenerator=i||et;var n=this.config.persistence_name||this.config.token,s=this.config.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*dr(s,60,36e3,\"session_idle_timeout_seconds\",1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.resetIdleTimer(),this._window_id_storage_key=\"ph_\"+n+\"_window_id\",this._primary_window_exists_storage_key=\"ph_\"+n+\"_primary_window_exists\",this._canUseSessionStorage()){var o=pt.parse(this._window_id_storage_key),a=pt.parse(this._primary_window_exists_storage_key);o&&!a?this._windowId=o:pt.remove(this._window_id_storage_key),pt.set(this._primary_window_exists_storage_key,!0)}if(null!==(r=this.config.bootstrap)&&void 0!==r&&r.sessionID)try{var l=(e=>{var t=e.replace(/-/g,\"\");if(32!==t.length)throw new Error(\"Not a valid UUID\");if(\"7\"!==t[12])throw new Error(\"Not a UUIDv7\");return parseInt(t.substring(0,12),16)})(this.config.bootstrap.sessionID);this._setSessionId(this.config.bootstrap.sessionID,(new Date).getTime(),l)}catch(e){xn.error(\"Invalid sessionID in bootstrap\",e)}this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return F(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter((t=>t!==e))}}_canUseSessionStorage(){return\"memory\"!==this.config.persistence&&!this.persistence.disabled&&pt.is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&pt.set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?pt.parse(this._window_id_storage_key):null}_setSessionId(e,t,i){e===this._sessionId&&t===this._sessionActivityTimestamp&&i===this._sessionStartTimestamp||(this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,this.persistence.register({[we]:[t,e,i]}))}_getSessionId(){if(this._sessionId&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this._sessionId,this._sessionStartTimestamp];var e=this.persistence.props[we];return x(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._setSessionId(null,null,null)}_listenToReloadWindow(){null==t||t.addEventListener(\"beforeunload\",(()=>{this._canUseSessionStorage()&&pt.remove(this._primary_window_exists_storage_key)}))}checkAndGetSessionAndWindowId(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this.config.__preview_experimental_cookieless_mode)throw new Error(\"checkAndGetSessionAndWindowId should not be called in __preview_experimental_cookieless_mode\");var i=t||(new Date).getTime(),[r,n,s]=this._getSessionId(),o=this._getWindowId(),a=M(s)&&s>0&&Math.abs(i-s)>864e5,l=!1,u=!n,c=!e&&Math.abs(i-r)>this.sessionTimeoutMs;u||c||a?(n=this._sessionIdGenerator(),o=this._windowIdGenerator(),xn.info(\"new session ID generated\",{sessionId:n,windowId:o,changeReason:{noSessionId:u,activityTimeout:c,sessionPastMaximumLength:a}}),s=i,l=!0):o||(o=this._windowIdGenerator(),l=!0);var d=0===r||!e||a?i:r,h=0===s?(new Date).getTime():s;return this._setWindowId(o),this._setSessionId(n,d,h),e||this.resetIdleTimer(),l&&this._sessionIdChangedHandlers.forEach((e=>e(n,o,l?{noSessionId:u,activityTimeout:c,sessionPastMaximumLength:a}:void 0))),{sessionId:n,windowId:o,sessionStartTimestamp:h,changeReason:l?{noSessionId:u,activityTimeout:c,sessionPastMaximumLength:a}:void 0,lastActivityTimestamp:r}}resetIdleTimer(){clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout((()=>{this.resetSessionId()}),1.1*this.sessionTimeoutMs)}}!function(e){e.US=\"us\",e.EU=\"eu\",e.CUSTOM=\"custom\"}(kn||(kn={}));var Cn=\"i.posthog.com\";class Pn{constructor(e){W(this,\"_regionCache\",{}),this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\\/$/,\"\");return\"https://app.posthog.com\"===e?\"https://us.i.posthog.com\":e}get uiHost(){var e,t=null===(e=this.instance.config.ui_host)||void 0===e?void 0:e.replace(/\\/$/,\"\");return t||(t=this.apiHost.replace(\".\".concat(Cn),\".posthog.com\")),\"https://app.posthog.com\"===t?\"https://us.posthog.com\":t}get region(){return this._regionCache[this.apiHost]||(/https:\\/\\/(app|us|us-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)?this._regionCache[this.apiHost]=kn.US:/https:\\/\\/(eu|eu-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)?this._regionCache[this.apiHost]=kn.EU:this._regionCache[this.apiHost]=kn.CUSTOM),this._regionCache[this.apiHost]}endpointFor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"\";if(t&&(t=\"/\"===t[0]?t:\"/\".concat(t)),\"ui\"===e)return this.uiHost+t;if(this.region===kn.CUSTOM)return this.apiHost+t;var i=Cn+t;switch(e){case\"assets\":return\"https://\".concat(this.region,\"-assets.\").concat(i);case\"api\":return\"https://\".concat(this.region,\".\").concat(i)}}}var Fn=\"posthog-js\";function Rn(e){var{organization:t,projectId:i,prefix:r,severityAllowList:n=[\"error\"]}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return s=>{var o,a,l,u,c;if(!(\"*\"===n||n.includes(s.level))||!e.__loaded)return s;s.tags||(s.tags={});var d=e.requestRouter.endpointFor(\"ui\",\"/project/\".concat(e.config.token,\"/person/\").concat(e.get_distinct_id()));s.tags[\"PostHog Person URL\"]=d,e.sessionRecordingStarted()&&(s.tags[\"PostHog Recording URL\"]=e.get_session_replay_url({withTimestamp:!0}));var h=(null===(o=s.exception)||void 0===o?void 0:o.values)||[];h.map((e=>{e.stacktrace&&(e.stacktrace.type=\"raw\")}));var _={$exception_message:(null===(a=h[0])||void 0===a?void 0:a.value)||s.message,$exception_type:null===(l=h[0])||void 0===l?void 0:l.type,$exception_personURL:d,$exception_level:s.level,$exception_list:h,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:(null===(u=h[0])||void 0===u?void 0:u.value)||s.message,$sentry_exception_type:null===(c=h[0])||void 0===c?void 0:c.type,$sentry_tags:s.tags};return t&&i&&(_.$sentry_url=(r||\"https://sentry.io/organizations/\")+t+\"/issues/?project=\"+i+\"&query=\"+s.event_id),e.exceptions.sendExceptionEvent(_),s}}class Tn{constructor(e,t,i,r,n){this.name=Fn,this.setupOnce=function(s){s(Rn(e,{organization:t,projectId:i,prefix:r,severityAllowList:n}))}}}var $n,On,Mn,Ln=B(\"[SegmentIntegration]\");function An(e,t){var i=e.config.segment;if(!i)return t();!function(e,t){var i=e.config.segment;if(!i)return t();var r=i=>{var r=()=>i.anonymousId()||et();e.config.get_device_id=r,i.id()&&(e.register({distinct_id:i.id(),$device_id:r()}),e.persistence.set_property($e,\"identified\")),t()},n=i.user();\"then\"in n&&I(n.then)?n.then((e=>r(e))):r(n)}(e,(()=>{i.register((e=>{Promise&&Promise.resolve||Ln.warn(\"This browser does not have Promise support, and can not use the segment integration\");var t=(t,i)=>{var r;if(!i)return t;t.event.userId||t.event.anonymousId===e.get_distinct_id()||(Ln.info(\"No userId set, resetting PostHog\"),e.reset()),t.event.userId&&t.event.userId!==e.get_distinct_id()&&(Ln.info(\"UserId set, identifying with PostHog\"),e.identify(t.event.userId));var n=e._calculate_event_properties(i,null!==(r=t.event.properties)&&void 0!==r?r:{},new Date);return t.event.properties=Object.assign({},n,t.event.properties),t};return{name:\"PostHog JS\",type:\"enrichment\",version:\"1.0.0\",isLoaded:()=>!0,load:()=>Promise.resolve(),track:e=>t(e,e.event.event),page:e=>t(e,\"$pageview\"),identify:e=>t(e,\"$identify\"),screen:e=>t(e,\"$screen\")}})(e)).then((()=>{t()}))}))}class Dn{constructor(e){this._instance=e}doPageView(e,i){var r,n=this._previousPageViewProperties(e,i);return this._currentPageview={pathname:null!==(r=null==t?void 0:t.location.pathname)&&void 0!==r?r:\"\",pageViewId:i,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this._previousPageViewProperties(e,null===(t=this._currentPageview)||void 0===t?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null===(e=this._currentPageview)||void 0===e?void 0:e.pageViewId}}_previousPageViewProperties(e,t){var i=this._currentPageview;if(!i)return{$pageview_id:t};var r={$pageview_id:t,$prev_pageview_id:i.pageViewId},n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:s,lastScrollY:o,maxScrollY:a,maxContentHeight:l,lastContentY:u,maxContentY:c}=n;if(!(F(s)||F(o)||F(a)||F(l)||F(u)||F(c))){s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c);var d=s<=1?1:dr(o/s,0,1),h=s<=1?1:dr(a/s,0,1),_=l<=1?1:dr(u/l,0,1),p=l<=1?1:dr(c/l,0,1);r=K(r,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:_,$prev_pageview_max_content:c,$prev_pageview_max_content_percentage:p})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}!function(e){e.Popover=\"popover\",e.API=\"api\",e.Widget=\"widget\"}($n||($n={})),function(e){e.Open=\"open\",e.MultipleChoice=\"multiple_choice\",e.SingleChoice=\"single_choice\",e.Rating=\"rating\",e.Link=\"link\"}(On||(On={})),function(e){e.NextQuestion=\"next_question\",e.End=\"end\",e.ResponseBased=\"response_based\",e.SpecificQuestion=\"specific_question\"}(Mn||(Mn={}));class Nn{constructor(){W(this,\"events\",{}),this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((e=>e!==t))}}emit(e,t){for(var i of this.events[e]||[])i(t);for(var r of this.events[\"*\"]||[])r(e,t)}}class qn{constructor(e){W(this,\"_debugEventEmitter\",new Nn),W(this,\"checkStep\",((e,t)=>this.checkStepEvent(e,t)&&this.checkStepUrl(e,t)&&this.checkStepElement(e,t))),W(this,\"checkStepEvent\",((e,t)=>null==t||!t.event||(null==e?void 0:e.event)===(null==t?void 0:t.event))),this.instance=e,this.actionEvents=new Set,this.actionRegistry=new Set}init(){var e;if(!F(null===(e=this.instance)||void 0===e?void 0:e._addCaptureHook)){var t;null===(t=this.instance)||void 0===t||t._addCaptureHook(((e,t)=>{this.on(e,t)}))}}register(e){var t,i;if(!F(null===(t=this.instance)||void 0===t?void 0:t._addCaptureHook)&&(e.forEach((e=>{var t,i;null===(t=this.actionRegistry)||void 0===t||t.add(e),null===(i=e.steps)||void 0===i||i.forEach((e=>{var t;null===(t=this.actionEvents)||void 0===t||t.add((null==e?void 0:e.event)||\"\")}))})),null!==(i=this.instance)&&void 0!==i&&i.autocapture)){var r,n=new Set;e.forEach((e=>{var t;null===(t=e.steps)||void 0===t||t.forEach((e=>{null!=e&&e.selector&&n.add(null==e?void 0:e.selector)}))})),null===(r=this.instance)||void 0===r||r.autocapture.setElementSelectors(n)}}on(e,t){var i;null!=t&&0!=e.length&&(this.actionEvents.has(e)||this.actionEvents.has(null==t?void 0:t.event))&&this.actionRegistry&&(null===(i=this.actionRegistry)||void 0===i?void 0:i.size)>0&&this.actionRegistry.forEach((e=>{this.checkAction(t,e)&&this._debugEventEmitter.emit(\"actionCaptured\",e.name)}))}_addActionHook(e){this.onAction(\"actionCaptured\",(t=>e(t)))}checkAction(e,t){if(null==(null==t?void 0:t.steps))return!1;for(var i of t.steps)if(this.checkStep(e,i))return!0;return!1}onAction(e,t){return this._debugEventEmitter.on(e,t)}checkStepUrl(e,t){if(null!=t&&t.url){var i,r=null==e||null===(i=e.properties)||void 0===i?void 0:i.$current_url;if(!r||\"string\"!=typeof r)return!1;if(!qn.matchString(r,null==t?void 0:t.url,(null==t?void 0:t.url_matching)||\"contains\"))return!1}return!0}static matchString(e,i,r){switch(r){case\"regex\":return!!t&&ft(e,i);case\"exact\":return i===e;case\"contains\":var n=qn.escapeStringRegexp(i).replace(/_/g,\".\").replace(/%/g,\".*\");return ft(e,n);default:return!1}}static escapeStringRegexp(e){return e.replace(/[|\\\\{}()[\\]^$+*?.]/g,\"\\\\$&\").replace(/-/g,\"\\\\x2d\")}checkStepElement(e,t){if((null!=t&&t.href||null!=t&&t.tag_name||null!=t&&t.text)&&!this.getElementsList(e).some((e=>!(null!=t&&t.href&&!qn.matchString(e.href||\"\",null==t?void 0:t.href,(null==t?void 0:t.href_matching)||\"exact\"))&&((null==t||!t.tag_name||e.tag_name===(null==t?void 0:t.tag_name))&&!(null!=t&&t.text&&!qn.matchString(e.text||\"\",null==t?void 0:t.text,(null==t?void 0:t.text_matching)||\"exact\")&&!qn.matchString(e.$el_text||\"\",null==t?void 0:t.text,(null==t?void 0:t.text_matching)||\"exact\"))))))return!1;if(null!=t&&t.selector){var i,r=null==e||null===(i=e.properties)||void 0===i?void 0:i.$element_selectors;if(!r)return!1;if(!r.includes(null==t?void 0:t.selector))return!1}return!0}getElementsList(e){return null==(null==e?void 0:e.properties.$elements)?[]:null==e?void 0:e.properties.$elements}}class Bn{constructor(e){this.instance=e,this.eventToSurveys=new Map,this.actionToSurveys=new Map}register(e){var t;F(null===(t=this.instance)||void 0===t?void 0:t._addCaptureHook)||(this.setupEventBasedSurveys(e),this.setupActionBasedSurveys(e))}setupActionBasedSurveys(e){var t=e.filter((e=>{var t,i,r,n;return(null===(t=e.conditions)||void 0===t?void 0:t.actions)&&(null===(i=e.conditions)||void 0===i||null===(r=i.actions)||void 0===r||null===(n=r.values)||void 0===n?void 0:n.length)>0}));if(0!==t.length){if(null==this.actionMatcher){this.actionMatcher=new qn(this.instance),this.actionMatcher.init();this.actionMatcher._addActionHook((e=>{this.onAction(e)}))}t.forEach((e=>{var t,i,r,n,s,o,a,l,u,c;e.conditions&&null!==(t=e.conditions)&&void 0!==t&&t.actions&&null!==(i=e.conditions)&&void 0!==i&&null!==(r=i.actions)&&void 0!==r&&r.values&&(null===(n=e.conditions)||void 0===n||null===(s=n.actions)||void 0===s||null===(o=s.values)||void 0===o?void 0:o.length)>0&&(null===(a=this.actionMatcher)||void 0===a||a.register(e.conditions.actions.values),null===(l=e.conditions)||void 0===l||null===(u=l.actions)||void 0===u||null===(c=u.values)||void 0===c||c.forEach((t=>{if(t&&t.name){var i=this.actionToSurveys.get(t.name);i&&i.push(e.id),this.actionToSurveys.set(t.name,i||[e.id])}})))}))}}setupEventBasedSurveys(e){var t;if(0!==e.filter((e=>{var t,i,r,n;return(null===(t=e.conditions)||void 0===t?void 0:t.events)&&(null===(i=e.conditions)||void 0===i||null===(r=i.events)||void 0===r||null===(n=r.values)||void 0===n?void 0:n.length)>0})).length){null===(t=this.instance)||void 0===t||t._addCaptureHook(((e,t)=>{this.onEvent(e,t)})),e.forEach((e=>{var t,i,r;null===(t=e.conditions)||void 0===t||null===(i=t.events)||void 0===i||null===(r=i.values)||void 0===r||r.forEach((t=>{if(t&&t.name){var i=this.eventToSurveys.get(t.name);i&&i.push(e.id),this.eventToSurveys.set(t.name,i||[e.id])}}))}))}}onEvent(e,t){var i,r,n=(null===(i=this.instance)||void 0===i||null===(r=i.persistence)||void 0===r?void 0:r.props[Re])||[];if(Bn.SURVEY_SHOWN_EVENT_NAME==e&&t&&n.length>0){var s,o=null==t||null===(s=t.properties)||void 0===s?void 0:s.$survey_id;if(o){var a=n.indexOf(o);a>=0&&(n.splice(a,1),this._updateActivatedSurveys(n))}}else this.eventToSurveys.has(e)&&this._updateActivatedSurveys(n.concat(this.eventToSurveys.get(e)||[]))}onAction(e){var t,i,r=(null===(t=this.instance)||void 0===t||null===(i=t.persistence)||void 0===i?void 0:i.props[Re])||[];this.actionToSurveys.has(e)&&this._updateActivatedSurveys(r.concat(this.actionToSurveys.get(e)||[]))}_updateActivatedSurveys(e){var t,i;null===(t=this.instance)||void 0===t||null===(i=t.persistence)||void 0===i||i.register({[Re]:[...new Set(e)]})}getSurveys(){var e,t,i=null===(e=this.instance)||void 0===e||null===(t=e.persistence)||void 0===t?void 0:t.props[Re];return i||[]}getEventToSurveys(){return this.eventToSurveys}_getActionMatcher(){return this.actionMatcher}}W(Bn,\"SURVEY_SHOWN_EVENT_NAME\",\"survey shown\");var Hn,Un,zn,jn,Wn,Vn,Gn,Jn,Yn={},Kn=[],Xn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Qn=Array.isArray;function Zn(e,t){for(var i in t)e[i]=t[i];return e}function es(e){var t=e.parentNode;t&&t.removeChild(e)}function ts(e,t,i,r,n){var s={type:e,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==n?++zn:n,__i:-1,__u:0};return null==n&&null!=Un.vnode&&Un.vnode(s),s}function is(e){return e.children}function rs(e,t){this.props=e,this.context=t}function ns(e,t){if(null==t)return e.__?ns(e.__,e.__i+1):null;for(var i;tt&&jn.sort(Gn));as.__r=0}function ls(e,t,i,r,n,s,o,a,l,u,c){var d,h,_,p,v,g=r&&r.__k||Kn,f=t.length;for(i.__d=l,us(i,t,g),l=i.__d,d=0;d0?ts(n.type,n.props,n.key,n.ref?n.ref:null,n.__v):n)?(n.__=e,n.__b=e.__b+1,a=ds(n,i,o=r+d,c),n.__i=a,s=null,-1!==a&&(c--,(s=i[a])&&(s.__u|=131072)),null==s||null===s.__v?(-1==a&&d--,\"function\"!=typeof n.type&&(n.__u|=65536)):a!==o&&(a===o+1?d++:a>o?c>l-o?d+=a-o:d--:d=a(null!=l&&0==(131072&l.__u)?1:0))for(;o>=0||a=0){if((l=t[o])&&0==(131072&l.__u)&&n==l.key&&s===l.type)return o;o--}if(a{},isPopup:!0,onPreviewSubmit:()=>{}});var Ss=B(\"[Surveys]\"),Es={icontains:e=>!!t&&t.location.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:e=>!!t&&-1===t.location.href.toLowerCase().indexOf(e.toLowerCase()),regex:e=>!!t&&ft(t.location.href,e),not_regex:e=>!!t&&!ft(t.location.href,e),exact:e=>(null==t?void 0:t.location.href)===e,is_not:e=>(null==t?void 0:t.location.href)!==e};class ks{constructor(e){this.instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){this._decideServerResponse=!!e.surveys,this.loadIfEnabled()}reset(){localStorage.removeItem(\"lastSeenSurveyDate\");var e=(()=>{for(var e=[],t=0;tlocalStorage.removeItem(e)))}loadIfEnabled(){var e,t,i,r=null==_||null===(e=_.__PosthogExtensions__)||void 0===e?void 0:e.generateSurveys;this.instance.config.disable_surveys||!this._decideServerResponse||r||(null==this._surveyEventReceiver&&(this._surveyEventReceiver=new Bn(this.instance)),null===(t=_.__PosthogExtensions__)||void 0===t||null===(i=t.loadExternalDependency)||void 0===i||i.call(t,this.instance,\"surveys\",(e=>{var t,i;if(e)return Ss.error(\"Could not load surveys script\",e);this._surveyManager=null===(t=_.__PosthogExtensions__)||void 0===t||null===(i=t.generateSurveys)||void 0===i?void 0:i.call(t,this.instance)})))}getSurveys(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.instance.config.disable_surveys)return e([]);null==this._surveyEventReceiver&&(this._surveyEventReceiver=new Bn(this.instance));var i=this.instance.get_property(Fe);if(i&&!t)return e(i);this.instance._send_request({url:this.instance.requestRouter.endpointFor(\"api\",\"/api/surveys/?token=\".concat(this.instance.config.token)),method:\"GET\",callback:t=>{var i;if(200!==t.statusCode||!t.json)return e([]);var r,n=t.json.surveys||[],s=n.filter((e=>{var t,i,r,n,s,o,a,l,u,c,d,h;return(null===(t=e.conditions)||void 0===t?void 0:t.events)&&(null===(i=e.conditions)||void 0===i||null===(r=i.events)||void 0===r?void 0:r.values)&&(null===(n=e.conditions)||void 0===n||null===(s=n.events)||void 0===s||null===(o=s.values)||void 0===o?void 0:o.length)>0||(null===(a=e.conditions)||void 0===a?void 0:a.actions)&&(null===(l=e.conditions)||void 0===l||null===(u=l.actions)||void 0===u?void 0:u.values)&&(null===(c=e.conditions)||void 0===c||null===(d=c.actions)||void 0===d||null===(h=d.values)||void 0===h?void 0:h.length)>0}));s.length>0&&(null===(r=this._surveyEventReceiver)||void 0===r||r.register(s));return null===(i=this.instance.persistence)||void 0===i||i.register({[Fe]:n}),e(n)}})}getActiveMatchingSurveys(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.getSurveys((t=>{var i,r=t.filter((e=>!(!e.start_date||e.end_date))).filter((e=>{var t,i,r,n;if(!e.conditions)return!0;var s=null===(t=e.conditions)||void 0===t||!t.url||Es[null!==(i=null===(r=e.conditions)||void 0===r?void 0:r.urlMatchType)&&void 0!==i?i:\"icontains\"](e.conditions.url),o=null===(n=e.conditions)||void 0===n||!n.selector||(null==a?void 0:a.querySelector(e.conditions.selector));return s&&o})),n=null===(i=this._surveyEventReceiver)||void 0===i?void 0:i.getSurveys(),s=r.filter((e=>{var t,i,r,s,o,a,l,u,c,d,h;if(!(e.linked_flag_key||e.targeting_flag_key||e.internal_targeting_flag_key||null!==(t=e.feature_flag_keys)&&void 0!==t&&t.length))return!0;var _=!e.linked_flag_key||this.instance.featureFlags.isFeatureEnabled(e.linked_flag_key),p=!e.targeting_flag_key||this.instance.featureFlags.isFeatureEnabled(e.targeting_flag_key),v=(null===(i=e.conditions)||void 0===i?void 0:i.events)&&(null===(r=e.conditions)||void 0===r||null===(s=r.events)||void 0===s?void 0:s.values)&&(null===(o=e.conditions)||void 0===o||null===(a=o.events)||void 0===a?void 0:a.values.length)>0,g=(null===(l=e.conditions)||void 0===l?void 0:l.actions)&&(null===(u=e.conditions)||void 0===u||null===(c=u.actions)||void 0===c?void 0:c.values)&&(null===(d=e.conditions)||void 0===d||null===(h=d.actions)||void 0===h?void 0:h.values.length)>0,f=!v&&!g||(null==n?void 0:n.includes(e.id)),m=this._canActivateRepeatedly(e),b=!(e.internal_targeting_flag_key&&!m)||this.instance.featureFlags.isFeatureEnabled(e.internal_targeting_flag_key),y=this.checkFlags(e);return _&&p&&b&&f&&y}));return e(s)}),t)}checkFlags(e){var t;return null===(t=e.feature_flag_keys)||void 0===t||!t.length||e.feature_flag_keys.every((e=>{var{key:t,value:i}=e;return!t||!i||this.instance.featureFlags.isFeatureEnabled(i)}))}getNextSurveyStep(e,t,i){var r,n=e.questions[t],s=t+1;if(null===(r=n.branching)||void 0===r||!r.type)return t===e.questions.length-1?Mn.End:s;if(n.branching.type===Mn.End)return Mn.End;if(n.branching.type===Mn.SpecificQuestion){if(Number.isInteger(n.branching.index))return n.branching.index}else if(n.branching.type===Mn.ResponseBased){if(n.type===On.SingleChoice){var o,a,l=n.choices.indexOf(\"\".concat(i));if(null!==(o=n.branching)&&void 0!==o&&null!==(a=o.responseValues)&&void 0!==a&&a.hasOwnProperty(l)){var u=n.branching.responseValues[l];return Number.isInteger(u)?u:u===Mn.End?Mn.End:s}}else if(n.type===On.Rating){var c,d;if(\"number\"!=typeof i||!Number.isInteger(i))throw new Error(\"The response type must be an integer\");var h=function(e,t){if(3===t){if(e<1||e>3)throw new Error(\"The response must be in range 1-3\");return 1===e?\"negative\":2===e?\"neutral\":\"positive\"}if(5===t){if(e<1||e>5)throw new Error(\"The response must be in range 1-5\");return e<=2?\"negative\":3===e?\"neutral\":\"positive\"}if(7===t){if(e<1||e>7)throw new Error(\"The response must be in range 1-7\");return e<=3?\"negative\":4===e?\"neutral\":\"positive\"}if(10===t){if(e<0||e>10)throw new Error(\"The response must be in range 0-10\");return e<=6?\"detractors\":e<=8?\"passives\":\"promoters\"}throw new Error(\"The scale must be one of: 3, 5, 7, 10\")}(i,n.scale);if(null!==(c=n.branching)&&void 0!==c&&null!==(d=c.responseValues)&&void 0!==d&&d.hasOwnProperty(h)){var _=n.branching.responseValues[h];return Number.isInteger(_)?_:_===Mn.End?Mn.End:s}}return s}return Ss.warn(\"Falling back to next question index due to unexpected branching type\"),s}_canActivateRepeatedly(e){var t;return O(null===(t=_.__PosthogExtensions__)||void 0===t?void 0:t.canActivateRepeatedly)?(Ss.warn(\"init was not called\"),!1):_.__PosthogExtensions__.canActivateRepeatedly(e)}canRenderSurvey(e){O(this._surveyManager)?Ss.warn(\"init was not called\"):this.getSurveys((t=>{var i=t.filter((t=>t.id===e))[0];this._surveyManager.canRenderSurvey(i)}))}renderSurvey(e,t){O(this._surveyManager)?Ss.warn(\"init was not called\"):this.getSurveys((i=>{var r=i.filter((t=>t.id===e))[0];this._surveyManager.renderSurvey(r,null==a?void 0:a.querySelector(t))}))}}var xs=B(\"[RateLimiter]\");class Is{constructor(e){var t,i;W(this,\"serverLimits\",{}),W(this,\"lastEventRateLimited\",!1),W(this,\"checkForLimiting\",(e=>{var t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach((e=>{xs.info(\"\".concat(e||\"events\",\" is quota limited.\")),this.serverLimits[e]=(new Date).getTime()+6e4}))}catch(e){return void xs.warn('could not rate limit - continuing. Error: \"'.concat(null==e?void 0:e.message,'\"'),{text:t})}})),this.instance=e,this.captureEventsPerSecond=(null===(t=e.config.rate_limiting)||void 0===t?void 0:t.events_per_second)||10,this.captureEventsBurstLimit=Math.max((null===(i=e.config.rate_limiting)||void 0===i?void 0:i.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(){var e,t,i,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=(new Date).getTime(),s=null!==(e=null===(t=this.instance.persistence)||void 0===t?void 0:t.get_property(Me))&&void 0!==e?e:{tokens:this.captureEventsBurstLimit,last:n};s.tokens+=(n-s.last)/1e3*this.captureEventsPerSecond,s.last=n,s.tokens>this.captureEventsBurstLimit&&(s.tokens=this.captureEventsBurstLimit);var o=s.tokens<1;return o||r||(s.tokens=Math.max(0,s.tokens-1)),!o||this.lastEventRateLimited||r||this.instance.capture(\"$$client_ingestion_warning\",{$$client_ingestion_warning_message:\"posthog-js client rate limited. Config is set to \".concat(this.captureEventsPerSecond,\" events per second and \").concat(this.captureEventsBurstLimit,\" events burst limit.\")},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=o,null===(i=this.instance.persistence)||void 0===i||i.set_property(Me,s),{isRateLimited:o,remainingTokens:s.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||\"events\"]||!1;return!1!==t&&(new Date).getTime(){var t=null==e?void 0:e.config;return j({initialPathName:(null==l?void 0:l.pathname)||\"\",referringDomain:wi.referringDomain()},wi.campaignParams({customTrackedParams:null==t?void 0:t.custom_campaign_params,maskPersonalDataProperties:null==t?void 0:t.mask_personal_data_properties,customPersonalDataProperties:null==t?void 0:t.custom_personal_data_properties}))};class Ps{constructor(e,t,i,r){W(this,\"_onSessionIdCallback\",(e=>{var t=this._getStoredProps();if(!t||t.sessionId!==e){var i={sessionId:e,props:this._sessionSourceParamGenerator(this.instance)};this._persistence.register({[Oe]:i})}})),this.instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=r||Cs,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStoredProps(){return this._persistence.props[Oe]}getSessionProps(){var e,t=null===(e=this._getStoredProps())||void 0===e?void 0:e.props;return t?{$client_session_initial_referring_host:t.referringDomain,$client_session_initial_pathname:t.initialPathName,$client_session_initial_utm_source:t.utm_source,$client_session_initial_utm_campaign:t.utm_campaign,$client_session_initial_utm_medium:t.utm_medium,$client_session_initial_utm_content:t.utm_content,$client_session_initial_utm_term:t.utm_term}:{}}}var Fs=[\"ahrefsbot\",\"ahrefssiteaudit\",\"applebot\",\"baiduspider\",\"better uptime bot\",\"bingbot\",\"bingpreview\",\"bot.htm\",\"bot.php\",\"crawler\",\"deepscan\",\"duckduckbot\",\"facebookexternal\",\"facebookcatalog\",\"gptbot\",\"http://yandex.com/bots\",\"hubspot\",\"ia_archiver\",\"linkedinbot\",\"mj12bot\",\"msnbot\",\"nessus\",\"petalbot\",\"pinterest\",\"prerender\",\"rogerbot\",\"screaming frog\",\"semrushbot\",\"sitebulb\",\"slurp\",\"turnitin\",\"twitterbot\",\"vercelbot\",\"yahoo! slurp\",\"yandexbot\",\"headlesschrome\",\"cypress\",\"Google-HotelAdsVerifier\",\"adsbot-google\",\"apis-google\",\"duplexweb-google\",\"feedfetcher-google\",\"google favicon\",\"google web preview\",\"google-read-aloud\",\"googlebot\",\"googleweblight\",\"mediapartners-google\",\"storebot-google\",\"Bytespider;\"],Rs=function(e,t){if(!e)return!1;var i=e.toLowerCase();return Fs.concat(t||[]).some((e=>{var t=e.toLowerCase();return-1!==i.indexOf(t)}))},Ts=function(e,t){if(!e)return!1;var i=e.userAgent;if(i&&Rs(i,t))return!0;try{var r=null==e?void 0:e.userAgentData;if(null!=r&&r.brands&&r.brands.some((e=>Rs(null==e?void 0:e.brand,t))))return!0}catch(e){}return!!e.webdriver};class $s{constructor(){this.clicks=[]}isRageClick(e,t,i){var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(t-r.y)<30&&i-r.timestamp<1e3){if(this.clicks.push({x:e,y:t,timestamp:i}),3===this.clicks.length)return!0}else this.clicks=[{x:e,y:t,timestamp:i}];return!1}}var Os=B(\"[Dead Clicks]\"),Ms=()=>!0,Ls=e=>{var t,i=!(null===(t=e.instance.persistence)||void 0===t||!t.get_property(he)),r=e.instance.config.capture_dead_clicks;return L(r)?r:i};class As{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[he]:null==e?void 0:e.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.loadScript((()=>{this.start()}))}loadScript(e){var t,i,r;null!==(t=_.__PosthogExtensions__)&&void 0!==t&&t.initDeadClicksAutocapture&&e(),null===(i=_.__PosthogExtensions__)||void 0===i||null===(r=i.loadExternalDependency)||void 0===r||r.call(i,this.instance,\"dead-clicks-autocapture\",(t=>{t?Os.error(\"failed to load script\",t):e()}))}start(){var e;if(a){if(!this._lazyLoadedDeadClicksAutocapture&&null!==(e=_.__PosthogExtensions__)&&void 0!==e&&e.initDeadClicksAutocapture){var t=C(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this._lazyLoadedDeadClicksAutocapture=_.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this._lazyLoadedDeadClicksAutocapture.start(a),Os.info(\"starting...\")}}else Os.error(\"`document` not found. Cannot start.\")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,Os.info(\"stopping...\"))}}var Ds=B(\"[Heatmaps]\");function Ns(e){return C(e)&&\"clientX\"in e&&\"clientY\"in e&&M(e.clientX)&&M(e.clientY)}class qs{constructor(e){var i;W(this,\"rageclicks\",new $s),W(this,\"_enabledServerSide\",!1),W(this,\"_initialized\",!1),W(this,\"_flushInterval\",null),this.instance=e,this._enabledServerSide=!(null===(i=this.instance.persistence)||void 0===i||!i.props[ue]),null==t||t.addEventListener(\"beforeunload\",(()=>{this.flush()}))}get flushIntervalMilliseconds(){var e=5e3;return C(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return F(this.instance.config.capture_heatmaps)?F(this.instance.config.enable_heatmaps)?this._enabledServerSide:this.instance.config.enable_heatmaps:!1!==this.instance.config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;Ds.info(\"starting...\"),this._setupListeners(),this._flushInterval=setInterval(this.flush.bind(this),this.flushIntervalMilliseconds)}else{var e,t;clearInterval(null!==(e=this._flushInterval)&&void 0!==e?e:void 0),null===(t=this.deadClicksCapture)||void 0===t||t.stop(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ue]:t}),this._enabledServerSide=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.buffer;return this.buffer=void 0,e}_onDeadClick(e){this._onClick(e.originalEvent,\"deadclick\")}_setupListeners(){t&&a&&(re(a,\"click\",(e=>this._onClick(e||(null==t?void 0:t.event))),!1,!0),re(a,\"mousemove\",(e=>this._onMouseMove(e||(null==t?void 0:t.event))),!1,!0),this.deadClicksCapture=new As(this.instance,Ms,this._onDeadClick.bind(this)),this.deadClicksCapture.startIfEnabled(),this._initialized=!0)}_getProperties(e,i){var r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),o=function(e,i,r){for(var n=e;n&&Fi(n)&&!Ri(n,\"body\");){if(n===r)return!1;if(m(i,null==t?void 0:t.getComputedStyle(n).position))return!0;n=Bi(n)}return!1}(Ni(e),[\"fixed\",\"sticky\"],s);return{x:e.clientX+(o?0:n),y:e.clientY+(o?0:r),target_fixed:o,type:i}}_onClick(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"click\";if(!Pi(e.target)&&Ns(e)){var r=this._getProperties(e,i);null!==(t=this.rageclicks)&&void 0!==t&&t.isRageClick(e.clientX,e.clientY,(new Date).getTime())&&this._capture(j(j({},r),{},{type:\"rageclick\"})),this._capture(r)}}_onMouseMove(e){!Pi(e.target)&&Ns(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout((()=>{this._capture(this._getProperties(e,\"mousemove\"))}),500))}_capture(e){if(t){var i=t.location.href;this.buffer=this.buffer||{},this.buffer[i]||(this.buffer[i]=[]),this.buffer[i].push(e)}}flush(){this.buffer&&!P(this.buffer)&&this.instance.capture(\"$$heatmap\",{$heatmap_data:this.getAndClearBuffer()})}}class Bs{constructor(e){W(this,\"_updateScrollData\",(()=>{var e,t,i,r;this.context||(this.context={});var n=this.scrollElement(),s=this.scrollY(),o=n?Math.max(0,n.scrollHeight-n.clientHeight):0,a=s+((null==n?void 0:n.clientHeight)||0),l=(null==n?void 0:n.scrollHeight)||0;this.context.lastScrollY=Math.ceil(s),this.context.maxScrollY=Math.max(s,null!==(e=this.context.maxScrollY)&&void 0!==e?e:0),this.context.maxScrollHeight=Math.max(o,null!==(t=this.context.maxScrollHeight)&&void 0!==t?t:0),this.context.lastContentY=a,this.context.maxContentY=Math.max(a,null!==(i=this.context.maxContentY)&&void 0!==i?i:0),this.context.maxContentHeight=Math.max(l,null!==(r=this.context.maxContentHeight)&&void 0!==r?r:0)})),this.instance=e}getContext(){return this.context}resetContext(){var e=this.context;return setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){null==t||t.addEventListener(\"scroll\",this._updateScrollData,!0),null==t||t.addEventListener(\"scrollend\",this._updateScrollData,!0),null==t||t.addEventListener(\"resize\",this._updateScrollData)}scrollElement(){if(!this.instance.config.scroll_root_selector)return null==t?void 0:t.document.documentElement;var e=x(this.instance.config.scroll_root_selector)?this.instance.config.scroll_root_selector:[this.instance.config.scroll_root_selector];for(var i of e){var r=null==t?void 0:t.document.querySelector(i);if(r)return r}}scrollY(){if(this.instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return t&&(t.scrollY||t.pageYOffset||t.document.documentElement.scrollTop)||0}scrollX(){if(this.instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return t&&(t.scrollX||t.pageXOffset||t.document.documentElement.scrollLeft)||0}}var Hs=B(\"[AutoCapture]\");function Us(e,t){return t.length>e?t.slice(0,e)+\"...\":t}function zs(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!Fi(t));return t}function js(e,t,i,r){var n=e.tagName.toLowerCase(),s={tag_name:n};qi.indexOf(n)>-1&&!i&&(\"a\"===n.toLowerCase()||\"button\"===n.toLowerCase()?s.$el_text=Us(1024,Xi(e)):s.$el_text=Us(1024,Di(e)));var o=Li(e);o.length>0&&(s.classes=o.filter((function(e){return\"\"!==e}))),Y(e.attributes,(function(i){var n;if((!zi(e)||-1!==[\"name\",\"id\",\"class\",\"aria-label\"].indexOf(i.name))&&((null==r||!r.includes(i.name))&&!t&&Ki(i.value)&&(n=i.name,!R(n)||\"_ngcontent\"!==n.substring(0,10)&&\"_nghost\"!==n.substring(0,7)))){var o=i.value;\"class\"===i.name&&(o=Oi(o).join(\" \")),s[\"attr__\"+i.name]=Us(1024,o)}}));for(var a=1,l=1,u=e;u=zs(u);)a++,u.tagName===e.tagName&&l++;return s.nth_child=a,s.nth_of_type=l,s}function Ws(e,i){for(var r,n,{e:s,maskAllElementAttributes:o,maskAllText:a,elementAttributeIgnoreList:l,elementsChainAsString:u}=i,c=[e],d=e;d.parentNode&&!Ri(d,\"body\");)$i(d.parentNode)?(c.push(d.parentNode.host),d=d.parentNode.host):(c.push(d.parentNode),d=d.parentNode);var h,_=[],p={},v=!1,g=!1;if(Y(c,(e=>{var t=Ui(e);\"a\"===e.tagName.toLowerCase()&&(v=e.getAttribute(\"href\"),v=t&&v&&Ki(v)&&v),m(Li(e),\"ph-no-capture\")&&(g=!0),_.push(js(e,o,a,l));var i=function(e){if(!Ui(e))return{};var t={};return Y(e.attributes,(function(e){if(e.name&&0===e.name.indexOf(\"data-ph-capture-attribute\")){var i=e.name.replace(\"data-ph-capture-attribute-\",\"\"),r=e.value;i&&r&&Ki(r)&&(t[i]=r)}})),t}(e);K(p,i)})),g)return{props:{},explicitNoCapture:g};if(a||(\"a\"===e.tagName.toLowerCase()||\"button\"===e.tagName.toLowerCase()?_[0].$el_text=Xi(e):_[0].$el_text=Di(e)),v){var f,b;_[0].attr__href=v;var y=null===(f=gt(v))||void 0===f?void 0:f.host,w=null==t||null===(b=t.location)||void 0===b?void 0:b.host;y&&w&&y!==w&&(h=v)}return{props:K({$event_type:s.type,$ce_version:1},u?{}:{$elements:_},{$elements_chain:Zi(_)},null!==(r=_[0])&&void 0!==r&&r.$el_text?{$el_text:null===(n=_[0])||void 0===n?void 0:n.$el_text}:{},h&&\"click\"===s.type?{$external_click_url:h}:{},p)}}class Vs{constructor(e){W(this,\"_initialized\",!1),W(this,\"_isDisabledServerSide\",null),W(this,\"rageclicks\",new $s),W(this,\"_elementsChainAsString\",!1),this.instance=e,this._elementSelectors=null}get config(){var e,t,i=C(this.instance.config.autocapture)?this.instance.config.autocapture:{};return i.url_allowlist=null===(e=i.url_allowlist)||void 0===e?void 0:e.map((e=>new RegExp(e))),i.url_ignorelist=null===(t=i.url_ignorelist)||void 0===t?void 0:t.map((e=>new RegExp(e))),i}_addDomEventHandlers(){if(this.isBrowserSupported()){if(t&&a){var e=e=>{e=e||(null==t?void 0:t.event);try{this._captureEvent(e)}catch(e){Hs.error(\"Failed to capture event\",e)}},i=e=>{e=e||(null==t?void 0:t.event),this._captureEvent(e,v)};re(a,\"submit\",e,!1,!0),re(a,\"change\",e,!1,!0),re(a,\"click\",e,!1,!0),this.config.capture_copied_text&&(re(a,\"copy\",i,!1,!0),re(a,\"cut\",i,!1,!0))}}else Hs.info(\"Disabling Automatic Event Collection because this browser is not supported\")}startIfEnabled(){this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this._elementsChainAsString=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[le]:!!e.autocapture_opt_out}),this._isDisabledServerSide=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this._elementSelectors=e}getElementSelectors(e){var t,i=[];return null===(t=this._elementSelectors)||void 0===t||t.forEach((t=>{var r=null==a?void 0:a.querySelectorAll(t);null==r||r.forEach((r=>{e===r&&i.push(t)}))})),i}get isEnabled(){var e,t,i=null===(e=this.instance.persistence)||void 0===e?void 0:e.props[le],r=this._isDisabledServerSide;if($(r)&&!L(i)&&!this.instance.config.advanced_disable_decide)return!1;var n=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!this.instance.config.autocapture&&!n}_captureEvent(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"$autocapture\";if(this.isEnabled){var r,n=Ni(e);if(Ti(n)&&(n=n.parentNode||null),\"$autocapture\"===i&&\"click\"===e.type&&e instanceof MouseEvent)this.instance.config.rageclick&&null!==(r=this.rageclicks)&&void 0!==r&&r.isRageClick(e.clientX,e.clientY,(new Date).getTime())&&this._captureEvent(e,\"$rageclick\");var s=i===v;if(n&&Hi(n,e,this.config,s,s?[\"copy\",\"cut\"]:void 0)){var{props:o,explicitNoCapture:a}=Ws(n,{e:e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.config.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString});if(a)return!1;var l=this.getElementSelectors(n);if(l&&l.length>0&&(o.$element_selectors=l),i===v){var u,c=Ai(null==t||null===(u=t.getSelection())||void 0===u?void 0:u.toString()),d=e.type||\"clipboard\";if(!c)return!1;o.$selected_content=c,o.$copy_type=d}return this.instance.capture(i,o),!0}}}isBrowserSupported(){return I(null==a?void 0:a.querySelectorAll)}}var Gs=B(\"[TracingHeaders]\");class Js{constructor(e){W(this,\"_restoreXHRPatch\",void 0),W(this,\"_restoreFetchPatch\",void 0),W(this,\"_startCapturing\",(()=>{var e,t,i,r;F(this._restoreXHRPatch)&&(null===(e=_.__PosthogExtensions__)||void 0===e||null===(t=e.tracingHeadersPatchFns)||void 0===t||t._patchXHR(this.instance.sessionManager));F(this._restoreFetchPatch)&&(null===(i=_.__PosthogExtensions__)||void 0===i||null===(r=i.tracingHeadersPatchFns)||void 0===r||r._patchFetch(this.instance.sessionManager))})),this.instance=e}_loadScript(e){var t,i,r;null!==(t=_.__PosthogExtensions__)&&void 0!==t&&t.tracingHeadersPatchFns&&e(),null===(i=_.__PosthogExtensions__)||void 0===i||null===(r=i.loadExternalDependency)||void 0===r||r.call(i,this.instance,\"tracing-headers\",(t=>{if(t)return Gs.error(\"failed to load script\",t);e()}))}startIfEnabledOrStop(){var e,t;this.instance.config.__add_tracing_headers?this._loadScript(this._startCapturing):(null===(e=this._restoreXHRPatch)||void 0===e||e.call(this),null===(t=this._restoreFetchPatch)||void 0===t||t.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0)}}var Ys;!function(e){e[e.PENDING=-1]=\"PENDING\",e[e.DENIED=0]=\"DENIED\",e[e.GRANTED=1]=\"GRANTED\"}(Ys||(Ys={}));class Ks{constructor(e){this.instance=e}get config(){return this.instance.config}get consent(){return this.getDnt()?Ys.DENIED:this.storedConsent}isOptedOut(){return this.consent===Ys.DENIED||this.consent===Ys.PENDING&&this.config.opt_out_capturing_by_default}isOptedIn(){return!this.isOptedOut()}optInOut(e){this.storage.set(this.storageKey,e?1:0,this.config.cookie_expiration,this.config.cross_subdomain_cookie,this.config.secure_cookie)}reset(){this.storage.remove(this.storageKey,this.config.cross_subdomain_cookie)}get storageKey(){var{token:e,opt_out_capturing_cookie_prefix:t}=this.instance.config;return(t||\"__ph_opt_in_out_\")+e}get storedConsent(){var e=this.storage.get(this.storageKey);return\"1\"===e?Ys.GRANTED:\"0\"===e?Ys.DENIED:Ys.PENDING}get storage(){if(!this._storage){var e=this.config.opt_out_capturing_persistence_type;this._storage=\"localStorage\"===e?lt:ot;var t=\"localStorage\"===e?ot:lt;t.get(this.storageKey)&&(this._storage.get(this.storageKey)||this.optInOut(\"1\"===t.get(this.storageKey)),t.remove(this.storageKey,this.config.cross_subdomain_cookie))}return this._storage}getDnt(){return!!this.config.respect_dnt&&!!ne([null==o?void 0:o.doNotTrack,null==o?void 0:o.msDoNotTrack,_.doNotTrack],(e=>m([!0,1,\"1\",\"yes\"],e)))}}var Xs=B(\"[ExceptionAutocapture]\");class Qs{constructor(e){var i;W(this,\"originalOnUnhandledRejectionHandler\",void 0),W(this,\"startCapturing\",(()=>{var e,i,r,n;if(t&&this.isEnabled&&!this.hasHandlers&&!this.isCapturing){var s=null===(e=_.__PosthogExtensions__)||void 0===e||null===(i=e.errorWrappingFunctions)||void 0===i?void 0:i.wrapOnError,o=null===(r=_.__PosthogExtensions__)||void 0===r||null===(n=r.errorWrappingFunctions)||void 0===n?void 0:n.wrapUnhandledRejection;if(s&&o)try{this.unwrapOnError=s(this.captureException.bind(this)),this.unwrapUnhandledRejection=o(this.captureException.bind(this))}catch(e){Xs.error(\"failed to start\",e),this.stopCapturing()}else Xs.error(\"failed to load error wrapping functions - cannot start\")}})),this.instance=e,this.remoteEnabled=!(null===(i=this.instance.persistence)||void 0===i||!i.props[ce]),this.startIfEnabled()}get isEnabled(){var e;return null!==(e=this.remoteEnabled)&&void 0!==e&&e}get isCapturing(){var e;return!(null==t||null===(e=t.onerror)||void 0===e||!e.__POSTHOG_INSTRUMENTED__)}get hasHandlers(){return this.originalOnUnhandledRejectionHandler||this.unwrapOnError}startIfEnabled(){this.isEnabled&&!this.isCapturing&&(Xs.info(\"enabled, starting...\"),this.loadScript(this.startCapturing))}loadScript(e){var t,i;this.hasHandlers&&e(),null===(t=_.__PosthogExtensions__)||void 0===t||null===(i=t.loadExternalDependency)||void 0===i||i.call(t,this.instance,\"exception-autocapture\",(t=>{if(t)return Xs.error(\"failed to load script\",t);e()}))}stopCapturing(){var e,t;null===(e=this.unwrapOnError)||void 0===e||e.call(this),null===(t=this.unwrapUnhandledRejection)||void 0===t||t.call(this)}onRemoteConfig(e){var t=e.autocaptureExceptions;this.remoteEnabled=!!t||!1,this.instance.persistence&&this.instance.persistence.register({[ce]:this.remoteEnabled}),this.startIfEnabled()}captureException(e){var t=this.instance.requestRouter.endpointFor(\"ui\");e.$exception_personURL=\"\".concat(t,\"/project/\").concat(this.instance.config.token,\"/person/\").concat(this.instance.get_distinct_id()),this.instance.exceptions.sendExceptionEvent(e)}}var Zs=B(\"[Web Vitals]\"),eo=9e5;class to{constructor(e){var t;W(this,\"_enabledServerSide\",!1),W(this,\"_initialized\",!1),W(this,\"buffer\",{url:void 0,metrics:[],firstMetricTimestamp:void 0}),W(this,\"_flushToCapture\",(()=>{clearTimeout(this._delayedFlushTimer),0!==this.buffer.metrics.length&&(this.instance.capture(\"$web_vitals\",this.buffer.metrics.reduce(((e,t)=>j(j({},e),{},{[\"$web_vitals_\".concat(t.name,\"_event\")]:j({},t),[\"$web_vitals_\".concat(t.name,\"_value\")]:t.value})),{})),this.buffer={url:void 0,metrics:[],firstMetricTimestamp:void 0})})),W(this,\"_addToBuffer\",(e=>{var t,i=null===(t=this.instance.sessionManager)||void 0===t?void 0:t.checkAndGetSessionAndWindowId(!0);if(F(i))Zs.error(\"Could not read session ID. Dropping metrics!\");else{this.buffer=this.buffer||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var r=this._currentURL();if(!F(r))if(O(null==e?void 0:e.name)||O(null==e?void 0:e.value))Zs.error(\"Invalid metric received\",e);else if(this._maxAllowedValue&&e.value>=this._maxAllowedValue)Zs.error(\"Ignoring metric with value >= \"+this._maxAllowedValue,e);else this.buffer.url!==r&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),F(this.buffer.url)&&(this.buffer.url=r),this.buffer.firstMetricTimestamp=F(this.buffer.firstMetricTimestamp)?Date.now():this.buffer.firstMetricTimestamp,e.attribution&&e.attribution.interactionTargetElement&&(e.attribution.interactionTargetElement=void 0),this.buffer.metrics.push(j(j({},e),{},{$current_url:r,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()}})),W(this,\"_startCapturing\",(()=>{var e,t,i,r,n=_.__PosthogExtensions__;F(n)||F(n.postHogWebVitalsCallbacks)||({onLCP:e,onCLS:t,onFCP:i,onINP:r}=n.postHogWebVitalsCallbacks),e&&t&&i&&r?(this.allowedMetrics.indexOf(\"LCP\")>-1&&e(this._addToBuffer.bind(this)),this.allowedMetrics.indexOf(\"CLS\")>-1&&t(this._addToBuffer.bind(this)),this.allowedMetrics.indexOf(\"FCP\")>-1&&i(this._addToBuffer.bind(this)),this.allowedMetrics.indexOf(\"INP\")>-1&&r(this._addToBuffer.bind(this)),this._initialized=!0):Zs.error(\"web vitals callbacks not loaded - not starting\")})),this.instance=e,this._enabledServerSide=!(null===(t=this.instance.persistence)||void 0===t||!t.props[de]),this.startIfEnabled()}get allowedMetrics(){var e,t,i=C(this.instance.config.capture_performance)?null===(e=this.instance.config.capture_performance)||void 0===e?void 0:e.web_vitals_allowed_metrics:void 0;return F(i)?(null===(t=this.instance.persistence)||void 0===t?void 0:t.props[_e])||[\"CLS\",\"FCP\",\"INP\",\"LCP\"]:i}get flushToCaptureTimeoutMs(){return(C(this.instance.config.capture_performance)?this.instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get _maxAllowedValue(){var e=C(this.instance.config.capture_performance)&&M(this.instance.config.capture_performance.__web_vitals_max_value)?this.instance.config.capture_performance.__web_vitals_max_value:eo;return 0{t?Zs.error(\"failed to load script\",t):e()}))}_currentURL(){var e=t?t.location.href:void 0;return e||Zs.error(\"Could not determine current URL\"),e}}var io={icontains:(e,i)=>!!t&&i.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,i)=>!!t&&-1===i.href.toLowerCase().indexOf(e.toLowerCase()),regex:(e,i)=>!!t&&ft(i.href,e),not_regex:(e,i)=>!!t&&!ft(i.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};class ro{constructor(e){var t=this;W(this,\"getWebExperimentsAndEvaluateDisplayLogic\",(function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];t.getWebExperiments((e=>{ro.logInfo(\"retrieved web experiments from the server\"),t._flagToExperiments=new Map,e.forEach((e=>{if(e.feature_flag_key){var i;if(t._flagToExperiments)ro.logInfo(\"setting flag key \",e.feature_flag_key,\" to web experiment \",e),null===(i=t._flagToExperiments)||void 0===i||i.set(e.feature_flag_key,e);var r=t.instance.getFeatureFlag(e.feature_flag_key);R(r)&&e.variants[r]&&t.applyTransforms(e.name,r,e.variants[r].transforms)}else if(e.variants)for(var n in e.variants){var s=e.variants[n];ro.matchesTestVariant(s)&&t.applyTransforms(e.name,n,s.transforms)}}))}),e)})),this.instance=e,this.instance.onFeatureFlags((e=>{this.onFeatureFlags(e)}))}onFeatureFlags(e){if(this._is_bot())ro.logInfo(\"Refusing to render web experiment since the viewer is a likely bot\");else if(!this.instance.config.disable_web_experiments){if(O(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ro.logInfo(\"applying feature flags\",e),e.forEach((e=>{var t;if(this._flagToExperiments&&null!==(t=this._flagToExperiments)&&void 0!==t&&t.has(e)){var i,r=this.instance.getFeatureFlag(e),n=null===(i=this._flagToExperiments)||void 0===i?void 0:i.get(e);r&&null!=n&&n.variants[r]&&this.applyTransforms(n.name,r,n.variants[r].transforms)}}))}}previewWebExperiment(){var e=ro.getWindowLocation();if(null!=e&&e.search){var t=bt(null==e?void 0:e.search,\"__experiment_id\"),i=bt(null==e?void 0:e.search,\"__experiment_variant\");t&&i&&(ro.logInfo(\"previewing web experiments \".concat(t,\" && \").concat(i)),this.getWebExperiments((e=>{this.showPreviewWebExperiment(parseInt(t),i,e)}),!1,!0))}}loadIfEnabled(){this.instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this.instance.config.disable_web_experiments&&!i)return e([]);var r=this.instance.get_property(\"$web_experiments\");if(r&&!t)return e(r);this.instance._send_request({url:this.instance.requestRouter.endpointFor(\"api\",\"/api/web_experiments/?token=\".concat(this.instance.config.token)),method:\"GET\",callback:t=>{if(200!==t.statusCode||!t.json)return e([]);var i=t.json.experiments||[];return e(i)}})}showPreviewWebExperiment(e,t,i){var r=i.filter((t=>t.id===e));r&&r.length>0&&(ro.logInfo(\"Previewing web experiment [\".concat(r[0].name,\"] with variant [\").concat(t,\"]\")),this.applyTransforms(r[0].name,t,r[0].variants[t].transforms))}static matchesTestVariant(e){return!O(e.conditions)&&(ro.matchUrlConditions(e)&&ro.matchUTMConditions(e))}static matchUrlConditions(e){var t;if(O(e.conditions)||O(null===(t=e.conditions)||void 0===t?void 0:t.url))return!0;var i,r,n,s=ro.getWindowLocation();return!!s&&(null===(i=e.conditions)||void 0===i||!i.url||io[null!==(r=null===(n=e.conditions)||void 0===n?void 0:n.urlMatchType)&&void 0!==r?r:\"icontains\"](e.conditions.url,s))}static getWindowLocation(){return null==t?void 0:t.location}static matchUTMConditions(e){var t;if(O(e.conditions)||O(null===(t=e.conditions)||void 0===t?void 0:t.utm))return!0;var i=wi.campaignParams();if(i.utm_source){var r,n,s,o,a,l,u,c,d,h,_,p,v,g,f,m,b=null===(r=e.conditions)||void 0===r||null===(n=r.utm)||void 0===n||!n.utm_campaign||(null===(s=e.conditions)||void 0===s||null===(o=s.utm)||void 0===o?void 0:o.utm_campaign)==i.utm_campaign,y=null===(a=e.conditions)||void 0===a||null===(l=a.utm)||void 0===l||!l.utm_source||(null===(u=e.conditions)||void 0===u||null===(c=u.utm)||void 0===c?void 0:c.utm_source)==i.utm_source,w=null===(d=e.conditions)||void 0===d||null===(h=d.utm)||void 0===h||!h.utm_medium||(null===(_=e.conditions)||void 0===_||null===(p=_.utm)||void 0===p?void 0:p.utm_medium)==i.utm_medium,S=null===(v=e.conditions)||void 0===v||null===(g=v.utm)||void 0===g||!g.utm_term||(null===(f=e.conditions)||void 0===f||null===(m=f.utm)||void 0===m?void 0:m.utm_term)==i.utm_term;return b&&w&&S&&y}return!1}static logInfo(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r{if(i.selector){var r;ro.logInfo(\"applying transform of variant \".concat(t,\" for experiment \").concat(e,\" \"),i);var n=null===(r=document)||void 0===r?void 0:r.querySelectorAll(i.selector);null==n||n.forEach((e=>{var t=e;i.attributes&&i.attributes.forEach((e=>{switch(e.name){case\"text\":t.innerText=e.value;break;case\"html\":t.innerHTML=e.value;break;case\"cssClass\":t.className=e.value;break;default:t.setAttribute(e.name,e.value)}})),i.text&&(t.innerText=i.text),i.html&&(t.parentElement?t.parentElement.innerHTML=i.html:t.innerHTML=i.html),i.css&&t.setAttribute(\"style\",i.css)}))}})):ro.logInfo(\"Control variants leave the page unmodified.\")}_is_bot(){return o&&this.instance?Ts(o,this.instance.config.custom_blocked_useragents):void 0}}class no{constructor(e){this.instance=e}sendExceptionEvent(e){this.instance.capture(\"$exception\",e,{_noTruncate:!0,_batchKey:\"exceptionEvent\"})}}var so=[\"$set_once\",\"$set\"],oo=B(\"[SiteApps]\");class ao{constructor(e){this.instance=e,this.bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this.instance.config.opt_in_site_apps}eventCollector(e,t){if(t){var i=this.globalsForEvent(t);this.bufferedInvocations.push(i),this.bufferedInvocations.length>1e3&&(this.bufferedInvocations=this.bufferedInvocations.slice(10))}}get siteAppLoaders(){var e,t;return null===(e=_._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(t=e[this.instance.config.token])||void 0===t?void 0:t.siteApps}init(){if(this.isEnabled){var e=this.instance._addCaptureHook(this.eventCollector.bind(this));this.stopBuffering=()=>{e(),this.bufferedInvocations=[],this.stopBuffering=void 0}}}globalsForEvent(e){var t,i,r,n,s,o,a;if(!e)throw new Error(\"Event payload is required\");var l={},u=this.instance.get_property(\"$groups\")||[],c=this.instance.get_property(\"$stored_group_properties\")||{};for(var[d,h]of Object.entries(c))l[d]={id:u[d],type:d,properties:h};var{$set_once:_,$set:p}=e;return{event:j(j({},V(e,so)),{},{properties:j(j(j({},e.properties),p?{$set:j(j({},null!==(t=null===(i=e.properties)||void 0===i?void 0:i.$set)&&void 0!==t?t:{}),p)}:{}),_?{$set_once:j(j({},null!==(r=null===(n=e.properties)||void 0===n?void 0:n.$set_once)&&void 0!==r?r:{}),_)}:{}),elements_chain:null!==(s=null===(o=e.properties)||void 0===o?void 0:o.$elements_chain)&&void 0!==s?s:\"\",distinct_id:null===(a=e.properties)||void 0===a?void 0:a.distinct_id}),person:{properties:this.instance.get_property(\"$stored_person_properties\")},groups:l}}setupSiteApp(e){var t={id:e.id,loaded:!1,errored:!1};this.apps[e.id]=t;var i=i=>{var r;for(var n of(this.apps[e.id].errored=!i,this.apps[e.id].loaded=!0,oo.info(\"Site app with id \".concat(e.id,\" \").concat(i?\"loaded\":\"errored\")),i&&this.bufferedInvocations.length&&(oo.info(\"Processing \".concat(this.bufferedInvocations.length,\" events for site app with id \").concat(e.id)),this.bufferedInvocations.forEach((e=>{var i;return null===(i=t.processEvent)||void 0===i?void 0:i.call(t,e)}))),Object.values(this.apps)))if(!n.loaded)return;null===(r=this.stopBuffering)||void 0===r||r.call(this)};try{var{processEvent:r}=e.init({posthog:this.instance,callback:e=>{i(e)}});r&&(t.processEvent=r)}catch(t){oo.error(\"Error while initializing PostHog app with config id \".concat(e.id),t),i(!1)}}onCapturedEvent(e){if(0!==Object.keys(this.apps).length){var t=this.globalsForEvent(e);for(var i of Object.values(this.apps))try{var r;null===(r=i.processEvent)||void 0===r||r.call(i,t)}catch(t){oo.error(\"Error while processing event \".concat(e.event,\" for site app \").concat(i.id),t)}}}onRemoteConfig(e){var t,i,r,n=this;if(null!==(t=this.siteAppLoaders)&&void 0!==t&&t.length){if(!this.isEnabled)return void oo.error('PostHog site apps are disabled. Enable the \"opt_in_site_apps\" config to proceed.');for(var s of this.siteAppLoaders)this.setupSiteApp(s);this.instance.on(\"eventCaptured\",(e=>this.onCapturedEvent(e)))}else if(null===(i=this.stopBuffering)||void 0===i||i.call(this),null!==(r=e.siteApps)&&void 0!==r&&r.length)if(this.isEnabled){var o=function(e,t){var i,r;_[\"__$$ph_site_app_\".concat(e)]=n.instance,null===(i=_.__PosthogExtensions__)||void 0===i||null===(r=i.loadSiteApp)||void 0===r||r.call(i,n.instance,t,(t=>{if(t)return oo.error(\"Error while initializing PostHog app with config id \".concat(e),t)}))};for(var{id:a,url:l}of e.siteApps)o(a,l)}else oo.error('PostHog site apps are disabled. Enable the \"opt_in_site_apps\" config to proceed.')}}function lo(e,t,i){return bn({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}var uo={},co=()=>{},ho=\"posthog\",_o=!gn&&-1===(null==h?void 0:h.indexOf(\"MSIE\"))&&-1===(null==h?void 0:h.indexOf(\"Mozilla\")),po=()=>{var e,i,r;return{api_host:\"https://us.i.posthog.com\",ui_host:null,token:\"\",autocapture:!0,rageclick:!0,cross_subdomain_cookie:(i=null==a?void 0:a.location,r=null==i?void 0:i.hostname,!!R(r)&&\"herokuapp.com\"!==r.split(\".\").slice(-2).join(\".\")),persistence:\"localStorage+cookie\",persistence_name:\"\",loaded:co,store_google:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:!0,capture_pageleave:\"if_capture_pageview\",debug:l&&R(null==l?void 0:l.search)&&-1!==l.search.indexOf(\"__posthog_debug=true\")||!1,verbose:!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,enable_recording_console_log:void 0,secure_cookie:\"https:\"===(null==t||null===(e=t.location)||void 0===e?void 0:e.protocol),ip:!0,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:\"localStorage\",opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},inapp_protocol:\"//\",inapp_link_new_window:!1,request_batching:!0,properties_string_max_length:65535,session_recording:{},mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,on_request_error:e=>{var t=\"Bad HTTP status: \"+e.statusCode+\" \"+e.text;q.error(t)},get_device_id:e=>e,_onCapture:co,capture_performance:void 0,name:\"posthog\",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:\"identified_only\",__add_tracing_headers:!1,before_send:void 0}},vo=e=>{var t={};F(e.process_person)||(t.person_profiles=e.process_person),F(e.xhr_headers)||(t.request_headers=e.xhr_headers),F(e.cookie_name)||(t.persistence_name=e.cookie_name),F(e.disable_cookie)||(t.disable_persistence=e.disable_cookie);var i=K({},t,e);return x(e.property_blacklist)&&(F(e.property_denylist)?i.property_denylist=e.property_blacklist:x(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:q.error(\"Invalid value for property_denylist config: \"+e.property_denylist)),i};class go{constructor(){W(this,\"__forceAllowLocalhost\",!1)}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){q.error(\"WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`\"),this.__forceAllowLocalhost=e}}class fo{get decideEndpointWasHit(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){W(this,\"webPerformance\",new go),W(this,\"version\",p.LIB_VERSION),W(this,\"_internalEventEmitter\",new Nn),this.config=po(),this.SentryIntegration=Tn,this.sentryIntegration=e=>function(e,t){var i=Rn(e,t);return{name:Fn,processEvent:e=>i(e)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint=\"/e/\",this._initialPageviewCaptured=!1,this._initialPersonProfilesConfig=null,this._cachedIdentify=null,this.featureFlags=new Ge(this),this.toolbar=new _n(this),this.scrollManager=new Bs(this),this.pageViewManager=new Dn(this),this.surveys=new ks(this),this.experiments=new ro(this),this.exceptions=new no(this),this.rateLimiter=new Is(this),this.requestRouter=new Pn(this),this.consent=new Ks(this),this.people={set:(e,t,i)=>{var r=R(e)?{[e]:t}:e;this.setPersonProperties(r),null==i||i({})},set_once:(e,t,i)=>{var r=R(e)?{[e]:t}:e;this.setPersonProperties(void 0,r),null==i||i({})}},this.on(\"eventCaptured\",(e=>q.info('send \"'.concat(null==e?void 0:e.event,'\"'),e)))}init(e,t,i){if(i&&i!==ho){var r,n=null!==(r=uo[i])&&void 0!==r?r:new fo;return n._init(e,t,i),uo[i]=n,uo[ho][i]=n,n}return this._init(e,t,i)}_init(i){var r,n,s,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=arguments.length>2?arguments[2]:void 0;if(F(i)||T(i))return q.critical(\"PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()\"),this;if(this.__loaded)return q.warn(\"You have already initialized PostHog! Re-initializing is a no-op\"),this;this.__loaded=!0,this.config={},this._triggered_notifs=[],o.person_profiles&&(this._initialPersonProfilesConfig=o.person_profiles),this.set_config(K({},po(),vo(o),{name:a,token:i})),this.config.on_xhr_error&&q.error(\"on_xhr_error is deprecated. Use on_request_error instead\"),this.compression=o.disable_compression?void 0:e.GZipJS,this.persistence=new Ei(this.config),this.sessionPersistence=\"sessionStorage\"===this.config.persistence||\"memory\"===this.config.persistence?this.persistence:new Ei(j(j({},this.config),{},{persistence:\"sessionStorage\"}));var l=j({},this.persistence.props),u=j({},this.sessionPersistence.props);if(this._requestQueue=new pn((e=>this._send_retriable_request(e))),this._retryQueue=new En(this),this.__request_queue=[],this.config.__preview_experimental_cookieless_mode||(this.sessionManager=new In(this),this.sessionPropsManager=new Ps(this,this.sessionManager,this.persistence)),new Js(this).startIfEnabledOrStop(),this.siteApps=new ao(this),null===(r=this.siteApps)||void 0===r||r.init(),this.config.__preview_experimental_cookieless_mode||(this.sessionRecording=new on(this),this.sessionRecording.startIfEnabledOrStop()),this.config.disable_scroll_properties||this.scrollManager.startMeasuringScrollPosition(),this.autocapture=new Vs(this),this.autocapture.startIfEnabled(),this.surveys.loadIfEnabled(),this.heatmaps=new qs(this),this.heatmaps.startIfEnabled(),this.webVitalsAutocapture=new to(this),this.exceptionObserver=new Qs(this),this.exceptionObserver.startIfEnabled(),this.deadClicksAutocapture=new As(this,Ls),this.deadClicksAutocapture.startIfEnabled(),p.DEBUG=p.DEBUG||this.config.debug,p.DEBUG&&q.info(\"Starting in debug mode\",{this:this,config:o,thisC:j({},this.config),p:l,s:u}),this._sync_opt_out_with_persistence(),void 0!==(null===(n=o.bootstrap)||void 0===n?void 0:n.distinctID)){var c,d,h=this.config.get_device_id(et()),_=null!==(c=o.bootstrap)&&void 0!==c&&c.isIdentifiedID?h:o.bootstrap.distinctID;this.persistence.set_property($e,null!==(d=o.bootstrap)&&void 0!==d&&d.isIdentifiedID?\"identified\":\"anonymous\"),this.register({distinct_id:o.bootstrap.distinctID,$device_id:_})}if(this._hasBootstrappedFeatureFlags()){var v,g,f=Object.keys((null===(v=o.bootstrap)||void 0===v?void 0:v.featureFlags)||{}).filter((e=>{var t,i;return!(null===(t=o.bootstrap)||void 0===t||null===(i=t.featureFlags)||void 0===i||!i[e])})).reduce(((e,t)=>{var i,r;return e[t]=(null===(i=o.bootstrap)||void 0===i||null===(r=i.featureFlags)||void 0===r?void 0:r[t])||!1,e}),{}),m=Object.keys((null===(g=o.bootstrap)||void 0===g?void 0:g.featureFlagPayloads)||{}).filter((e=>f[e])).reduce(((e,t)=>{var i,r,n,s;null!==(i=o.bootstrap)&&void 0!==i&&null!==(r=i.featureFlagPayloads)&&void 0!==r&&r[t]&&(e[t]=null===(n=o.bootstrap)||void 0===n||null===(s=n.featureFlagPayloads)||void 0===s?void 0:s[t]);return e}),{});this.featureFlags.receivedFeatureFlags({featureFlags:f,featureFlagPayloads:m})}if(this.config.__preview_experimental_cookieless_mode)this.register_once({distinct_id:Be,$device_id:null},\"\");else if(!this.get_distinct_id()){var b=this.config.get_device_id(et());this.register_once({distinct_id:b,$device_id:b},\"\"),this.persistence.set_property($e,\"anonymous\")}return null==t||null===(s=t.addEventListener)||void 0===s||s.call(t,\"onpagehide\"in self?\"pagehide\":\"unload\",this._handle_unload.bind(this)),this.toolbar.maybeLoadToolbar(),o.segment?An(this,(()=>this._loaded())):this._loaded(),I(this.config._onCapture)&&this.config._onCapture!==co&&(q.warn(\"onCapture is deprecated. Please use `before_send` instead\"),this.on(\"eventCaptured\",(e=>this.config._onCapture(e.event,e)))),this}_onRemoteConfig(t){var i,r,n,s,o,l,u,c,d;if(!a||!a.body)return q.info(\"document not ready yet, trying again in 500 milliseconds...\"),void setTimeout((()=>{this._onRemoteConfig(t)}),500);this.compression=void 0,t.supportedCompression&&!this.config.disable_compression&&(this.compression=m(t.supportedCompression,e.GZipJS)?e.GZipJS:m(t.supportedCompression,e.Base64)?e.Base64:void 0),null!==(i=t.analytics)&&void 0!==i&&i.endpoint&&(this.analyticsDefaultEndpoint=t.analytics.endpoint),this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:t.defaultIdentifiedOnly?\"identified_only\":\"always\"}),null===(r=this.siteApps)||void 0===r||r.onRemoteConfig(t),null===(n=this.sessionRecording)||void 0===n||n.onRemoteConfig(t),null===(s=this.autocapture)||void 0===s||s.onRemoteConfig(t),null===(o=this.heatmaps)||void 0===o||o.onRemoteConfig(t),null===(l=this.surveys)||void 0===l||l.onRemoteConfig(t),null===(u=this.webVitalsAutocapture)||void 0===u||u.onRemoteConfig(t),null===(c=this.exceptionObserver)||void 0===c||c.onRemoteConfig(t),null===(d=this.deadClicksAutocapture)||void 0===d||d.onRemoteConfig(t)}_loaded(){try{this.config.loaded(this)}catch(e){q.critical(\"`loaded` function failed\",e)}this._start_queue_if_opted_in(),this.config.capture_pageview&&setTimeout((()=>{this.consent.isOptedIn()&&this._captureInitialPageview()}),1),new ln(this).load(),this.featureFlags.decide()}_start_queue_if_opted_in(){var e;this.has_opted_out_capturing()||this.config.request_batching&&(null===(e=this._requestQueue)||void 0===e||e.enable())}_dom_loaded(){this.has_opted_out_capturing()||J(this.__request_queue,(e=>this._send_retriable_request(e))),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t;this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(\"$pageleave\"),null===(e=this._requestQueue)||void 0===e||e.unload(),null===(t=this._retryQueue)||void 0===t||t.unload()):this._shouldCapturePageleave()&&this.capture(\"$pageleave\",null,{transport:\"sendBeacon\"})}_send_request(e){this.__loaded&&(_o?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=mn(e.url,{ip:this.config.ip?1:0}),e.headers=j({},this.config.request_headers),e.compression=\"best-available\"===e.compression?this.compression:e.compression,e.fetchOptions=e.fetchOptions||this.config.fetch_options,(e=>{var t,i,r,n=j({},e);n.timeout=n.timeout||6e4,n.url=mn(n.url,{_:(new Date).getTime().toString(),ver:p.LIB_VERSION,compression:n.compression});var s=null!==(t=n.transport)&&void 0!==t?t:\"fetch\",o=null!==(i=null===(r=ne(wn,(e=>e.transport===s)))||void 0===r?void 0:r.method)&&void 0!==i?i:wn[0].method;if(!o)throw new Error(\"No available transport method\");o(n)})(j(j({},e),{},{callback:t=>{var i,r,n;(this.rateLimiter.checkForLimiting(t),t.statusCode>=400)&&(null===(r=(n=this.config).on_request_error)||void 0===r||r.call(n,t));null===(i=e.callback)||void 0===i||i.call(e,t)}}))))}_send_retriable_request(e){this._retryQueue?this._retryQueue.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,i=[],r=[],n=[];J(e,(e=>{e&&(t=e[0],x(t)?n.push(e):I(e)?e.call(this):x(e)&&\"alias\"===t?i.push(e):x(e)&&-1!==t.indexOf(\"capture\")&&I(this[t])?n.push(e):r.push(e))}));var s=function(e,t){J(e,(function(e){if(x(e[0])){var i=t;Y(e,(function(e){i=i[e[0]].apply(i,e.slice(1))}))}else this[e[0]].apply(this,e.slice(1))}),t)};s(i,this),s(r,this),s(n,this)}_hasBootstrappedFeatureFlags(){var e,t;return(null===(e=this.config.bootstrap)||void 0===e?void 0:e.featureFlags)&&Object.keys(null===(t=this.config.bootstrap)||void 0===t?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,i){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue){if(!this.consent.isOptedOut())if(!F(e)&&R(e)){if(this.config.opt_out_useragent_filter||!this._is_bot()){var n=null!=i&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(null==n||!n.isRateLimited){this.sessionPersistence.update_search_keyword(),this.config.store_google&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.store_google||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,o=(null==i?void 0:i.timestamp)||s,a=et(),l={uuid:a,event:e,properties:this._calculate_event_properties(e,t||{},o,a)};n&&(l.properties.$lib_rate_limit_remaining_tokens=n.remainingTokens),(null==i?void 0:i.$set)&&(l.$set=null==i?void 0:i.$set);var u=this._calculate_set_once_properties(null==i?void 0:i.$set_once);u&&(l.$set_once=u),(l=ie(l,null!=i&&i._noTruncate?null:this.config.properties_string_max_length)).timestamp=o,F(null==i?void 0:i.timestamp)||(l.properties.$event_time_override_provided=!0,l.properties.$event_time_override_system_time=s);var c=j(j({},l.properties.$set),l.$set);if(P(c)||this.setPersonPropertiesForFlags(c),!O(this.config.before_send)){var d=this._runBeforeSend(l);if(!d)return;l=d}this._internalEventEmitter.emit(\"eventCaptured\",l);var h={method:\"POST\",url:null!==(r=null==i?void 0:i._url)&&void 0!==r?r:this.requestRouter.endpointFor(\"api\",this.analyticsDefaultEndpoint),data:l,compression:\"best-available\",batchKey:null==i?void 0:i._batchKey};return!this.config.request_batching||i&&(null==i||!i._batchKey)||null!=i&&i.send_instantly?this._send_retriable_request(h):this._requestQueue.enqueue(h),l}q.critical(\"This capture call is ignored due to client rate limiting.\")}}else q.error(\"No event name provided to posthog.capture\")}else q.uninitializedWarning(\"posthog.capture\")}_addCaptureHook(e){return this.on(\"eventCaptured\",(t=>e(t.event,t)))}_calculate_event_properties(e,t,i,r){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return t;var n=this.persistence.remove_event_timer(e),s=j({},t);if(s.token=this.config.token,this.config.__preview_experimental_cookieless_mode&&(s.$cookieless_mode=!0),\"$snapshot\"===e){var o=j(j({},this.persistence.properties()),this.sessionPersistence.properties());return s.distinct_id=o.distinct_id,(!R(s.distinct_id)&&!M(s.distinct_id)||T(s.distinct_id))&&q.error(\"Invalid distinct_id for replay event. This indicates a bug in your implementation\"),s}var l,u=wi.properties({maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties});if(this.sessionManager){var{sessionId:c,windowId:d}=this.sessionManager.checkAndGetSessionAndWindowId();s.$session_id=c,s.$window_id=d}if(this.sessionRecording&&(s.$recording_status=this.sessionRecording.status),this.requestRouter.region===kn.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),this.sessionPropsManager&&this.config.__preview_send_client_session_params&&(\"$pageview\"===e||\"$pageleave\"===e||\"$autocapture\"===e)){var _=this.sessionPropsManager.getSessionProps();s=K(s,_)}if(l=\"$pageview\"===e?this.pageViewManager.doPageView(i,r):\"$pageleave\"===e?this.pageViewManager.doPageLeave(i):this.pageViewManager.doEvent(),s=K(s,l),\"$pageview\"===e&&a&&(s.title=a.title),!F(n)){var p=i.getTime()-n;s.$duration=parseFloat((p/1e3).toFixed(3))}h&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?\"bot\":\"browser\"),(s=K({},u,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),x(this.config.property_denylist)?Y(this.config.property_denylist,(function(e){delete s[e]})):q.error(\"Invalid value for property_denylist config: \"+this.config.property_denylist+\" or property_blacklist config: \"+this.config.property_blacklist);var v=this.config.sanitize_properties;v&&(q.error(\"sanitize_properties is deprecated. Use before_send instead\"),s=v(s,e));var g=this._hasPersonProcessing();return s.$process_person_profile=g,g&&this._requirePersonProcessing(\"_calculate_event_properties\"),s}_calculate_set_once_properties(e){if(!this.persistence||!this._hasPersonProcessing())return e;var t=K({},this.persistence.get_initial_props(),e||{}),i=this.config.sanitize_properties;return i&&(q.error(\"sanitize_properties is deprecated. Use before_send instead\"),t=i(t,\"$set_once\")),P(t)?void 0:t}register(e,t){var i;null===(i=this.persistence)||void 0===i||i.register(e,t)}register_once(e,t,i){var r;null===(r=this.persistence)||void 0===r||r.register_once(e,t,i)}register_for_session(e){var t;null===(t=this.sessionPersistence)||void 0===t||t.register(e)}unregister(e){var t;null===(t=this.persistence)||void 0===t||t.unregister(e)}unregister_for_session(e){var t;null===(t=this.sessionPersistence)||void 0===t||t.unregister(e)}_register_single(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(t)}catch(e){return t}}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,t){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t)}getEarlyAccessFeatures(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.featureFlags.getEarlyAccessFeatures(e,t)}on(e,t){return this._internalEventEmitter.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSessionId(e){var t,i;return null!==(t=null===(i=this.sessionManager)||void 0===i?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}canRenderSurvey(e){this.surveys.canRenderSurvey(e)}getNextSurveyStep(e,t,i){return this.surveys.getNextSurveyStep(e,t,i)}identify(e,t,i){if(!this.__loaded||!this.persistence)return q.uninitializedWarning(\"posthog.identify\");if(M(e)&&(e=e.toString(),q.warn(\"The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.\")),e){if([\"distinct_id\",\"distinctid\"].includes(e.toLowerCase()))q.critical('The string \"'.concat(e,'\" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'));else if(this._requirePersonProcessing(\"posthog.identify\")){var r=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property(\"$device_id\")){var n=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:n},\"\")}e!==r&&e!==this.get_property(oe)&&(this.unregister(oe),this.register({distinct_id:e}));var s=\"anonymous\"===(this.persistence.get_property($e)||\"anonymous\");e!==r&&s?(this.persistence.set_property($e,\"identified\"),this.setPersonPropertiesForFlags(t||{},!1),this.capture(\"$identify\",{distinct_id:e,$anon_distinct_id:r},{$set:t||{},$set_once:i||{}}),this.featureFlags.setAnonymousDistinctId(r),this._cachedIdentify=lo(e,t,i)):(t||i)&&(this._cachedIdentify!==lo(e,t,i)?(this.setPersonProperties(t,i),this._cachedIdentify=lo(e,t,i)):q.info(\"A duplicate posthog.identify call was made with the same properties. It has been ignored.\")),e!==r&&(this.reloadFeatureFlags(),this.unregister(Te))}}else q.error(\"Unique user id has not been set in posthog.identify\")}setPersonProperties(e,t){(e||t)&&this._requirePersonProcessing(\"posthog.setPersonProperties\")&&(this.setPersonPropertiesForFlags(e||{}),this.capture(\"$set\",{$set:e||{},$set_once:t||{}}))}group(e,t,i){if(e&&t){if(this._requirePersonProcessing(\"posthog.group\")){var r=this.getGroups();r[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j(j({},r),{},{[e]:t})}),i&&(this.capture(\"$groupidentify\",{$group_type:e,$group_key:t,$group_set:i}),this.setGroupPropertiesForFlags({[e]:i})),r[e]===t||i||this.reloadFeatureFlags()}}else q.error(\"posthog.group requires a group type and group key\")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];this._requirePersonProcessing(\"posthog.setGroupPropertiesForFlags\")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,i,r,n,s;if(q.info(\"reset\"),!this.__loaded)return q.uninitializedWarning(\"posthog.reset\");var o=this.get_property(\"$device_id\");if(this.consent.reset(),null===(t=this.persistence)||void 0===t||t.clear(),null===(i=this.sessionPersistence)||void 0===i||i.clear(),null===(r=this.surveys)||void 0===r||r.reset(),null===(n=this.persistence)||void 0===n||n.set_property($e,\"anonymous\"),null===(s=this.sessionManager)||void 0===s||s.resetSessionId(),this._cachedIdentify=null,this.config.__preview_experimental_cookieless_mode)this.register_once({distinct_id:Be,$device_id:null},\"\");else{var a=this.config.get_device_id(et());this.register_once({distinct_id:a,$device_id:e?a:o},\"\")}}get_distinct_id(){return this.get_property(\"distinct_id\")}getGroups(){return this.get_property(\"$groups\")||{}}get_session_id(){var e,t;return null!==(e=null===(t=this.sessionManager)||void 0===t?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:\"\"}get_session_replay_url(e){if(!this.sessionManager)return\"\";var{sessionId:t,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor(\"ui\",\"/project/\".concat(this.config.token,\"/replay/\").concat(t));if(null!=e&&e.withTimestamp&&i){var n,s=null!==(n=e.timestampLookBack)&&void 0!==n?n:10;if(!i)return r;var o=Math.max(Math.floor(((new Date).getTime()-i)/1e3)-s,0);r+=\"?t=\".concat(o)}return r}alias(e,t){return e===this.get_property(se)?(q.critical(\"Attempting to create alias for existing People user - aborting.\"),-2):this._requirePersonProcessing(\"posthog.alias\")?(F(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(oe,e),this.capture(\"$create_alias\",{alias:e,distinct_id:t})):(q.warn(\"alias matches current distinct_id - skipping api call.\"),this.identify(e),-1)):void 0}set_config(e){var t,i,r,n,s=j({},this.config);C(e)&&(K(this.config,vo(e)),null===(t=this.persistence)||void 0===t||t.update_config(this.config,s),this.sessionPersistence=\"sessionStorage\"===this.config.persistence||\"memory\"===this.config.persistence?this.persistence:new Ei(j(j({},this.config),{},{persistence:\"sessionStorage\"})),lt.is_supported()&&\"true\"===lt.get(\"ph_debug\")&&(this.config.debug=!0),this.config.debug&&(p.DEBUG=!0,q.info(\"set_config\",{config:e,oldConfig:s,newConfig:j({},this.config)})),null===(i=this.sessionRecording)||void 0===i||i.startIfEnabledOrStop(),null===(r=this.autocapture)||void 0===r||r.startIfEnabled(),null===(n=this.heatmaps)||void 0===n||n.startIfEnabled(),this.surveys.loadIfEnabled(),this._sync_opt_out_with_persistence())}startSessionRecording(e){var t=!0===e,i={sampling:t||!(null==e||!e.sampling),linked_flag:t||!(null==e||!e.linked_flag),url_trigger:t||!(null==e||!e.url_trigger),event_trigger:t||!(null==e||!e.event_trigger)};if(Object.values(i).some(Boolean)){var r,n,s,o,a;if(null===(r=this.sessionManager)||void 0===r||r.checkAndGetSessionAndWindowId(),i.sampling)null===(n=this.sessionRecording)||void 0===n||n.overrideSampling();if(i.linked_flag)null===(s=this.sessionRecording)||void 0===s||s.overrideLinkedFlag();if(i.url_trigger)null===(o=this.sessionRecording)||void 0===o||o.overrideTrigger(\"url\");if(i.event_trigger)null===(a=this.sessionRecording)||void 0===a||a.overrideTrigger(\"event\")}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!(null===(e=this.sessionRecording)||void 0===e||!e.started)}captureException(e,t){var i,r=new Error(\"PostHog syntheticException\"),n=I(null===(i=_.__PosthogExtensions__)||void 0===i?void 0:i.parseErrorAsProperties)?_.__PosthogExtensions__.parseErrorAsProperties([e.message,void 0,void 0,void 0,e],{syntheticException:r}):j({$exception_level:\"error\",$exception_list:[{type:e.name,value:e.message,mechanism:{handled:!0,synthetic:!1}}]},t);this.exceptions.sendExceptionEvent(n)}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return null===(t=this.persistence)||void 0===t?void 0:t.props[e]}getSessionProperty(e){var t;return null===(t=this.sessionPersistence)||void 0===t?void 0:t.props[e]}toString(){var e,t=null!==(e=this.config.name)&&void 0!==e?e:ho;return t!==ho&&(t=ho+\".\"+t),t}_isIdentified(){var e,t;return\"identified\"===(null===(e=this.persistence)||void 0===e?void 0:e.get_property($e))||\"identified\"===(null===(t=this.sessionPersistence)||void 0===t?void 0:t.get_property($e))}_hasPersonProcessing(){var e,t,i,r;return!(\"never\"===this.config.person_profiles||\"identified_only\"===this.config.person_profiles&&!this._isIdentified()&&P(this.getGroups())&&(null===(e=this.persistence)||void 0===e||null===(t=e.props)||void 0===t||!t[oe])&&(null===(i=this.persistence)||void 0===i||null===(r=i.props)||void 0===r||!r[Ne]))}_shouldCapturePageleave(){return!0===this.config.capture_pageleave||\"if_capture_pageview\"===this.config.capture_pageleave&&this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing(\"posthog.createPersonProfile\")&&this.setPersonProperties({},{})}_requirePersonProcessing(e){return\"never\"===this.config.person_profiles?(q.error(e+' was called, but process_person is set to \"never\". This call will be ignored.'),!1):(this._register_single(Ne,!0),!0)}_sync_opt_out_with_persistence(){var e,t,i,r,n=this.consent.isOptedOut(),s=this.config.opt_out_persistence_by_default,o=this.config.disable_persistence||n&&!!s;(null===(e=this.persistence)||void 0===e?void 0:e.disabled)!==o&&(null===(i=this.persistence)||void 0===i||i.set_disabled(o));(null===(t=this.sessionPersistence)||void 0===t?void 0:t.disabled)!==o&&(null===(r=this.sessionPersistence)||void 0===r||r.set_disabled(o))}opt_in_capturing(e){var t;(this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),F(null==e?void 0:e.captureEventName)||null!=e&&e.captureEventName)&&this.capture(null!==(t=null==e?void 0:e.captureEventName)&&void 0!==t?t:\"$opt_in\",null==e?void 0:e.captureProperties,{send_instantly:!0});this.config.capture_pageview&&this._captureInitialPageview()}opt_out_capturing(){this.consent.optInOut(!1),this._sync_opt_out_with_persistence()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return o?Ts(o,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){a&&!this._initialPageviewCaptured&&(this._initialPageviewCaptured=!0,this.capture(\"$pageview\",{title:a.title},{send_instantly:!0}))}debug(e){!1===e?(null==t||t.console.log(\"You've disabled debug mode.\"),localStorage&&localStorage.removeItem(\"ph_debug\"),this.set_config({debug:!1})):(null==t||t.console.log(\"You're now in debug mode. All calls to PostHog will be logged in your console.\\nYou can disable this with `posthog.debug(false)`.\"),localStorage&&localStorage.setItem(\"ph_debug\",\"true\"),this.set_config({debug:!0}))}_runBeforeSend(e){if(O(this.config.before_send))return e;var t=x(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var r of t){if(i=r(i),O(i)){var n=\"Event '\".concat(e.event,\"' was rejected in beforeSend function\");return D(e.event)?q.warn(\"\".concat(n,\". This can cause unexpected behavior.\")):q.info(n),null}i.properties&&!P(i.properties)||q.warn(\"Event '\".concat(e.event,\"' has no properties after beforeSend function, this is likely an error.\"))}return i}getPageViewId(){var e;return null===(e=this.pageViewManager._currentPageview)||void 0===e?void 0:e.pageViewId}}!function(e,t){for(var i=0;i element)');\n return;\n }\n\n if (options.recordCrossDomainIFrames) {\n window._fs_run_in_iframe = true;\n }\n\n if (options.recordOnlyThisIFrame) {\n window._fs_is_outer_script = true;\n }\n\n snippet(options);\n\n if (options.devMode === true) {\n var message = 'FullStory was initialized in devMode and will stop recording';\n event('FullStory Dev Mode', {\n message_str: message\n });\n shutdown();\n window._fs_dev_mode = true;\n console.warn(message);\n }\n};\n\nvar initOnce = function initOnce(fn, message) {\n return function () {\n if (window._fs_initialized) {\n if (message) console.warn(message);\n return;\n }\n\n fn.apply(void 0, arguments);\n window._fs_initialized = true;\n };\n};\n\nvar init = initOnce(_init, 'FullStory init has already been called once, additional invocations are ignored');\n\nexport { anonymize, consent, event, getCurrentSessionURL, identify, init, log, restart, setUserVars, shutdown };\n","import posthog from 'posthog-js';\nimport * as FullStory from '@fullstory/browser';\n\n// NOTE: We don't want to initialize PostHog in non-prod mode most of the time, to limit session usage.\nconst shouldInitializePosthog = process.env.REACT_APP_ENABLE_POSTHOG;\n\nexport const initAnalytics = () => {\n if (shouldInitializePosthog) {\n console.info('Initializing PostHog');\n\n if (!process.env.REACT_APP_POSTHOG_API_KEY) {\n console.error('REACT_APP_POSTHOG_API_KEY is not set');\n return;\n }\n\n posthog.init(process.env.REACT_APP_POSTHOG_API_KEY, {\n api_host: 'https://us.posthog.com',\n });\n }\n\n FullStory.init({ orgId: '167FTE' }); // TODO: remove this once we're no longer using FullStory\n};\n\nexport const captureEvent = (\n eventName: string,\n payload: Record = {},\n) => {\n posthog.capture(eventName, payload);\n\n FullStory.event(eventName, payload); // TODO: remove this once we're no longer using FullStory\n};\n","import styled from 'styled-components';\n\nconst Content = styled.div`\n height: 100%;\n max-height: 100%;\n overflow: hidden;\n display: flex;\n flex-direction: column;\n ${({ noPadding }) =>\n noPadding ? '' : `padding: 0 var(--content-x-padding);`};\n`;\n\nexport default Content;\n","export const NOT_FOUND = 'Not Found';\n","import React, { useEffect } from 'react';\nimport styled from 'styled-components';\nimport { useRouteError } from 'react-router';\nimport { getRootUrl } from '../utils/utils';\nimport { captureEvent } from '../utils/analytics';\nimport Content from '../components/layout/Content';\nimport { notifyMonitoring } from '../utils/monitoring';\nimport { NOT_FOUND } from '../constants/errors';\n\nconst PAGE_NOT_FOUND = 'Oops, looks like this page does not exist';\nconst SOMETHING_WRONG = 'Oops, something went wrong!';\n\nconst ErrorBoundaryContainer = styled.div`\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n justify-content: flex-start;\n padding: 48px;\n`;\n\nconst ImgContainer = styled.div`\n height: 30vh;\n border-radius: 16px;\n`;\n\nexport const DefaultErrorView = ({ message = SOMETHING_WRONG }) => (\n \n \n

{message}

\n

\n This may be a bad URL. Try going back to home{' '}\n and trying again. If the problem persists, start a chat with us using\n the blue chat icon or{' '}\n send us an email!\n

\n \n \n \n {process.env.NODE_ENV === 'development' && (\n
\n

Hey, developer!

\n

The application encountered an error. Find it in the console.

\n
\n )}\n
\n
\n);\n\nexport const NotFoundView = () => ;\n\nconst ErrorBoundaryView = () => {\n const error = useRouteError();\n const notFound = error.message === NOT_FOUND;\n\n useEffect(() => {\n captureEvent('error-boundary-hit');\n }, []);\n\n if (!notFound) notifyMonitoring(error);\n\n return notFound ? : ;\n};\n\nexport default ErrorBoundaryView;\n","// TinyColor v1.4.2\n// https://github.com/bgrins/TinyColor\n// Brian Grinstead, MIT License\n\n(function(Math) {\n\nvar trimLeft = /^\\s+/,\n trimRight = /\\s+$/,\n tinyCounter = 0,\n mathRound = Math.round,\n mathMin = Math.min,\n mathMax = Math.max,\n mathRandom = Math.random;\n\nfunction tinycolor (color, opts) {\n\n color = (color) ? color : '';\n opts = opts || { };\n\n // If input is already a tinycolor, return itself\n if (color instanceof tinycolor) {\n return color;\n }\n // If we are called as a function, call using new instead\n if (!(this instanceof tinycolor)) {\n return new tinycolor(color, opts);\n }\n\n var rgb = inputToRGB(color);\n this._originalInput = color,\n this._r = rgb.r,\n this._g = rgb.g,\n this._b = rgb.b,\n this._a = rgb.a,\n this._roundA = mathRound(100*this._a) / 100,\n this._format = opts.format || rgb.format;\n this._gradientType = opts.gradientType;\n\n // Don't let the range of [0,255] come back in [0,1].\n // Potentially lose a little bit of precision here, but will fix issues where\n // .5 gets interpreted as half of the total, instead of half of 1\n // If it was supposed to be 128, this was already taken care of by `inputToRgb`\n if (this._r < 1) { this._r = mathRound(this._r); }\n if (this._g < 1) { this._g = mathRound(this._g); }\n if (this._b < 1) { this._b = mathRound(this._b); }\n\n this._ok = rgb.ok;\n this._tc_id = tinyCounter++;\n}\n\ntinycolor.prototype = {\n isDark: function() {\n return this.getBrightness() < 128;\n },\n isLight: function() {\n return !this.isDark();\n },\n isValid: function() {\n return this._ok;\n },\n getOriginalInput: function() {\n return this._originalInput;\n },\n getFormat: function() {\n return this._format;\n },\n getAlpha: function() {\n return this._a;\n },\n getBrightness: function() {\n //http://www.w3.org/TR/AERT#color-contrast\n var rgb = this.toRgb();\n return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;\n },\n getLuminance: function() {\n //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef\n var rgb = this.toRgb();\n var RsRGB, GsRGB, BsRGB, R, G, B;\n RsRGB = rgb.r/255;\n GsRGB = rgb.g/255;\n BsRGB = rgb.b/255;\n\n if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}\n if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}\n if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}\n return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);\n },\n setAlpha: function(value) {\n this._a = boundAlpha(value);\n this._roundA = mathRound(100*this._a) / 100;\n return this;\n },\n toHsv: function() {\n var hsv = rgbToHsv(this._r, this._g, this._b);\n return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };\n },\n toHsvString: function() {\n var hsv = rgbToHsv(this._r, this._g, this._b);\n var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);\n return (this._a == 1) ?\n \"hsv(\" + h + \", \" + s + \"%, \" + v + \"%)\" :\n \"hsva(\" + h + \", \" + s + \"%, \" + v + \"%, \"+ this._roundA + \")\";\n },\n toHsl: function() {\n var hsl = rgbToHsl(this._r, this._g, this._b);\n return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };\n },\n toHslString: function() {\n var hsl = rgbToHsl(this._r, this._g, this._b);\n var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);\n return (this._a == 1) ?\n \"hsl(\" + h + \", \" + s + \"%, \" + l + \"%)\" :\n \"hsla(\" + h + \", \" + s + \"%, \" + l + \"%, \"+ this._roundA + \")\";\n },\n toHex: function(allow3Char) {\n return rgbToHex(this._r, this._g, this._b, allow3Char);\n },\n toHexString: function(allow3Char) {\n return '#' + this.toHex(allow3Char);\n },\n toHex8: function(allow4Char) {\n return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);\n },\n toHex8String: function(allow4Char) {\n return '#' + this.toHex8(allow4Char);\n },\n toRgb: function() {\n return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };\n },\n toRgbString: function() {\n return (this._a == 1) ?\n \"rgb(\" + mathRound(this._r) + \", \" + mathRound(this._g) + \", \" + mathRound(this._b) + \")\" :\n \"rgba(\" + mathRound(this._r) + \", \" + mathRound(this._g) + \", \" + mathRound(this._b) + \", \" + this._roundA + \")\";\n },\n toPercentageRgb: function() {\n return { r: mathRound(bound01(this._r, 255) * 100) + \"%\", g: mathRound(bound01(this._g, 255) * 100) + \"%\", b: mathRound(bound01(this._b, 255) * 100) + \"%\", a: this._a };\n },\n toPercentageRgbString: function() {\n return (this._a == 1) ?\n \"rgb(\" + mathRound(bound01(this._r, 255) * 100) + \"%, \" + mathRound(bound01(this._g, 255) * 100) + \"%, \" + mathRound(bound01(this._b, 255) * 100) + \"%)\" :\n \"rgba(\" + mathRound(bound01(this._r, 255) * 100) + \"%, \" + mathRound(bound01(this._g, 255) * 100) + \"%, \" + mathRound(bound01(this._b, 255) * 100) + \"%, \" + this._roundA + \")\";\n },\n toName: function() {\n if (this._a === 0) {\n return \"transparent\";\n }\n\n if (this._a < 1) {\n return false;\n }\n\n return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;\n },\n toFilter: function(secondColor) {\n var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);\n var secondHex8String = hex8String;\n var gradientType = this._gradientType ? \"GradientType = 1, \" : \"\";\n\n if (secondColor) {\n var s = tinycolor(secondColor);\n secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);\n }\n\n return \"progid:DXImageTransform.Microsoft.gradient(\"+gradientType+\"startColorstr=\"+hex8String+\",endColorstr=\"+secondHex8String+\")\";\n },\n toString: function(format) {\n var formatSet = !!format;\n format = format || this._format;\n\n var formattedString = false;\n var hasAlpha = this._a < 1 && this._a >= 0;\n var needsAlphaFormat = !formatSet && hasAlpha && (format === \"hex\" || format === \"hex6\" || format === \"hex3\" || format === \"hex4\" || format === \"hex8\" || format === \"name\");\n\n if (needsAlphaFormat) {\n // Special case for \"transparent\", all other non-alpha formats\n // will return rgba when there is transparency.\n if (format === \"name\" && this._a === 0) {\n return this.toName();\n }\n return this.toRgbString();\n }\n if (format === \"rgb\") {\n formattedString = this.toRgbString();\n }\n if (format === \"prgb\") {\n formattedString = this.toPercentageRgbString();\n }\n if (format === \"hex\" || format === \"hex6\") {\n formattedString = this.toHexString();\n }\n if (format === \"hex3\") {\n formattedString = this.toHexString(true);\n }\n if (format === \"hex4\") {\n formattedString = this.toHex8String(true);\n }\n if (format === \"hex8\") {\n formattedString = this.toHex8String();\n }\n if (format === \"name\") {\n formattedString = this.toName();\n }\n if (format === \"hsl\") {\n formattedString = this.toHslString();\n }\n if (format === \"hsv\") {\n formattedString = this.toHsvString();\n }\n\n return formattedString || this.toHexString();\n },\n clone: function() {\n return tinycolor(this.toString());\n },\n\n _applyModification: function(fn, args) {\n var color = fn.apply(null, [this].concat([].slice.call(args)));\n this._r = color._r;\n this._g = color._g;\n this._b = color._b;\n this.setAlpha(color._a);\n return this;\n },\n lighten: function() {\n return this._applyModification(lighten, arguments);\n },\n brighten: function() {\n return this._applyModification(brighten, arguments);\n },\n darken: function() {\n return this._applyModification(darken, arguments);\n },\n desaturate: function() {\n return this._applyModification(desaturate, arguments);\n },\n saturate: function() {\n return this._applyModification(saturate, arguments);\n },\n greyscale: function() {\n return this._applyModification(greyscale, arguments);\n },\n spin: function() {\n return this._applyModification(spin, arguments);\n },\n\n _applyCombination: function(fn, args) {\n return fn.apply(null, [this].concat([].slice.call(args)));\n },\n analogous: function() {\n return this._applyCombination(analogous, arguments);\n },\n complement: function() {\n return this._applyCombination(complement, arguments);\n },\n monochromatic: function() {\n return this._applyCombination(monochromatic, arguments);\n },\n splitcomplement: function() {\n return this._applyCombination(splitcomplement, arguments);\n },\n triad: function() {\n return this._applyCombination(triad, arguments);\n },\n tetrad: function() {\n return this._applyCombination(tetrad, arguments);\n }\n};\n\n// If input is an object, force 1 into \"1.0\" to handle ratios properly\n// String input requires \"1.0\" as input, so 1 will be treated as 1\ntinycolor.fromRatio = function(color, opts) {\n if (typeof color == \"object\") {\n var newColor = {};\n for (var i in color) {\n if (color.hasOwnProperty(i)) {\n if (i === \"a\") {\n newColor[i] = color[i];\n }\n else {\n newColor[i] = convertToPercentage(color[i]);\n }\n }\n }\n color = newColor;\n }\n\n return tinycolor(color, opts);\n};\n\n// Given a string or object, convert that input to RGB\n// Possible string inputs:\n//\n// \"red\"\n// \"#f00\" or \"f00\"\n// \"#ff0000\" or \"ff0000\"\n// \"#ff000000\" or \"ff000000\"\n// \"rgb 255 0 0\" or \"rgb (255, 0, 0)\"\n// \"rgb 1.0 0 0\" or \"rgb (1, 0, 0)\"\n// \"rgba (255, 0, 0, 1)\" or \"rgba 255, 0, 0, 1\"\n// \"rgba (1.0, 0, 0, 1)\" or \"rgba 1.0, 0, 0, 1\"\n// \"hsl(0, 100%, 50%)\" or \"hsl 0 100% 50%\"\n// \"hsla(0, 100%, 50%, 1)\" or \"hsla 0 100% 50%, 1\"\n// \"hsv(0, 100%, 100%)\" or \"hsv 0 100% 100%\"\n//\nfunction inputToRGB(color) {\n\n var rgb = { r: 0, g: 0, b: 0 };\n var a = 1;\n var s = null;\n var v = null;\n var l = null;\n var ok = false;\n var format = false;\n\n if (typeof color == \"string\") {\n color = stringInputToObject(color);\n }\n\n if (typeof color == \"object\") {\n if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {\n rgb = rgbToRgb(color.r, color.g, color.b);\n ok = true;\n format = String(color.r).substr(-1) === \"%\" ? \"prgb\" : \"rgb\";\n }\n else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {\n s = convertToPercentage(color.s);\n v = convertToPercentage(color.v);\n rgb = hsvToRgb(color.h, s, v);\n ok = true;\n format = \"hsv\";\n }\n else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {\n s = convertToPercentage(color.s);\n l = convertToPercentage(color.l);\n rgb = hslToRgb(color.h, s, l);\n ok = true;\n format = \"hsl\";\n }\n\n if (color.hasOwnProperty(\"a\")) {\n a = color.a;\n }\n }\n\n a = boundAlpha(a);\n\n return {\n ok: ok,\n format: color.format || format,\n r: mathMin(255, mathMax(rgb.r, 0)),\n g: mathMin(255, mathMax(rgb.g, 0)),\n b: mathMin(255, mathMax(rgb.b, 0)),\n a: a\n };\n}\n\n\n// Conversion Functions\n// --------------------\n\n// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:\n// \n\n// `rgbToRgb`\n// Handle bounds / percentage checking to conform to CSS color spec\n// \n// *Assumes:* r, g, b in [0, 255] or [0, 1]\n// *Returns:* { r, g, b } in [0, 255]\nfunction rgbToRgb(r, g, b){\n return {\n r: bound01(r, 255) * 255,\n g: bound01(g, 255) * 255,\n b: bound01(b, 255) * 255\n };\n}\n\n// `rgbToHsl`\n// Converts an RGB color value to HSL.\n// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]\n// *Returns:* { h, s, l } in [0,1]\nfunction rgbToHsl(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, l = (max + min) / 2;\n\n if(max == min) {\n h = s = 0; // achromatic\n }\n else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n\n h /= 6;\n }\n\n return { h: h, s: s, l: l };\n}\n\n// `hslToRgb`\n// Converts an HSL color value to RGB.\n// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]\n// *Returns:* { r, g, b } in the set [0, 255]\nfunction hslToRgb(h, s, l) {\n var r, g, b;\n\n h = bound01(h, 360);\n s = bound01(s, 100);\n l = bound01(l, 100);\n\n function hue2rgb(p, q, t) {\n if(t < 0) t += 1;\n if(t > 1) t -= 1;\n if(t < 1/6) return p + (q - p) * 6 * t;\n if(t < 1/2) return q;\n if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;\n return p;\n }\n\n if(s === 0) {\n r = g = b = l; // achromatic\n }\n else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1/3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1/3);\n }\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n}\n\n// `rgbToHsv`\n// Converts an RGB color value to HSV\n// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]\n// *Returns:* { h, s, v } in [0,1]\nfunction rgbToHsv(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, v = max;\n\n var d = max - min;\n s = max === 0 ? 0 : d / max;\n\n if(max == min) {\n h = 0; // achromatic\n }\n else {\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n h /= 6;\n }\n return { h: h, s: s, v: v };\n}\n\n// `hsvToRgb`\n// Converts an HSV color value to RGB.\n// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]\n// *Returns:* { r, g, b } in the set [0, 255]\n function hsvToRgb(h, s, v) {\n\n h = bound01(h, 360) * 6;\n s = bound01(s, 100);\n v = bound01(v, 100);\n\n var i = Math.floor(h),\n f = h - i,\n p = v * (1 - s),\n q = v * (1 - f * s),\n t = v * (1 - (1 - f) * s),\n mod = i % 6,\n r = [v, q, p, p, t, v][mod],\n g = [t, v, v, q, p, p][mod],\n b = [p, p, t, v, v, q][mod];\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n}\n\n// `rgbToHex`\n// Converts an RGB color to hex\n// Assumes r, g, and b are contained in the set [0, 255]\n// Returns a 3 or 6 character hex\nfunction rgbToHex(r, g, b, allow3Char) {\n\n var hex = [\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16))\n ];\n\n // Return a 3 character hex if possible\n if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);\n }\n\n return hex.join(\"\");\n}\n\n// `rgbaToHex`\n// Converts an RGBA color plus alpha transparency to hex\n// Assumes r, g, b are contained in the set [0, 255] and\n// a in [0, 1]. Returns a 4 or 8 character rgba hex\nfunction rgbaToHex(r, g, b, a, allow4Char) {\n\n var hex = [\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16)),\n pad2(convertDecimalToHex(a))\n ];\n\n // Return a 4 character hex if possible\n if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);\n }\n\n return hex.join(\"\");\n}\n\n// `rgbaToArgbHex`\n// Converts an RGBA color to an ARGB Hex8 string\n// Rarely used, but required for \"toFilter()\"\nfunction rgbaToArgbHex(r, g, b, a) {\n\n var hex = [\n pad2(convertDecimalToHex(a)),\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16))\n ];\n\n return hex.join(\"\");\n}\n\n// `equals`\n// Can be called with any tinycolor input\ntinycolor.equals = function (color1, color2) {\n if (!color1 || !color2) { return false; }\n return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();\n};\n\ntinycolor.random = function() {\n return tinycolor.fromRatio({\n r: mathRandom(),\n g: mathRandom(),\n b: mathRandom()\n });\n};\n\n\n// Modification Functions\n// ----------------------\n// Thanks to less.js for some of the basics here\n// \n\nfunction desaturate(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s -= amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n}\n\nfunction saturate(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s += amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n}\n\nfunction greyscale(color) {\n return tinycolor(color).desaturate(100);\n}\n\nfunction lighten (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l += amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n}\n\nfunction brighten(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var rgb = tinycolor(color).toRgb();\n rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));\n rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));\n rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));\n return tinycolor(rgb);\n}\n\nfunction darken (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l -= amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n}\n\n// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.\n// Values outside of this range will be wrapped into this range.\nfunction spin(color, amount) {\n var hsl = tinycolor(color).toHsl();\n var hue = (hsl.h + amount) % 360;\n hsl.h = hue < 0 ? 360 + hue : hue;\n return tinycolor(hsl);\n}\n\n// Combination Functions\n// ---------------------\n// Thanks to jQuery xColor for some of the ideas behind these\n// \n\nfunction complement(color) {\n var hsl = tinycolor(color).toHsl();\n hsl.h = (hsl.h + 180) % 360;\n return tinycolor(hsl);\n}\n\nfunction triad(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })\n ];\n}\n\nfunction tetrad(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })\n ];\n}\n\nfunction splitcomplement(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),\n tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})\n ];\n}\n\nfunction analogous(color, results, slices) {\n results = results || 6;\n slices = slices || 30;\n\n var hsl = tinycolor(color).toHsl();\n var part = 360 / slices;\n var ret = [tinycolor(color)];\n\n for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {\n hsl.h = (hsl.h + part) % 360;\n ret.push(tinycolor(hsl));\n }\n return ret;\n}\n\nfunction monochromatic(color, results) {\n results = results || 6;\n var hsv = tinycolor(color).toHsv();\n var h = hsv.h, s = hsv.s, v = hsv.v;\n var ret = [];\n var modification = 1 / results;\n\n while (results--) {\n ret.push(tinycolor({ h: h, s: s, v: v}));\n v = (v + modification) % 1;\n }\n\n return ret;\n}\n\n// Utility Functions\n// ---------------------\n\ntinycolor.mix = function(color1, color2, amount) {\n amount = (amount === 0) ? 0 : (amount || 50);\n\n var rgb1 = tinycolor(color1).toRgb();\n var rgb2 = tinycolor(color2).toRgb();\n\n var p = amount / 100;\n\n var rgba = {\n r: ((rgb2.r - rgb1.r) * p) + rgb1.r,\n g: ((rgb2.g - rgb1.g) * p) + rgb1.g,\n b: ((rgb2.b - rgb1.b) * p) + rgb1.b,\n a: ((rgb2.a - rgb1.a) * p) + rgb1.a\n };\n\n return tinycolor(rgba);\n};\n\n\n// Readability Functions\n// ---------------------\n// false\n// tinycolor.isReadable(\"#000\", \"#111\",{level:\"AA\",size:\"large\"}) => false\ntinycolor.isReadable = function(color1, color2, wcag2) {\n var readability = tinycolor.readability(color1, color2);\n var wcag2Parms, out;\n\n out = false;\n\n wcag2Parms = validateWCAG2Parms(wcag2);\n switch (wcag2Parms.level + wcag2Parms.size) {\n case \"AAsmall\":\n case \"AAAlarge\":\n out = readability >= 4.5;\n break;\n case \"AAlarge\":\n out = readability >= 3;\n break;\n case \"AAAsmall\":\n out = readability >= 7;\n break;\n }\n return out;\n\n};\n\n// `mostReadable`\n// Given a base color and a list of possible foreground or background\n// colors for that base, returns the most readable color.\n// Optionally returns Black or White if the most readable color is unreadable.\n// *Example*\n// tinycolor.mostReadable(tinycolor.mostReadable(\"#123\", [\"#124\", \"#125\"],{includeFallbackColors:false}).toHexString(); // \"#112255\"\n// tinycolor.mostReadable(tinycolor.mostReadable(\"#123\", [\"#124\", \"#125\"],{includeFallbackColors:true}).toHexString(); // \"#ffffff\"\n// tinycolor.mostReadable(\"#a8015a\", [\"#faf3f3\"],{includeFallbackColors:true,level:\"AAA\",size:\"large\"}).toHexString(); // \"#faf3f3\"\n// tinycolor.mostReadable(\"#a8015a\", [\"#faf3f3\"],{includeFallbackColors:true,level:\"AAA\",size:\"small\"}).toHexString(); // \"#ffffff\"\ntinycolor.mostReadable = function(baseColor, colorList, args) {\n var bestColor = null;\n var bestScore = 0;\n var readability;\n var includeFallbackColors, level, size ;\n args = args || {};\n includeFallbackColors = args.includeFallbackColors ;\n level = args.level;\n size = args.size;\n\n for (var i= 0; i < colorList.length ; i++) {\n readability = tinycolor.readability(baseColor, colorList[i]);\n if (readability > bestScore) {\n bestScore = readability;\n bestColor = tinycolor(colorList[i]);\n }\n }\n\n if (tinycolor.isReadable(baseColor, bestColor, {\"level\":level,\"size\":size}) || !includeFallbackColors) {\n return bestColor;\n }\n else {\n args.includeFallbackColors=false;\n return tinycolor.mostReadable(baseColor,[\"#fff\", \"#000\"],args);\n }\n};\n\n\n// Big List of Colors\n// ------------------\n// \nvar names = tinycolor.names = {\n aliceblue: \"f0f8ff\",\n antiquewhite: \"faebd7\",\n aqua: \"0ff\",\n aquamarine: \"7fffd4\",\n azure: \"f0ffff\",\n beige: \"f5f5dc\",\n bisque: \"ffe4c4\",\n black: \"000\",\n blanchedalmond: \"ffebcd\",\n blue: \"00f\",\n blueviolet: \"8a2be2\",\n brown: \"a52a2a\",\n burlywood: \"deb887\",\n burntsienna: \"ea7e5d\",\n cadetblue: \"5f9ea0\",\n chartreuse: \"7fff00\",\n chocolate: \"d2691e\",\n coral: \"ff7f50\",\n cornflowerblue: \"6495ed\",\n cornsilk: \"fff8dc\",\n crimson: \"dc143c\",\n cyan: \"0ff\",\n darkblue: \"00008b\",\n darkcyan: \"008b8b\",\n darkgoldenrod: \"b8860b\",\n darkgray: \"a9a9a9\",\n darkgreen: \"006400\",\n darkgrey: \"a9a9a9\",\n darkkhaki: \"bdb76b\",\n darkmagenta: \"8b008b\",\n darkolivegreen: \"556b2f\",\n darkorange: \"ff8c00\",\n darkorchid: \"9932cc\",\n darkred: \"8b0000\",\n darksalmon: \"e9967a\",\n darkseagreen: \"8fbc8f\",\n darkslateblue: \"483d8b\",\n darkslategray: \"2f4f4f\",\n darkslategrey: \"2f4f4f\",\n darkturquoise: \"00ced1\",\n darkviolet: \"9400d3\",\n deeppink: \"ff1493\",\n deepskyblue: \"00bfff\",\n dimgray: \"696969\",\n dimgrey: \"696969\",\n dodgerblue: \"1e90ff\",\n firebrick: \"b22222\",\n floralwhite: \"fffaf0\",\n forestgreen: \"228b22\",\n fuchsia: \"f0f\",\n gainsboro: \"dcdcdc\",\n ghostwhite: \"f8f8ff\",\n gold: \"ffd700\",\n goldenrod: \"daa520\",\n gray: \"808080\",\n green: \"008000\",\n greenyellow: \"adff2f\",\n grey: \"808080\",\n honeydew: \"f0fff0\",\n hotpink: \"ff69b4\",\n indianred: \"cd5c5c\",\n indigo: \"4b0082\",\n ivory: \"fffff0\",\n khaki: \"f0e68c\",\n lavender: \"e6e6fa\",\n lavenderblush: \"fff0f5\",\n lawngreen: \"7cfc00\",\n lemonchiffon: \"fffacd\",\n lightblue: \"add8e6\",\n lightcoral: \"f08080\",\n lightcyan: \"e0ffff\",\n lightgoldenrodyellow: \"fafad2\",\n lightgray: \"d3d3d3\",\n lightgreen: \"90ee90\",\n lightgrey: \"d3d3d3\",\n lightpink: \"ffb6c1\",\n lightsalmon: \"ffa07a\",\n lightseagreen: \"20b2aa\",\n lightskyblue: \"87cefa\",\n lightslategray: \"789\",\n lightslategrey: \"789\",\n lightsteelblue: \"b0c4de\",\n lightyellow: \"ffffe0\",\n lime: \"0f0\",\n limegreen: \"32cd32\",\n linen: \"faf0e6\",\n magenta: \"f0f\",\n maroon: \"800000\",\n mediumaquamarine: \"66cdaa\",\n mediumblue: \"0000cd\",\n mediumorchid: \"ba55d3\",\n mediumpurple: \"9370db\",\n mediumseagreen: \"3cb371\",\n mediumslateblue: \"7b68ee\",\n mediumspringgreen: \"00fa9a\",\n mediumturquoise: \"48d1cc\",\n mediumvioletred: \"c71585\",\n midnightblue: \"191970\",\n mintcream: \"f5fffa\",\n mistyrose: \"ffe4e1\",\n moccasin: \"ffe4b5\",\n navajowhite: \"ffdead\",\n navy: \"000080\",\n oldlace: \"fdf5e6\",\n olive: \"808000\",\n olivedrab: \"6b8e23\",\n orange: \"ffa500\",\n orangered: \"ff4500\",\n orchid: \"da70d6\",\n palegoldenrod: \"eee8aa\",\n palegreen: \"98fb98\",\n paleturquoise: \"afeeee\",\n palevioletred: \"db7093\",\n papayawhip: \"ffefd5\",\n peachpuff: \"ffdab9\",\n peru: \"cd853f\",\n pink: \"ffc0cb\",\n plum: \"dda0dd\",\n powderblue: \"b0e0e6\",\n purple: \"800080\",\n rebeccapurple: \"663399\",\n red: \"f00\",\n rosybrown: \"bc8f8f\",\n royalblue: \"4169e1\",\n saddlebrown: \"8b4513\",\n salmon: \"fa8072\",\n sandybrown: \"f4a460\",\n seagreen: \"2e8b57\",\n seashell: \"fff5ee\",\n sienna: \"a0522d\",\n silver: \"c0c0c0\",\n skyblue: \"87ceeb\",\n slateblue: \"6a5acd\",\n slategray: \"708090\",\n slategrey: \"708090\",\n snow: \"fffafa\",\n springgreen: \"00ff7f\",\n steelblue: \"4682b4\",\n tan: \"d2b48c\",\n teal: \"008080\",\n thistle: \"d8bfd8\",\n tomato: \"ff6347\",\n turquoise: \"40e0d0\",\n violet: \"ee82ee\",\n wheat: \"f5deb3\",\n white: \"fff\",\n whitesmoke: \"f5f5f5\",\n yellow: \"ff0\",\n yellowgreen: \"9acd32\"\n};\n\n// Make it easy to access colors via `hexNames[hex]`\nvar hexNames = tinycolor.hexNames = flip(names);\n\n\n// Utilities\n// ---------\n\n// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`\nfunction flip(o) {\n var flipped = { };\n for (var i in o) {\n if (o.hasOwnProperty(i)) {\n flipped[o[i]] = i;\n }\n }\n return flipped;\n}\n\n// Return a valid alpha value [0,1] with all invalid values being set to 1\nfunction boundAlpha(a) {\n a = parseFloat(a);\n\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n\n return a;\n}\n\n// Take input from [0, n] and return it as [0, 1]\nfunction bound01(n, max) {\n if (isOnePointZero(n)) { n = \"100%\"; }\n\n var processPercent = isPercentage(n);\n n = mathMin(max, mathMax(0, parseFloat(n)));\n\n // Automatically convert percentage into number\n if (processPercent) {\n n = parseInt(n * max, 10) / 100;\n }\n\n // Handle floating point rounding errors\n if ((Math.abs(n - max) < 0.000001)) {\n return 1;\n }\n\n // Convert into [0, 1] range if it isn't already\n return (n % max) / parseFloat(max);\n}\n\n// Force a number between 0 and 1\nfunction clamp01(val) {\n return mathMin(1, mathMax(0, val));\n}\n\n// Parse a base-16 hex value into a base-10 integer\nfunction parseIntFromHex(val) {\n return parseInt(val, 16);\n}\n\n// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1\n// \nfunction isOnePointZero(n) {\n return typeof n == \"string\" && n.indexOf('.') != -1 && parseFloat(n) === 1;\n}\n\n// Check to see if string passed in is a percentage\nfunction isPercentage(n) {\n return typeof n === \"string\" && n.indexOf('%') != -1;\n}\n\n// Force a hex value to have 2 characters\nfunction pad2(c) {\n return c.length == 1 ? '0' + c : '' + c;\n}\n\n// Replace a decimal with it's percentage value\nfunction convertToPercentage(n) {\n if (n <= 1) {\n n = (n * 100) + \"%\";\n }\n\n return n;\n}\n\n// Converts a decimal to a hex value\nfunction convertDecimalToHex(d) {\n return Math.round(parseFloat(d) * 255).toString(16);\n}\n// Converts a hex value to a decimal\nfunction convertHexToDecimal(h) {\n return (parseIntFromHex(h) / 255);\n}\n\nvar matchers = (function() {\n\n // \n var CSS_INTEGER = \"[-\\\\+]?\\\\d+%?\";\n\n // \n var CSS_NUMBER = \"[-\\\\+]?\\\\d*\\\\.\\\\d+%?\";\n\n // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.\n var CSS_UNIT = \"(?:\" + CSS_NUMBER + \")|(?:\" + CSS_INTEGER + \")\";\n\n // Actual matching.\n // Parentheses and commas are optional, but not required.\n // Whitespace can take the place of commas or opening paren\n var PERMISSIVE_MATCH3 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n var PERMISSIVE_MATCH4 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n\n return {\n CSS_UNIT: new RegExp(CSS_UNIT),\n rgb: new RegExp(\"rgb\" + PERMISSIVE_MATCH3),\n rgba: new RegExp(\"rgba\" + PERMISSIVE_MATCH4),\n hsl: new RegExp(\"hsl\" + PERMISSIVE_MATCH3),\n hsla: new RegExp(\"hsla\" + PERMISSIVE_MATCH4),\n hsv: new RegExp(\"hsv\" + PERMISSIVE_MATCH3),\n hsva: new RegExp(\"hsva\" + PERMISSIVE_MATCH4),\n hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,\n hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/\n };\n})();\n\n// `isValidCSSUnit`\n// Take in a single string / number and check to see if it looks like a CSS unit\n// (see `matchers` above for definition).\nfunction isValidCSSUnit(color) {\n return !!matchers.CSS_UNIT.exec(color);\n}\n\n// `stringInputToObject`\n// Permissive string parsing. Take in a number of formats, and output an object\n// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`\nfunction stringInputToObject(color) {\n\n color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();\n var named = false;\n if (names[color]) {\n color = names[color];\n named = true;\n }\n else if (color == 'transparent') {\n return { r: 0, g: 0, b: 0, a: 0, format: \"name\" };\n }\n\n // Try to match string input using regular expressions.\n // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]\n // Just return an object and let the conversion functions handle that.\n // This way the result will be the same whether the tinycolor is initialized with string or object.\n var match;\n if ((match = matchers.rgb.exec(color))) {\n return { r: match[1], g: match[2], b: match[3] };\n }\n if ((match = matchers.rgba.exec(color))) {\n return { r: match[1], g: match[2], b: match[3], a: match[4] };\n }\n if ((match = matchers.hsl.exec(color))) {\n return { h: match[1], s: match[2], l: match[3] };\n }\n if ((match = matchers.hsla.exec(color))) {\n return { h: match[1], s: match[2], l: match[3], a: match[4] };\n }\n if ((match = matchers.hsv.exec(color))) {\n return { h: match[1], s: match[2], v: match[3] };\n }\n if ((match = matchers.hsva.exec(color))) {\n return { h: match[1], s: match[2], v: match[3], a: match[4] };\n }\n if ((match = matchers.hex8.exec(color))) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n a: convertHexToDecimal(match[4]),\n format: named ? \"name\" : \"hex8\"\n };\n }\n if ((match = matchers.hex6.exec(color))) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n if ((match = matchers.hex4.exec(color))) {\n return {\n r: parseIntFromHex(match[1] + '' + match[1]),\n g: parseIntFromHex(match[2] + '' + match[2]),\n b: parseIntFromHex(match[3] + '' + match[3]),\n a: convertHexToDecimal(match[4] + '' + match[4]),\n format: named ? \"name\" : \"hex8\"\n };\n }\n if ((match = matchers.hex3.exec(color))) {\n return {\n r: parseIntFromHex(match[1] + '' + match[1]),\n g: parseIntFromHex(match[2] + '' + match[2]),\n b: parseIntFromHex(match[3] + '' + match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n\n return false;\n}\n\nfunction validateWCAG2Parms(parms) {\n // return valid WCAG2 parms for isReadable.\n // If input parms are invalid, return {\"level\":\"AA\", \"size\":\"small\"}\n var level, size;\n parms = parms || {\"level\":\"AA\", \"size\":\"small\"};\n level = (parms.level || \"AA\").toUpperCase();\n size = (parms.size || \"small\").toLowerCase();\n if (level !== \"AA\" && level !== \"AAA\") {\n level = \"AA\";\n }\n if (size !== \"small\" && size !== \"large\") {\n size = \"small\";\n }\n return {\"level\":level, \"size\":size};\n}\n\n// Node: Export function\nif (typeof module !== \"undefined\" && module.exports) {\n module.exports = tinycolor;\n}\n// AMD/requirejs: Define the module\nelse if (typeof define === 'function' && define.amd) {\n define(function () {return tinycolor;});\n}\n// Browser: Expose to window\nelse {\n window.tinycolor = tinycolor;\n}\n\n})(Math);\n","import tinycolor from 'tinycolor2';\n\nimport {\n BRIGHT_COLORS,\n CHART_COLORS,\n INACTIVE_CHART_COLOR,\n} from '../constants/colors';\nimport { NONE, UNKNOWN_CROP_NAME } from '../constants/fields';\nimport { getCustomLayerColor, layerIsCustom } from './layers';\n\nexport const cropThemes = {\n DARK: 'dark',\n LIGHT: 'light',\n};\n\nexport const defaultCropColorForTheme = (theme) =>\n theme === cropThemes.DARK ? '#9B9A97' : '#9C9FA0'; // dark/light grey\n\nconst noCropColor = 'rgba(0,0,0,0.2)'; // Transparent black\n\n// if crop.color doesn't exist, return undefined\n// else, return its hex code\nconst cropColorForTheme = (crop, theme) =>\n crop?.color &&\n (theme === cropThemes.DARK\n ? `#${crop?.color?.hexDark}`\n : `#${crop?.color?.hexLight}`);\n\nexport const colorForCrop = (crop, theme = cropThemes.DARK) =>\n cropColorForTheme(crop, theme) || defaultCropColorForTheme(theme);\n\nexport const cropColorsMap = (crops, theme) => {\n const colorMap = {};\n crops.forEach((crop) => {\n colorMap[crop.name] = colorForCrop(crop, theme);\n });\n colorMap[NONE] = noCropColor;\n colorMap[UNKNOWN_CROP_NAME] = defaultCropColorForTheme(theme);\n return colorMap;\n};\n\n// if item is a crop, use its color\n// otherwise, pick from CHART_COLORS based on index\nexport const getItemColor = (item, index, theme = cropThemes.DARK) =>\n ((c) =>\n c === defaultCropColorForTheme(theme)\n ? CHART_COLORS[index % CHART_COLORS.length]\n : c)(colorForCrop(item, theme));\n\n// items could be crops\n// or any other type of object\nexport const addItemColors = (items) =>\n items.map((item, index) => ({\n ...item,\n color: getItemColor(item, index),\n }));\n\nexport const getUnusedBrightColor = (colors) =>\n colors.length >= BRIGHT_COLORS.length\n ? BRIGHT_COLORS[colors.length % BRIGHT_COLORS.length]\n : BRIGHT_COLORS.find((c) => !colors.includes(c));\n\nexport const getPaintColor = (layer) => {\n if (layerIsCustom(layer)) return getCustomLayerColor(layer);\n\n const { paintProperties } = layer;\n const color =\n paintProperties.paint['line-color'] || paintProperties.paint['fill-color'];\n if (Array.isArray(color)) {\n // Handle basic match/case expressions by returning the default color\n const defaultMatchColor = color[color.length - 1];\n return typeof defaultMatchColor === 'string' &&\n ['match', 'case'].includes(color[0])\n ? defaultMatchColor\n : // Return black by default for unhandled cases\n '#000000';\n }\n return color;\n};\n\n// When there is an active item, show the INACTIVE_CHART_COLOR\n// for inactive items\nexport const getChartItemColor = (id, activeKey, color) => {\n const isActive = activeKey === id;\n const showColor = isActive || activeKey === '';\n return showColor ? color : INACTIVE_CHART_COLOR;\n};\n\nexport const MAP_ACTIVE_COLOR = '#03ecfc';\n\nexport const darkenColor = (color) => tinycolor(color).darken(25).toString();\n\nexport const getLightness = (color) => tinycolor(color).toHsl().l;\n\n/**\n * Given a color and a hue gradient, returns the position (0 to 1) of the color in\n * the gradient, or null if the color is not in the gradient.\n */\nexport const getColorPositionInGradient = (colorString, gradientStrings) => {\n const color = tinycolor(colorString).toHsl();\n const gradient = gradientStrings.map((s) => tinycolor(s).toHsl());\n\n // We need to least 2 colors to make a gradient:\n if (gradient.length < 2) return null;\n\n // We need a defined color:\n if (!colorString || colorString.length === 0) return null;\n\n // see if any colors are a direct match\n const matchIndex = gradient.findIndex(\n (gradientColor) => gradientColor.h === color.h,\n );\n if (matchIndex !== -1) return matchIndex / (gradient.length - 1);\n\n // get the index of the left element of the pair that the color is between\n const leftIndex = gradient.slice(0, -1).findIndex((left, i) => {\n const right = gradient[i + 1];\n return left.h < color.h && color.h < right.h;\n });\n\n if (leftIndex === -1) return null; // no match\n\n const left = gradient[leftIndex];\n const right = gradient[leftIndex + 1];\n\n // Calculate the position of the color between the left and right colors\n const position = (color.h - left.h) / (right.h - left.h);\n\n // Return the position within the whole gradient, as a value between 0 and 1\n return (leftIndex + position) / (gradient.length - 1);\n};\n\n/**\n * This fn is the opposite of getColorPositionInGradient. Returns hue of the\n * gradient at a given position, on a 0-1 scale.\n */\nexport const getGradientHueAtPosition = (position, gradientStrings) => {\n const gradient = gradientStrings.map((s) => tinycolor(s).toHsl());\n\n // We need to least 2 colors to make a gradient:\n if (gradient.length < 2) return null;\n\n // We need a defined position:\n if (position === null || position < 0 || position > 1) return null;\n\n // get the index of the left element of the pair that the color is between\n const positionIndex = position * (gradient.length - 1);\n const leftIndex = Math.floor(positionIndex);\n\n const left = gradient[leftIndex];\n const right = gradient[leftIndex + 1];\n\n return (left.h + (right.h - left.h) * (positionIndex - leftIndex)) / 360;\n};\n\nexport const isGrayscale = (colorString) =>\n tinycolor(colorString).toHsl().s === 0;\n\n/**\n * Compute the perceptual difference between two colors using the Delta-E\n * approach. Returns a number between 0 and 100, where 0 means the colors are\n * identical.\n *\n * See:\n * - https://zschuessler.github.io/DeltaE/learn/\n * - https://github.com/antimatter15/rgb-lab\n */\nexport const getColorDifference = (colorA, colorB) => {\n const getRgb = (colorString) => {\n const { r, g, b } = tinycolor(colorString).toRgb();\n return [r, g, b];\n };\n\n const rgbA = getRgb(colorA);\n const rgbB = getRgb(colorB);\n\n const rgb2lab = (rgb) => {\n let r = rgb[0] / 255;\n let g = rgb[1] / 255;\n let b = rgb[2] / 255;\n\n let x;\n let y;\n let z;\n\n r = r > 0.04045 ? (r + 0.055) / 1.055 ** 2.4 : r / 12.92;\n g = g > 0.04045 ? (g + 0.055) / 1.055 ** 2.4 : g / 12.92;\n b = b > 0.04045 ? (b + 0.055) / 1.055 ** 2.4 : b / 12.92;\n\n x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047;\n y = (r * 0.2126 + g * 0.7152 + b * 0.0722) / 1.0;\n z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883;\n\n x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;\n y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;\n z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;\n\n return [116 * y - 16, 500 * (x - y), 200 * (y - z)];\n };\n\n const labA = rgb2lab(rgbA);\n const labB = rgb2lab(rgbB);\n\n const deltaL = labA[0] - labB[0];\n const deltaA = labA[1] - labB[1];\n const deltaB = labA[2] - labB[2];\n\n const c1 = Math.sqrt(labA[1] * labA[1] + labA[2] * labA[2]);\n const c2 = Math.sqrt(labB[1] * labB[1] + labB[2] * labB[2]);\n const deltaC = c1 - c2;\n\n let deltaH = deltaA * deltaA + deltaB * deltaB - deltaC * deltaC;\n deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH);\n\n const sc = 1.0 + 0.045 * c1;\n const sh = 1.0 + 0.015 * c1;\n\n const deltaLKlsl = deltaL / 1.0;\n const deltaCkcsc = deltaC / sc;\n const deltaHkhsh = deltaH / sh;\n\n const i =\n deltaLKlsl * deltaLKlsl + deltaCkcsc * deltaCkcsc + deltaHkhsh * deltaHkhsh;\n\n return i < 0 ? 0 : Math.sqrt(i);\n};\n","/* Mapbox GL JS is Copyright © 2020 Mapbox and subject to the Mapbox Terms of Service ((https://www.mapbox.com/legal/tos/). */\n(function (global, factory) {\ntypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\ntypeof define === 'function' && define.amd ? define(factory) :\n(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mapboxgl = factory());\n})(this, (function () { 'use strict';\n\n/* eslint-disable */\n\nvar shared, worker, mapboxgl;\n// define gets called three times: one for each chunk. we rely on the order\n// they're imported to know which is which\nfunction define(_, chunk) {\nif (!shared) {\n shared = chunk;\n} else if (!worker) {\n worker = chunk;\n} else {\n var workerBundleString = \"self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; (\" + shared + \")(sharedChunk); (\" + worker + \")(sharedChunk); self.onerror = null;\"\n\n var sharedChunk = {};\n shared(sharedChunk);\n mapboxgl = chunk(sharedChunk);\n if (typeof window !== 'undefined' && window && window.URL && window.URL.createObjectURL) {\n mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));\n }\n}\n}\n\n\ndefine([\"exports\"],(function(t){\"use strict\";var e=\"3.2.0\";let r;const n={API_URL:\"https://api.mapbox.com\",get API_URL_REGEX(){if(null==r){const t=/^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/|\\?|$)/i;try{r=null!=process.env.API_URL_REGEX?new RegExp(process.env.API_URL_REGEX):t;}catch(e){r=t;}}return r},get API_TILEJSON_REGEX(){return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/v[0-9]*\\/.*\\.json.*$)/i},get API_SPRITE_REGEX(){return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/styles\\/v[0-9]*\\/)(.*\\/sprite.*\\..*$)/i},get API_FONTS_REGEX(){return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/fonts\\/v[0-9]*\\/)(.*\\.pbf.*$)/i},get API_STYLE_REGEX(){return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/styles\\/v[0-9]*\\/)(.*$)/i},get API_CDN_URL_REGEX(){return /^((https?:)?\\/\\/)?api\\.mapbox\\.c(n|om)(\\/mapbox-gl-js\\/)(.*$)/i},get EVENTS_URL(){if(!n.API_URL)return null;try{const t=new URL(n.API_URL);return \"api.mapbox.cn\"===t.hostname?\"https://events.mapbox.cn/events/v2\":\"api.mapbox.com\"===t.hostname?\"https://events.mapbox.com/events/v2\":null}catch(t){return null}},SESSION_PATH:\"/map-sessions/v1\",FEEDBACK_URL:\"https://apps.mapbox.com/feedback\",TILE_URL_VERSION:\"v4\",RASTER_URL_PREFIX:\"raster/v1\",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:\"mapbox://styles/mapbox/standard\",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:\"https://api.mapbox.com/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm\",GLYPHS_URL:\"mapbox://fonts/mapbox/{fontstack}/{range}.pbf\"},i={supported:!1,testSupport:function(t){!o&&a&&(l?c(t):s=t);}};let s,a,o=!1,l=!1;const u=\"undefined\"!=typeof self?self:{};function c(t){const e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,a),t.isContextLost())return;i.supported=!0;}catch(t){}t.deleteTexture(e),o=!0;}u.document&&(a=u.document.createElement(\"img\"),a.onload=function(){s&&c(s),s=null,l=!0;},a.onerror=function(){o=!0,s=null;},a.src=\"data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=\");const h=\"01\";function p(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,\"default\")?t.default:t}var f=d;function d(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}d.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var m=p(f),y=g;function g(t,e){this.x=t,this.y=e;}g.prototype={clone:function(){return new g(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},g.convert=function(t){return t instanceof g?t:Array.isArray(t)?new g(t[0],t[1]):t};var x=p(y);const v=Math.PI/180,b=180/Math.PI;function _(t){return t*v}function w(t){return t*b}const M=[[0,0],[1,0],[1,1],[0,1]];function A(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function S(t,e,r,n){const i=new m(t,e,r,n);return function(t){return i.solve(t)}}const I=S(.25,.1,.25,1);function k(t,e,r){return Math.min(r,Math.max(e,t))}function T(t,e,r){return (r=k((r-t)/(e-t),0,1))*r*(3-2*r)}function P(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function z(t,e,r){if(!t.length)return r(null,[]);let n=t.length;const i=new Array(t.length);let s=null;t.forEach(((t,a)=>{e(t,((t,e)=>{t&&(s=t),i[a]=e,0==--n&&r(s,i);}));}));}function E(t){const e=[];for(const r in t)e.push(t[r]);return e}function B(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let D=1;function C(){return D++}function R(){return function t(e){return e?(e^Math.random()*(16>>e/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,t)}()}function L(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function V(t){return !!t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)}function O(t,e){t.forEach((t=>{e[t]&&(e[t]=e[t].bind(e));}));}function F(t,e){return -1!==t.indexOf(e,t.length-e.length)}function j(t,e,r){const n={};for(const i in t)n[i]=e.call(r||this,t[i],i,t);return n}function U(t,e,r){const n={};for(const i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function N(t){return Array.isArray(t)?t.map(N):\"object\"==typeof t&&t?j(t,N):t}const $={};function q(t){$[t]||(\"undefined\"!=typeof console&&console.warn(t),$[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function Y(t){let e=0;for(let r,n,i=0,s=t.length,a=s-1;i@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)(?:\\=(?:([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)|(?:\\\"((?:[^\"\\\\]|\\\\.)*)\\\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),\"\"})),e[\"max-age\"]){const t=parseInt(e[\"max-age\"],10);isNaN(t)?delete e[\"max-age\"]:e[\"max-age\"]=t;}return e}let W=null;function H(t){try{const e=self[t];return e.setItem(\"_mapbox_test_\",1),e.removeItem(\"_mapbox_test_\"),!0}catch(t){return !1}}function J(t,e){return [t[4*e],t[4*e+1],t[4*e+2],t[4*e+3]]}function Q(t,e,r,n){for(;e>1;t[i]>1;t[i]<=n?e=i+1:r=i;}return e}const et=\"mapbox-tiles\";let rt=500,nt=50;let it,st;function at(){try{return caches}catch(t){}}function ot(){const t=at();t&&!it&&(it=t.open(et));}function lt(t){const e=t.indexOf(\"?\");if(e<0)return t;const r=function(t){const e=t.indexOf(\"?\");return e>0?t.slice(e+1).split(\"&\"):[]}(t),n=r.filter((t=>{const e=t.split(\"=\");return \"language\"===e[0]||\"worldview\"===e[0]}));return n.length?`${t.slice(0,e)}?${n.join(\"&\")}`:t.slice(0,e)}let ut=1/0;const ct={Unknown:\"Unknown\",Style:\"Style\",Source:\"Source\",Tile:\"Tile\",Glyphs:\"Glyphs\",SpriteImage:\"SpriteImage\",SpriteJSON:\"SpriteJSON\",Image:\"Image\",Model:\"Model\"};\"function\"==typeof Object.freeze&&Object.freeze(ct);class ht extends Error{constructor(t,e,r){401===e&&wt(r)&&(t+=\": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes\"),super(t),this.status=e,this.url=r;}toString(){return `${this.name}: ${this.message} (${this.status}): ${this.url}`}}const pt=X()?()=>self.worker&&self.worker.referrer:()=>(\"blob:\"===location.protocol?parent:self).location.href;const ft=function(t,e){if(!(/^file:/.test(r=t.url)||/^file:/.test(pt())&&!/^\\w+:/.test(r))){if(self.fetch&&self.Request&&self.AbortController&&Request.prototype.hasOwnProperty(\"signal\"))return function(t,e){const r=new AbortController,n=new Request(t.url,{method:t.method||\"GET\",body:t.body,credentials:t.credentials,headers:t.headers,referrer:pt(),referrerPolicy:t.referrerPolicy,signal:r.signal});let i=!1,s=!1;const a=(o=n.url).indexOf(\"sku=\")>0&&wt(o);var o;\"json\"===t.type&&n.headers.set(\"Accept\",\"application/json\");const l=(r,i,o)=>{if(s)return;if(r&&\"SecurityError\"!==r.message&&q(r.toString()),i&&o)return u(i);const l=Date.now();fetch(n).then((r=>{if(r.ok){const t=a?r.clone():null;return u(r,t,l)}return e(new ht(r.statusText,r.status,t.url))})).catch((r=>{\"AbortError\"!==r.name&&e(new Error(`${r.message} ${t.url}`));}));},u=(r,a,o)=>{(\"arrayBuffer\"===t.type?r.arrayBuffer():\"json\"===t.type?r.json():r.text()).then((t=>{s||(a&&o&&function(t,e,r){if(ot(),!it)return;const n={status:e.status,statusText:e.statusText,headers:new Headers};e.headers.forEach(((t,e)=>n.headers.set(e,t)));const i=K(e.headers.get(\"Cache-Control\")||\"\");if(i[\"no-store\"])return;i[\"max-age\"]&&n.headers.set(\"Expires\",new Date(r+1e3*i[\"max-age\"]).toUTCString());const s=n.headers.get(\"Expires\");s&&(new Date(s).getTime()-r<42e4||function(t,e){if(void 0===st)try{new Response(new ReadableStream),st=!0;}catch(t){st=!1;}st?e(t.body):t.blob().then(e);}(e,(e=>{const r=new Response(e,n);ot(),it&&it.then((e=>e.put(lt(t.url),r))).catch((t=>q(t.message)));})));}(n,a,o),i=!0,e(null,t,r.headers.get(\"Cache-Control\"),r.headers.get(\"Expires\")));})).catch((t=>{s||e(new Error(t.message));}));};return a?function(t,e){if(ot(),!it)return e(null);const r=lt(t.url);it.then((t=>{t.match(r).then((n=>{const i=function(t){if(!t)return !1;const e=new Date(t.headers.get(\"Expires\")||0),r=K(t.headers.get(\"Cache-Control\")||\"\");return e>Date.now()&&!r[\"no-cache\"]}(n);t.delete(r),i&&t.put(r,n.clone()),e(null,n,i);})).catch(e);})).catch(e);}(n,l):l(null,null),{cancel:()=>{s=!0,i||r.abort();}}}(t,e);if(X()&&self.worker&&self.worker.actor)return self.worker.actor.send(\"getResource\",t,e,void 0,!0)}var r;return function(t,e){const r=new XMLHttpRequest;r.open(t.method||\"GET\",t.url,!0),\"arrayBuffer\"===t.type&&(r.responseType=\"arraybuffer\");for(const e in t.headers)r.setRequestHeader(e,t.headers[e]);return \"json\"===t.type&&(r.responseType=\"text\",r.setRequestHeader(\"Accept\",\"application/json\")),r.withCredentials=\"include\"===t.credentials,r.onerror=()=>{e(new Error(r.statusText));},r.onload=()=>{if((r.status>=200&&r.status<300||0===r.status)&&null!==r.response){let n=r.response;if(\"json\"===t.type)try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n,r.getResponseHeader(\"Cache-Control\"),r.getResponseHeader(\"Expires\"));}else e(new ht(r.statusText,r.status,t.url));},r.send(t.body),{cancel:()=>r.abort()}}(t,e)},dt=function(t,e){return ft(B(t,{type:\"arrayBuffer\"}),e)};function mt(t){const e=document.createElement(\"a\");return e.href=t,e.protocol===location.protocol&&e.host===location.host}const yt=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=\";let gt,xt;gt=[],xt=0;const vt=function(t,e){if(i.supported&&(t.headers||(t.headers={}),t.headers.accept=\"image/webp,*/*\"),xt>=n.MAX_PARALLEL_IMAGE_REQUESTS){const r={requestParameters:t,callback:e,cancelled:!1,cancel(){this.cancelled=!0;}};return gt.push(r),r}xt++;let r=!1;const s=()=>{if(!r)for(r=!0,xt--;gt.length&&xt{s(),t?e(t):r&&(self.createImageBitmap?function(t,e){const r=new Blob([new Uint8Array(t)],{type:\"image/png\"});createImageBitmap(r).then((t=>{e(null,t);})).catch((t=>{e(new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`));}));}(r,((t,r)=>e(t,r,n,i))):function(t,e){const r=new Image;r.onload=()=>{e(null,r),URL.revokeObjectURL(r.src),r.onload=null,requestAnimationFrame((()=>{r.src=yt;}));},r.onerror=()=>e(new Error(\"Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.\"));const n=new Blob([new Uint8Array(t)],{type:\"image/png\"});r.src=t.byteLength?URL.createObjectURL(n):yt;}(r,((t,r)=>e(t,r,n,i))));}));return {cancel:()=>{a.cancel(),s();}}},bt=\"NO_ACCESS_TOKEN\";function _t(t){return 0===t.indexOf(\"mapbox:\")}function wt(t){return n.API_URL_REGEX.test(t)}function Mt(t){return n.API_CDN_URL_REGEX.test(t)}function At(t){return n.API_STYLE_REGEX.test(t)&&!St(t)}function St(t){return n.API_SPRITE_REGEX.test(t)}const It=/^(\\w+):\\/\\/([^/?]*)(\\/[^?]+)?\\??(.+)?/;function kt(t){const e=t.match(It);if(!e)throw new Error(\"Unable to parse URL object\");return {protocol:e[1],authority:e[2],path:e[3]||\"/\",params:e[4]?e[4].split(\"&\"):[]}}function Tt(t){const e=t.params.length?`?${t.params.join(\"&\")}`:\"\";return `${t.protocol}://${t.authority}${t.path}${e}`}const Pt=\"mapbox.eventData\";function zt(t){if(!t)return null;const e=t.split(\".\");if(!e||3!==e.length)return null;try{return JSON.parse(decodeURIComponent(atob(e[1]).split(\"\").map((t=>\"%\"+(\"00\"+t.charCodeAt(0).toString(16)).slice(-2))).join(\"\")))}catch(t){return null}}class Et{constructor(t){this.type=t,this.anonId=null,this.eventData={},this.queue=[],this.pendingRequest=null;}getStorageKey(t){const e=zt(n.ACCESS_TOKEN);let r=\"\";return r=e&&e.u?btoa(encodeURIComponent(e.u).replace(/%([0-9A-F]{2})/g,((t,e)=>String.fromCharCode(Number(\"0x\"+e))))):n.ACCESS_TOKEN||\"\",t?`${Pt}.${t}:${r}`:`${Pt}:${r}`}fetchEventData(){const t=H(\"localStorage\"),e=this.getStorageKey(),r=this.getStorageKey(\"uuid\");if(t)try{const t=localStorage.getItem(e);t&&(this.eventData=JSON.parse(t));const n=localStorage.getItem(r);n&&(this.anonId=n);}catch(t){q(\"Unable to read from LocalStorage\");}}saveEventData(){const t=H(\"localStorage\"),e=this.getStorageKey(),r=this.getStorageKey(\"uuid\"),n=this.anonId;if(t&&n)try{localStorage.setItem(r,n),Object.keys(this.eventData).length>=1&&localStorage.setItem(e,JSON.stringify(this.eventData));}catch(t){q(\"Unable to write to LocalStorage\");}}processRequests(t){}postEvent(t,e,r,i){if(!n.EVENTS_URL)return;const s=kt(n.EVENTS_URL);s.params.push(`access_token=${i||n.ACCESS_TOKEN||\"\"}`);const a={event:this.type,created:new Date(t).toISOString()},o=e?B(a,e):a,l={url:Tt(s),headers:{\"Content-Type\":\"text/plain\"},body:JSON.stringify([o])};this.pendingRequest=function(t,e){return ft(B(t,{method:\"POST\"}),e)}(l,(t=>{this.pendingRequest=null,r(t),this.saveEventData(),this.processRequests(i);}));}queueRequest(t,e){this.queue.push(t),this.processRequests(e);}}const Bt=new class extends Et{constructor(t){super(\"appUserTurnstile\"),this._customAccessToken=t;}postTurnstileEvent(t,e){n.EVENTS_URL&&n.ACCESS_TOKEN&&Array.isArray(t)&&t.some((t=>_t(t)||wt(t)))&&this.queueRequest(Date.now(),e);}processRequests(t){if(this.pendingRequest||0===this.queue.length)return;this.anonId&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const r=zt(n.ACCESS_TOKEN),i=r?r.u:n.ACCESS_TOKEN;let s=i!==this.eventData.tokenU;V(this.anonId)||(this.anonId=R(),s=!0);const a=this.queue.shift();if(this.eventData.lastSuccess){const t=new Date(this.eventData.lastSuccess),e=new Date(a),r=(a-this.eventData.lastSuccess)/864e5;s=s||r>=1||r<-1||t.getDate()!==e.getDate();}else s=!0;s?this.postEvent(a,{sdkIdentifier:\"mapbox-gl-js\",sdkVersion:e,skuId:h,\"enabled.telemetry\":!1,userId:this.anonId},(t=>{t||(this.eventData.lastSuccess=a,this.eventData.tokenU=i);}),t):this.processRequests();}},Dt=Bt.postTurnstileEvent.bind(Bt),Ct=new class extends Et{constructor(){super(\"map.load\"),this.success={},this.skuToken=\"\";}postMapLoadEvent(t,e,r,i){this.skuToken=e,this.errorCb=i,n.EVENTS_URL&&(r||n.ACCESS_TOKEN?this.queueRequest({id:t,timestamp:Date.now()},r):this.errorCb(new Error(bt)));}processRequests(t){if(this.pendingRequest||0===this.queue.length)return;const{id:r,timestamp:n}=this.queue.shift();r&&this.success[r]||(this.anonId||this.fetchEventData(),V(this.anonId)||(this.anonId=R()),this.postEvent(n,{sdkIdentifier:\"mapbox-gl-js\",sdkVersion:e,skuId:h,skuToken:this.skuToken,userId:this.anonId},(t=>{t?this.errorCb(t):r&&(this.success[r]=!0);}),t));}},Rt=Ct.postMapLoadEvent.bind(Ct),Lt=new class extends Et{constructor(){super(\"gljs.performance\");}postPerformanceEvent(t,e){n.EVENTS_URL&&(t||n.ACCESS_TOKEN)&&this.queueRequest({timestamp:Date.now(),performanceData:e},t);}processRequests(t){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:r,performanceData:n}=this.queue.shift(),i=function(t){const r=performance.getEntriesByType(\"resource\"),n=performance.getEntriesByType(\"mark\"),i=function(t){const e={};if(t)for(const r in t)if(\"other\"!==r)for(const n of t[r]){const t=`${r}ResolveRangeMin`,i=`${r}ResolveRangeMax`,s=`${r}RequestCount`,a=`${r}RequestCachedCount`;e[t]=Math.min(e[t]||1/0,n.startTime),e[i]=Math.max(e[i]||-1/0,n.responseEnd);const o=t=>{void 0===e[t]&&(e[t]=0),++e[t];};void 0!==n.transferSize&&0===n.transferSize&&o(a),o(s);}return e}(function(t,e){const r={};if(t)for(const n of t){const t=e(n);void 0===r[t]&&(r[t]=[]),r[t].push(n);}return r}(r,Nt)),s=window.devicePixelRatio,a=navigator.connection||navigator.mozConnection||navigator.webkitConnection,o=a?a.effectiveType:void 0,l={counters:[],metadata:[],attributes:[]},u=(t,e,r)=>{null!=r&&t.push({name:e,value:r.toString()});};for(const t in i)u(l.counters,t,i[t]);if(t.interactionRange[0]!==1/0&&t.interactionRange[1]!==-1/0&&(u(l.counters,\"interactionRangeMin\",t.interactionRange[0]),u(l.counters,\"interactionRangeMax\",t.interactionRange[1])),n)for(const t of Object.keys(Ut)){const e=Ut[t],r=n.find((t=>t.name===e));r&&u(l.counters,e,r.startTime);}return u(l.counters,\"visibilityHidden\",t.visibilityHidden),u(l.attributes,\"style\",function(t){if(t)for(const e of t){const t=e.name.split(\"?\")[0];if(At(t)){const e=t.split(\"/\").slice(-2);if(2===e.length)return `mapbox://styles/${e[0]}/${e[1]}`}}}(r)),u(l.attributes,\"terrainEnabled\",t.terrainEnabled?\"true\":\"false\"),u(l.attributes,\"fogEnabled\",t.fogEnabled?\"true\":\"false\"),u(l.attributes,\"projection\",t.projection),u(l.attributes,\"zoom\",t.zoom),u(l.metadata,\"devicePixelRatio\",s),u(l.metadata,\"connectionEffectiveType\",o),u(l.metadata,\"navigatorUserAgent\",navigator.userAgent),u(l.metadata,\"screenWidth\",window.screen.width),u(l.metadata,\"screenHeight\",window.screen.height),u(l.metadata,\"windowWidth\",window.innerWidth),u(l.metadata,\"windowHeight\",window.innerHeight),u(l.metadata,\"mapWidth\",t.width/s),u(l.metadata,\"mapHeight\",t.height/s),u(l.metadata,\"webglRenderer\",t.renderer),u(l.metadata,\"webglVendor\",t.vendor),u(l.metadata,\"sdkVersion\",e),u(l.metadata,\"sdkIdentifier\",\"mapbox-gl-js\"),l}(n);for(const t of i.metadata);for(const t of i.counters);for(const t of i.attributes);this.postEvent(r,i,(()=>{}),t);}},Vt=Lt.postPerformanceEvent.bind(Lt),Ot=new class extends Et{constructor(){super(\"map.auth\"),this.success={},this.skuToken=\"\";}getSession(t,e,r,i){if(!n.API_URL||!n.SESSION_PATH)return;const s=kt(n.API_URL+n.SESSION_PATH);s.params.push(`sku=${e||\"\"}`),s.params.push(`access_token=${i||n.ACCESS_TOKEN||\"\"}`);const a={url:Tt(s),headers:{\"Content-Type\":\"text/plain\"}};this.pendingRequest=function(t,e){return ft(B(t,{method:\"GET\"}),e)}(a,(t=>{this.pendingRequest=null,r(t),this.saveEventData(),this.processRequests(i);}));}getSessionAPI(t,e,r,i){this.skuToken=e,this.errorCb=i,n.SESSION_PATH&&n.API_URL&&(r||n.ACCESS_TOKEN?this.queueRequest({id:t,timestamp:Date.now()},r):this.errorCb(new Error(bt)));}processRequests(t){if(this.pendingRequest||0===this.queue.length)return;const{id:e,timestamp:r}=this.queue.shift();e&&this.success[e]||this.getSession(r,this.skuToken,(t=>{t?this.errorCb(t):e&&(this.success[e]=!0);}),t);}},Ft=Ot.getSessionAPI.bind(Ot),jt=new Set,Ut={create:\"create\",load:\"load\",fullLoad:\"fullLoad\"};function Nt(t){const e=t.name.split(\"?\")[0];return Mt(e)&&e.includes(\"mapbox-gl.js\")?\"javascript\":Mt(e)&&e.includes(\"mapbox-gl.css\")?\"css\":function(t){return n.API_FONTS_REGEX.test(t)}(e)?\"fontRange\":St(e)?\"sprite\":At(e)?\"style\":function(t){return n.API_TILEJSON_REGEX.test(t)}(e)?\"tilejson\":\"other\"}function $t(t){const e=t?t.url.toString():void 0;return e?performance.getEntriesByName(e):[]}let qt,Gt,Yt,Zt,Xt;function Kt(){return null==qt&&(qt=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext(\"2d\")&&\"function\"==typeof self.createImageBitmap),qt}const Wt={now:()=>void 0!==Zt?Zt:performance.now(),setNow(t){Zt=t;},restoreNow(){Zt=void 0;},frame(t){const e=requestAnimationFrame(t);return {cancel:()=>cancelAnimationFrame(e)}},getImageData(t,e=0){const{width:r,height:n}=t;Xt||(Xt=document.createElement(\"canvas\"));const i=Xt.getContext(\"2d\",{willReadFrequently:!0});if(!i)throw new Error(\"failed to create canvas 2d context\");return (r>Xt.width||n>Xt.height)&&(Xt.width=r,Xt.height=n),i.clearRect(-e,-e,r+2*e,n+2*e),i.drawImage(t,0,0,r,n),i.getImageData(-e,-e,r+2*e,n+2*e)},resolveURL:t=>(Gt||(Gt=document.createElement(\"a\")),Gt.href=t,Gt.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return !!window.matchMedia&&(null==Yt&&(Yt=window.matchMedia(\"(prefers-reduced-motion: reduce)\")),Yt.matches)},hasCanvasFingerprintNoise(){if(!Kt())return !1;const t=new OffscreenCanvas(85,1),e=t.getContext(\"2d\",{willReadFrequently:!0});let r=0;for(let n=0;nthis.once(t,e)))}fire(t,e){\"string\"==typeof t&&(t=new Qt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)Jt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(B(t,\"function\"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof te&&console.error(t.error);return this}listens(t){return !!(this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t))}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var re=JSON.parse('{\"$version\":8,\"$root\":{\"version\":{\"required\":true,\"type\":\"enum\",\"values\":[8]},\"fragment\":{\"type\":\"boolean\"},\"name\":{\"type\":\"string\"},\"metadata\":{\"type\":\"*\"},\"center\":{\"type\":\"array\",\"value\":\"number\"},\"zoom\":{\"type\":\"number\"},\"bearing\":{\"type\":\"number\",\"default\":0,\"period\":360},\"pitch\":{\"type\":\"number\",\"default\":0},\"light\":{\"type\":\"light\"},\"lights\":{\"required\":false,\"type\":\"array\",\"value\":\"light-3d\"},\"terrain\":{\"type\":\"terrain\",\"optional\":true},\"fog\":{\"type\":\"fog\"},\"camera\":{\"type\":\"camera\"},\"imports\":{\"type\":\"array\",\"value\":\"import\"},\"schema\":{\"type\":\"schema\"},\"sources\":{\"required\":true,\"type\":\"sources\"},\"sprite\":{\"type\":\"string\"},\"glyphs\":{\"type\":\"string\",\"default\":\"mapbox://fonts/mapbox/{fontstack}/{range}.pbf\"},\"transition\":{\"type\":\"transition\"},\"projection\":{\"type\":\"projection\"},\"layers\":{\"required\":true,\"type\":\"array\",\"value\":\"layer\"},\"models\":{\"type\":\"models\"}},\"model\":{\"type\":\"string\",\"required\":true},\"import\":{\"id\":{\"type\":\"string\",\"required\":true},\"url\":{\"type\":\"string\",\"required\":true},\"config\":{\"type\":\"config\"},\"data\":{\"type\":\"$root\"}},\"config\":{\"*\":{\"type\":\"*\"}},\"schema\":{\"*\":{\"type\":\"option\"}},\"option\":{\"default\":{\"type\":\"*\",\"required\":true},\"type\":{\"type\":\"enum\",\"values\":{\"string\":1,\"number\":1,\"boolean\":1,\"color\":1}},\"array\":{\"type\":\"boolean\"},\"minValue\":{\"type\":\"number\"},\"maxValue\":{\"type\":\"number\"},\"stepValue\":{\"type\":\"number\"},\"values\":{\"type\":\"array\",\"value\":\"*\"},\"metadata\":{\"type\":\"*\"}},\"models\":{\"*\":{\"type\":\"model\"}},\"light-3d\":{\"id\":{\"type\":\"string\",\"required\":true},\"properties\":{\"type\":\"properties\"},\"type\":{\"type\":\"enum\",\"values\":{\"ambient\":{},\"directional\":{},\"flat\":{}}}},\"properties\":[\"properties_light_directional\",\"properties_light_ambient\",\"properties_light_flat\"],\"properties_light_directional\":{\"direction\":{\"type\":\"array\",\"default\":[210,30],\"minimum\":[0,0],\"maximum\":[360,90],\"length\":2,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":\"#ffffff\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"intensity\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":0.5,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"cast-shadows\":{\"type\":\"boolean\",\"default\":false,\"expression\":{},\"property-type\":\"data-constant\"},\"shadow-intensity\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":1,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true}},\"properties_light_ambient\":{\"color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":\"#ffffff\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"intensity\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":0.5,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true}},\"properties_light_flat\":{\"anchor\":{\"type\":\"enum\",\"default\":\"viewport\",\"values\":{\"map\":1,\"viewport\":1},\"property-type\":\"data-constant\",\"expression\":{\"parameters\":[\"zoom\"]}},\"position\":{\"type\":\"array\",\"default\":[1.15,210,30],\"length\":3,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":\"#ffffff\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"intensity\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":0.5,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true}},\"sources\":{\"*\":{\"type\":\"source\"}},\"source\":[\"source_vector\",\"source_raster\",\"source_raster_dem\",\"source_raster_array\",\"source_geojson\",\"source_video\",\"source_image\",\"source_model\"],\"source_vector\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"vector\":1}},\"url\":{\"type\":\"string\"},\"tiles\":{\"type\":\"array\",\"value\":\"string\"},\"bounds\":{\"type\":\"array\",\"value\":\"number\",\"length\":4,\"default\":[-180,-85.051129,180,85.051129]},\"scheme\":{\"type\":\"enum\",\"values\":{\"xyz\":1,\"tms\":1},\"default\":\"xyz\"},\"minzoom\":{\"type\":\"number\",\"default\":0},\"maxzoom\":{\"type\":\"number\",\"default\":22},\"attribution\":{\"type\":\"string\"},\"promoteId\":{\"type\":\"promoteId\"},\"volatile\":{\"type\":\"boolean\",\"default\":false},\"*\":{\"type\":\"*\"}},\"source_raster\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"raster\":1}},\"url\":{\"type\":\"string\"},\"tiles\":{\"type\":\"array\",\"value\":\"string\"},\"bounds\":{\"type\":\"array\",\"value\":\"number\",\"length\":4,\"default\":[-180,-85.051129,180,85.051129]},\"minzoom\":{\"type\":\"number\",\"default\":0},\"maxzoom\":{\"type\":\"number\",\"default\":22},\"tileSize\":{\"type\":\"number\",\"default\":512},\"scheme\":{\"type\":\"enum\",\"values\":{\"xyz\":1,\"tms\":1},\"default\":\"xyz\"},\"attribution\":{\"type\":\"string\"},\"volatile\":{\"type\":\"boolean\",\"default\":false},\"*\":{\"type\":\"*\"}},\"source_raster_dem\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"raster-dem\":1}},\"url\":{\"type\":\"string\"},\"tiles\":{\"type\":\"array\",\"value\":\"string\"},\"bounds\":{\"type\":\"array\",\"value\":\"number\",\"length\":4,\"default\":[-180,-85.051129,180,85.051129]},\"minzoom\":{\"type\":\"number\",\"default\":0},\"maxzoom\":{\"type\":\"number\",\"default\":22},\"tileSize\":{\"type\":\"number\",\"default\":512},\"attribution\":{\"type\":\"string\"},\"encoding\":{\"type\":\"enum\",\"values\":{\"terrarium\":1,\"mapbox\":1},\"default\":\"mapbox\"},\"volatile\":{\"type\":\"boolean\",\"default\":false},\"*\":{\"type\":\"*\"}},\"source_raster_array\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"raster-array\":1}},\"url\":{\"type\":\"string\"},\"tiles\":{\"type\":\"array\",\"value\":\"string\"},\"bounds\":{\"type\":\"array\",\"value\":\"number\",\"length\":4,\"default\":[-180,-85.051129,180,85.051129]},\"minzoom\":{\"type\":\"number\",\"default\":0},\"maxzoom\":{\"type\":\"number\",\"default\":22},\"tileSize\":{\"type\":\"number\",\"default\":512},\"attribution\":{\"type\":\"string\"},\"rasterLayers\":{\"type\":\"*\"},\"*\":{\"type\":\"*\"}},\"source_geojson\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"geojson\":1}},\"data\":{\"type\":\"*\"},\"maxzoom\":{\"type\":\"number\",\"default\":18},\"attribution\":{\"type\":\"string\"},\"buffer\":{\"type\":\"number\",\"default\":128,\"maximum\":512,\"minimum\":0},\"filter\":{\"type\":\"*\"},\"tolerance\":{\"type\":\"number\",\"default\":0.375},\"cluster\":{\"type\":\"boolean\",\"default\":false},\"clusterRadius\":{\"type\":\"number\",\"default\":50,\"minimum\":0},\"clusterMaxZoom\":{\"type\":\"number\"},\"clusterMinPoints\":{\"type\":\"number\"},\"clusterProperties\":{\"type\":\"*\"},\"lineMetrics\":{\"type\":\"boolean\",\"default\":false},\"generateId\":{\"type\":\"boolean\",\"default\":false},\"promoteId\":{\"type\":\"promoteId\"}},\"source_video\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"video\":1}},\"urls\":{\"required\":true,\"type\":\"array\",\"value\":\"string\"},\"coordinates\":{\"required\":true,\"type\":\"array\",\"length\":4,\"value\":{\"type\":\"array\",\"length\":2,\"value\":\"number\"}}},\"source_image\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"image\":1}},\"url\":{\"required\":false,\"type\":\"string\"},\"coordinates\":{\"required\":true,\"type\":\"array\",\"length\":4,\"value\":{\"type\":\"array\",\"length\":2,\"value\":\"number\"}}},\"source_model\":{\"type\":{\"required\":true,\"type\":\"enum\",\"values\":{\"model\":1,\"batched-model\":1}},\"maxzoom\":{\"type\":\"number\",\"default\":18},\"minzoom\":{\"type\":\"number\",\"default\":0},\"tiles\":{\"type\":\"array\",\"value\":\"string\"}},\"layer\":{\"id\":{\"type\":\"string\",\"required\":true},\"type\":{\"type\":\"enum\",\"values\":{\"fill\":{},\"line\":{},\"symbol\":{},\"circle\":{},\"heatmap\":{},\"fill-extrusion\":{},\"raster\":{},\"hillshade\":{},\"model\":{},\"background\":{},\"sky\":{},\"slot\":{}},\"required\":true},\"metadata\":{\"type\":\"*\"},\"source\":{\"type\":\"string\"},\"source-layer\":{\"type\":\"string\"},\"slot\":{\"type\":\"string\"},\"minzoom\":{\"type\":\"number\",\"minimum\":0,\"maximum\":24},\"maxzoom\":{\"type\":\"number\",\"minimum\":0,\"maximum\":24},\"filter\":{\"type\":\"filter\"},\"layout\":{\"type\":\"layout\"},\"paint\":{\"type\":\"paint\"}},\"layout\":[\"layout_fill\",\"layout_line\",\"layout_circle\",\"layout_heatmap\",\"layout_fill-extrusion\",\"layout_symbol\",\"layout_raster\",\"layout_hillshade\",\"layout_background\",\"layout_sky\",\"layout_model\"],\"layout_background\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_sky\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_model\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"},\"model-id\":{\"type\":\"string\",\"default\":\"\",\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]}}},\"layout_fill\":{\"fill-sort-key\":{\"type\":\"number\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_circle\":{\"circle-sort-key\":{\"type\":\"number\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_heatmap\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_fill-extrusion\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"},\"fill-extrusion-edge-radius\":{\"type\":\"number\",\"private\":true,\"default\":0,\"minimum\":0,\"maximum\":1,\"expression\":{},\"property-type\":\"constant\"}},\"layout_line\":{\"line-cap\":{\"type\":\"enum\",\"values\":{\"butt\":1,\"round\":1,\"square\":1},\"default\":\"butt\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"line-join\":{\"type\":\"enum\",\"values\":{\"bevel\":1,\"round\":1,\"miter\":1},\"default\":\"miter\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"line-miter-limit\":{\"type\":\"number\",\"default\":2,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"line-round-limit\":{\"type\":\"number\",\"default\":1.05,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"line-sort-key\":{\"type\":\"number\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_symbol\":{\"symbol-placement\":{\"type\":\"enum\",\"values\":{\"point\":1,\"line\":1,\"line-center\":1},\"default\":\"point\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"symbol-spacing\":{\"type\":\"number\",\"default\":250,\"minimum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"symbol-avoid-edges\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"symbol-sort-key\":{\"type\":\"number\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"symbol-z-order\":{\"type\":\"enum\",\"values\":{\"auto\":1,\"viewport-y\":1,\"source\":1},\"default\":\"auto\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"symbol-z-elevate\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-allow-overlap\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-ignore-placement\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-optional\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-rotation-alignment\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1,\"auto\":1},\"default\":\"auto\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-size\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-text-fit\":{\"type\":\"enum\",\"values\":{\"none\":1,\"width\":1,\"height\":1,\"both\":1},\"default\":\"none\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-text-fit-padding\":{\"type\":\"array\",\"value\":\"number\",\"length\":4,\"default\":[0,0,0,0],\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-image\":{\"type\":\"resolvedImage\",\"tokens\":true,\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-rotate\":{\"type\":\"number\",\"default\":0,\"period\":360,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-padding\":{\"type\":\"number\",\"default\":2,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-keep-upright\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-offset\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-anchor\":{\"type\":\"enum\",\"values\":{\"center\":1,\"left\":1,\"right\":1,\"top\":1,\"bottom\":1,\"top-left\":1,\"top-right\":1,\"bottom-left\":1,\"bottom-right\":1},\"default\":\"center\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"icon-pitch-alignment\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1,\"auto\":1},\"default\":\"auto\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-pitch-alignment\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1,\"auto\":1},\"default\":\"auto\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-rotation-alignment\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1,\"auto\":1},\"default\":\"auto\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-field\":{\"type\":\"formatted\",\"default\":\"\",\"tokens\":true,\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-font\":{\"type\":\"array\",\"value\":\"string\",\"default\":[\"Open Sans Regular\",\"Arial Unicode MS Regular\"],\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-size\":{\"type\":\"number\",\"default\":16,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-max-width\":{\"type\":\"number\",\"default\":10,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-line-height\":{\"type\":\"number\",\"default\":1.2,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-letter-spacing\":{\"type\":\"number\",\"default\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-justify\":{\"type\":\"enum\",\"values\":{\"auto\":1,\"left\":1,\"center\":1,\"right\":1},\"default\":\"center\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-radial-offset\":{\"type\":\"number\",\"default\":0,\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]}},\"text-variable-anchor\":{\"type\":\"array\",\"value\":\"enum\",\"values\":{\"center\":1,\"left\":1,\"right\":1,\"top\":1,\"bottom\":1,\"top-left\":1,\"top-right\":1,\"bottom-left\":1,\"bottom-right\":1},\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-anchor\":{\"type\":\"enum\",\"values\":{\"center\":1,\"left\":1,\"right\":1,\"top\":1,\"bottom\":1,\"top-left\":1,\"top-right\":1,\"bottom-left\":1,\"bottom-right\":1},\"default\":\"center\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-max-angle\":{\"type\":\"number\",\"default\":45,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-writing-mode\":{\"type\":\"array\",\"value\":\"enum\",\"values\":{\"horizontal\":1,\"vertical\":1},\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-rotate\":{\"type\":\"number\",\"default\":0,\"period\":360,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-padding\":{\"type\":\"number\",\"default\":2,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-keep-upright\":{\"type\":\"boolean\",\"default\":true,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-transform\":{\"type\":\"enum\",\"values\":{\"none\":1,\"uppercase\":1,\"lowercase\":1},\"default\":\"none\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-offset\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"text-allow-overlap\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-ignore-placement\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-optional\":{\"type\":\"boolean\",\"default\":false,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_raster\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"layout_hillshade\":{\"visibility\":{\"type\":\"enum\",\"values\":{\"visible\":1,\"none\":1},\"default\":\"visible\",\"expression\":{},\"property-type\":\"constant\"}},\"filter\":{\"type\":\"array\",\"value\":\"*\"},\"filter_symbol\":{\"type\":\"boolean\",\"default\":false,\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\",\"pitch\",\"distance-from-center\"]}},\"filter_fill\":{\"type\":\"boolean\",\"default\":false,\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]}},\"filter_line\":{\"type\":\"boolean\",\"default\":false,\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]}},\"filter_circle\":{\"type\":\"boolean\",\"default\":false,\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]}},\"filter_fill-extrusion\":{\"type\":\"boolean\",\"default\":false,\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]}},\"filter_heatmap\":{\"type\":\"boolean\",\"default\":false,\"property-type\":\"data-driven\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]}},\"filter_operator\":{\"type\":\"enum\",\"values\":{\"==\":1,\"!=\":1,\">\":1,\">=\":1,\"<\":1,\"<=\":1,\"in\":1,\"!in\":1,\"all\":1,\"any\":1,\"none\":1,\"has\":1,\"!has\":1}},\"geometry_type\":{\"type\":\"enum\",\"values\":{\"Point\":1,\"LineString\":1,\"Polygon\":1}},\"function\":{\"expression\":{\"type\":\"expression\"},\"stops\":{\"type\":\"array\",\"value\":\"function_stop\"},\"base\":{\"type\":\"number\",\"default\":1,\"minimum\":0},\"property\":{\"type\":\"string\",\"default\":\"$zoom\"},\"type\":{\"type\":\"enum\",\"values\":{\"identity\":1,\"exponential\":1,\"interval\":1,\"categorical\":1},\"default\":\"exponential\"},\"colorSpace\":{\"type\":\"enum\",\"values\":{\"rgb\":1,\"lab\":1,\"hcl\":1},\"default\":\"rgb\"},\"default\":{\"type\":\"*\",\"required\":false}},\"function_stop\":{\"type\":\"array\",\"minimum\":0,\"maximum\":24,\"value\":[\"number\",\"color\"],\"length\":2},\"expression\":{\"type\":\"array\",\"value\":\"*\",\"minimum\":1},\"fog\":{\"range\":{\"type\":\"array\",\"default\":[0.5,10],\"minimum\":-20,\"maximum\":20,\"length\":2,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true}},\"color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":\"#ffffff\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true},\"transition\":true},\"high-color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":\"#245cdf\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true},\"transition\":true},\"space-color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":[\"interpolate\",[\"linear\"],[\"zoom\"],4,\"#010b19\",7,\"#367ab9\"],\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true},\"transition\":true},\"horizon-blend\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":[\"interpolate\",[\"linear\"],[\"zoom\"],4,0.2,7,0.1],\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true},\"transition\":true},\"star-intensity\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":[\"interpolate\",[\"linear\"],[\"zoom\"],5,0.35,6,0],\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true},\"transition\":true},\"vertical-range\":{\"type\":\"array\",\"default\":[0,0],\"minimum\":0,\"length\":2,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"],\"relaxZoomRestriction\":true}}},\"camera\":{\"camera-projection\":{\"type\":\"enum\",\"values\":{\"perspective\":1,\"orthographic\":1},\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"default\":\"perspective\",\"property-type\":\"data-constant\"}},\"light\":{\"anchor\":{\"type\":\"enum\",\"default\":\"viewport\",\"values\":{\"map\":1,\"viewport\":1},\"property-type\":\"data-constant\",\"expression\":{\"parameters\":[\"zoom\"]}},\"position\":{\"type\":\"array\",\"default\":[1.15,210,30],\"length\":3,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"color\":{\"type\":\"color\",\"property-type\":\"data-constant\",\"default\":\"#ffffff\",\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"intensity\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":0.5,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true}},\"projection\":{\"name\":{\"type\":\"enum\",\"values\":{\"albers\":1,\"equalEarth\":1,\"equirectangular\":1,\"lambertConformalConic\":1,\"mercator\":1,\"naturalEarth\":1,\"winkelTripel\":1,\"globe\":1},\"default\":\"mercator\",\"required\":true},\"center\":{\"type\":\"array\",\"length\":2,\"value\":\"number\",\"property-type\":\"data-constant\",\"minimum\":[-180,-90],\"maximum\":[180,90]},\"parallels\":{\"type\":\"array\",\"length\":2,\"value\":\"number\",\"property-type\":\"data-constant\",\"minimum\":[-90,-90],\"maximum\":[90,90]}},\"terrain\":{\"source\":{\"type\":\"string\",\"required\":true},\"exaggeration\":{\"type\":\"number\",\"property-type\":\"data-constant\",\"default\":1,\"minimum\":0,\"maximum\":1000,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true}},\"paint\":[\"paint_fill\",\"paint_line\",\"paint_circle\",\"paint_heatmap\",\"paint_fill-extrusion\",\"paint_symbol\",\"paint_raster\",\"paint_hillshade\",\"paint_background\",\"paint_sky\",\"paint_model\"],\"paint_fill\":{\"fill-antialias\":{\"type\":\"boolean\",\"default\":true,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"fill-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"fill-outline-color\":{\"type\":\"color\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"fill-translate\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-translate-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-pattern\":{\"type\":\"resolvedImage\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"fill-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"}},\"paint_fill-extrusion\":{\"fill-extrusion-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-extrusion-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"fill-extrusion-translate\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-extrusion-translate-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-extrusion-pattern\":{\"type\":\"resolvedImage\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"fill-extrusion-height\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\"]},\"property-type\":\"data-driven\"},\"fill-extrusion-base\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\"]},\"property-type\":\"data-driven\"},\"fill-extrusion-vertical-gradient\":{\"type\":\"boolean\",\"default\":true,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"fill-extrusion-ambient-occlusion-intensity\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"private\":true,\"default\":0,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"fill-extrusion-ambient-occlusion-radius\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"private\":true,\"default\":3,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"fill-extrusion-ambient-occlusion-wall-radius\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"default\":3,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"fill-extrusion-ambient-occlusion-ground-radius\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"default\":3,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"transition\":true},\"fill-extrusion-ambient-occlusion-ground-attenuation\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"default\":0.69,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"fill-extrusion-flood-light-color\":{\"property-type\":\"data-constant\",\"type\":\"color\",\"default\":\"#ffffff\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]}},\"fill-extrusion-flood-light-intensity\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"default\":0,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]}},\"fill-extrusion-flood-light-wall-radius\":{\"property-type\":\"data-driven\",\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\"]}},\"fill-extrusion-flood-light-ground-radius\":{\"property-type\":\"data-driven\",\"type\":\"number\",\"default\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\"]}},\"fill-extrusion-flood-light-ground-attenuation\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"default\":0.69,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"fill-extrusion-vertical-scale\":{\"property-type\":\"data-constant\",\"type\":\"number\",\"default\":1,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"fill-extrusion-rounded-roof\":{\"property-type\":\"data-constant\",\"type\":\"boolean\",\"default\":true,\"expression\":{\"parameters\":[\"zoom\"]}},\"fill-extrusion-cutoff-fade-range\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"maximum\":1,\"expression\":{},\"property-type\":\"data-constant\"},\"fill-extrusion-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"}},\"paint_line\":{\"line-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"line-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"line-translate\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"line-translate-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"line-width\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"line-gap-width\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"line-offset\":{\"type\":\"number\",\"default\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"line-blur\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"line-dasharray\":{\"type\":\"array\",\"value\":\"number\",\"minimum\":0,\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"line-pattern\":{\"type\":\"resolvedImage\",\"expression\":{\"parameters\":[\"zoom\",\"feature\"]},\"property-type\":\"data-driven\"},\"line-gradient\":{\"type\":\"color\",\"expression\":{\"interpolated\":true,\"parameters\":[\"line-progress\"]},\"property-type\":\"color-ramp\"},\"line-trim-offset\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"minimum\":[0,0],\"maximum\":[1,1],\"property-type\":\"constant\"},\"line-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"},\"line-border-width\":{\"type\":\"number\",\"private\":true,\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\"]},\"property-type\":\"data-driven\"},\"line-border-color\":{\"type\":\"color\",\"private\":true,\"default\":\"rgba(0, 0, 0, 0)\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\"]},\"property-type\":\"data-driven\"}},\"paint_circle\":{\"circle-radius\":{\"type\":\"number\",\"default\":5,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-blur\":{\"type\":\"number\",\"default\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-translate\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"circle-translate-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"circle-pitch-scale\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"circle-pitch-alignment\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"viewport\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"circle-stroke-width\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-stroke-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-stroke-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"circle-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"}},\"paint_heatmap\":{\"heatmap-radius\":{\"type\":\"number\",\"default\":30,\"minimum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"heatmap-weight\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"heatmap-intensity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"heatmap-color\":{\"type\":\"color\",\"default\":[\"interpolate\",[\"linear\"],[\"heatmap-density\"],0,\"rgba(0, 0, 255, 0)\",0.1,\"royalblue\",0.3,\"cyan\",0.5,\"lime\",0.7,\"yellow\",1,\"red\"],\"expression\":{\"interpolated\":true,\"parameters\":[\"heatmap-density\"]},\"property-type\":\"color-ramp\"},\"heatmap-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"}},\"paint_symbol\":{\"icon-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"icon-emissive-strength\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"text-emissive-strength\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"icon-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"icon-halo-color\":{\"type\":\"color\",\"default\":\"rgba(0, 0, 0, 0)\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"icon-halo-width\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"icon-halo-blur\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"icon-translate\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-translate-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-image-cross-fade\":{\"type\":\"number\",\"property-type\":\"data-driven\",\"default\":0,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"transition\":true},\"text-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"text-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"overridable\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"text-halo-color\":{\"type\":\"color\",\"default\":\"rgba(0, 0, 0, 0)\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"text-halo-width\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"text-halo-blur\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"feature\",\"feature-state\",\"measure-light\"]},\"property-type\":\"data-driven\"},\"text-translate\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"default\":[0,0],\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"text-translate-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"map\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"icon-color-saturation\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{},\"property-type\":\"data-constant\"}},\"paint_raster\":{\"raster-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-color\":{\"type\":\"color\",\"expression\":{\"interpolated\":true,\"parameters\":[\"raster-value\"]},\"property-type\":\"color-ramp\"},\"raster-color-mix\":{\"type\":\"array\",\"default\":[0.2126,0.7152,0.0722,0],\"length\":4,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"raster-color-range\":{\"type\":\"array\",\"default\":[0,1],\"length\":2,\"value\":\"number\",\"property-type\":\"data-constant\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]}},\"raster-hue-rotate\":{\"type\":\"number\",\"default\":0,\"period\":360,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-brightness-min\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-brightness-max\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-saturation\":{\"type\":\"number\",\"default\":0,\"minimum\":-1,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-contrast\":{\"type\":\"number\",\"default\":0,\"minimum\":-1,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-resampling\":{\"type\":\"enum\",\"values\":{\"linear\":1,\"nearest\":1},\"default\":\"linear\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-fade-duration\":{\"type\":\"number\",\"default\":300,\"minimum\":0,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"raster-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"},\"raster-array-band\":{\"type\":\"string\",\"required\":false,\"property-type\":\"data-constant\"},\"raster-elevation\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"}},\"paint_hillshade\":{\"hillshade-illumination-direction\":{\"type\":\"number\",\"default\":335,\"minimum\":0,\"maximum\":359,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"hillshade-illumination-anchor\":{\"type\":\"enum\",\"values\":{\"map\":1,\"viewport\":1},\"default\":\"viewport\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"hillshade-exaggeration\":{\"type\":\"number\",\"default\":0.5,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"hillshade-shadow-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"},\"hillshade-highlight-color\":{\"type\":\"color\",\"default\":\"#FFFFFF\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"},\"hillshade-accent-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"},\"hillshade-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"}},\"paint_background\":{\"background-color\":{\"type\":\"color\",\"default\":\"#000000\",\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"background-pattern\":{\"type\":\"resolvedImage\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"background-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"background-emissive-strength\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\",\"measure-light\"]},\"property-type\":\"data-constant\"}},\"paint_sky\":{\"sky-type\":{\"type\":\"enum\",\"values\":{\"gradient\":1,\"atmosphere\":1},\"default\":\"atmosphere\",\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"sky-atmosphere-sun\":{\"type\":\"array\",\"value\":\"number\",\"length\":2,\"minimum\":[0,0],\"maximum\":[360,180],\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"sky-atmosphere-sun-intensity\":{\"type\":\"number\",\"default\":10,\"minimum\":0,\"maximum\":100,\"property-type\":\"data-constant\"},\"sky-gradient-center\":{\"type\":\"array\",\"value\":\"number\",\"default\":[0,0],\"length\":2,\"minimum\":[0,0],\"maximum\":[360,180],\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"sky-gradient-radius\":{\"type\":\"number\",\"default\":90,\"minimum\":0,\"maximum\":180,\"expression\":{\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"sky-gradient\":{\"type\":\"color\",\"default\":[\"interpolate\",[\"linear\"],[\"sky-radial-progress\"],0.8,\"#87ceeb\",1,\"white\"],\"expression\":{\"interpolated\":true,\"parameters\":[\"sky-radial-progress\"]},\"property-type\":\"color-ramp\"},\"sky-atmosphere-halo-color\":{\"type\":\"color\",\"default\":\"white\",\"property-type\":\"data-constant\"},\"sky-atmosphere-color\":{\"type\":\"color\",\"default\":\"white\",\"property-type\":\"data-constant\"},\"sky-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"}},\"paint_model\":{\"model-opacity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"transition\":true,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\"},\"model-rotation\":{\"type\":\"array\",\"value\":\"number\",\"length\":3,\"default\":[0,0,0],\"period\":360,\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"zoom\"]},\"transition\":true},\"model-scale\":{\"type\":\"array\",\"value\":\"number\",\"length\":3,\"default\":[1,1,1],\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"zoom\"]},\"transition\":true},\"model-translation\":{\"type\":\"array\",\"value\":\"number\",\"length\":3,\"default\":[0,0,0],\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"zoom\"]},\"transition\":true},\"model-color\":{\"type\":\"color\",\"default\":\"#ffffff\",\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"measure-light\",\"zoom\"]},\"transition\":true},\"model-color-mix-intensity\":{\"type\":\"number\",\"property-type\":\"data-driven\",\"default\":0,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"measure-light\"]},\"transition\":true},\"model-type\":{\"type\":\"enum\",\"values\":{\"common-3d\":1,\"location-indicator\":1},\"default\":\"common-3d\",\"property-type\":\"data-constant\"},\"model-cast-shadows\":{\"type\":\"boolean\",\"default\":true,\"expression\":{},\"property-type\":\"data-constant\"},\"model-receive-shadows\":{\"type\":\"boolean\",\"default\":true,\"expression\":{},\"property-type\":\"data-constant\"},\"model-ambient-occlusion-intensity\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"expression\":{\"interpolated\":true,\"parameters\":[\"zoom\"]},\"property-type\":\"data-constant\",\"transition\":true},\"model-emissive-strength\":{\"type\":\"number\",\"property-type\":\"data-driven\",\"default\":0,\"minimum\":0,\"maximum\":5,\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"measure-light\"]},\"transition\":true},\"model-roughness\":{\"type\":\"number\",\"default\":1,\"minimum\":0,\"maximum\":1,\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\"]},\"transition\":true},\"model-height-based-emissive-strength-multiplier\":{\"type\":\"array\",\"default\":[1,1,1,1,0],\"length\":5,\"value\":\"number\",\"property-type\":\"data-driven\",\"expression\":{\"interpolated\":true,\"parameters\":[\"feature\",\"feature-state\",\"measure-light\"]},\"transition\":true},\"model-cutoff-fade-range\":{\"type\":\"number\",\"default\":0,\"minimum\":0,\"maximum\":1,\"expression\":{},\"property-type\":\"data-constant\"}},\"transition\":{\"duration\":{\"type\":\"number\",\"default\":300,\"minimum\":0},\"delay\":{\"type\":\"number\",\"default\":0,\"minimum\":0}},\"property-type\":{\"data-driven\":{\"type\":\"property-type\"},\"color-ramp\":{\"type\":\"property-type\"},\"data-constant\":{\"type\":\"property-type\"},\"constant\":{\"type\":\"property-type\"}},\"promoteId\":{\"*\":{\"type\":\"string\"}}}');class ne{constructor(t,e,r,n){this.message=(t?`${t}: `:\"\")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);}}class ie extends ne{}function se(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}function ae(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function oe(t){if(Array.isArray(t))return t.map(oe);if(t instanceof Object&&!(t instanceof Number||t instanceof String||t instanceof Boolean)){const e={};for(const r in t)e[r]=oe(t[r]);return e}return ae(t)}class le extends Error{constructor(t,e){super(e),this.message=e,this.key=t;}}var ue=le;class ce{constructor(t,e=[]){this.parent=t,this.bindings={};for(const[t,r]of e)this.bindings[t]=r;}concat(t){return new ce(this,t)}get(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(`${t} not found in scope.`)}has(t){return !!this.bindings[t]||!!this.parent&&this.parent.has(t)}}var he=ce;const pe={kind:\"null\"},fe={kind:\"number\"},de={kind:\"string\"},me={kind:\"boolean\"},ye={kind:\"color\"},ge={kind:\"object\"},xe={kind:\"value\"},ve={kind:\"collator\"},be={kind:\"formatted\"},_e={kind:\"resolvedImage\"};function we(t,e){return {kind:\"array\",itemType:t,N:e}}function Me(t){if(\"array\"===t.kind){const e=Me(t.itemType);return \"number\"==typeof t.N?`array<${e}, ${t.N}>`:\"value\"===t.itemType.kind?\"array\":`array<${e}>`}return t.kind}const Ae=[pe,fe,de,me,ye,be,ge,we(xe),_e];function Se(t,e){if(\"error\"===e.kind)return null;if(\"array\"===t.kind){if(\"array\"===e.kind&&(0===e.N&&\"value\"===e.itemType.kind||!Se(t.itemType,e.itemType))&&(\"number\"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if(\"value\"===t.kind)for(const t of Ae)if(!Se(t,e))return null}return `Expected ${Me(t)} but found ${Me(e)} instead.`}function Ie(t,e){return e.some((e=>e.kind===t.kind))}function ke(t,e){return e.some((e=>\"null\"===e?null===t:\"array\"===e?Array.isArray(t):\"object\"===e?t&&!Array.isArray(t)&&\"object\"==typeof t:e===typeof t))}var Te,Pe={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function ze(t){return (t=Math.round(t))<0?0:t>255?255:t}function Ee(t){return ze(\"%\"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function Be(t){return (e=\"%\"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))<0?0:e>1?1:e;var e;}function De(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{Te={}.parseCSSColor=function(t){var e,r=t.replace(/ /g,\"\").toLowerCase();if(r in Pe)return Pe[r].slice();if(\"#\"===r[0])return 4===r.length?(e=parseInt(r.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===r.length&&(e=parseInt(r.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var n=r.indexOf(\"(\"),i=r.indexOf(\")\");if(-1!==n&&i+1===r.length){var s=r.substr(0,n),a=r.substr(n+1,i-(n+1)).split(\",\"),o=1;switch(s){case\"rgba\":if(4!==a.length)return null;o=Be(a.pop());case\"rgb\":return 3!==a.length?null:[Ee(a[0]),Ee(a[1]),Ee(a[2]),o];case\"hsla\":if(4!==a.length)return null;o=Be(a.pop());case\"hsl\":if(3!==a.length)return null;var l=(parseFloat(a[0])%360+360)%360/360,u=Be(a[1]),c=Be(a[2]),h=c<=.5?c*(u+1):c+u-c*u,p=2*c-h;return [ze(255*De(p,h,l+1/3)),ze(255*De(p,h,l)),ze(255*De(p,h,l-1/3)),o];default:return null}}return null};}catch(t){}class Ce{constructor(t,e,r,n=1){this.r=t,this.g=e,this.b=r,this.a=n;}static parse(t){if(!t)return;if(t instanceof Ce)return t;if(\"string\"!=typeof t)return;const e=Te(t);return e?new Ce(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3]):void 0}toString(){const[t,e,r,n]=this.toArray();return `rgba(${Math.round(t)},${Math.round(e)},${Math.round(r)},${n})`}toArray(){const{r:t,g:e,b:r,a:n}=this;return 0===n?[0,0,0,0]:[255*t/n,255*e/n,255*r/n,n]}toArray01(){const{r:t,g:e,b:r,a:n}=this;return 0===n?[0,0,0,0]:[t/n,e/n,r/n,n]}toArray01Scaled(t){const{r:e,g:r,b:n,a:i}=this;return 0===i?[0,0,0]:[e/i*t,r/i*t,n/i*t]}toArray01PremultipliedAlpha(){const{r:t,g:e,b:r,a:n}=this;return [t,e,r,n]}toArray01Linear(){const{r:t,g:e,b:r,a:n}=this;return 0===n?[0,0,0,0]:[Math.pow(t/n,2.2),Math.pow(e/n,2.2),Math.pow(r/n,2.2),n]}}Ce.black=new Ce(0,0,0,1),Ce.white=new Ce(1,1,1,1),Ce.transparent=new Ce(0,0,0,0),Ce.red=new Ce(1,0,0,1),Ce.blue=new Ce(0,0,1,1);var Re=Ce;class Le{constructor(t,e,r){this.sensitivity=t?e?\"variant\":\"case\":e?\"accent\":\"base\",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:\"search\"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Ve{constructor(t,e,r,n,i){this.text=t.normalize?t.normalize():t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;}}class Oe{constructor(t){this.sections=t;}static fromString(t){return new Oe([new Ve(t,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.namePrimary.length))}static factory(t){return t instanceof Oe?t:Oe.fromString(t)}toString(){return 0===this.sections.length?\"\":this.sections.map((t=>t.text)).join(\"\")}serialize(){const t=[\"format\"];for(const e of this.sections){if(e.image){t.push([\"image\",e.image.namePrimary]);continue}t.push(e.text);const r={};e.fontStack&&(r[\"text-font\"]=[\"literal\",e.fontStack.split(\",\")]),e.scale&&(r[\"font-scale\"]=e.scale),e.textColor&&(r[\"text-color\"]=[\"rgba\"].concat(e.textColor.toArray())),t.push(r);}return t}}class Fe{constructor(t){this.namePrimary=t.namePrimary,t.nameSecondary&&(this.nameSecondary=t.nameSecondary),this.available=t.available;}toString(){return this.nameSecondary?`[${this.namePrimary},${this.nameSecondary}]`:this.namePrimary}static fromString(t,e){return t?new Fe({namePrimary:t,nameSecondary:e,available:!1}):null}serialize(){return this.nameSecondary?[\"image\",this.namePrimary,this.nameSecondary]:[\"image\",this.namePrimary]}}function je(t,e,r,n){return \"number\"==typeof t&&t>=0&&t<=255&&\"number\"==typeof e&&e>=0&&e<=255&&\"number\"==typeof r&&r>=0&&r<=255?void 0===n||\"number\"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(\", \")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(\"number\"==typeof n?[t,e,r,n]:[t,e,r]).join(\", \")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Ue(t){if(null===t)return !0;if(\"string\"==typeof t)return !0;if(\"boolean\"==typeof t)return !0;if(\"number\"==typeof t)return !0;if(t instanceof Re)return !0;if(t instanceof Le)return !0;if(t instanceof Oe)return !0;if(t instanceof Fe)return !0;if(Array.isArray(t)){for(const e of t)if(!Ue(e))return !1;return !0}if(\"object\"==typeof t){for(const e in t)if(!Ue(t[e]))return !1;return !0}return !1}function Ne(t){if(null===t)return pe;if(\"string\"==typeof t)return de;if(\"boolean\"==typeof t)return me;if(\"number\"==typeof t)return fe;if(t instanceof Re)return ye;if(t instanceof Le)return ve;if(t instanceof Oe)return be;if(t instanceof Fe)return _e;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ne(e);if(r){if(r===t)continue;r=xe;break}r=t;}return we(r||xe,e)}return ge}function $e(t){const e=typeof t;return null===t?\"\":\"string\"===e||\"number\"===e||\"boolean\"===e?String(t):t instanceof Re||t instanceof Oe||t instanceof Fe?t.toString():JSON.stringify(t)}class qe{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Ue(t[1]))return e.error(\"invalid value\");const r=t[1];let n=Ne(r);const i=e.expectedType;return \"array\"!==n.kind||0!==n.N||!i||\"array\"!==i.kind||\"number\"==typeof i.N&&0!==i.N||(n=i),new qe(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}serialize(){return \"array\"===this.type.kind||\"object\"===this.type.kind?[\"literal\",this.value]:this.value instanceof Re?[\"rgba\"].concat(this.value.toArray()):this.value instanceof Oe?this.value.serialize():this.value}}var Ge=qe,Ye=class{constructor(t){this.name=\"ExpressionEvaluationError\",this.message=t;}toJSON(){return this.message}};const Ze={string:de,number:fe,boolean:me,object:ge};class Xe{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error(\"Expected at least one argument.\");let r,n=1;const i=t[0];if(\"array\"===i){let i,s;if(t.length>2){const r=t[1];if(\"string\"!=typeof r||!(r in Ze)||\"object\"===r)return e.error('The item type argument of \"array\" must be one of string, number, boolean',1);i=Ze[r],n++;}else i=xe;if(t.length>3){if(null!==t[2]&&(\"number\"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to \"array\" must be a positive integer literal',2);s=t[2],n++;}r=we(i,s);}else r=Ze[i];const s=[];for(;nt.outputDefined()))}serialize(){const t=this.type,e=[t.kind];if(\"array\"===t.kind){const r=t.itemType;if(\"string\"===r.kind||\"number\"===r.kind||\"boolean\"===r.kind){e.push(r.kind);const n=t.N;(\"number\"==typeof n||this.args.length>1)&&e.push(n);}}return e.concat(this.args.map((t=>t.serialize())))}}var Ke=Xe;class We{constructor(t){this.type=be,this.sections=t;}static parse(t,e){if(t.length<2)return e.error(\"Expected at least one argument.\");const r=t[1];if(!Array.isArray(r)&&\"object\"==typeof r)return e.error(\"First argument must be an image or text section.\");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&\"object\"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s[\"font-scale\"]&&(t=e.parse(s[\"font-scale\"],1,fe),!t))return null;let r=null;if(s[\"text-font\"]&&(r=e.parse(s[\"text-font\"],1,we(de)),!r))return null;let a=null;if(s[\"text-color\"]&&(a=e.parse(s[\"text-color\"],1,ye),!a))return null;const o=n[n.length-1];o.scale=t,o.font=r,o.textColor=a;}else {const s=e.parse(t[r],1,xe);if(!s)return null;const a=s.type.kind;if(\"string\"!==a&&\"value\"!==a&&\"null\"!==a&&\"resolvedImage\"!==a)return e.error(\"Formatted text type must be 'string', 'value', 'image' or 'null'.\");i=!0,n.push({content:s,scale:null,font:null,textColor:null});}}return new We(n)}evaluate(t){return new Oe(this.sections.map((e=>{const r=e.content.evaluate(t);return Ne(r)===_e?new Ve(\"\",r,null,null,null):new Ve($e(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(\",\"):null,e.textColor?e.textColor.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor);}outputDefined(){return !1}serialize(){const t=[\"format\"];for(const e of this.sections){t.push(e.content.serialize());const r={};e.scale&&(r[\"font-scale\"]=e.scale.serialize()),e.font&&(r[\"text-font\"]=e.font.serialize()),e.textColor&&(r[\"text-color\"]=e.textColor.serialize()),t.push(r);}return t}}class He{constructor(t,e){this.type=_e,this.inputPrimary=t,this.inputSecondary=e;}static parse(t,e){if(t.length<2)return e.error(\"Expected two or more arguments.\");const r=e.parse(t[1],1,de);if(!r)return e.error(\"No image name provided.\");if(2===t.length)return new He(r);const n=e.parse(t[2],1,de);return n?new He(r,n):e.error(\"Secondary image variant is not a string.\")}evaluate(t){const e=Fe.fromString(this.inputPrimary.evaluate(t),this.inputSecondary?this.inputSecondary.evaluate(t):void 0);return e&&t.availableImages&&(e.available=t.availableImages.indexOf(e.namePrimary)>-1,e.nameSecondary&&e.available&&t.availableImages&&(e.available=t.availableImages.indexOf(e.nameSecondary)>-1)),e}eachChild(t){t(this.inputPrimary),this.inputSecondary&&t(this.inputSecondary);}outputDefined(){return !1}serialize(){return this.inputSecondary?[\"image\",this.inputPrimary.serialize(),this.inputSecondary.serialize()]:[\"image\",this.inputPrimary.serialize()]}}function Je(t){return t instanceof Number?\"number\":t instanceof String?\"string\":t instanceof Boolean?\"boolean\":Array.isArray(t)?\"array\":null===t?\"null\":typeof t}const Qe={\"to-boolean\":me,\"to-color\":ye,\"to-number\":fe,\"to-string\":de};class tr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error(\"Expected at least one argument.\");const r=t[0],n=[];let i=pe;if(\"to-array\"===r){if(!Array.isArray(t[1]))return null;const r=t[1].length;if(e.expectedType){if(\"array\"!==e.expectedType.kind)return e.error(`Expected ${e.expectedType.kind} but found array.`);i=we(e.expectedType.itemType,r);}else {if(!(r>0&&Ue(t[1][0])))return null;i=we(Ne(t[1][0]),r);}for(let s=0;s4?`Invalid rbga value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:je(e[0],e[1],e[2],e[3]),!r))return new Re(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ye(r||`Could not parse color from value '${\"string\"==typeof e?e:String(JSON.stringify(e))}'`)}if(\"number\"===this.type.kind){let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ye(`Could not convert ${JSON.stringify(e)} to number.`)}return \"formatted\"===this.type.kind?Oe.fromString($e(this.args[0].evaluate(t))):\"resolvedImage\"===this.type.kind?Fe.fromString($e(this.args[0].evaluate(t))):\"array\"===this.type.kind?this.args.map((e=>e.evaluate(t))):$e(this.args[0].evaluate(t))}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}serialize(){if(\"formatted\"===this.type.kind)return new We([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(\"resolvedImage\"===this.type.kind)return new He(this.args[0]).serialize();const t=\"array\"===this.type.kind?[]:[`to-${this.type.kind}`];return this.eachChild((e=>{t.push(e.serialize());})),t}}var er=tr;const rr=[\"Unknown\",\"Point\",\"LineString\",\"Polygon\"];var nr=class{constructor(t,e){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=t,this.options=e;}id(){return this.feature&&void 0!==this.feature.id?this.feature.id:null}geometryType(){return this.feature?\"number\"==typeof this.feature.type?rr[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&\"geometry\"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(t){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const t=this.featureDistanceData.center,e=this.featureDistanceData.scale,{x:r,y:n}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(r*e-t[0])+this.featureDistanceData.bearing[1]*(n*e-t[1])}return 0}parseColor(t){let e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=Re.parse(t)),e}getConfig(t){return this.options?this.options.get(t):null}};class ir{constructor(t,e,r,n,i){this.name=t,this.type=e,this._evaluate=r,this.args=n,this._overloadIndex=i;}evaluate(t){if(!this._evaluate){const t=ir.definitions[this.name];this._evaluate=Array.isArray(t)?t[2]:t.overloads[this._overloadIndex][1];}return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}serialize(){return [this.name].concat(this.args.map((t=>t.serialize())))}static parse(t,e){const r=t[0],n=ir.definitions[r];if(!n)return e.error(`Unknown expression \"${r}\". If you wanted a literal array, use [\"literal\", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=[];let o=null,l=-1;for(const[n,u]of s){if(Array.isArray(n)&&n.length!==t.length-1)continue;a.push(n),l++,o=new xn(e.registry,e.path,null,e.scope,void 0,e._scope,e.options);const s=[];let c=!1;for(let e=1;et))).map(sr).join(\" | \"),n=[];for(let r=1;ri;){if(s-i>600){var o=s-i+1,l=n-i+1,u=Math.log(o),c=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*c*(o-c)/o)*(l-o/2<0?-1:1);t(r,n,Math.max(i,Math.floor(n-l*c/o+h)),Math.min(s,Math.floor(n+(o-l)*c/o+h)),a);}var p=r[n],f=i,d=s;for(e(r,i,n),a(r[s],p)>0&&e(r,i,s);f0;)d--;}0===a(r[i],p)?e(r,i,d):e(r,++d,s),d<=n&&(i=d+1),n<=d&&(s=d-1);}}function e(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function r(t,e){return te?1:0}return function(e,n,i,s,a){t(e,n,i||0,s||e.length-1,a||r);}}();var ur=p(lr.exports);function cr(t){let e=0;for(let r,n,i=0,s=t.length,a=s-1;i=e[2]||t[1]<=e[1]||t[3]>=e[3])}function fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function dr(t,e,r=!1){let n=!1;for(let o=0,l=e.length;o(i=t)[1]!=(a=c)[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}}var i,s,a;return n}function mr(t,e,r,n){const i=n[0]-r[0],s=n[1]-r[1],a=(t[0]-r[0])*s-i*(t[1]-r[1]),o=(e[0]-r[0])*s-i*(e[1]-r[1]);return a>0&&o<0||a<0&&o>0}function yr(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!mr(t,e,r,n)||!mr(r,n,t,e));var i,s;}const gr=8192;function xr(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*gr),Math.round(n*i*gr)]}function vr(t,e){for(let r=0;rr[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}hr(e,t);}function Ir(t,e,r,n){const i=Math.pow(2,n.z)*gr,s=[n.x*gr,n.y*gr],a=[];if(!t)return a;for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Sr(n,e,r,i),a.push(n);}return a}function kr(t,e,r,n){const i=Math.pow(2,n.z)*gr,s=[n.x*gr,n.y*gr],a=[];if(!t)return a;for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];hr(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Sr(n,e,r,i);}var o;return a}class Tr{constructor(t,e){this.type=me,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Ue(t[1])){const e=t[1];if(\"FeatureCollection\"===e.type)for(let t=0;t180;)t-=360;return t}return i.fromTile=function(t,e,r){var s=Math.PI*(1-2*(t+.5)/Math.pow(2,e)),a=Math.atan(.5*(Math.exp(s)-Math.exp(-s)))/n;return new i(a,r)},s.units.get=function(){return t},i.prototype.distance=function(t,e){var r=l(t[0]-e[0])*this.kx,n=(t[1]-e[1])*this.ky;return Math.sqrt(r*r+n*n)},i.prototype.bearing=function(t,e){var r=l(e[0]-t[0])*this.kx;return Math.atan2(r,(e[1]-t[1])*this.ky)/n},i.prototype.destination=function(t,e,r){var i=r*n;return this.offset(t,Math.sin(i)*e,Math.cos(i)*e)},i.prototype.offset=function(t,e,r){return [t[0]+e/this.kx,t[1]+r/this.ky]},i.prototype.lineDistance=function(t){for(var e=0,r=0;re)return o(i,s,(e-(r-a))/a)}return t[t.length-1]},i.prototype.pointToSegmentDistance=function(t,e,r){var n=e[0],i=e[1],s=l(r[0]-n)*this.kx,a=(r[1]-i)*this.ky,o=0;return 0===s&&0===a||((o=(l(t[0]-n)*this.kx*s+(t[1]-i)*this.ky*a)/(s*s+a*a))>1?(n=r[0],i=r[1]):o>0&&(n+=s/this.kx*o,i+=a/this.ky*o)),s=l(t[0]-n)*this.kx,a=(t[1]-i)*this.ky,Math.sqrt(s*s+a*a)},i.prototype.pointOnLine=function(t,e){for(var r,n,i,s,a=1/0,o=0;o1?(u=t[o+1][0],c=t[o+1][1]):f>0&&(u+=h/this.kx*f,c+=p/this.ky*f));var d=(h=l(e[0]-u)*this.kx)*h+(p=(e[1]-c)*this.ky)*p;di.index||n.index===i.index&&n.t>i.t){var s=n;n=i,i=s;}var o=[n.point],l=n.index+1,u=i.index;!a(r[l],o[0])&&l<=u&&o.push(r[l]);for(var c=l+1;c<=u;c++)o.push(r[c]);return a(r[u],i.point)||o.push(i.point),o},i.prototype.lineSliceAlong=function(t,e,r){for(var n=0,i=[],s=0;st&&0===i.length&&i.push(o(a,l,(t-(n-u))/u)),n>=e)return i.push(o(a,l,(e-(n-u))/u)),i;n>t&&i.push(l);}return i},i.prototype.bufferPoint=function(t,e){var r=e/this.ky,n=e/this.kx;return [t[0]-n,t[1]-r,t[0]+n,t[1]+r]},i.prototype.bufferBBox=function(t,e){var r=e/this.ky,n=e/this.kx;return [t[0]-n,t[1]-r,t[2]+n,t[3]+r]},i.prototype.insideBBox=function(t,e){return l(t[0]-e[0])>=0&&l(t[0]-e[2])<=0&&t[1]>=e[1]&&t[1]<=e[3]},Object.defineProperties(i,s),i}();var Er=p(zr.exports),Br={exports:{}};Br.exports=function(){var t=function(t,r){if(void 0===t&&(t=[]),void 0===r&&(r=e),this.data=t,this.length=this.data.length,this.compare=r,this.length>0)for(var n=(this.length>>1)-1;n>=0;n--)this._down(n);};function e(t,e){return te?1:0}return t.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1);},t.prototype.pop=function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}},t.prototype.peek=function(){return this.data[0]},t.prototype._up=function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;},t.prototype._down=function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t=0)break;e[t]=a,t=s;}e[t]=i;},t}();var Dr=p(Br.exports),Cr=8192;function Rr(t,e){return e.dist-t.dist}const Lr=100,Vr=50;function Or(t){const e=[1/0,1/0,-1/0,-1/0];if(e.length!==t.length)return !1;for(let r=0;r=t[0]&&t[1]t[1])return [null,null];const r=Fr(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}{if(1===r)return [t,null];const e=Math.floor(r/2)-1;return [[t[0],t[0]+e],[t[0]+e+1,t[1]]]}}function Nr(t,e){const r=[1/0,1/0,-1/0,-1/0];if(!jr(e,t.length))return r;for(let n=e[0];n<=e[1];++n)hr(r,t[n]);return r}function $r(t){const e=[1/0,1/0,-1/0,-1/0];for(let r=0;re[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(pr(i,s)){if(tn(t,e))return 0}else if(tn(e,t))return 0;let a=n;for(const n of t)for(let t=0,i=n.length,s=i-1;t=s)continue;const u=i.range1;if(Fr(u)<=o){if(!jr(u,t.length))return NaN;if(e){const e=Qr(t,u,r,n);if(0===(s=Math.min(s,e)))return s}else for(let e=u[0];e<=u[1];++e){const i=Jr(t[e],r,n);if(0===(s=Math.min(s,i)))return s}}else {const r=Ur(u,e);if(null!==r[0]){const e=qr(Nr(t,r[0]),l,n);e=a)continue;const c=s.range1,h=s.range2;if(Fr(c)<=l&&Fr(h)<=u){if(!jr(c,t.length)||!jr(h,r.length))return NaN;if(e&&n?a=Math.min(a,Wr(t,c,r,h,i)):e||n?e&&!n?a=Math.min(a,Xr(r,h,t,c,i)):!e&&n&&(a=Math.min(a,Xr(t,c,r,h,i))):a=Math.min(a,Hr(t,c,r,h,i)),0===a)return a}else {const s=Ur(c,e),l=Ur(h,n);rn(o,a,i,t,r,s[0],l[0]),rn(o,a,i,t,r,s[0],l[1]),rn(o,a,i,t,r,s[1],l[0]),rn(o,a,i,t,r,s[1],l[1]);}}return a}function an(t,e,r,n,i=1/0){let s=i;const a=Nr(t,[0,t.length-1]);for(const i of r)if(!(s!==1/0&&qr(a,Nr(i,[0,i.length-1]),n)>=s)&&(s=Math.min(s,sn(t,e,i,!0,n,s)),0===s))return s;return s}function on(t,e,r,n,i=1/0){let s=i;const a=Nr(t,[0,t.length-1]);for(const i of r){if(s!==1/0&&qr(a,$r(i),n)>=s)continue;const r=nn(t,e,i,n,s);if(isNaN(r))return r;if(0===(s=Math.min(s,r)))return s}return s}function ln(t){return \"Point\"===t||\"MultiPoint\"===t||\"LineString\"===t||\"MultiLineString\"===t||\"Polygon\"===t||\"MultiPolygon\"===t}class un{constructor(t,e){this.type=fe,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires either one argument, but found ' ${t.length-1} instead.`);if(Ue(t[1])){const e=t[1];if(\"FeatureCollection\"===e.type){for(let t=0;t{e&&!hn(t)&&(e=!1);})),e}function pn(t){if(t instanceof ar&&\"feature-state\"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!pn(t)&&(e=!1);})),e}function fn(t){if(t instanceof ar&&\"config\"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!fn(t)&&(e=!1);})),e}function dn(t,e){if(t instanceof ar&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!dn(t,e)&&(r=!1);})),r}class mn{constructor(t,e){this.type=e.type,this.name=t,this.boundExpression=e;}static parse(t,e){if(2!==t.length||\"string\"!=typeof t[1])return e.error(\"'var' expression requires exactly one string literal argument.\");const r=t[1];return e.scope.has(r)?new mn(r,e.scope.get(r)):e.error(`Unknown variable \"${r}\". Make sure \"${r}\" has been bound in an enclosing \"let\" expression before using it.`,1)}evaluate(t){return this.boundExpression.evaluate(t)}eachChild(){}outputDefined(){return !1}serialize(){return [\"var\",this.name]}}var yn=mn;class gn{constructor(t,e=[],r,n=new he,i=[],s,a){this.registry=t,this.path=e,this.key=e.map((t=>`[${t}]`)).join(\"\"),this.scope=n,this.errors=i,this.expectedType=r,this._scope=s,this.options=a;}parse(t,e,r,n,i={}){return e||r?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return \"assert\"===r?new Ke(e,[t]):\"coerce\"===r?new er(e,[t]):t}if(null!==t&&\"string\"!=typeof t&&\"boolean\"!=typeof t&&\"number\"!=typeof t||(t=[\"literal\",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].');const n=\"string\"==typeof t[0]?this.registry[t[0]]:void 0;if(n){let i=n.parse(t,this);if(!i)return null;if(this.expectedType){const t=this.expectedType,n=i.type;if(\"string\"!==t.kind&&\"number\"!==t.kind&&\"boolean\"!==t.kind&&\"object\"!==t.kind&&\"array\"!==t.kind||\"value\"!==n.kind)if(\"color\"!==t.kind&&\"formatted\"!==t.kind&&\"resolvedImage\"!==t.kind||\"value\"!==n.kind&&\"string\"!==n.kind){if(this.checkSubtype(t,n))return null}else i=r(i,t,e.typeAnnotation||\"coerce\");else i=r(i,t,e.typeAnnotation||\"assert\");}if(!(i instanceof Ge)&&\"resolvedImage\"!==i.type.kind&&vn(i)){const t=new nr(this._scope,this.options);try{i=new Ge(i.type,i.evaluate(t));}catch(t){return this.error(t.message),null}}return i}return er.parse([\"to-array\",t],this)}return this.error(void 0===t?\"'undefined' value invalid. Use null instead.\":\"object\"==typeof t?'Bare objects invalid. Use [\"literal\", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n=\"number\"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new gn(this.registry,n,e||null,i,this.errors,this._scope,this.options)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join(\"\")}`;this.errors.push(new ue(r,t));}checkSubtype(t,e){const r=Se(t,e);return r&&this.error(r),r}}var xn=gn;function vn(t){if(t instanceof yn)return vn(t.boundExpression);if(t instanceof ar&&\"error\"===t.name)return !1;if(t instanceof ar&&\"config\"===t.name)return !1;if(t instanceof or)return !1;if(t instanceof Pr)return !1;if(t instanceof cn)return !1;const e=t instanceof er||t instanceof Ke;let r=!0;return t.eachChild((t=>{r=e?r&&vn(t):r&&t instanceof Ge;})),!!r&&hn(t)&&dn(t,[\"zoom\",\"heatmap-density\",\"line-progress\",\"raster-value\",\"sky-radial-progress\",\"accumulated\",\"is-supported-script\",\"pitch\",\"distance-from-center\",\"measure-light\"])}function bn(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ye(\"Input is not a number.\");a=o-1;}return 0}class _n{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error(\"Expected an even number of arguments.\");const r=e.parse(t[1],1,fe);if(!r)return null;const n=[];let i=null;e.expectedType&&\"value\"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for \"step\" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new _n(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[bn(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}serialize(){const t=[\"step\",this.input.serialize()];for(let e=0;e0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t}}var wn=_n;function Mn(t,e,r){return t*(1-r)+e*r}function An(t,e,r){return t.map(((t,n)=>Mn(t,e[n],r)))}var Sn=Object.freeze({__proto__:null,array:An,color:function(t,e,r){return new Re(Mn(t.r,e.r,r),Mn(t.g,e.g,r),Mn(t.b,e.b,r),Mn(t.a,e.a,r))},number:Mn});const In=.95047,kn=1.08883,Tn=4/29,Pn=6/29,zn=3*Pn*Pn,En=Pn*Pn*Pn,Bn=Math.PI/180,Dn=180/Math.PI;function Cn(t){return t>En?Math.pow(t,1/3):t/zn+Tn}function Rn(t){return t>Pn?t*t*t:zn*(t-Tn)}function Ln(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Vn(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function On(t){const e=Vn(t.r),r=Vn(t.g),n=Vn(t.b),i=Cn((.4124564*e+.3575761*r+.1804375*n)/In),s=Cn((.2126729*e+.7151522*r+.072175*n)/1);return {l:116*s-16,a:500*(i-s),b:200*(s-Cn((.0193339*e+.119192*r+.9503041*n)/kn)),alpha:t.a}}function Fn(t){let e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=1*Rn(e),r=In*Rn(r),n=kn*Rn(n),new Re(Ln(3.2404542*r-1.5371385*e-.4985314*n),Ln(-.969266*r+1.8760108*e+.041556*n),Ln(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}function jn(t,e,r){const n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}const Un={forward:On,reverse:Fn,interpolate:function(t,e,r){return {l:Mn(t.l,e.l,r),a:Mn(t.a,e.a,r),b:Mn(t.b,e.b,r),alpha:Mn(t.alpha,e.alpha,r)}}},Nn={forward:function(t){const{l:e,a:r,b:n}=On(t),i=Math.atan2(n,r)*Dn;return {h:i<0?i+360:i,c:Math.sqrt(r*r+n*n),l:e,alpha:t.a}},reverse:function(t){const e=t.h*Bn,r=t.c;return Fn({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return {h:jn(t.h,e.h,r),c:Mn(t.c,e.c,r),l:Mn(t.l,e.l,r),alpha:Mn(t.alpha,e.alpha,r)}}};var $n=Object.freeze({__proto__:null,hcl:Nn,lab:Un});class qn{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if(\"exponential\"===t.name)i=Gn(e,t.base,r,n);else if(\"linear\"===t.name)i=Gn(e,1,r,n);else if(\"cubic-bezier\"===t.name){const s=t.controlPoints;i=new m(s[0],s[1],s[2],s[3]).solve(Gn(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error(\"Expected an interpolation type expression.\",1);if(\"linear\"===n[0])n={name:\"linear\"};else if(\"exponential\"===n[0]){const t=n[1];if(\"number\"!=typeof t)return e.error(\"Exponential interpolation requires a numeric base.\",1,1);n={name:\"exponential\",base:t};}else {if(\"cubic-bezier\"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>\"number\"!=typeof t||t<0||t>1)))return e.error(\"Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.\",1);n={name:\"cubic-bezier\",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error(\"Expected an even number of arguments.\");if(i=e.parse(i,2,fe),!i)return null;const a=[];let o=null;\"interpolate-hcl\"===r||\"interpolate-lab\"===r?o=ye:e.expectedType&&\"value\"!==e.expectedType.kind&&(o=e.expectedType);for(let t=0;t=r)return e.error('Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return \"number\"===o.kind||\"color\"===o.kind||\"array\"===o.kind&&\"number\"===o.itemType.kind&&\"number\"==typeof o.N?new qn(o,r,n,i,a):e.error(`Type ${Me(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=bn(e,n),a=qn.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);return \"interpolate\"===this.operator?Sn[this.type.kind.toLowerCase()](o,l,a):\"interpolate-hcl\"===this.operator?Nn.reverse(Nn.interpolate(Nn.forward(o),Nn.forward(l),a)):Un.reverse(Un.interpolate(Un.forward(o),Un.forward(l),a))}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}serialize(){let t;t=\"linear\"===this.interpolation.name?[\"linear\"]:\"exponential\"===this.interpolation.name?1===this.interpolation.base?[\"linear\"]:[\"exponential\",this.interpolation.base]:[\"cubic-bezier\"].concat(this.interpolation.controlPoints);const e=[this.operator,t,this.input.serialize()];for(let t=0;tSe(n,t.type)));return new Zn(s?xe:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args){if(n++,r=i.evaluate(t),r&&r instanceof Fe&&!r.available&&(e||(e=r),r=null,n===this.args.length))return e;if(null!==r)break}return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}serialize(){const t=[\"coalesce\"];return this.eachChild((e=>{t.push(e.serialize());})),t}}var Xn=Zn;class Kn{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ye(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ye(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}serialize(){return [\"at\",this.index.serialize(),this.input.serialize()]}}var Jn=Hn;class Qn{constructor(t,e){this.type=me,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,xe),n=e.parse(t[2],2,xe);return r&&n?Ie(r.type,[me,de,fe,pe,xe])?new Qn(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Me(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(null==r)return !1;if(!ke(e,[\"boolean\",\"string\",\"number\",\"null\"]))throw new Ye(`Expected first argument to be of type boolean, string, number or null, but found ${Me(Ne(e))} instead.`);if(!ke(r,[\"string\",\"array\"]))throw new Ye(`Expected second argument to be of type array or string, but found ${Me(Ne(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}serialize(){return [\"in\",this.needle.serialize(),this.haystack.serialize()]}}var ti=Qn;class ei{constructor(t,e,r){this.type=fe,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,xe),n=e.parse(t[2],2,xe);if(!r||!n)return null;if(!Ie(r.type,[me,de,fe,pe,xe]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Me(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,fe);return i?new ei(r,n,i):null}return new ei(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!ke(e,[\"boolean\",\"string\",\"number\",\"null\"]))throw new Ye(`Expected first argument to be of type boolean, string, number or null, but found ${Me(Ne(e))} instead.`);if(!ke(r,[\"string\",\"array\"]))throw new Ye(`Expected second argument to be of type array or string, but found ${Me(Ne(r))} instead.`);if(this.fromIndex){const n=this.fromIndex.evaluate(t);return r.indexOf(e,n)}return r.indexOf(e)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}serialize(){if(null!=this.fromIndex&&void 0!==this.fromIndex){const t=this.fromIndex.serialize();return [\"index-of\",this.needle.serialize(),this.haystack.serialize(),t]}return [\"index-of\",this.needle.serialize(),this.haystack.serialize()]}}var ri=ei;class ni{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error(\"Expected an even number of arguments.\");let r,n;e.expectedType&&\"value\"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(\"number\"==typeof t&&Math.floor(t)!==t)return u.error(\"Numeric branch labels must be integer values.\");if(r){if(u.checkSubtype(r,Ne(t)))return null}else r=Ne(t);if(void 0!==i[String(t)])return u.error(\"Branch labels must be unique.\");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,xe);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?\"value\"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new ni(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ne(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}serialize(){const t=[\"match\",this.input.serialize()],e=Object.keys(this.cases).sort(),r=[],n={};for(const t of e){const e=n[this.cases[t]];void 0===e?(n[this.cases[t]]=r.length,r.push([this.cases[t],[t]])):r[e][1].push(t);}const i=t=>\"number\"===this.inputType.kind?Number(t):t;for(const[e,n]of r)t.push(1===n.length?i(n[0]):n.map(i)),t.push(this.outputs[e].serialize());return t.push(this.otherwise.serialize()),t}}var ii=ni;class si{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error(\"Expected an odd number of arguments.\");let r;e.expectedType&&\"value\"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}serialize(){const t=[\"case\"];return this.eachChild((e=>{t.push(e.serialize());})),t}}var ai=si;class oi{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,xe),n=e.parse(t[2],2,fe);if(!r||!n)return null;if(!Ie(r.type,[we(xe),de,xe]))return e.error(`Expected first argument to be of type array or string, but found ${Me(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,fe);return i?new oi(r.type,r,n,i):null}return new oi(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);if(!ke(e,[\"string\",\"array\"]))throw new Ye(`Expected first argument to be of type array or string, but found ${Me(Ne(e))} instead.`);if(this.endIndex){const n=this.endIndex.evaluate(t);return e.slice(r,n)}return e.slice(r)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}serialize(){if(null!=this.endIndex&&void 0!==this.endIndex){const t=this.endIndex.serialize();return [\"slice\",this.input.serialize(),this.beginIndex.serialize(),t]}return [\"slice\",this.input.serialize(),this.beginIndex.serialize()]}}var li=oi;function ui(t,e){return \"==\"===t||\"!=\"===t?\"boolean\"===e.kind||\"string\"===e.kind||\"number\"===e.kind||\"null\"===e.kind||\"value\"===e.kind:\"string\"===e.kind||\"number\"===e.kind||\"value\"===e.kind}function ci(t,e,r,n){return 0===n.compare(e,r)}function hi(t,e,r){const n=\"==\"!==t&&\"!=\"!==t;return class i{constructor(t,e,r){this.type=me,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument=\"value\"===t.type.kind||\"value\"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error(\"Expected two or three arguments.\");const r=t[0];let s=e.parse(t[1],1,xe);if(!s)return null;if(!ui(r,s.type))return e.concat(1).error(`\"${r}\" comparisons are not supported for type '${Me(s.type)}'.`);let a=e.parse(t[2],2,xe);if(!a)return null;if(!ui(r,a.type))return e.concat(2).error(`\"${r}\" comparisons are not supported for type '${Me(a.type)}'.`);if(s.type.kind!==a.type.kind&&\"value\"!==s.type.kind&&\"value\"!==a.type.kind)return e.error(`Cannot compare types '${Me(s.type)}' and '${Me(a.type)}'.`);n&&(\"value\"===s.type.kind&&\"value\"!==a.type.kind?s=new Ke(a.type,[s]):\"value\"!==s.type.kind&&\"value\"===a.type.kind&&(a=new Ke(s.type,[a])));let o=null;if(4===t.length){if(\"string\"!==s.type.kind&&\"string\"!==a.type.kind&&\"value\"!==s.type.kind&&\"value\"!==a.type.kind)return e.error(\"Cannot use collator to compare non-string types.\");if(o=e.parse(t[3],3,ve),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ne(s),r=Ne(a);if(e.kind!==r.kind||\"string\"!==e.kind&&\"number\"!==e.kind)throw new Ye(`Expected arguments for \"${t}\" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ne(s),r=Ne(a);if(\"string\"!==t.kind||\"string\"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}serialize(){const e=[t];return this.eachChild((t=>{e.push(t.serialize());})),e}}}const pi=hi(\"==\",(function(t,e,r){return e===r}),ci),fi=hi(\"!=\",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !ci(0,e,r,n)})),di=hi(\"<\",(function(t,e,r){return e\",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),yi=hi(\"<=\",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),gi=hi(\">=\",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class xi{constructor(t,e,r,n,i,s){this.type=de,this.number=t,this.locale=e,this.currency=r,this.unit=n,this.minFractionDigits=i,this.maxFractionDigits=s;}static parse(t,e){if(3!==t.length)return e.error(\"Expected two arguments.\");const r=e.parse(t[1],1,fe);if(!r)return null;const n=t[2];if(\"object\"!=typeof n||Array.isArray(n))return e.error(\"NumberFormat options argument must be an object.\");let i=null;if(n.locale&&(i=e.parse(n.locale,1,de),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,de),!s))return null;let a=null;if(n.unit&&(a=e.parse(n.unit,1,de),!a))return null;let o=null;if(n[\"min-fraction-digits\"]&&(o=e.parse(n[\"min-fraction-digits\"],1,fe),!o))return null;let l=null;return n[\"max-fraction-digits\"]&&(l=e.parse(n[\"max-fraction-digits\"],1,fe),!l)?null:new xi(r,i,s,a,o,l)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:(this.currency?\"currency\":this.unit&&\"unit\")||\"decimal\",currency:this.currency?this.currency.evaluate(t):void 0,unit:this.unit?this.unit.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.unit&&t(this.unit),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}serialize(){const t={};return this.locale&&(t.locale=this.locale.serialize()),this.currency&&(t.currency=this.currency.serialize()),this.unit&&(t.unit=this.unit.serialize()),this.minFractionDigits&&(t[\"min-fraction-digits\"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(t[\"max-fraction-digits\"]=this.maxFractionDigits.serialize()),[\"number-format\",this.number.serialize(),t]}}class vi{constructor(t){this.type=fe,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?\"array\"!==r.type.kind&&\"string\"!==r.type.kind&&\"value\"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Me(r.type)} instead.`):new vi(r):null}evaluate(t){const e=this.input.evaluate(t);if(\"string\"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new Ye(`Expected value to be of type string or array, but found ${Me(Ne(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}serialize(){const t=[\"length\"];return this.eachChild((e=>{t.push(e.serialize());})),t}}function bi(t){return function(){t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}const _i={\"==\":pi,\"!=\":fi,\">\":mi,\"<\":di,\">=\":gi,\"<=\":yi,array:Ke,at:Jn,boolean:Ke,case:ai,coalesce:Xn,collator:or,format:We,image:He,in:ti,\"index-of\":ri,interpolate:Yn,\"interpolate-hcl\":Yn,\"interpolate-lab\":Yn,length:vi,let:Wn,literal:Ge,match:ii,number:Ke,\"number-format\":xi,object:Ke,slice:li,step:wn,string:Ke,\"to-boolean\":er,\"to-color\":er,\"to-number\":er,\"to-string\":er,var:yn,within:Pr,distance:cn};function wi(t,[e,r,n,i]){e=e.evaluate(t),r=r.evaluate(t),n=n.evaluate(t);const s=i?i.evaluate(t):1,a=je(e,r,n,s);if(a)throw new Ye(a);return new Re(e/255*s,r/255*s,n/255*s,s)}function Mi(t,[e,r,n,i]){e=e.evaluate(t),r=r.evaluate(t),n=n.evaluate(t);const s=i?i.evaluate(t):1,a=function(t,e,r,n){return \"number\"==typeof t&&t>=0&&t<=360?\"number\"==typeof e&&e>=0&&e<=100&&\"number\"==typeof r&&r>=0&&r<=100?void 0===n||\"number\"==typeof n&&n>=0&&n<=1?null:`Invalid hsla value [${[t,e,r,n].join(\", \")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(\"number\"==typeof n?[t,e,r,n]:[t,e,r]).join(\", \")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(\"number\"==typeof n?[t,e,r,n]:[t,e,r]).join(\", \")}]: 'h' must be between 0 and 360.`}(e,r,n,s);if(a)throw new Ye(a);const o=`hsla(${e}, ${r}%, ${n}%, ${s})`,l=Re.parse(o);if(!l)throw new Ye(`Failed to parse HSLA color: ${o}`);return l}function Ai(t,e){return t in e}function Si(t,e){const r=e[t];return void 0===r?null:r}function Ii(t,e){switch(t){case\"string\":return String(e);case\"number\":return +e;case\"boolean\":return !!e;case\"color\":return Re.parse(e)}return e}function ki(t,e,r,n){return void 0!==n&&(t=n*Math.round(t/n)),void 0!==e&&tr&&(t=r),t}function Ti(t,e,r){e=[e,r,t.scope].filter(Boolean).join(\"\u001f\");const n=t.getConfig(e);if(!n)return null;const{type:i,value:s,values:a,minValue:o,maxValue:l,stepValue:u}=n,c=n.default.evaluate(t);let h=c;if(s){const e=t.scope;t.scope=(e||\"\").split(\"\u001f\").slice(1).join(\"\u001f\"),h=s.evaluate(t),t.scope=e;}return i&&(h=Ii(i,h)),void 0!==s&&void 0!==h&&a&&!a.includes(h)&&(h=c,i&&(h=Ii(i,h))),void 0===h||void 0===o&&void 0===l&&void 0===u||(\"number\"==typeof h?h=ki(h,o,l,u):Array.isArray(h)&&(h=h.map((t=>\"number\"==typeof t?ki(t,o,l,u):t)))),h}function Pi(t){return {type:t}}ar.register(_i,{error:[{kind:\"error\"},[de],(t,[e])=>{throw new Ye(e.evaluate(t))}],typeof:[de,[xe],(t,[e])=>Me(Ne(e.evaluate(t)))],\"to-rgba\":[we(fe,4),[ye],(t,[e])=>e.evaluate(t).toArray()],rgb:[ye,[fe,fe,fe],wi],rgba:[ye,[fe,fe,fe,fe],wi],hsl:[ye,[fe,fe,fe],Mi],hsla:[ye,[fe,fe,fe,fe],Mi],has:{type:me,overloads:[[[de],(t,[e])=>Ai(e.evaluate(t),t.properties())],[[de,ge],(t,[e,r])=>Ai(e.evaluate(t),r.evaluate(t))]]},get:{type:xe,overloads:[[[de],(t,[e])=>Si(e.evaluate(t),t.properties())],[[de,ge],(t,[e,r])=>Si(e.evaluate(t),r.evaluate(t))]]},config:{type:xe,overloads:[[[de],(t,[e])=>Ti(t,e.evaluate(t))],[[de,de],(t,[e,r])=>Ti(t,e.evaluate(t),r.evaluate(t))]]},\"feature-state\":[xe,[de],(t,[e])=>Si(e.evaluate(t),t.featureState||{})],properties:[ge,[],t=>t.properties()],\"geometry-type\":[de,[],t=>t.geometryType()],id:[xe,[],t=>t.id()],zoom:[fe,[],t=>t.globals.zoom],pitch:[fe,[],t=>t.globals.pitch||0],\"distance-from-center\":[fe,[],t=>t.distanceFromCenter()],\"measure-light\":[fe,[de],(t,[e])=>t.measureLight(e.evaluate(t))],\"heatmap-density\":[fe,[],t=>t.globals.heatmapDensity||0],\"line-progress\":[fe,[],t=>t.globals.lineProgress||0],\"raster-value\":[fe,[],t=>t.globals.rasterValue||0],\"sky-radial-progress\":[fe,[],t=>t.globals.skyRadialProgress||0],accumulated:[xe,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],\"+\":[fe,Pi(fe),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],\"*\":[fe,Pi(fe),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],\"-\":{type:fe,overloads:[[[fe,fe],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[fe],(t,[e])=>-e.evaluate(t)]]},\"/\":[fe,[fe,fe],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],\"%\":[fe,[fe,fe],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[fe,[],()=>Math.LN2],pi:[fe,[],()=>Math.PI],e:[fe,[],()=>Math.E],\"^\":[fe,[fe,fe],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[fe,[fe],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[fe,[fe],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[fe,[fe],(t,[e])=>Math.log(e.evaluate(t))],log2:[fe,[fe],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[fe,[fe],(t,[e])=>Math.sin(e.evaluate(t))],cos:[fe,[fe],(t,[e])=>Math.cos(e.evaluate(t))],tan:[fe,[fe],(t,[e])=>Math.tan(e.evaluate(t))],asin:[fe,[fe],(t,[e])=>Math.asin(e.evaluate(t))],acos:[fe,[fe],(t,[e])=>Math.acos(e.evaluate(t))],atan:[fe,[fe],(t,[e])=>Math.atan(e.evaluate(t))],min:[fe,Pi(fe),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[fe,Pi(fe),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[fe,[fe],(t,[e])=>Math.abs(e.evaluate(t))],round:[fe,[fe],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[fe,[fe],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[fe,[fe],(t,[e])=>Math.ceil(e.evaluate(t))],\"filter-==\":[me,[de,xe],(t,[e,r])=>t.properties()[e.value]===r.value],\"filter-id-==\":[me,[xe],(t,[e])=>t.id()===e.value],\"filter-type-==\":[me,[de],(t,[e])=>t.geometryType()===e.value],\"filter-<\":[me,[de,xe],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r\":[me,[de,xe],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],\"filter-id->\":[me,[xe],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],\"filter-<=\":[me,[de,xe],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],\"filter-id-<=\":[me,[xe],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],\"filter->=\":[me,[de,xe],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],\"filter-id->=\":[me,[xe],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],\"filter-has\":[me,[xe],(t,[e])=>e.value in t.properties()],\"filter-has-id\":[me,[],t=>null!==t.id()&&void 0!==t.id()],\"filter-type-in\":[me,[we(de)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],\"filter-id-in\":[me,[we(xe)],(t,[e])=>e.value.indexOf(t.id())>=0],\"filter-in-small\":[me,[de,we(xe)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],\"filter-in-large\":[me,[de,we(xe)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:me,overloads:[[[me,me],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Pi(me),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:me,overloads:[[[me,me],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Pi(me),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},\"!\":[me,[me],(t,[e])=>!e.evaluate(t)],\"is-supported-script\":[me,[de],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[de,[de],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[de,[de],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[de,Pi(xe),(t,e)=>e.map((e=>$e(e.evaluate(t)))).join(\"\")],\"resolved-locale\":[de,[ve],(t,[e])=>e.evaluate(t).resolvedLocale()],random:[fe,[fe,fe,xe],(t,e)=>{const[r,n,i]=e.map((e=>e.evaluate(t)));if(r>n)return r;if(r===n)return r;let s;if(\"string\"==typeof i)s=function(t){let e=0;if(0===t.length)return e;for(let r=0;r-1}function Ci(t){return \"data-driven\"===t[\"property-type\"]}function Ri(t){return Di(t.expression,\"measure-light\")}function Li(t){return Di(t.expression,\"zoom\")}function Vi(t){return !!t.expression&&t.expression.interpolated}function Oi(t){return \"object\"==typeof t&&null!==t&&!Array.isArray(t)}function Fi(t){return t}function ji(t,e){const r=\"color\"===e.type,n=t.stops&&\"object\"==typeof t.stops[0][0],i=n||!(n||void 0!==t.property),s=t.type||(Vi(e)?\"exponential\":\"interval\");if(r&&((t=se({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],Re.parse(t[1])]))),t.default=Re.parse(t.default?t.default:e.default)),t.colorSpace&&\"rgb\"!==t.colorSpace&&!$n[t.colorSpace])throw new Error(`Unknown color space: ${t.colorSpace}`);let a,o,l;if(\"exponential\"===s)a=qi;else if(\"interval\"===s)a=$i;else if(\"categorical\"===s){a=Ni,o=Object.create(null);for(const e of t.stops)o[e[0]]=e[1];l=typeof t.stops[0][0];}else {if(\"identity\"!==s)throw new Error(`Unknown function type \"${s}\"`);a=Gi;}if(n){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>qi({stops:i,base:t.base},e,r).evaluate(r,n)}}if(i){const r=\"exponential\"===s?{name:\"exponential\",base:void 0!==t.base?t.base:1}:null;return {kind:\"camera\",interpolationType:r,interpolationFactor:Yn.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>a(t,e,r,o,l)}}return {kind:\"source\",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Ui(t.default,e.default):a(t,e,i,o,l)}}}function Ui(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Ni(t,e,r,n,i){return Ui(typeof r===i?n[r]:void 0,t.default,e.default)}function $i(t,e,r){if(\"number\"!==Je(r))return Ui(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=bn(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function qi(t,e,r){const n=void 0!==t.base?t.base:1;if(\"number\"!==Je(r))return Ui(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=bn(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1];let u=Sn[e.type]||Fi;if(t.colorSpace&&\"rgb\"!==t.colorSpace){const e=$n[t.colorSpace];u=(t,r)=>e.reverse(e.interpolate(e.forward(t),e.forward(r),a));}return \"function\"==typeof o.evaluate?{evaluate(...t){const e=o.evaluate.apply(void 0,t),r=l.evaluate.apply(void 0,t);if(void 0!==e&&void 0!==r)return u(e,r,a)}}:u(o,l,a)}function Gi(t,e,r){return \"color\"===e.type?r=Re.parse(r):\"formatted\"===e.type?r=Oe.fromString(r.toString()):\"resolvedImage\"===e.type?r=Fe.fromString(r.toString()):Je(r)===e.type||\"enum\"===e.type&&e.values[r]||(r=void 0),Ui(r,t.default,e.default)}class Yi{constructor(t,e,r,n){this.expression=t,this._warningHistory={},this._evaluator=new nr(r,n),this._defaultValue=e?function(t){return \"color\"===t.type&&(Oi(t.default)||Array.isArray(t.default))?new Re(0,0,0,0):\"color\"===t.type?Re.parse(t.default)||null:void 0===t.default?null:t.default}(e):null,this._enumValues=e&&\"enum\"===e.type?e.values:null;}evaluateWithoutErrorHandling(t,e,r,n,i,s,a,o){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n||null,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this._evaluator.featureTileCoord=a||null,this._evaluator.featureDistanceData=o||null,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s,a,o){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n||null,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null,this._evaluator.featureTileCoord=a||null,this._evaluator.featureDistanceData=o||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||\"number\"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ye(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(\", \")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,\"undefined\"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function Zi(t){return Array.isArray(t)&&t.length>0&&\"string\"==typeof t[0]&&t[0]in zi}function Xi(t,e,r,n){const i=new xn(zi,[],e?function(t){const e={color:ye,string:de,number:fe,enum:de,boolean:me,formatted:be,resolvedImage:_e};return \"array\"===t.type?we(e[t.value]||xe,t.length):e[t.type]}(e):void 0,void 0,void 0,r,n),s=i.parse(t,void 0,void 0,void 0,e&&\"string\"===e.type?{typeAnnotation:\"coerce\"}:void 0);return s?Ei(new Yi(s,e,r,n)):Bi(i.errors)}class Ki{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isLightConstant=r,this.isStateDependent=\"constant\"!==t&&!pn(e.expression),this.isConfigDependent=!fn(e.expression);}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}}class Wi{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent=\"camera\"!==t&&!pn(e.expression),this.isLightConstant=i,this.isConfigDependent=!fn(e.expression),this.interpolationType=n;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?Yn.interpolationFactor(this.interpolationType,t,e,r):0}}function Hi(t,e,r,n){if(\"error\"===(t=Xi(t,e,r,n)).result)return t;const i=t.value.expression,s=hn(i);if(!s&&!Ci(e))return Bi([new ue(\"\",\"data expressions not supported\")]);const a=dn(i,[\"zoom\",\"pitch\",\"distance-from-center\"]);if(!a&&!Li(e))return Bi([new ue(\"\",\"zoom expressions not supported\")]);const o=dn(i,[\"measure-light\"]);if(!o&&!Ri(e))return Bi([new ue(\"\",\"measure-light expression not supported\")]);const l=e.expression&&e.expression.relaxZoomRestriction,u=Qi(i);return u||a||l?u instanceof ue?Bi([u]):u instanceof Yn&&!Vi(e)?Bi([new ue(\"\",'\"interpolate\" expressions cannot be used with this property')]):Ei(u?new Wi(s?\"camera\":\"composite\",t.value,u.labels,u instanceof Yn?u.interpolation:void 0,o):new Ki(s?\"constant\":\"source\",t.value,o)):Bi([new ue(\"\",'\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression, or in the properties of atmosphere.')])}class Ji{constructor(t,e){this._parameters=t,this._specification=e,se(this,ji(this._parameters,this._specification));}static deserialize(t){return new Ji(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function Qi(t){let e=null;if(t instanceof Wn)e=Qi(t.result);else if(t instanceof Xn){for(const r of t.args)if(e=Qi(r),e)break}else (t instanceof wn||t instanceof Yn)&&t.input instanceof ar&&\"zoom\"===t.input.name&&(e=t);return e instanceof ue||t.eachChild((t=>{const r=Qi(t);r instanceof ue?e=r:e&&r&&e!==r&&(e=new ue(\"\",'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.'));})),e}function ts(t){const e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},s=t.style,a=t.styleSpec;let o=[];const l=Je(r);if(\"object\"!==l)return [new ne(e,r,`object expected, ${l} found`)];for(const t in r){const l=t.split(\".\")[0];let u;i[l]?u=i[l]:n[l]?u=Ls:i[\"*\"]?u=i[\"*\"]:n[\"*\"]&&(u=Ls),u?o=o.concat(u({key:(e?`${e}.`:e)+t,value:r[t],valueSpec:n[l]||n[\"*\"],style:s,styleSpec:a,object:r,objectKey:t},r)):o.push(new ie(e,r[t],`unknown property \"${t}\"`));}for(const t in n)i[t]||n[t].required&&void 0===n[t].default&&void 0===r[t]&&o.push(new ne(e,r,`missing required property \"${t}\"`));return o}function es(t){const e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,s=t.key,a=t.arrayElementValidator||Ls;if(\"array\"!==Je(e))return [new ne(s,e,`array expected, ${Je(e)} found`)];if(r.length&&e.length!==r.length)return [new ne(s,e,`array length ${r.length} expected, length ${e.length} found`)];if(r[\"min-length\"]&&e.lengthi)return [new ne(e,r,`${r} is greater than the maximum value ${i}`)]}return []}function ns(t){const e=t.valueSpec,r=ae(t.value.type);let n,i,s,a={};const o=\"categorical\"!==r&&void 0===t.value.property,l=!o,u=\"array\"===Je(t.value.stops)&&\"array\"===Je(t.value.stops[0])&&\"object\"===Je(t.value.stops[0][0]),c=ts({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if(\"identity\"===r)return [new ne(t.key,t.value,'identity function may not have a \"stops\" property')];let e=[];const n=t.value;return e=e.concat(es({key:t.key,value:n,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),\"array\"===Je(n)&&0===n.length&&e.push(new ne(t.key,n,\"array must have at least one stop\")),e},default:function(t){return Ls({key:t.key,value:t.value,valueSpec:e,style:t.style,styleSpec:t.styleSpec})}}});return \"identity\"===r&&o&&c.push(new ne(t.key,t.value,'missing required property \"property\"')),\"identity\"===r||t.value.stops||c.push(new ne(t.key,t.value,'missing required property \"stops\"')),\"exponential\"===r&&t.valueSpec.expression&&!Vi(t.valueSpec)&&c.push(new ne(t.key,t.value,\"exponential functions not supported\")),t.styleSpec.$version>=8&&(l&&!Ci(t.valueSpec)?c.push(new ne(t.key,t.value,\"property functions not supported\")):o&&!Li(t.valueSpec)&&c.push(new ne(t.key,t.value,\"zoom functions not supported\"))),\"categorical\"!==r&&!u||void 0!==t.value.property||c.push(new ne(t.key,t.value,'\"property\" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if(\"array\"!==Je(n))return [new ne(o,n,`array expected, ${Je(n)} found`)];if(2!==n.length)return [new ne(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if(\"object\"!==Je(n[0]))return [new ne(o,n,`object expected, ${Je(n[0])} found`)];if(void 0===n[0].zoom)return [new ne(o,n,\"object stop key must have zoom\")];if(void 0===n[0].value)return [new ne(o,n,\"object stop key must have value\")];const e=ae(n[0].zoom);if(\"number\"!=typeof e)return [new ne(o,n[0].zoom,\"stop zoom values must be numbers\")];if(s&&s>e)return [new ne(o,n[0].zoom,\"stop zoom values must appear in ascending order\")];e!==s&&(s=e,i=void 0,a={}),r=r.concat(ts({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:rs,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},n));return Zi(oe(n[1]))?r.concat([new ne(`${o}[1]`,n[1],\"expressions are not allowed in function stops.\")]):r.concat(Ls({key:`${o}[1]`,value:n[1],valueSpec:e,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Je(t.value),l=ae(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new ne(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if(\"number\"!==o&&\"string\"!==o&&\"boolean\"!==o&&\"number\"!=typeof l&&\"string\"!=typeof l&&\"boolean\"!=typeof l)return [new ne(t.key,u,\"stop domain value must be a number, string, or boolean\")];if(\"number\"!==o&&\"categorical\"!==r){let n=`number expected, ${o} found`;return Ci(e)&&void 0===r&&(n+='\\nIf you intended to use a categorical function, specify `\"type\": \"categorical\"`.'),[new ne(t.key,u,n)]}return \"categorical\"!==r||\"number\"!==o||\"number\"==typeof l&&isFinite(l)&&Math.floor(l)===l?\"categorical\"!==r&&\"number\"===o&&\"number\"==typeof l&&\"number\"==typeof i&&void 0!==i&&lnew ne(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if(\"property\"===t.expressionContext&&\"text-font\"===t.propertyKey&&!r.outputDefined())return [new ne(t.key,t.value,`Invalid data expression for \"${t.propertyKey}\". Output values must be contained as literals within the expression.`)];if(\"property\"===t.expressionContext&&\"layout\"===t.propertyType&&!pn(r))return [new ne(t.key,t.value,'\"feature-state\" data expressions are not supported with layout properties.')];if(\"filter\"===t.expressionContext)return ss(r,t);if(t.expressionContext&&0===t.expressionContext.indexOf(\"cluster\")){if(!dn(r,[\"zoom\",\"feature-state\"]))return [new ne(t.key,t.value,'\"zoom\" and \"feature-state\" expressions are not supported with cluster properties.')];if(\"cluster-initial\"===t.expressionContext&&!hn(r))return [new ne(t.key,t.value,\"Feature data expressions are not supported with initial expression part of cluster properties.\")]}return []}function ss(t,e){const r=new Set([\"zoom\",\"feature-state\",\"pitch\",\"distance-from-center\"]);if(e.valueSpec&&e.valueSpec.expression)for(const t of e.valueSpec.expression.parameters)r.delete(t);if(0===r.size)return [];const n=[];return t instanceof ar&&r.has(t.name)?[new ne(e.key,e.value,`[\"${t.name}\"] expression is not supported in a filter for a ${e.object.type} layer with id: ${e.object.id}`)]:(t.eachChild((t=>{n.push(...ss(t,e));})),n)}function as(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(ae(r))&&i.push(new ne(e,r,`expected one of [${n.values.join(\", \")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(ae(r))&&i.push(new ne(e,r,`expected one of [${Object.keys(n.values).join(\", \")}], ${JSON.stringify(r)} found`)),i}function os(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case\"has\":return t.length>=2&&\"$id\"!==t[1]&&\"$type\"!==t[1];case\"in\":return t.length>=3&&(\"string\"!=typeof t[1]||Array.isArray(t[2]));case\"!in\":case\"!has\":case\"none\":return !1;case\"==\":case\"!=\":case\">\":case\">=\":case\"<\":case\"<=\":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case\"any\":case\"all\":for(const e of t.slice(1))if(!os(e)&&\"boolean\"!=typeof e)return !1;return !0;default:return !0}}function ls(t,e=\"fill\"){if(null==t)return {filter:()=>!0,needGeometry:!1,needFeature:!1};os(t)||(t=ms(t));const r=t;let n=!0;try{n=function(t){if(!hs(t))return t;let e=oe(t);return cs(e),e=us(e),e}(r);}catch(t){console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate.\\nThis is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md\\nand paste the contents of this message in the report.\\nThank you!\\nFilter Expression:\\n${JSON.stringify(r,null,2)}\\n `);}const i=re[`filter_${e}`],s=Xi(n,i);let a=null;if(\"error\"===s.result)throw new Error(s.value.map((t=>`${t.key}: ${t.message}`)).join(\", \"));a=(t,e,r)=>s.value.evaluate(t,e,{},r);let o=null,l=null;if(n!==r){const t=Xi(r,i);if(\"error\"===t.result)throw new Error(t.value.map((t=>`${t.key}: ${t.message}`)).join(\", \"));o=(e,r,n,i,s)=>t.value.evaluate(e,r,{},n,void 0,void 0,i,s),l=!hn(t.value.expression);}return {filter:a,dynamicFilter:o||void 0,needGeometry:ds(n),needFeature:!!l}}function us(t){if(!Array.isArray(t))return t;const e=function(t){if(ps.has(t[0]))for(let e=1;eus(t)))}function cs(t){let e=!1;const r=[];if(\"case\"===t[0]){for(let n=1;n\",\">=\",\"<\",\"<=\",\"to-boolean\"]);function fs(t,e){return te?1:0}function ds(t){if(!Array.isArray(t))return !1;if(\"within\"===t[0]||\"distance\"===t[0])return !0;for(let e=1;e\"===e||\"<=\"===e||\">=\"===e?ys(t[1],t[2],e):\"any\"===e?(r=t.slice(1),[\"any\"].concat(r.map(ms))):\"all\"===e?[\"all\"].concat(t.slice(1).map(ms)):\"none\"===e?[\"all\"].concat(t.slice(1).map(ms).map(vs)):\"in\"===e?gs(t[1],t.slice(2)):\"!in\"===e?vs(gs(t[1],t.slice(2))):\"has\"===e?xs(t[1]):\"!has\"!==e||vs(xs(t[1]));var r;}function ys(t,e,r){switch(t){case\"$type\":return [`filter-type-${r}`,e];case\"$id\":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function gs(t,e){if(0===e.length)return !1;switch(t){case\"$type\":return [\"filter-type-in\",[\"literal\",e]];case\"$id\":return [\"filter-id-in\",[\"literal\",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?[\"filter-in-large\",t,[\"literal\",e.sort(fs)]]:[\"filter-in-small\",t,[\"literal\",e]]}}function xs(t){switch(t){case\"$type\":return !0;case\"$id\":return [\"filter-has-id\"];default:return [\"filter-has\",t]}}function vs(t){return [\"!\",t]}function bs(t){return os(oe(t.value))?is(se({},t,{expressionContext:\"filter\",valueSpec:t.styleSpec[`filter_${t.layerType||\"fill\"}`]})):_s(t)}function _s(t){const e=t.value,r=t.key;if(\"array\"!==Je(e))return [new ne(r,e,`array expected, ${Je(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new ne(r,e,\"filter array must have at least 1 element\")];switch(s=s.concat(as({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),ae(e[0])){case\"<\":case\"<=\":case\">\":case\">=\":e.length>=2&&\"$type\"===ae(e[1])&&s.push(new ne(r,e,`\"$type\" cannot be use with operator \"${e[0]}\"`));case\"==\":case\"!=\":3!==e.length&&s.push(new ne(r,e,`filter array for operator \"${e[0]}\" must have 3 elements`));case\"in\":case\"!in\":e.length>=2&&(i=Je(e[1]),\"string\"!==i&&s.push(new ne(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new ne(n,r[t],`\"${t}\" is prohibited for ref layers`));})),i.layers.forEach((e=>{ae(e.id)===o&&(t=e);})),t?t.ref?e.push(new ne(n,r.ref,\"ref cannot reference another ref layer\")):a=ae(t.type):\"string\"==typeof o&&e.push(new ne(n,r.ref,`ref layer \"${o}\" not found`));}else if(\"background\"!==a&&\"sky\"!==a&&\"slot\"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&ae(t.type);t?\"vector\"===s&&\"raster\"===a?e.push(new ne(n,r.source,`layer \"${r.id}\" requires a raster source`)):\"raster\"===s&&\"raster\"!==a?e.push(new ne(n,r.source,`layer \"${r.id}\" requires a vector source`)):\"vector\"!==s||r[\"source-layer\"]?\"raster-dem\"===s&&\"hillshade\"!==a?e.push(new ne(n,r.source,\"raster-dem source can only be used with layer type 'hillshade'.\")):\"line\"!==a||!r.paint||!r.paint[\"line-gradient\"]&&!r.paint[\"line-trim-offset\"]||\"geojson\"===s&&t.lineMetrics||e.push(new ne(n,r,`layer \"${r.id}\" specifies a line-gradient, which requires a GeoJSON source with \\`lineMetrics\\` enabled.`)):e.push(new ne(n,r,`layer \"${r.id}\" must specify a \"source-layer\"`)):e.push(new ne(n,r.source,`source \"${r.source}\" not found`));}else e.push(new ne(n,r,'missing required property \"source\"'));return e=e.concat(ts({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{\"*\":()=>[],type:()=>Ls({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:\"type\"}),filter:t=>bs(se({layerType:a},t)),layout:t=>ts({layer:r,key:t.key,value:t.value,valueSpec:{},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{\"*\":t=>As(se({layerType:a},t))}}),paint:t=>ts({layer:r,key:t.key,value:t.value,valueSpec:{},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{\"*\":t=>Ms(se({layerType:a,layer:r},t))}})}})),e}function Is(t){const e=t.value,r=t.key,n=Je(e);return \"string\"!==n?[new ne(r,e,`string expected, ${n} found`)]:[]}const ks={promoteId:function({key:t,value:e}){if(\"string\"===Je(e))return Is({key:t,value:e});{const r=[];for(const n in e)r.push(...Is({key:`${t}.${n}`,value:e[n]}));return r}}};function Ts(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return [new ne(r,e,'\"type\" is required')];const s=ae(e.type);let a=[];switch([\"vector\",\"raster\",\"raster-dem\"].includes(s)&&(e.url||e.tiles||a.push(new ie(r,e,'Either \"url\" or \"tiles\" is required.'))),s){case\"vector\":case\"raster\":case\"raster-dem\":return a=a.concat(ts({key:r,value:e,valueSpec:n[`source_${s.replace(\"-\",\"_\")}`],style:t.style,styleSpec:n,objectElementValidators:ks})),a;case\"geojson\":if(a=ts({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,objectElementValidators:ks}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s=\"string\"==typeof n?[n,[\"accumulated\"],[\"get\",t]]:n;a.push(...is({key:`${r}.${t}.map`,value:i,expressionContext:\"cluster-map\"})),a.push(...is({key:`${r}.${t}.reduce`,value:s,expressionContext:\"cluster-reduce\"}));}return a;case\"video\":return ts({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case\"image\":return ts({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case\"canvas\":return [new ne(r,null,\"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.\",\"source.canvas\")];default:return as({key:`${r}.type`,value:e.type,valueSpec:{values:Ps(n)},style:i,styleSpec:n})}}function Ps(t){return t.source.reduce(((e,r)=>{const n=t[r];return \"enum\"===n.type.type&&(e=e.concat(Object.keys(n.type.values))),e}),[])}function zs(t){const e=t.value;let r=[];if(!e)return r;const n=Je(e);return \"string\"!==n?(r=r.concat([new ne(t.key,e,`string expected, \"${n}\" found`)]),r):(function(t){const e=-1===t.indexOf(\"://\");try{return new URL(t,e?\"http://example.com\":void 0),!0}catch(t){return !1}}(e)||(r=r.concat([new ne(t.key,e,`invalid url \"${e}\"`)])),r)}function Es(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Je(e);if(void 0===e)return s;if(\"object\"!==a)return s=s.concat([new ne(\"light\",e,`object expected, ${a} found`)]),s;for(const t in e){const a=t.match(/^(.*)-transition$/);s=s.concat(a&&n[a[1]]&&n[a[1]].transition?Ls({key:t,value:e[t],valueSpec:r.transition,style:i,styleSpec:r}):n[t]?Ls({key:t,value:e[t],valueSpec:n[t],style:i,styleSpec:r}):[new ne(t,e[t],`unknown property \"${t}\"`)]);}return s}function Bs(t){const e=t.value;let r=[];if(!e)return r;const n=Je(e);if(\"object\"!==n)return r=r.concat([new ne(\"light-3d\",e,`object expected, ${n} found`)]),r;const i=t.styleSpec,s=i[\"light-3d\"],a=t.key,o=t.style,l=t.style.lights;for(const t of [\"type\",\"id\"])if(!(t in e))return r=r.concat([new ne(\"light-3d\",e,`missing property ${t} on light`)]),r;if(e.type&&l)for(let n=0;n[],array:es,boolean:function(t){const e=t.value,r=t.key,n=Je(e);return \"boolean\"!==n?[new ne(r,e,`boolean expected, ${n} found`)]:[]},number:rs,color:function(t){const e=t.key,r=t.value,n=Je(r);return \"string\"!==n?[new ne(e,r,`color expected, ${n} found`)]:null===Te(r)?[new ne(e,r,`color expected, \"${r}\" found`)]:[]},enum:as,filter:bs,function:ns,layer:Ss,object:ts,source:Ts,model:zs,light:Es,\"light-3d\":Bs,terrain:Ds,fog:Cs,string:Is,formatted:function(t){return 0===Is(t).length?[]:is(t)},resolvedImage:function(t){return 0===Is(t).length?[]:is(t)},projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style;let s=[];const a=Je(e);if(\"object\"===a)for(const t in e)s=s.concat(Ls({key:t,value:e[t],valueSpec:n[t],style:i,styleSpec:r}));else \"string\"!==a&&(s=s.concat([new ne(\"projection\",e,`object or string expected, ${a} found`)]));return s},import:function(t){const{value:e,styleSpec:r}=t,{data:n,...i}=e;Object.defineProperty(i,\"__line__\",{value:e.__line__,enumerable:!1});let s=ts(se({},t,{value:i,valueSpec:r.import}));return \"\"===ae(i.id)&&s.push(new ne(`${t.key}.id`,i,\"import id can't be an empty string\")),n&&(s=s.concat(Os(n,r,{key:`${t.key}.data`}))),s}};function Ls(t,e=!1){const r=t.value,n=t.valueSpec,i=t.styleSpec;if(n.expression&&Oi(ae(r)))return ns(t);if(n.expression&&Zi(oe(r)))return is(t);if(n.type&&Rs[n.type]){const r=Rs[n.type](t);return !0===e&&r.length>0&&\"array\"===Je(t.value)?is(t):r}return ts(se({},t,{valueSpec:n.type?i[n.type]:n}))}function Vs(t){const e=t.value,r=t.key,n=Is(t);return n.length||(-1===e.indexOf(\"{fontstack}\")&&n.push(new ne(r,e,'\"glyphs\" url must include a \"{fontstack}\" token')),-1===e.indexOf(\"{range}\")&&n.push(new ne(r,e,'\"glyphs\" url must include a \"{range}\" token'))),n}function Os(t,e=re,r={}){return Ls({key:r.key||\"\",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:Vs,\"*\":()=>[]}})}function Fs(t,e=re){return Ns(Os(t,e))}const js=t=>Ns(Ms(t)),Us=t=>Ns(As(t));function Ns(t){return t.slice().sort(((t,e)=>t.line&&e.line?t.line-e.line:0))}function $s(t,e){let r=!1;if(e&&e.length)for(const n of e)n instanceof ie?q(n.message):(t.fire(new te(new Error(n.message))),r=!0);return r}var qs=Ys,Gs=3;function Ys(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(var s=0;s=c[f+0]&&n>=c[f+1])?(a[p]=!0,s.push(u[p])):a[p]=!1;}}},Ys.prototype._forEachCell=function(t,e,r,n,i,s,a,o){for(var l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n),p=l;p<=c;p++)for(var f=u;f<=h;f++){var d=this.d*f+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(f),this._convertFromCellCoord(p+1),this._convertFromCellCoord(f+1)))&&i.call(this,t,e,r,n,d,s,a,o))return}},Ys.prototype._convertFromCellCoord=function(t){return (t-this.padding)/this.scale},Ys.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},Ys.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=Gs+this.cells.length+1+1,r=0,n=0;n=0||(i[r]=Js(t[r],e)));t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error(\"$name property is reserved for worker serialization logic.\");return \"Object\"!==n&&(i.$name=n),i}throw new Error(\"can't serialize object of type \"+typeof t)}function Qs(t){if(null==t||\"boolean\"==typeof t||\"number\"==typeof t||\"string\"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||Ws(t)||Hs(t)||ArrayBuffer.isView(t)||t instanceof ImageData)return t;if(Array.isArray(t))return t.map(Qs);if(\"object\"==typeof t){const e=t.$name||\"Object\";if(\"Map\"===e){const e=new Map;for(const r of Object.keys(t))\"$name\"!==r&&e.set(r,Qs(t[r]));return e}const{klass:r}=Xs[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const e of Object.keys(t))\"$name\"!==e&&(n[e]=Qs(t[e]));return n}throw new Error(\"can't deserialize object of type \"+typeof t)}const ta={\"Latin-1 Supplement\":t=>t>=128&&t<=255,Arabic:t=>t>=1536&&t<=1791,\"Arabic Supplement\":t=>t>=1872&&t<=1919,\"Arabic Extended-A\":t=>t>=2208&&t<=2303,\"Hangul Jamo\":t=>t>=4352&&t<=4607,\"Unified Canadian Aboriginal Syllabics\":t=>t>=5120&&t<=5759,Khmer:t=>t>=6016&&t<=6143,\"Unified Canadian Aboriginal Syllabics Extended\":t=>t>=6320&&t<=6399,\"General Punctuation\":t=>t>=8192&&t<=8303,\"Letterlike Symbols\":t=>t>=8448&&t<=8527,\"Number Forms\":t=>t>=8528&&t<=8591,\"Miscellaneous Technical\":t=>t>=8960&&t<=9215,\"Control Pictures\":t=>t>=9216&&t<=9279,\"Optical Character Recognition\":t=>t>=9280&&t<=9311,\"Enclosed Alphanumerics\":t=>t>=9312&&t<=9471,\"Geometric Shapes\":t=>t>=9632&&t<=9727,\"Miscellaneous Symbols\":t=>t>=9728&&t<=9983,\"Miscellaneous Symbols and Arrows\":t=>t>=11008&&t<=11263,\"CJK Radicals Supplement\":t=>t>=11904&&t<=12031,\"Kangxi Radicals\":t=>t>=12032&&t<=12255,\"Ideographic Description Characters\":t=>t>=12272&&t<=12287,\"CJK Symbols and Punctuation\":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Bopomofo:t=>t>=12544&&t<=12591,\"Hangul Compatibility Jamo\":t=>t>=12592&&t<=12687,Kanbun:t=>t>=12688&&t<=12703,\"Bopomofo Extended\":t=>t>=12704&&t<=12735,\"CJK Strokes\":t=>t>=12736&&t<=12783,\"Katakana Phonetic Extensions\":t=>t>=12784&&t<=12799,\"Enclosed CJK Letters and Months\":t=>t>=12800&&t<=13055,\"CJK Compatibility\":t=>t>=13056&&t<=13311,\"CJK Unified Ideographs Extension A\":t=>t>=13312&&t<=19903,\"Yijing Hexagram Symbols\":t=>t>=19904&&t<=19967,\"CJK Unified Ideographs\":t=>t>=19968&&t<=40959,\"Yi Syllables\":t=>t>=40960&&t<=42127,\"Yi Radicals\":t=>t>=42128&&t<=42191,\"Hangul Jamo Extended-A\":t=>t>=43360&&t<=43391,\"Hangul Syllables\":t=>t>=44032&&t<=55215,\"Hangul Jamo Extended-B\":t=>t>=55216&&t<=55295,\"Private Use Area\":t=>t>=57344&&t<=63743,\"CJK Compatibility Ideographs\":t=>t>=63744&&t<=64255,\"Arabic Presentation Forms-A\":t=>t>=64336&&t<=65023,\"Vertical Forms\":t=>t>=65040&&t<=65055,\"CJK Compatibility Forms\":t=>t>=65072&&t<=65103,\"Small Form Variants\":t=>t>=65104&&t<=65135,\"Arabic Presentation Forms-B\":t=>t>=65136&&t<=65279,\"Halfwidth and Fullwidth Forms\":t=>t>=65280&&t<=65519,\"CJK Unified Ideographs Extension B\":t=>t>=131072&&t<=173791};function ea(t){for(const e of t)if(ia(e.charCodeAt(0)))return !0;return !1}function ra(t){for(const e of t)if(!na(e.charCodeAt(0)))return !1;return !0}function na(t){return !(ta.Arabic(t)||ta[\"Arabic Supplement\"](t)||ta[\"Arabic Extended-A\"](t)||ta[\"Arabic Presentation Forms-A\"](t)||ta[\"Arabic Presentation Forms-B\"](t))}function ia(t){return !(746!==t&&747!==t&&(t<4352||!(ta[\"Bopomofo Extended\"](t)||ta.Bopomofo(t)||ta[\"CJK Compatibility Forms\"](t)&&!(t>=65097&&t<=65103)||ta[\"CJK Compatibility Ideographs\"](t)||ta[\"CJK Compatibility\"](t)||ta[\"CJK Radicals Supplement\"](t)||ta[\"CJK Strokes\"](t)||!(!ta[\"CJK Symbols and Punctuation\"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||ta[\"CJK Unified Ideographs Extension A\"](t)||ta[\"CJK Unified Ideographs\"](t)||ta[\"Enclosed CJK Letters and Months\"](t)||ta[\"Hangul Compatibility Jamo\"](t)||ta[\"Hangul Jamo Extended-A\"](t)||ta[\"Hangul Jamo Extended-B\"](t)||ta[\"Hangul Jamo\"](t)||ta[\"Hangul Syllables\"](t)||ta.Hiragana(t)||ta[\"Ideographic Description Characters\"](t)||ta.Kanbun(t)||ta[\"Kangxi Radicals\"](t)||ta[\"Katakana Phonetic Extensions\"](t)||ta.Katakana(t)&&12540!==t||!(!ta[\"Halfwidth and Fullwidth Forms\"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!ta[\"Small Form Variants\"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||ta[\"Unified Canadian Aboriginal Syllabics\"](t)||ta[\"Unified Canadian Aboriginal Syllabics Extended\"](t)||ta[\"Vertical Forms\"](t)||ta[\"Yijing Hexagram Symbols\"](t)||ta[\"Yi Syllables\"](t)||ta[\"Yi Radicals\"](t))))}function sa(t){return !(ia(t)||function(t){return !!(ta[\"Latin-1 Supplement\"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||ta[\"General Punctuation\"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||ta[\"Letterlike Symbols\"](t)||ta[\"Number Forms\"](t)||ta[\"Miscellaneous Technical\"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||ta[\"Control Pictures\"](t)&&9251!==t||ta[\"Optical Character Recognition\"](t)||ta[\"Enclosed Alphanumerics\"](t)||ta[\"Geometric Shapes\"](t)||ta[\"Miscellaneous Symbols\"](t)&&!(t>=9754&&t<=9759)||ta[\"Miscellaneous Symbols and Arrows\"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||ta[\"CJK Symbols and Punctuation\"](t)||ta.Katakana(t)||ta[\"Private Use Area\"](t)||ta[\"CJK Compatibility Forms\"](t)||ta[\"Small Form Variants\"](t)||ta[\"Halfwidth and Fullwidth Forms\"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function aa(t){return t>=1424&&t<=2303||ta[\"Arabic Presentation Forms-A\"](t)||ta[\"Arabic Presentation Forms-B\"](t)}function oa(t,e){return !(!e&&aa(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||ta.Khmer(t))}function la(t){for(const e of t)if(aa(e.charCodeAt(0)))return !0;return !1}const ua=\"deferred\",ca=\"loading\",ha=\"loaded\";let pa=null,fa=\"unavailable\",da=null;const ma=function(t){t&&\"string\"==typeof t&&t.indexOf(\"NetworkError\")>-1&&(fa=\"error\"),pa&&pa(t);};function ya(){ga.fire(new Qt(\"pluginStateChange\",{pluginStatus:fa,pluginURL:da}));}const ga=new ee,xa=function(){return fa},va=function(){if(fa!==ua||!da)throw new Error(\"rtl-text-plugin cannot be downloaded unless a pluginURL is specified\");fa=ca,ya(),da&&dt({url:da},(t=>{t?ma(t):(fa=ha,ya());}));},ba={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>fa===ha||null!=ba.applyArabicShaping,isLoading:()=>fa===ca,setState(t){fa=t.pluginStatus,da=t.pluginURL;},isParsed:()=>null!=ba.applyArabicShaping&&null!=ba.processBidirectionalText&&null!=ba.processStyledBidirectionalText,getPluginURL:()=>da};class _a{constructor(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.transition=e.transition,this.pitch=e.pitch,this.brightness=e.brightness):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0);}isSupportedScript(t){return function(t,e){for(const r of t)if(!oa(r.charCodeAt(0),e))return !1;return !0}(t,ba.isLoaded())}}class wa{constructor(t,e,r,n){this.property=t,this.value=e,this.expression=function(t,e,r,n){if(Oi(t))return new Ji(t,e);if(Zi(t)||Array.isArray(t)&&t.length>0){const i=Hi(t,e,r,n);if(\"error\"===i.result)throw new Error(i.value.map((t=>`${t.key}: ${t.message}`)).join(\", \"));return i.value}{let r=t;return \"string\"==typeof t&&\"color\"===e.type&&(r=Re.parse(t)),{kind:\"constant\",isConfigDependent:!1,evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r,n);}isDataDriven(){return \"source\"===this.expression.kind||\"composite\"===this.expression.kind}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Ma{constructor(t,e,r){this.property=t,this.value=new wa(t,void 0,e,r);}transitioned(t,e){return new Sa(this.property,this.value,e,B({},t.transition,this.transition),t.now)}untransitioned(){return new Sa(this.property,this.value,null,{},0)}}class Aa{constructor(t,e,r){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._scope=e,this._options=r,this.isConfigDependent=!1;}getValue(t){return N(this._values[t].value.value)}setValue(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Ma(this._values[t].property,this._scope,this._options)),this._values[t].value=new wa(this._values[t].property,null===e?void 0:N(e),this._scope,this._options),this.isConfigDependent=this.isConfigDependent||this._values[t].value.expression.isConfigDependent;}setTransitionOrValue(t,e){e&&(this._options=e);const r=this._properties.properties;if(t)for(const e in t){const n=t[e];if(F(e,\"-transition\")){const t=e.slice(0,-11);r[t]&&this.setTransition(t,n);}else r[e]&&this.setValue(e,n);}}getTransition(t){return N(this._values[t].transition)}setTransition(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new Ma(this._values[t].property)),this._values[t].transition=N(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Ia(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Ia(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Sa{constructor(t,e,r,n,i){const s=n.delay||0,a=n.duration||0;i=i||0,this.property=t,this.value=e,this.begin=i+s,this.end=this.begin+a,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.isConfigDependent=!1,\"custom\"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,\"background\"!==t.type&&\"sky\"!==t.type&&\"slot\"!==t.type&&(this.source=t.source,this.sourceLayer=t[\"source-layer\"],this.filter=t.filter),t.slot&&(this.slot=t.slot),e.layout&&(this._unevaluatedLayout=new ka(e.layout,this.scope,n),this.isConfigDependent=this.isConfigDependent||this._unevaluatedLayout.isConfigDependent),e.paint)){this._transitionablePaint=new Aa(e.paint,this.scope,n);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this.isConfigDependent=this.isConfigDependent||this._transitionablePaint.isConfigDependent,this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Pa(e.paint);}}getLayoutProperty(t){return \"visibility\"===t?this.visibility:this._unevaluatedLayout.getValue(t)}setLayoutProperty(t,e,r={}){if(null!=e&&this._validate(Us,`layers.${this.id}.layout.${t}`,t,e,r))return;if(\"custom\"===this.type&&\"visibility\"===t)return void(this.visibility=e);const n=this._unevaluatedLayout;n._properties.properties[t]&&(n.setValue(t,e),this.isConfigDependent=this.isConfigDependent||n.isConfigDependent,\"visibility\"===t&&this.possiblyEvaluateVisibility());}possiblyEvaluateVisibility(){this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0});}getPaintProperty(t){return F(t,La)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(js,`layers.${this.id}.paint.${t}`,t,e,r))return !1;const n=this._transitionablePaint,i=n._properties.properties;if(F(t,La)){const r=t.slice(0,-11);return i[r]&&n.setTransition(r,e||void 0),!1}if(!i[t])return !1;const s=n._values[t],a=s.value.isDataDriven(),o=s.value;n.setValue(t,e),this.isConfigDependent=this.isConfigDependent||n.isConfigDependent,this._handleSpecialPaintPropertyUpdate(t);const l=n._values[t].value,u=l.isDataDriven(),c=F(t,\"pattern\")||\"line-dasharray\"===t;return u||a||c||this._handleOverridablePaintPropertyUpdate(t,o,l)}_handleSpecialPaintPropertyUpdate(t){}getProgramIds(){return null}getDefaultProgramParams(t,e){return null}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||\"none\"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){return U({id:this.id,type:this.type,slot:this.slot,source:this.source,\"source-layer\":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()},((t,e)=>!(void 0===t||\"layout\"===e&&!Object.keys(t).length||\"paint\"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&$s(this,t.call(Fs,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:re,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isSky(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}hasShadowPass(){return !1}canCastShadows(){return !1}hasLightBeamPass(){return !1}cutoffRange(){return 0}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Ta&&Ci(e.property.specification)&&(\"source\"===e.value.kind||\"composite\"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}compileFilter(){this._filterCompiled||(this._featureFilter=ls(this.filter),this._filterCompiled=!0);}invalidateCompiledFilter(){this._filterCompiled=!1;}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(){this._stats&&(this._stats.numRenderedVerticesInShadowPass=0,this._stats.numRenderedVerticesInTransparentPass=0);}}const Oa={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Fa{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class ja{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.add(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error(\"_refreshViews() must be implemented by each concrete StructArray layout\")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null;}}function Ua(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Oa[t.type].BYTES_PER_ELEMENT,s=r=Na(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Na(r,Math.max(n,e)),alignment:e}}function Na(t,e){return Math.ceil(t/e)*e}class $a extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}$a.prototype.bytesPerElement=4,Ks($a,\"StructArrayLayout2i4\");class qa extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}qa.prototype.bytesPerElement=6,Ks(qa,\"StructArrayLayout3i6\");class Ga extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ga.prototype.bytesPerElement=8,Ks(Ga,\"StructArrayLayout4i8\");class Ya extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=5*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,this.int16[a+4]=s,t}}Ya.prototype.bytesPerElement=10,Ks(Ya,\"StructArrayLayout5i10\");class Za extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s,a)}emplace(t,e,r,n,i,s,a,o){const l=6*t,u=12*t,c=3*t;return this.int16[l+0]=e,this.int16[l+1]=r,this.uint8[u+4]=n,this.uint8[u+5]=i,this.uint8[u+6]=s,this.uint8[u+7]=a,this.float32[c+2]=o,t}}Za.prototype.bytesPerElement=12,Ks(Za,\"StructArrayLayout2i4ub1f12\");class Xa extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}Xa.prototype.bytesPerElement=16,Ks(Xa,\"StructArrayLayout4f16\");class Ka extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=6*t,o=3*t;return this.uint16[a+0]=e,this.uint16[a+1]=r,this.uint16[a+2]=n,this.uint16[a+3]=i,this.float32[o+2]=s,t}}Ka.prototype.bytesPerElement=12,Ks(Ka,\"StructArrayLayout4ui1f12\");class Wa extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.uint16[s+0]=e,this.uint16[s+1]=r,this.uint16[s+2]=n,this.uint16[s+3]=i,t}}Wa.prototype.bytesPerElement=8,Ks(Wa,\"StructArrayLayout4ui8\");class Ha extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Ha.prototype.bytesPerElement=12,Ks(Ha,\"StructArrayLayout6i12\");class Ja extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}Ja.prototype.bytesPerElement=24,Ks(Ja,\"StructArrayLayout4i4ui4i24\");class Qa extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=10*t,l=5*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.float32[l+2]=i,this.float32[l+3]=s,this.float32[l+4]=a,t}}Qa.prototype.bytesPerElement=20,Ks(Qa,\"StructArrayLayout3i3f20\");class to extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}to.prototype.bytesPerElement=4,Ks(to,\"StructArrayLayout1ul4\");class eo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}eo.prototype.bytesPerElement=4,Ks(eo,\"StructArrayLayout2ui4\");class ro extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=this.length;return this.resize(f+1),this.emplace(f,t,e,r,n,i,s,a,o,l,u,c,h,p)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f){const d=20*t,m=10*t;return this.int16[d+0]=e,this.int16[d+1]=r,this.int16[d+2]=n,this.int16[d+3]=i,this.int16[d+4]=s,this.float32[m+3]=a,this.float32[m+4]=o,this.float32[m+5]=l,this.float32[m+6]=u,this.int16[d+14]=c,this.uint32[m+8]=h,this.uint16[d+18]=p,this.uint16[d+19]=f,t}}ro.prototype.bytesPerElement=40,Ks(ro,\"StructArrayLayout5i4f1i1ul2ui40\");class no extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s,a)}emplace(t,e,r,n,i,s,a,o){const l=8*t;return this.int16[l+0]=e,this.int16[l+1]=r,this.int16[l+2]=n,this.int16[l+4]=i,this.int16[l+5]=s,this.int16[l+6]=a,this.int16[l+7]=o,t}}no.prototype.bytesPerElement=16,Ks(no,\"StructArrayLayout3i2i2i16\");class io extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}io.prototype.bytesPerElement=16,Ks(io,\"StructArrayLayout2f1f2i16\");class so extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=12*t,a=3*t;return this.uint8[s+0]=e,this.uint8[s+1]=r,this.float32[a+1]=n,this.float32[a+2]=i,t}}so.prototype.bytesPerElement=12,Ks(so,\"StructArrayLayout2ub2f12\");class ao extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ao.prototype.bytesPerElement=6,Ks(ao,\"StructArrayLayout3ui6\");class oo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b){const _=this.length;return this.resize(_+1),this.emplace(_,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b,_){const w=30*t,M=15*t,A=60*t;return this.int16[w+0]=e,this.int16[w+1]=r,this.int16[w+2]=n,this.float32[M+2]=i,this.float32[M+3]=s,this.uint16[w+8]=a,this.uint16[w+9]=o,this.uint32[M+5]=l,this.uint32[M+6]=u,this.uint32[M+7]=c,this.uint16[w+16]=h,this.uint16[w+17]=p,this.uint16[w+18]=f,this.float32[M+10]=d,this.float32[M+11]=m,this.uint8[A+48]=y,this.uint8[A+49]=g,this.uint8[A+50]=x,this.uint32[M+13]=v,this.int16[w+28]=b,this.uint8[A+58]=_,t}}oo.prototype.bytesPerElement=60,Ks(oo,\"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60\");class lo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b,_,w,M,A,S,I,k,T,P,z,E){const B=this.length;return this.resize(B+1),this.emplace(B,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b,_,w,M,A,S,I,k,T,P,z,E)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b,_,w,M,A,S,I,k,T,P,z,E,B){const D=20*t,C=40*t,R=80*t;return this.float32[D+0]=e,this.float32[D+1]=r,this.int16[C+4]=n,this.int16[C+5]=i,this.int16[C+6]=s,this.int16[C+7]=a,this.int16[C+8]=o,this.int16[C+9]=l,this.int16[C+10]=u,this.int16[C+11]=c,this.int16[C+12]=h,this.uint16[C+13]=p,this.uint16[C+14]=f,this.uint16[C+15]=d,this.uint16[C+16]=m,this.uint16[C+17]=y,this.uint16[C+18]=g,this.uint16[C+19]=x,this.uint16[C+20]=v,this.uint16[C+21]=b,this.uint16[C+22]=_,this.uint16[C+23]=w,this.uint16[C+24]=M,this.uint16[C+25]=A,this.uint16[C+26]=S,this.uint16[C+27]=I,this.uint32[D+14]=k,this.float32[D+15]=T,this.float32[D+16]=P,this.float32[D+17]=z,this.float32[D+18]=E,this.uint8[R+76]=B,t}}lo.prototype.bytesPerElement=80,Ks(lo,\"StructArrayLayout2f9i15ui1ul4f1ub80\");class uo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}uo.prototype.bytesPerElement=4,Ks(uo,\"StructArrayLayout1f4\");class co extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=5*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.float32[a+3]=i,this.float32[a+4]=s,t}}co.prototype.bytesPerElement=20,Ks(co,\"StructArrayLayout5f20\");class ho extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s,a)}emplace(t,e,r,n,i,s,a,o){const l=7*t;return this.float32[l+0]=e,this.float32[l+1]=r,this.float32[l+2]=n,this.float32[l+3]=i,this.float32[l+4]=s,this.float32[l+5]=a,this.float32[l+6]=o,t}}ho.prototype.bytesPerElement=28,Ks(ho,\"StructArrayLayout7f28\");class po extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=6*t;return this.uint32[3*t+0]=e,this.uint16[s+2]=r,this.uint16[s+3]=n,this.uint16[s+4]=i,t}}po.prototype.bytesPerElement=12,Ks(po,\"StructArrayLayout1ul3ui12\");class fo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}fo.prototype.bytesPerElement=2,Ks(fo,\"StructArrayLayout1ui2\");class mo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}mo.prototype.bytesPerElement=12,Ks(mo,\"StructArrayLayout3f12\");class yo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}yo.prototype.bytesPerElement=8,Ks(yo,\"StructArrayLayout2f8\");class go extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m){const y=this.length;return this.resize(y+1),this.emplace(y,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y){const g=16*t;return this.float32[g+0]=e,this.float32[g+1]=r,this.float32[g+2]=n,this.float32[g+3]=i,this.float32[g+4]=s,this.float32[g+5]=a,this.float32[g+6]=o,this.float32[g+7]=l,this.float32[g+8]=u,this.float32[g+9]=c,this.float32[g+10]=h,this.float32[g+11]=p,this.float32[g+12]=f,this.float32[g+13]=d,this.float32[g+14]=m,this.float32[g+15]=y,t}}go.prototype.bytesPerElement=64,Ks(go,\"StructArrayLayout16f64\");class xo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s,a)}emplace(t,e,r,n,i,s,a,o){const l=10*t,u=5*t;return this.uint16[l+0]=e,this.uint16[l+1]=r,this.uint16[l+2]=n,this.uint16[l+3]=i,this.float32[u+2]=s,this.float32[u+3]=a,this.float32[u+4]=o,t}}xo.prototype.bytesPerElement=20,Ks(xo,\"StructArrayLayout4ui3f20\");class vo extends ja{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint8[1*t+0]=e,t}}vo.prototype.bytesPerElement=1,Ks(vo,\"StructArrayLayout1ub1\");class bo extends Fa{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.int16[this._pos2+3]}get tileAnchorY(){return this._structArray.int16[this._pos2+4]}get x1(){return this._structArray.float32[this._pos4+3]}get y1(){return this._structArray.float32[this._pos4+4]}get x2(){return this._structArray.float32[this._pos4+5]}get y2(){return this._structArray.float32[this._pos4+6]}get padding(){return this._structArray.int16[this._pos2+14]}get featureIndex(){return this._structArray.uint32[this._pos4+8]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+18]}get bucketIndex(){return this._structArray.uint16[this._pos2+19]}}bo.prototype.size=40;class _o extends ro{get(t){return new bo(this,t)}}Ks(_o,\"CollisionBoxArray\");class wo extends Fa{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(t){this._structArray.uint8[this._pos1+49]=t;}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(t){this._structArray.uint8[this._pos1+50]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(t){this._structArray.uint32[this._pos4+13]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(t){this._structArray.uint8[this._pos1+58]=t;}}wo.prototype.size=60;class Mo extends oo{get(t){return new wo(this,t)}}Ks(Mo,\"PlacedSymbolArray\");class Ao extends Fa{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(t){this._structArray.uint32[this._pos4+14]=t;}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(t){this._structArray.float32[this._pos4+18]=t;}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}}Ao.prototype.size=80;class So extends lo{get(t){return new Ao(this,t)}}Ks(So,\"SymbolInstanceArray\");class Io extends uo{getoffsetX(t){return this.float32[1*t+0]}}Ks(Io,\"GlyphOffsetArray\");class ko extends $a{getx(t){return this.int16[2*t+0]}gety(t){return this.int16[2*t+1]}}Ks(ko,\"SymbolLineVertexArray\");class To extends Fa{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}get layoutVertexArrayOffset(){return this._structArray.uint16[this._pos2+4]}}To.prototype.size=12;class Po extends po{get(t){return new To(this,t)}}Ks(Po,\"FeatureIndexArray\");class zo extends eo{geta_centroid_pos0(t){return this.uint16[2*t+0]}geta_centroid_pos1(t){return this.uint16[2*t+1]}}Ks(zo,\"FillExtrusionCentroidArray\");const Eo=Ua([{name:\"a_pos\",components:2,type:\"Int16\"}],4),Bo=Ua([{name:\"a_pos_3\",components:3,type:\"Int16\"},{name:\"a_pos_normal_3\",components:3,type:\"Int16\"}]);class Do{constructor(t=[]){this.segments=t;}_prepareSegment(t,e,r,n){let i=this.segments[this.segments.length-1];return t>Do.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Do.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}`),(!i||i.vertexLength+t>Do.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e,primitiveOffset:r,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i}prepareSegment(t,e,r,n){return this._prepareSegment(t,e.length,r.length,n)}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Do([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Co(t,e){return 256*(t=k(Math.floor(t),0,255))+k(Math.floor(e),0,255)}Do.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Ks(Do,\"SegmentVector\");const Ro=Ua([{name:\"a_pattern\",components:4,type:\"Uint16\"},{name:\"a_pixel_ratio\",components:1,type:\"Float32\"}]),Lo=Ua([{name:\"a_dash\",components:4,type:\"Uint16\"}]);var Vo={exports:{}},Oo={exports:{}};!function(t){t.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};}(Oo);var Fo=Oo.exports,jo={exports:{}};!function(t){t.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};}(jo);var Uo=Fo,No=jo.exports;Vo.exports=Uo,Vo.exports.murmur3=Uo,Vo.exports.murmur2=No;var $o=p(Vo.exports);class qo{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(Go(t)),this.positions.push(e,r,n);}eachPosition(t,e){const r=Go(t);let n=0,i=this.ids.length-1;for(;n>1;this.ids[t]>=r?i=t:n=t+1;}for(;this.ids[n]===r;)e(this.positions[3*n],this.positions[3*n+1],this.positions[3*n+2]),n++;}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return Yo(r,n,0,r.length-1),e&&(e.add(r.buffer),e.add(n.buffer)),{ids:r,positions:n}}static deserialize(t){const e=new qo;let r;e.ids=t.ids,e.positions=t.positions;for(const t of e.ids)t!==r&&e.uniqueIds.push(t),r=t;return e.indexed=!0,e}}function Go(t){const e=+t;return !isNaN(e)&&Number.MIN_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER?e:$o(String(t))}function Yo(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;Zo(t,s,a),Zo(e,3*s,3*a),Zo(e,3*s+1,3*a+1),Zo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r,n,i){e.set(t,i,n.constantOr(this.value));}getBinding(t,e){return \"color\"===this.type?new tl(t):new Wo(t)}}class ll{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.pattern=null,this.pixelRatio=1;}setConstantPatternPositions(t){this.pixelRatio=t.pixelRatio||1,this.pattern=t.tl.concat(t.br);}setUniform(t,e,r,n,i){const s=\"u_pattern\"===i||\"u_dash\"===i?this.pattern:\"u_pixel_ratio\"===i?this.pixelRatio:null;s&&e.set(t,i,s);}getBinding(t,e){return \"u_pattern\"===e||\"u_dash\"===e?new Qo(t):new Wo(t)}}class ul{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:\"Float32\",components:\"color\"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r,n,i,s,a){const o=this.paintVertexArray.length,l=this.expression.evaluate(new _a(0,{brightness:s}),e,{},i,n,a);this.paintVertexArray.resize(t),this._setPaintValue(o,t,l);}updatePaintArray(t,e,r,n,i,s,a){const o=this.expression.evaluate({zoom:0,brightness:a},r,n,void 0,i);this._setPaintValue(t,e,o);}_setPaintValue(t,e,r){if(\"color\"===this.type){const n=al(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:\"Float32\",components:\"color\"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r,n,i,s,a){const o=this.expression.evaluate(new _a(this.zoom,{brightness:s}),e,{},i,n,a),l=this.expression.evaluate(new _a(this.zoom+1,{brightness:s}),e,{},i,n,a),u=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(u,t,o,l);}updatePaintArray(t,e,r,n,i,s,a){const o=this.expression.evaluate({zoom:this.zoom,brightness:a},r,n,void 0,i),l=this.expression.evaluate({zoom:this.zoom+1,brightness:a},r,n,void 0,i);this._setPaintValue(t,e,o,l);}_setPaintValue(t,e,r,n){if(\"color\"===this.type){const i=al(r),s=al(n);for(let r=t;r!0)){this.binders={},this._buffers=[];const n=[];for(const i in t.paint._values){const s=t.paint.get(i);if(!r(i))continue;if(!(s instanceof Ta&&Ci(s.property.specification)))continue;const a=ml(i,t.type),o=s.value,l=s.property.specification.type,u=!!s.property.useIntegerZoom,c=\"line-dasharray\"===i||i.endsWith(\"pattern\"),h=\"line-dasharray\"===i&&\"constant\"!==t.layout.get(\"line-cap\").value.kind;if(\"constant\"!==o.kind||h)if(\"source\"===o.kind||h||c){const e=xl(i,l,\"source\");this.binders[i]=c?new hl(o,a,l,e,t.id):new ul(o,a,l,e),n.push(`/a_${i}`);}else {const t=xl(i,l,\"composite\");this.binders[i]=new cl(o,a,l,u,e,t),n.push(`/z_${i}`);}else this.binders[i]=c?new ll(o.value,a):new ol(o.value,a,l),n.push(`/u_${i}`);}this.cacheKey=n.sort().join(\"\");}getMaxValue(t){const e=this.binders[t];return e instanceof ul||e instanceof cl?e.maxValue:0}populatePaintArrays(t,e,r,n,i,s,a){for(const o in this.binders){const l=this.binders[o];(l instanceof ul||l instanceof cl||l instanceof hl)&&l.populatePaintArray(t,e,r,n,i,s,a);}}setConstantPatternPositions(t){for(const e in this.binders){const r=this.binders[e];r instanceof ll&&r.setConstantPatternPositions(t);}}updatePaintArrays(t,e,r,n,i,s,a,o){let l=!1;const u=Object.keys(t),c=0!==u.length,h=c?u:e.uniqueIds;for(const u in this.binders){const p=this.binders[u];if((p instanceof ul||p instanceof cl||p instanceof hl)&&(!0===p.expression.isStateDependent||!1===p.expression.isLightConstant)){const f=i.paint.get(u);p.expression=f.value;for(const r of h){const i=t[r.toString()];e.eachPosition(r,((t,e,r)=>{const l=n.feature(t);p.updatePaintArray(e,r,l,i,s,a,o);}));}if(!c)for(const e of r.uniqueIds){const i=t[e.toString()];r.eachPosition(e,((t,e,r)=>{const l=n.feature(t);p.updatePaintArray(e,r,l,i,s,a,o);}));}l=!0;}}return l}defines(){const t=[];for(const e in this.binders){const r=this.binders[e];(r instanceof ol||r instanceof ll)&&t.push(...r.uniformNames.map((t=>`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof ul||r instanceof cl||r instanceof hl)for(let e=0;e!0)){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new pl(n,e,r);this.needsUpload=!1,this._featureMap=new qo,this._featureMapWithoutIds=new qo,this._bufferOffset=0,this._idlessCounter=0;}populatePaintArrays(t,e,r,n,i,s,a,o){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n,i,s,a,o);void 0!==e.id?this._featureMap.add(e.id,r,this._bufferOffset,t):(this._featureMapWithoutIds.add(this._idlessCounter,r,this._bufferOffset,t),this._idlessCounter+=1),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n,i,s){for(const a of r)this.needsUpload=this.programConfigurations[a.id].updatePaintArrays(t,this._featureMap,this._featureMapWithoutIds,e,a,n,i,s||0)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}const dl={\"text-opacity\":[\"opacity\"],\"icon-opacity\":[\"opacity\"],\"text-color\":[\"fill_color\"],\"icon-color\":[\"fill_color\"],\"text-emissive-strength\":[\"emissive_strength\"],\"icon-emissive-strength\":[\"emissive_strength\"],\"text-halo-color\":[\"halo_color\"],\"icon-halo-color\":[\"halo_color\"],\"text-halo-blur\":[\"halo_blur\"],\"icon-halo-blur\":[\"halo_blur\"],\"text-halo-width\":[\"halo_width\"],\"icon-halo-width\":[\"halo_width\"],\"line-gap-width\":[\"gapwidth\"],\"line-pattern\":[\"pattern\",\"pixel_ratio\"],\"fill-pattern\":[\"pattern\",\"pixel_ratio\"],\"fill-extrusion-pattern\":[\"pattern\",\"pixel_ratio\"],\"line-dasharray\":[\"dash\"]};function ml(t,e){return dl[t]||[t.replace(`${e}-`,\"\").replace(/-/g,\"_\")]}const yl={\"line-pattern\":{source:Ka,composite:Ka},\"fill-pattern\":{source:Ka,composite:Ka},\"fill-extrusion-pattern\":{source:Ka,composite:Ka},\"line-dasharray\":{source:Wa,composite:Wa}},gl={color:{source:yo,composite:Xa},number:{source:uo,composite:yo}};function xl(t,e,r){const n=yl[t];return n&&n[r]||gl[e][r]}Ks(ol,\"ConstantBinder\"),Ks(ll,\"PatternConstantBinder\"),Ks(ul,\"SourceExpressionBinder\"),Ks(hl,\"PatternCompositeBinder\"),Ks(cl,\"CompositeExpressionBinder\"),Ks(pl,\"ProgramConfiguration\",{omit:[\"_buffers\"]}),Ks(fl,\"ProgramConfigurationSet\");class vl{constructor(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));}setNorthEast(t){return this._ne=t instanceof Zh?new Zh(t.lng,t.lat):Zh.convert(t),this}setSouthWest(t){return this._sw=t instanceof Zh?new Zh(t.lng,t.lat):Zh.convert(t),this}extend(t){const e=this._sw,r=this._ne;let n,i;if(t instanceof Zh)n=t,i=t;else {if(!(t instanceof vl))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(vl.convert(t)):this.extend(Zh.convert(t)):\"object\"==typeof t&&null!==t&&t.hasOwnProperty(\"lat\")&&(t.hasOwnProperty(\"lon\")||t.hasOwnProperty(\"lng\"))?this.extend(Zh.convert(t)):this;if(n=t._sw,i=t._ne,!n||!i)return this}return e||r?(e.lng=Math.min(n.lng,e.lng),e.lat=Math.min(n.lat,e.lat),r.lng=Math.max(i.lng,r.lng),r.lat=Math.max(i.lat,r.lat)):(this._sw=new Zh(n.lng,n.lat),this._ne=new Zh(i.lng,i.lat)),this}getCenter(){return new Zh((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new Zh(this.getWest(),this.getNorth())}getSouthEast(){return new Zh(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(t){const{lng:e,lat:r}=Zh.convert(t);let n=this._sw.lng<=e&&e<=this._ne.lng;return this._sw.lng>this._ne.lng&&(n=this._sw.lng>=e&&e>=this._ne.lng),this._sw.lat<=r&&r<=this._ne.lat&&n}static convert(t){return !t||t instanceof vl?t:new vl(t)}}var bl={},_l={};Object.defineProperty(_l,\"__esModule\",{value:!0}),_l.setMatrixArrayType=function(t){_l.ARRAY_TYPE=Ml=t;},_l.toRadian=function(t){return t*Sl},_l.equals=function(t,e){return Math.abs(t-e)<=wl*Math.max(1,Math.abs(t),Math.abs(e))},_l.RANDOM=_l.ARRAY_TYPE=_l.EPSILON=void 0;var wl=1e-6;_l.EPSILON=wl;var Ml=\"undefined\"!=typeof Float32Array?Float32Array:Array;_l.ARRAY_TYPE=Ml;var Al=Math.random;_l.RANDOM=Al;var Sl=Math.PI/180;Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});var Il={};function kl(t){return kl=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},kl(t)}Object.defineProperty(Il,\"__esModule\",{value:!0}),Il.create=function(){var t=new Tl.ARRAY_TYPE(4);return Tl.ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},Il.clone=function(t){var e=new Tl.ARRAY_TYPE(4);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e},Il.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t},Il.identity=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t},Il.fromValues=function(t,e,r,n){var i=new Tl.ARRAY_TYPE(4);return i[0]=t,i[1]=e,i[2]=r,i[3]=n,i},Il.set=function(t,e,r,n,i){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t},Il.transpose=function(t,e){if(t===e){var r=e[1];t[1]=e[2],t[2]=r;}else t[0]=e[0],t[1]=e[2],t[2]=e[1],t[3]=e[3];return t},Il.invert=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=r*s-i*n;return a?(t[0]=s*(a=1/a),t[1]=-n*a,t[2]=-i*a,t[3]=r*a,t):null},Il.adjoint=function(t,e){var r=e[0];return t[0]=e[3],t[1]=-e[1],t[2]=-e[2],t[3]=r,t},Il.determinant=function(t){return t[0]*t[3]-t[2]*t[1]},Il.multiply=zl,Il.rotate=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=Math.sin(r),l=Math.cos(r);return t[0]=n*l+s*o,t[1]=i*l+a*o,t[2]=n*-o+s*l,t[3]=i*-o+a*l,t},Il.scale=function(t,e,r){var n=e[1],i=e[2],s=e[3],a=r[0],o=r[1];return t[0]=e[0]*a,t[1]=n*a,t[2]=i*o,t[3]=s*o,t},Il.fromRotation=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t},Il.fromScaling=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=e[1],t},Il.str=function(t){return \"mat2(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\")\"},Il.frob=function(t){return Math.hypot(t[0],t[1],t[2],t[3])},Il.LDU=function(t,e,r,n){return t[2]=n[2]/n[0],r[0]=n[0],r[1]=n[1],r[3]=n[3]-t[2]*r[1],[t,e,r]},Il.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t},Il.subtract=El,Il.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]},Il.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=e[0],o=e[1],l=e[2],u=e[3];return Math.abs(r-a)<=Tl.EPSILON*Math.max(1,Math.abs(r),Math.abs(a))&&Math.abs(n-o)<=Tl.EPSILON*Math.max(1,Math.abs(n),Math.abs(o))&&Math.abs(i-l)<=Tl.EPSILON*Math.max(1,Math.abs(i),Math.abs(l))&&Math.abs(s-u)<=Tl.EPSILON*Math.max(1,Math.abs(s),Math.abs(u))},Il.multiplyScalar=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},Il.multiplyScalarAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t},Il.sub=Il.mul=void 0;var Tl=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==kl(t)&&\"function\"!=typeof t)return {default:t};var r=Pl(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function Pl(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (Pl=function(t){return t?r:e})(t)}function zl(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=r[0],l=r[1],u=r[2],c=r[3];return t[0]=n*o+s*l,t[1]=i*o+a*l,t[2]=n*u+s*c,t[3]=i*u+a*c,t}function El(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}Il.mul=zl,Il.sub=El;var Bl={};function Dl(t){return Dl=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},Dl(t)}Object.defineProperty(Bl,\"__esModule\",{value:!0}),Bl.create=function(){var t=new Cl.ARRAY_TYPE(6);return Cl.ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t},Bl.clone=function(t){var e=new Cl.ARRAY_TYPE(6);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e},Bl.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t},Bl.identity=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t},Bl.fromValues=function(t,e,r,n,i,s){var a=new Cl.ARRAY_TYPE(6);return a[0]=t,a[1]=e,a[2]=r,a[3]=n,a[4]=i,a[5]=s,a},Bl.set=function(t,e,r,n,i,s,a){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=s,t[5]=a,t},Bl.invert=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=r*s-n*i;return l?(t[0]=s*(l=1/l),t[1]=-n*l,t[2]=-i*l,t[3]=r*l,t[4]=(i*o-s*a)*l,t[5]=(n*a-r*o)*l,t):null},Bl.determinant=function(t){return t[0]*t[3]-t[1]*t[2]},Bl.multiply=Ll,Bl.rotate=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=Math.sin(r),c=Math.cos(r);return t[0]=n*c+s*u,t[1]=i*c+a*u,t[2]=n*-u+s*c,t[3]=i*-u+a*c,t[4]=o,t[5]=l,t},Bl.scale=function(t,e,r){var n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=r[0],u=r[1];return t[0]=e[0]*l,t[1]=n*l,t[2]=i*u,t[3]=s*u,t[4]=a,t[5]=o,t},Bl.translate=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=r[0],c=r[1];return t[0]=n,t[1]=i,t[2]=s,t[3]=a,t[4]=n*u+s*c+o,t[5]=i*u+a*c+l,t},Bl.fromRotation=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t[4]=0,t[5]=0,t},Bl.fromScaling=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=e[1],t[4]=0,t[5]=0,t},Bl.fromTranslation=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=e[0],t[5]=e[1],t},Bl.str=function(t){return \"mat2d(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\", \"+t[4]+\", \"+t[5]+\")\"},Bl.frob=function(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],1)},Bl.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t},Bl.subtract=Vl,Bl.multiplyScalar=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t},Bl.multiplyScalarAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t},Bl.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]},Bl.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=e[0],u=e[1],c=e[2],h=e[3],p=e[4],f=e[5];return Math.abs(r-l)<=Cl.EPSILON*Math.max(1,Math.abs(r),Math.abs(l))&&Math.abs(n-u)<=Cl.EPSILON*Math.max(1,Math.abs(n),Math.abs(u))&&Math.abs(i-c)<=Cl.EPSILON*Math.max(1,Math.abs(i),Math.abs(c))&&Math.abs(s-h)<=Cl.EPSILON*Math.max(1,Math.abs(s),Math.abs(h))&&Math.abs(a-p)<=Cl.EPSILON*Math.max(1,Math.abs(a),Math.abs(p))&&Math.abs(o-f)<=Cl.EPSILON*Math.max(1,Math.abs(o),Math.abs(f))},Bl.sub=Bl.mul=void 0;var Cl=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==Dl(t)&&\"function\"!=typeof t)return {default:t};var r=Rl(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function Rl(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (Rl=function(t){return t?r:e})(t)}function Ll(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=r[0],c=r[1],h=r[2],p=r[3],f=r[4],d=r[5];return t[0]=n*u+s*c,t[1]=i*u+a*c,t[2]=n*h+s*p,t[3]=i*h+a*p,t[4]=n*f+s*d+o,t[5]=i*f+a*d+l,t}function Vl(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t}Bl.mul=Ll,Bl.sub=Vl;var Ol={};function Fl(t){return Fl=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},Fl(t)}Object.defineProperty(Ol,\"__esModule\",{value:!0}),Ol.create=function(){var t=new jl.ARRAY_TYPE(9);return jl.ARRAY_TYPE!=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,t},Ol.fromMat4=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t},Ol.clone=function(t){var e=new jl.ARRAY_TYPE(9);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e},Ol.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t},Ol.fromValues=function(t,e,r,n,i,s,a,o,l){var u=new jl.ARRAY_TYPE(9);return u[0]=t,u[1]=e,u[2]=r,u[3]=n,u[4]=i,u[5]=s,u[6]=a,u[7]=o,u[8]=l,u},Ol.set=function(t,e,r,n,i,s,a,o,l,u){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=s,t[5]=a,t[6]=o,t[7]=l,t[8]=u,t},Ol.identity=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},Ol.transpose=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=r,t[5]=e[7],t[6]=n,t[7]=i;}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];return t},Ol.invert=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=c*a-o*u,p=-c*s+o*l,f=u*s-a*l,d=r*h+n*p+i*f;return d?(t[0]=h*(d=1/d),t[1]=(-c*n+i*u)*d,t[2]=(o*n-i*a)*d,t[3]=p*d,t[4]=(c*r-i*l)*d,t[5]=(-o*r+i*s)*d,t[6]=f*d,t[7]=(-u*r+n*l)*d,t[8]=(a*r-n*s)*d,t):null},Ol.adjoint=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8];return t[0]=a*c-o*u,t[1]=i*u-n*c,t[2]=n*o-i*a,t[3]=o*l-s*c,t[4]=r*c-i*l,t[5]=i*s-r*o,t[6]=s*u-a*l,t[7]=n*l-r*u,t[8]=r*a-n*s,t},Ol.determinant=function(t){var e=t[3],r=t[4],n=t[5],i=t[6],s=t[7],a=t[8];return t[0]*(a*r-n*s)+t[1]*(-a*e+n*i)+t[2]*(s*e-r*i)},Ol.multiply=Nl,Ol.translate=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=r[0],f=r[1];return t[0]=n,t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=p*n+f*a+u,t[7]=p*i+f*o+c,t[8]=p*s+f*l+h,t},Ol.rotate=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=Math.sin(r),f=Math.cos(r);return t[0]=f*n+p*a,t[1]=f*i+p*o,t[2]=f*s+p*l,t[3]=f*a-p*n,t[4]=f*o-p*i,t[5]=f*l-p*s,t[6]=u,t[7]=c,t[8]=h,t},Ol.scale=function(t,e,r){var n=r[0],i=r[1];return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=i*e[3],t[4]=i*e[4],t[5]=i*e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t},Ol.fromTranslation=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=e[0],t[7]=e[1],t[8]=1,t},Ol.fromRotation=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},Ol.fromScaling=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=e[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},Ol.fromMat2d=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=0,t[3]=e[2],t[4]=e[3],t[5]=0,t[6]=e[4],t[7]=e[5],t[8]=1,t},Ol.fromQuat=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=r+r,o=n+n,l=i+i,u=r*a,c=n*a,h=n*o,p=i*a,f=i*o,d=i*l,m=s*a,y=s*o,g=s*l;return t[0]=1-h-d,t[3]=c-g,t[6]=p+y,t[1]=c+g,t[4]=1-u-d,t[7]=f-m,t[2]=p-y,t[5]=f+m,t[8]=1-u-h,t},Ol.normalFromMat4=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],m=e[13],y=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,_=n*l-i*o,w=n*u-s*o,M=i*u-s*l,A=c*m-h*d,S=c*y-p*d,I=c*g-f*d,k=h*y-p*m,T=h*g-f*m,P=p*g-f*y,z=x*P-v*T+b*k+_*I-w*S+M*A;return z?(t[0]=(o*P-l*T+u*k)*(z=1/z),t[1]=(l*I-a*P-u*S)*z,t[2]=(a*T-o*I+u*A)*z,t[3]=(i*T-n*P-s*k)*z,t[4]=(r*P-i*I+s*S)*z,t[5]=(n*I-r*T-s*A)*z,t[6]=(m*M-y*w+g*_)*z,t[7]=(y*b-d*M-g*v)*z,t[8]=(d*w-m*b+g*x)*z,t):null},Ol.projection=function(t,e,r){return t[0]=2/e,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t},Ol.str=function(t){return \"mat3(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\", \"+t[4]+\", \"+t[5]+\", \"+t[6]+\", \"+t[7]+\", \"+t[8]+\")\"},Ol.frob=function(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},Ol.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t},Ol.subtract=$l,Ol.multiplyScalar=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t},Ol.multiplyScalarAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t},Ol.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]},Ol.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=e[0],p=e[1],f=e[2],d=e[3],m=e[4],y=e[5],g=e[6],x=e[7],v=e[8];return Math.abs(r-h)<=jl.EPSILON*Math.max(1,Math.abs(r),Math.abs(h))&&Math.abs(n-p)<=jl.EPSILON*Math.max(1,Math.abs(n),Math.abs(p))&&Math.abs(i-f)<=jl.EPSILON*Math.max(1,Math.abs(i),Math.abs(f))&&Math.abs(s-d)<=jl.EPSILON*Math.max(1,Math.abs(s),Math.abs(d))&&Math.abs(a-m)<=jl.EPSILON*Math.max(1,Math.abs(a),Math.abs(m))&&Math.abs(o-y)<=jl.EPSILON*Math.max(1,Math.abs(o),Math.abs(y))&&Math.abs(l-g)<=jl.EPSILON*Math.max(1,Math.abs(l),Math.abs(g))&&Math.abs(u-x)<=jl.EPSILON*Math.max(1,Math.abs(u),Math.abs(x))&&Math.abs(c-v)<=jl.EPSILON*Math.max(1,Math.abs(c),Math.abs(v))},Ol.sub=Ol.mul=void 0;var jl=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==Fl(t)&&\"function\"!=typeof t)return {default:t};var r=Ul(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function Ul(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (Ul=function(t){return t?r:e})(t)}function Nl(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=r[0],f=r[1],d=r[2],m=r[3],y=r[4],g=r[5],x=r[6],v=r[7],b=r[8];return t[0]=p*n+f*a+d*u,t[1]=p*i+f*o+d*c,t[2]=p*s+f*l+d*h,t[3]=m*n+y*a+g*u,t[4]=m*i+y*o+g*c,t[5]=m*s+y*l+g*h,t[6]=x*n+v*a+b*u,t[7]=x*i+v*o+b*c,t[8]=x*s+v*l+b*h,t}function $l(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t}Ol.mul=Nl,Ol.sub=$l;var ql={};function Gl(t){return Gl=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},Gl(t)}Object.defineProperty(ql,\"__esModule\",{value:!0}),ql.create=function(){var t=new Yl.ARRAY_TYPE(16);return Yl.ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},ql.clone=function(t){var e=new Yl.ARRAY_TYPE(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},ql.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},ql.fromValues=function(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m){var y=new Yl.ARRAY_TYPE(16);return y[0]=t,y[1]=e,y[2]=r,y[3]=n,y[4]=i,y[5]=s,y[6]=a,y[7]=o,y[8]=l,y[9]=u,y[10]=c,y[11]=h,y[12]=p,y[13]=f,y[14]=d,y[15]=m,y},ql.set=function(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=s,t[5]=a,t[6]=o,t[7]=l,t[8]=u,t[9]=c,t[10]=h,t[11]=p,t[12]=f,t[13]=d,t[14]=m,t[15]=y,t},ql.identity=Xl,ql.transpose=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],s=e[6],a=e[7],o=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=s,t[11]=e[14],t[12]=i,t[13]=a,t[14]=o;}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t},ql.invert=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],m=e[13],y=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,_=n*l-i*o,w=n*u-s*o,M=i*u-s*l,A=c*m-h*d,S=c*y-p*d,I=c*g-f*d,k=h*y-p*m,T=h*g-f*m,P=p*g-f*y,z=x*P-v*T+b*k+_*I-w*S+M*A;return z?(t[0]=(o*P-l*T+u*k)*(z=1/z),t[1]=(i*T-n*P-s*k)*z,t[2]=(m*M-y*w+g*_)*z,t[3]=(p*w-h*M-f*_)*z,t[4]=(l*I-a*P-u*S)*z,t[5]=(r*P-i*I+s*S)*z,t[6]=(y*b-d*M-g*v)*z,t[7]=(c*M-p*b+f*v)*z,t[8]=(a*T-o*I+u*A)*z,t[9]=(n*I-r*T-s*A)*z,t[10]=(d*w-m*b+g*x)*z,t[11]=(h*b-c*w-f*x)*z,t[12]=(o*S-a*k-l*A)*z,t[13]=(r*k-n*S+i*A)*z,t[14]=(m*v-d*_-y*x)*z,t[15]=(c*_-h*v+p*x)*z,t):null},ql.adjoint=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],m=e[13],y=e[14],g=e[15];return t[0]=o*(p*g-f*y)-h*(l*g-u*y)+m*(l*f-u*p),t[1]=-(n*(p*g-f*y)-h*(i*g-s*y)+m*(i*f-s*p)),t[2]=n*(l*g-u*y)-o*(i*g-s*y)+m*(i*u-s*l),t[3]=-(n*(l*f-u*p)-o*(i*f-s*p)+h*(i*u-s*l)),t[4]=-(a*(p*g-f*y)-c*(l*g-u*y)+d*(l*f-u*p)),t[5]=r*(p*g-f*y)-c*(i*g-s*y)+d*(i*f-s*p),t[6]=-(r*(l*g-u*y)-a*(i*g-s*y)+d*(i*u-s*l)),t[7]=r*(l*f-u*p)-a*(i*f-s*p)+c*(i*u-s*l),t[8]=a*(h*g-f*m)-c*(o*g-u*m)+d*(o*f-u*h),t[9]=-(r*(h*g-f*m)-c*(n*g-s*m)+d*(n*f-s*h)),t[10]=r*(o*g-u*m)-a*(n*g-s*m)+d*(n*u-s*o),t[11]=-(r*(o*f-u*h)-a*(n*f-s*h)+c*(n*u-s*o)),t[12]=-(a*(h*y-p*m)-c*(o*y-l*m)+d*(o*p-l*h)),t[13]=r*(h*y-p*m)-c*(n*y-i*m)+d*(n*p-i*h),t[14]=-(r*(o*y-l*m)-a*(n*y-i*m)+d*(n*l-i*o)),t[15]=r*(o*p-l*h)-a*(n*p-i*h)+c*(n*l-i*o),t},ql.determinant=function(t){var e=t[0],r=t[1],n=t[2],i=t[3],s=t[4],a=t[5],o=t[6],l=t[7],u=t[8],c=t[9],h=t[10],p=t[11],f=t[12],d=t[13],m=t[14],y=t[15];return (e*a-r*s)*(h*y-p*m)-(e*o-n*s)*(c*y-p*d)+(e*l-i*s)*(c*m-h*d)+(r*o-n*a)*(u*y-p*f)-(r*l-i*a)*(u*m-h*f)+(n*l-i*o)*(u*d-c*f)},ql.multiply=Kl,ql.translate=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,m=r[0],y=r[1],g=r[2];return e===t?(t[12]=e[0]*m+e[4]*y+e[8]*g+e[12],t[13]=e[1]*m+e[5]*y+e[9]*g+e[13],t[14]=e[2]*m+e[6]*y+e[10]*g+e[14],t[15]=e[3]*m+e[7]*y+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*m+o*y+h*g+e[12],t[13]=i*m+l*y+p*g+e[13],t[14]=s*m+u*y+f*g+e[14],t[15]=a*m+c*y+d*g+e[15]),t},ql.scale=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},ql.rotate=function(t,e,r,n){var i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b,_,w,M,A,S,I,k,T=n[0],P=n[1],z=n[2],E=Math.hypot(T,P,z);return E0?(r[0]=2*(o*a+c*n+l*s-u*i)/h,r[1]=2*(l*a+c*i+u*n-o*s)/h,r[2]=2*(u*a+c*s+o*i-l*n)/h):(r[0]=2*(o*a+c*n+l*s-u*i),r[1]=2*(l*a+c*i+u*n-o*s),r[2]=2*(u*a+c*s+o*i-l*n)),Wl(t,e,r),t},ql.getTranslation=function(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t},ql.getScaling=Hl,ql.getRotation=function(t,e){var r=new Yl.ARRAY_TYPE(3);Hl(r,e);var n=1/r[0],i=1/r[1],s=1/r[2],a=e[0]*n,o=e[1]*i,l=e[2]*s,u=e[4]*n,c=e[5]*i,h=e[6]*s,p=e[8]*n,f=e[9]*i,d=e[10]*s,m=a+c+d,y=0;return m>0?(y=2*Math.sqrt(m+1),t[3]=.25*y,t[0]=(h-f)/y,t[1]=(p-l)/y,t[2]=(o-u)/y):a>c&&a>d?(y=2*Math.sqrt(1+a-c-d),t[3]=(h-f)/y,t[0]=.25*y,t[1]=(o+u)/y,t[2]=(p+l)/y):c>d?(y=2*Math.sqrt(1+c-a-d),t[3]=(p-l)/y,t[0]=(o+u)/y,t[1]=.25*y,t[2]=(h+f)/y):(y=2*Math.sqrt(1+d-a-c),t[3]=(o-u)/y,t[0]=(p+l)/y,t[1]=(h+f)/y,t[2]=.25*y),t},ql.fromRotationTranslationScale=function(t,e,r,n){var i=e[0],s=e[1],a=e[2],o=e[3],l=i+i,u=s+s,c=a+a,h=i*l,p=i*u,f=i*c,d=s*u,m=s*c,y=a*c,g=o*l,x=o*u,v=o*c,b=n[0],_=n[1],w=n[2];return t[0]=(1-(d+y))*b,t[1]=(p+v)*b,t[2]=(f-x)*b,t[3]=0,t[4]=(p-v)*_,t[5]=(1-(h+y))*_,t[6]=(m+g)*_,t[7]=0,t[8]=(f+x)*w,t[9]=(m-g)*w,t[10]=(1-(h+d))*w,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t},ql.fromRotationTranslationScaleOrigin=function(t,e,r,n,i){var s=e[0],a=e[1],o=e[2],l=e[3],u=s+s,c=a+a,h=o+o,p=s*u,f=s*c,d=s*h,m=a*c,y=a*h,g=o*h,x=l*u,v=l*c,b=l*h,_=n[0],w=n[1],M=n[2],A=i[0],S=i[1],I=i[2],k=(1-(m+g))*_,T=(f+b)*_,P=(d-v)*_,z=(f-b)*w,E=(1-(p+g))*w,B=(y+x)*w,D=(d+v)*M,C=(y-x)*M,R=(1-(p+m))*M;return t[0]=k,t[1]=T,t[2]=P,t[3]=0,t[4]=z,t[5]=E,t[6]=B,t[7]=0,t[8]=D,t[9]=C,t[10]=R,t[11]=0,t[12]=r[0]+A-(k*A+z*S+D*I),t[13]=r[1]+S-(T*A+E*S+C*I),t[14]=r[2]+I-(P*A+B*S+R*I),t[15]=1,t},ql.fromQuat=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=r+r,o=n+n,l=i+i,u=r*a,c=n*a,h=n*o,p=i*a,f=i*o,d=i*l,m=s*a,y=s*o,g=s*l;return t[0]=1-h-d,t[1]=c+g,t[2]=p-y,t[3]=0,t[4]=c-g,t[5]=1-u-d,t[6]=f+m,t[7]=0,t[8]=p+y,t[9]=f-m,t[10]=1-u-h,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},ql.frustum=function(t,e,r,n,i,s,a){var o=1/(r-e),l=1/(i-n),u=1/(s-a);return t[0]=2*s*o,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*s*l,t[6]=0,t[7]=0,t[8]=(r+e)*o,t[9]=(i+n)*l,t[10]=(a+s)*u,t[11]=-1,t[12]=0,t[13]=0,t[14]=a*s*2*u,t[15]=0,t},ql.perspectiveNO=Jl,ql.perspectiveZO=function(t,e,r,n,i){var s,a=1/Math.tan(e/2);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,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!=i&&i!==1/0?(t[10]=i*(s=1/(n-i)),t[14]=i*n*s):(t[10]=-1,t[14]=-n),t},ql.perspectiveFromFieldOfView=function(t,e,r,n){var i=Math.tan(e.upDegrees*Math.PI/180),s=Math.tan(e.downDegrees*Math.PI/180),a=Math.tan(e.leftDegrees*Math.PI/180),o=Math.tan(e.rightDegrees*Math.PI/180),l=2/(a+o),u=2/(i+s);return t[0]=l,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=u,t[6]=0,t[7]=0,t[8]=-(a-o)*l*.5,t[9]=(i-s)*u*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t},ql.orthoNO=Ql,ql.orthoZO=function(t,e,r,n,i,s,a){var o=1/(e-r),l=1/(n-i),u=1/(s-a);return t[0]=-2*o,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=u,t[11]=0,t[12]=(e+r)*o,t[13]=(i+n)*l,t[14]=s*u,t[15]=1,t},ql.lookAt=function(t,e,r,n){var i,s,a,o,l,u,c,h,p,f,d=e[0],m=e[1],y=e[2],g=n[0],x=n[1],v=n[2],b=r[0],_=r[1],w=r[2];return Math.abs(d-b)0&&(c*=f=1/Math.sqrt(f),h*=f,p*=f);var d=l*p-u*h,m=u*c-o*p,y=o*h-l*c;return (f=d*d+m*m+y*y)>0&&(d*=f=1/Math.sqrt(f),m*=f,y*=f),t[0]=d,t[1]=m,t[2]=y,t[3]=0,t[4]=h*y-p*m,t[5]=p*d-c*y,t[6]=c*m-h*d,t[7]=0,t[8]=c,t[9]=h,t[10]=p,t[11]=0,t[12]=i,t[13]=s,t[14]=a,t[15]=1,t},ql.str=function(t){return \"mat4(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\", \"+t[4]+\", \"+t[5]+\", \"+t[6]+\", \"+t[7]+\", \"+t[8]+\", \"+t[9]+\", \"+t[10]+\", \"+t[11]+\", \"+t[12]+\", \"+t[13]+\", \"+t[14]+\", \"+t[15]+\")\"},ql.frob=function(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])},ql.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t},ql.subtract=tu,ql.multiplyScalar=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t},ql.multiplyScalarAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t[9]=e[9]+r[9]*n,t[10]=e[10]+r[10]*n,t[11]=e[11]+r[11]*n,t[12]=e[12]+r[12]*n,t[13]=e[13]+r[13]*n,t[14]=e[14]+r[14]*n,t[15]=e[15]+r[15]*n,t},ql.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},ql.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],p=t[10],f=t[11],d=t[12],m=t[13],y=t[14],g=t[15],x=e[0],v=e[1],b=e[2],_=e[3],w=e[4],M=e[5],A=e[6],S=e[7],I=e[8],k=e[9],T=e[10],P=e[11],z=e[12],E=e[13],B=e[14],D=e[15];return Math.abs(r-x)<=Yl.EPSILON*Math.max(1,Math.abs(r),Math.abs(x))&&Math.abs(n-v)<=Yl.EPSILON*Math.max(1,Math.abs(n),Math.abs(v))&&Math.abs(i-b)<=Yl.EPSILON*Math.max(1,Math.abs(i),Math.abs(b))&&Math.abs(s-_)<=Yl.EPSILON*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-w)<=Yl.EPSILON*Math.max(1,Math.abs(a),Math.abs(w))&&Math.abs(o-M)<=Yl.EPSILON*Math.max(1,Math.abs(o),Math.abs(M))&&Math.abs(l-A)<=Yl.EPSILON*Math.max(1,Math.abs(l),Math.abs(A))&&Math.abs(u-S)<=Yl.EPSILON*Math.max(1,Math.abs(u),Math.abs(S))&&Math.abs(c-I)<=Yl.EPSILON*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-k)<=Yl.EPSILON*Math.max(1,Math.abs(h),Math.abs(k))&&Math.abs(p-T)<=Yl.EPSILON*Math.max(1,Math.abs(p),Math.abs(T))&&Math.abs(f-P)<=Yl.EPSILON*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-z)<=Yl.EPSILON*Math.max(1,Math.abs(d),Math.abs(z))&&Math.abs(m-E)<=Yl.EPSILON*Math.max(1,Math.abs(m),Math.abs(E))&&Math.abs(y-B)<=Yl.EPSILON*Math.max(1,Math.abs(y),Math.abs(B))&&Math.abs(g-D)<=Yl.EPSILON*Math.max(1,Math.abs(g),Math.abs(D))},ql.sub=ql.mul=ql.ortho=ql.perspective=void 0;var Yl=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==Gl(t)&&\"function\"!=typeof t)return {default:t};var r=Zl(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function Zl(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (Zl=function(t){return t?r:e})(t)}function Xl(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Kl(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],m=e[12],y=e[13],g=e[14],x=e[15],v=r[0],b=r[1],_=r[2],w=r[3];return t[0]=v*n+b*o+_*h+w*m,t[1]=v*i+b*l+_*p+w*y,t[2]=v*s+b*u+_*f+w*g,t[3]=v*a+b*c+_*d+w*x,t[4]=(v=r[4])*n+(b=r[5])*o+(_=r[6])*h+(w=r[7])*m,t[5]=v*i+b*l+_*p+w*y,t[6]=v*s+b*u+_*f+w*g,t[7]=v*a+b*c+_*d+w*x,t[8]=(v=r[8])*n+(b=r[9])*o+(_=r[10])*h+(w=r[11])*m,t[9]=v*i+b*l+_*p+w*y,t[10]=v*s+b*u+_*f+w*g,t[11]=v*a+b*c+_*d+w*x,t[12]=(v=r[12])*n+(b=r[13])*o+(_=r[14])*h+(w=r[15])*m,t[13]=v*i+b*l+_*p+w*y,t[14]=v*s+b*u+_*f+w*g,t[15]=v*a+b*c+_*d+w*x,t}function Wl(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=n+n,l=i+i,u=s+s,c=n*o,h=n*l,p=n*u,f=i*l,d=i*u,m=s*u,y=a*o,g=a*l,x=a*u;return t[0]=1-(f+m),t[1]=h+x,t[2]=p-g,t[3]=0,t[4]=h-x,t[5]=1-(c+m),t[6]=d+y,t[7]=0,t[8]=p+g,t[9]=d-y,t[10]=1-(c+f),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function Hl(t,e){var r=e[4],n=e[5],i=e[6],s=e[8],a=e[9],o=e[10];return t[0]=Math.hypot(e[0],e[1],e[2]),t[1]=Math.hypot(r,n,i),t[2]=Math.hypot(s,a,o),t}function Jl(t,e,r,n,i){var s,a=1/Math.tan(e/2);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,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!=i&&i!==1/0?(t[10]=(i+n)*(s=1/(n-i)),t[14]=2*i*n*s):(t[10]=-1,t[14]=-2*n),t}function Ql(t,e,r,n,i,s,a){var o=1/(e-r),l=1/(n-i),u=1/(s-a);return t[0]=-2*o,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*u,t[11]=0,t[12]=(e+r)*o,t[13]=(i+n)*l,t[14]=(a+s)*u,t[15]=1,t}function tu(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}ql.perspective=Jl,ql.ortho=Ql,ql.mul=Kl,ql.sub=tu;var eu={},ru={};function nu(t){return nu=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},nu(t)}Object.defineProperty(ru,\"__esModule\",{value:!0}),ru.create=au,ru.clone=function(t){var e=new iu.ARRAY_TYPE(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},ru.length=ou,ru.fromValues=function(t,e,r){var n=new iu.ARRAY_TYPE(3);return n[0]=t,n[1]=e,n[2]=r,n},ru.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},ru.set=function(t,e,r,n){return t[0]=e,t[1]=r,t[2]=n,t},ru.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t},ru.subtract=lu,ru.multiply=uu,ru.divide=cu,ru.ceil=function(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t},ru.floor=function(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t},ru.min=function(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t},ru.max=function(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t},ru.round=function(t,e){return t[0]=Math.round(e[0]),t[1]=Math.round(e[1]),t[2]=Math.round(e[2]),t},ru.scale=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t},ru.scaleAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},ru.distance=hu,ru.squaredDistance=pu,ru.squaredLength=fu,ru.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t},ru.inverse=function(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t},ru.normalize=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},ru.dot=du,ru.cross=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[0],o=r[1],l=r[2];return t[0]=i*l-s*o,t[1]=s*a-n*l,t[2]=n*o-i*a,t},ru.lerp=function(t,e,r,n){var i=e[0],s=e[1],a=e[2];return t[0]=i+n*(r[0]-i),t[1]=s+n*(r[1]-s),t[2]=a+n*(r[2]-a),t},ru.hermite=function(t,e,r,n,i,s){var a=s*s,o=a*(2*s-3)+1,l=a*(s-2)+s,u=a*(s-1),c=a*(3-2*s);return t[0]=e[0]*o+r[0]*l+n[0]*u+i[0]*c,t[1]=e[1]*o+r[1]*l+n[1]*u+i[1]*c,t[2]=e[2]*o+r[2]*l+n[2]*u+i[2]*c,t},ru.bezier=function(t,e,r,n,i,s){var a=1-s,o=a*a,l=s*s,u=o*a,c=3*s*o,h=3*l*a,p=l*s;return t[0]=e[0]*u+r[0]*c+n[0]*h+i[0]*p,t[1]=e[1]*u+r[1]*c+n[1]*h+i[1]*p,t[2]=e[2]*u+r[2]*c+n[2]*h+i[2]*p,t},ru.random=function(t,e){e=e||1;var r=2*iu.RANDOM()*Math.PI,n=2*iu.RANDOM()-1,i=Math.sqrt(1-n*n)*e;return t[0]=Math.cos(r)*i,t[1]=Math.sin(r)*i,t[2]=n*e,t},ru.transformMat4=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},ru.transformMat3=function(t,e,r){var n=e[0],i=e[1],s=e[2];return t[0]=n*r[0]+i*r[3]+s*r[6],t[1]=n*r[1]+i*r[4]+s*r[7],t[2]=n*r[2]+i*r[5]+s*r[8],t},ru.transformQuat=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=e[0],o=e[1],l=e[2],u=i*l-s*o,c=s*a-n*l,h=n*o-i*a,p=i*h-s*c,f=s*u-n*h,d=n*c-i*u,m=2*r[3];return c*=m,h*=m,f*=2,d*=2,t[0]=a+(u*=m)+(p*=2),t[1]=o+c+f,t[2]=l+h+d,t},ru.rotateX=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},ru.rotateY=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},ru.rotateZ=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},ru.angle=function(t,e){var r=t[0],n=t[1],i=t[2],s=e[0],a=e[1],o=e[2],l=Math.sqrt(r*r+n*n+i*i)*Math.sqrt(s*s+a*a+o*o),u=l&&du(t,e)/l;return Math.acos(Math.min(Math.max(u,-1),1))},ru.zero=function(t){return t[0]=0,t[1]=0,t[2]=0,t},ru.str=function(t){return \"vec3(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\")\"},ru.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]},ru.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=e[0],a=e[1],o=e[2];return Math.abs(r-s)<=iu.EPSILON*Math.max(1,Math.abs(r),Math.abs(s))&&Math.abs(n-a)<=iu.EPSILON*Math.max(1,Math.abs(n),Math.abs(a))&&Math.abs(i-o)<=iu.EPSILON*Math.max(1,Math.abs(i),Math.abs(o))},ru.forEach=ru.sqrLen=ru.len=ru.sqrDist=ru.dist=ru.div=ru.mul=ru.sub=void 0;var iu=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==nu(t)&&\"function\"!=typeof t)return {default:t};var r=su(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function su(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (su=function(t){return t?r:e})(t)}function au(){var t=new iu.ARRAY_TYPE(3);return iu.ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function ou(t){return Math.hypot(t[0],t[1],t[2])}function lu(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function uu(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function cu(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function hu(t,e){return Math.hypot(e[0]-t[0],e[1]-t[1],e[2]-t[2])}function pu(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}function fu(t){var e=t[0],r=t[1],n=t[2];return e*e+r*r+n*n}function du(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}ru.sub=lu,ru.mul=uu,ru.div=cu,ru.dist=hu,ru.sqrDist=pu,ru.len=ou,ru.sqrLen=fu;var mu,yu=(mu=au(),function(t,e,r,n,i,s){var a,o;for(e||(e=3),r||(r=0),o=n?Math.min(n*e+r,t.length):t.length,a=r;a0&&(a=1/Math.sqrt(a)),t[0]=r*a,t[1]=n*a,t[2]=i*a,t[3]=s*a,t},gu.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},gu.cross=function(t,e,r,n){var i=r[0]*n[1]-r[1]*n[0],s=r[0]*n[2]-r[2]*n[0],a=r[0]*n[3]-r[3]*n[0],o=r[1]*n[2]-r[2]*n[1],l=r[1]*n[3]-r[3]*n[1],u=r[2]*n[3]-r[3]*n[2],c=e[0],h=e[1],p=e[2],f=e[3];return t[0]=h*u-p*l+f*o,t[1]=-c*u+p*a-f*s,t[2]=c*l-h*a+f*i,t[3]=-c*o+h*s-p*i,t},gu.lerp=function(t,e,r,n){var i=e[0],s=e[1],a=e[2],o=e[3];return t[0]=i+n*(r[0]-i),t[1]=s+n*(r[1]-s),t[2]=a+n*(r[2]-a),t[3]=o+n*(r[3]-o),t},gu.random=function(t,e){var r,n,i,s,a,o;e=e||1;do{a=(r=2*vu.RANDOM()-1)*r+(n=2*vu.RANDOM()-1)*n;}while(a>=1);do{o=(i=2*vu.RANDOM()-1)*i+(s=2*vu.RANDOM()-1)*s;}while(o>=1);var l=Math.sqrt((1-a)/o);return t[0]=e*r,t[1]=e*n,t[2]=e*i*l,t[3]=e*s*l,t},gu.transformMat4=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*s+r[12]*a,t[1]=r[1]*n+r[5]*i+r[9]*s+r[13]*a,t[2]=r[2]*n+r[6]*i+r[10]*s+r[14]*a,t[3]=r[3]*n+r[7]*i+r[11]*s+r[15]*a,t},gu.transformQuat=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[0],o=r[1],l=r[2],u=r[3],c=u*n+o*s-l*i,h=u*i+l*n-a*s,p=u*s+a*i-o*n,f=-a*n-o*i-l*s;return t[0]=c*u+f*-a+h*-l-p*-o,t[1]=h*u+f*-o+p*-a-c*-l,t[2]=p*u+f*-l+c*-o-h*-a,t[3]=e[3],t},gu.zero=function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t},gu.str=function(t){return \"vec4(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\")\"},gu.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]},gu.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=e[0],o=e[1],l=e[2],u=e[3];return Math.abs(r-a)<=vu.EPSILON*Math.max(1,Math.abs(r),Math.abs(a))&&Math.abs(n-o)<=vu.EPSILON*Math.max(1,Math.abs(n),Math.abs(o))&&Math.abs(i-l)<=vu.EPSILON*Math.max(1,Math.abs(i),Math.abs(l))&&Math.abs(s-u)<=vu.EPSILON*Math.max(1,Math.abs(s),Math.abs(u))},gu.forEach=gu.sqrLen=gu.len=gu.sqrDist=gu.dist=gu.div=gu.mul=gu.sub=void 0;var vu=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==xu(t)&&\"function\"!=typeof t)return {default:t};var r=bu(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function bu(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (bu=function(t){return t?r:e})(t)}function _u(){var t=new vu.ARRAY_TYPE(4);return vu.ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function wu(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}function Mu(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t}function Au(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t[3]=e[3]/r[3],t}function Su(t,e){return Math.hypot(e[0]-t[0],e[1]-t[1],e[2]-t[2],e[3]-t[3])}function Iu(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2],s=e[3]-t[3];return r*r+n*n+i*i+s*s}function ku(t){return Math.hypot(t[0],t[1],t[2],t[3])}function Tu(t){var e=t[0],r=t[1],n=t[2],i=t[3];return e*e+r*r+n*n+i*i}gu.sub=wu,gu.mul=Mu,gu.div=Au,gu.dist=Su,gu.sqrDist=Iu,gu.len=ku,gu.sqrLen=Tu;var Pu=function(){var t=_u();return function(e,r,n,i,s,a){var o,l;for(r||(r=4),n||(n=0),l=i?Math.min(i*r+n,e.length):e.length,o=n;oEu.EPSILON?(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n):(t[0]=1,t[1]=0,t[2]=0),r},eu.getAngle=function(t,e){var r=Gu(t,e);return Math.acos(2*r*r-1)},eu.multiply=Fu,eu.rotateX=function(t,e,r){r*=.5;var n=e[0],i=e[1],s=e[2],a=e[3],o=Math.sin(r),l=Math.cos(r);return t[0]=n*l+a*o,t[1]=i*l+s*o,t[2]=s*l-i*o,t[3]=a*l-n*o,t},eu.rotateY=function(t,e,r){r*=.5;var n=e[0],i=e[1],s=e[2],a=e[3],o=Math.sin(r),l=Math.cos(r);return t[0]=n*l-s*o,t[1]=i*l+a*o,t[2]=s*l+n*o,t[3]=a*l-i*o,t},eu.rotateZ=function(t,e,r){r*=.5;var n=e[0],i=e[1],s=e[2],a=e[3],o=Math.sin(r),l=Math.cos(r);return t[0]=n*l+i*o,t[1]=i*l-n*o,t[2]=s*l+a*o,t[3]=a*l-s*o,t},eu.calculateW=function(t,e){var r=e[0],n=e[1],i=e[2];return t[0]=r,t[1]=n,t[2]=i,t[3]=Math.sqrt(Math.abs(1-r*r-n*n-i*i)),t},eu.exp=ju,eu.ln=Uu,eu.pow=function(t,e,r){return Uu(t,e),qu(t,t,r),ju(t,t),t},eu.slerp=Nu,eu.random=function(t){var e=Eu.RANDOM(),r=Eu.RANDOM(),n=Eu.RANDOM(),i=Math.sqrt(1-e),s=Math.sqrt(e);return t[0]=i*Math.sin(2*Math.PI*r),t[1]=i*Math.cos(2*Math.PI*r),t[2]=s*Math.sin(2*Math.PI*n),t[3]=s*Math.cos(2*Math.PI*n),t},eu.invert=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=r*r+n*n+i*i+s*s,o=a?1/a:0;return t[0]=-r*o,t[1]=-n*o,t[2]=-i*o,t[3]=s*o,t},eu.conjugate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},eu.fromMat3=$u,eu.fromEuler=function(t,e,r,n){var i=.5*Math.PI/180;e*=i,r*=i,n*=i;var s=Math.sin(e),a=Math.cos(e),o=Math.sin(r),l=Math.cos(r),u=Math.sin(n),c=Math.cos(n);return t[0]=s*l*c-a*o*u,t[1]=a*o*c+s*l*u,t[2]=a*l*u-s*o*c,t[3]=a*l*c+s*o*u,t},eu.str=function(t){return \"quat(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\")\"},eu.setAxes=eu.sqlerp=eu.rotationTo=eu.equals=eu.exactEquals=eu.normalize=eu.sqrLen=eu.squaredLength=eu.len=eu.length=eu.lerp=eu.dot=eu.scale=eu.mul=eu.add=eu.set=eu.copy=eu.fromValues=eu.clone=void 0;var Eu=Lu(_l),Bu=Lu(Ol),Du=Lu(ru),Cu=Lu(gu);function Ru(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (Ru=function(t){return t?r:e})(t)}function Lu(t,e){if(!e&&t&&t.__esModule)return t;if(null===t||\"object\"!==zu(t)&&\"function\"!=typeof t)return {default:t};var r=Ru(e);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}function Vu(){var t=new Eu.ARRAY_TYPE(4);return Eu.ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Ou(t,e,r){r*=.5;var n=Math.sin(r);return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=Math.cos(r),t}function Fu(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=r[0],l=r[1],u=r[2],c=r[3];return t[0]=n*c+a*o+i*u-s*l,t[1]=i*c+a*l+s*o-n*u,t[2]=s*c+a*u+n*l-i*o,t[3]=a*c-n*o-i*l-s*u,t}function ju(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=Math.sqrt(r*r+n*n+i*i),o=Math.exp(s),l=a>0?o*Math.sin(a)/a:0;return t[0]=r*l,t[1]=n*l,t[2]=i*l,t[3]=o*Math.cos(a),t}function Uu(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=Math.sqrt(r*r+n*n+i*i),o=a>0?Math.atan2(a,s)/a:0;return t[0]=r*o,t[1]=n*o,t[2]=i*o,t[3]=.5*Math.log(r*r+n*n+i*i+s*s),t}function Nu(t,e,r,n){var i,s,a,o,l,u=e[0],c=e[1],h=e[2],p=e[3],f=r[0],d=r[1],m=r[2],y=r[3];return (s=u*f+c*d+h*m+p*y)<0&&(s=-s,f=-f,d=-d,m=-m,y=-y),1-s>Eu.EPSILON?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*f,t[1]=o*c+l*d,t[2]=o*h+l*m,t[3]=o*p+l*y,t}function $u(t,e){var r,n=e[0]+e[4]+e[8];if(n>0)r=Math.sqrt(n+1),t[3]=.5*r,t[0]=(e[5]-e[7])*(r=.5/r),t[1]=(e[6]-e[2])*r,t[2]=(e[1]-e[3])*r;else {var i=0;e[4]>e[0]&&(i=1),e[8]>e[3*i+i]&&(i=2);var s=(i+1)%3,a=(i+2)%3;r=Math.sqrt(e[3*i+i]-e[3*s+s]-e[3*a+a]+1),t[i]=.5*r,t[3]=(e[3*s+a]-e[3*a+s])*(r=.5/r),t[s]=(e[3*s+i]+e[3*i+s])*r,t[a]=(e[3*a+i]+e[3*i+a])*r;}return t}eu.clone=Cu.clone,eu.fromValues=Cu.fromValues,eu.copy=Cu.copy,eu.set=Cu.set,eu.add=Cu.add,eu.mul=Fu;var qu=Cu.scale;eu.scale=qu;var Gu=Cu.dot;eu.dot=Gu,eu.lerp=Cu.lerp;var Yu=Cu.length;eu.length=Yu,eu.len=Yu;var Zu=Cu.squaredLength;eu.squaredLength=Zu,eu.sqrLen=Zu;var Xu=Cu.normalize;eu.normalize=Xu,eu.exactEquals=Cu.exactEquals,eu.equals=Cu.equals;var Ku,Wu,Hu,Ju=(Ku=Du.create(),Wu=Du.fromValues(1,0,0),Hu=Du.fromValues(0,1,0),function(t,e,r){var n=Du.dot(e,r);return n<-.999999?(Du.cross(Ku,Wu,e),Du.len(Ku)<1e-6&&Du.cross(Ku,Hu,e),Du.normalize(Ku,Ku),Ou(t,Ku,Math.PI),t):n>.999999?(t[0]=0,t[1]=0,t[2]=0,t[3]=1,t):(Du.cross(Ku,e,r),t[0]=Ku[0],t[1]=Ku[1],t[2]=Ku[2],t[3]=1+n,Xu(t,t))});eu.rotationTo=Ju;var Qu,tc,ec=(Qu=Vu(),tc=Vu(),function(t,e,r,n,i,s){return Nu(Qu,e,i,s),Nu(tc,r,n,s),Nu(t,Qu,tc,2*s*(1-s)),t});eu.sqlerp=ec;var rc,nc=(rc=Bu.create(),function(t,e,r,n){return rc[0]=r[0],rc[3]=r[1],rc[6]=r[2],rc[1]=n[0],rc[4]=n[1],rc[7]=n[2],rc[2]=-e[0],rc[5]=-e[1],rc[8]=-e[2],Xu(t,$u(t,rc))});eu.setAxes=nc;var ic={};function sc(t){return sc=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},sc(t)}Object.defineProperty(ic,\"__esModule\",{value:!0}),ic.create=function(){var t=new ac.ARRAY_TYPE(8);return ac.ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0),t[3]=1,t},ic.clone=function(t){var e=new ac.ARRAY_TYPE(8);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e},ic.fromValues=function(t,e,r,n,i,s,a,o){var l=new ac.ARRAY_TYPE(8);return l[0]=t,l[1]=e,l[2]=r,l[3]=n,l[4]=i,l[5]=s,l[6]=a,l[7]=o,l},ic.fromRotationTranslationValues=function(t,e,r,n,i,s,a){var o=new ac.ARRAY_TYPE(8);o[0]=t,o[1]=e,o[2]=r,o[3]=n;var l=.5*i,u=.5*s,c=.5*a;return o[4]=l*n+u*r-c*e,o[5]=u*n+c*t-l*r,o[6]=c*n+l*e-u*t,o[7]=-l*t-u*e-c*r,o},ic.fromRotationTranslation=hc,ic.fromTranslation=function(t,e){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=.5*e[0],t[5]=.5*e[1],t[6]=.5*e[2],t[7]=0,t},ic.fromRotation=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=0,t[5]=0,t[6]=0,t[7]=0,t},ic.fromMat4=function(t,e){var r=oc.create();lc.getRotation(r,e);var n=new ac.ARRAY_TYPE(3);return lc.getTranslation(n,e),hc(t,r,n),t},ic.copy=pc,ic.identity=function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t},ic.set=function(t,e,r,n,i,s,a,o,l){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=s,t[5]=a,t[6]=o,t[7]=l,t},ic.getDual=function(t,e){return t[0]=e[4],t[1]=e[5],t[2]=e[6],t[3]=e[7],t},ic.setDual=function(t,e){return t[4]=e[0],t[5]=e[1],t[6]=e[2],t[7]=e[3],t},ic.getTranslation=function(t,e){var r=e[4],n=e[5],i=e[6],s=e[7],a=-e[0],o=-e[1],l=-e[2],u=e[3];return t[0]=2*(r*u+s*a+n*l-i*o),t[1]=2*(n*u+s*o+i*a-r*l),t[2]=2*(i*u+s*l+r*o-n*a),t},ic.translate=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=.5*r[0],l=.5*r[1],u=.5*r[2],c=e[4],h=e[5],p=e[6],f=e[7];return t[0]=n,t[1]=i,t[2]=s,t[3]=a,t[4]=a*o+i*u-s*l+c,t[5]=a*l+s*o-n*u+h,t[6]=a*u+n*l-i*o+p,t[7]=-n*o-i*l-s*u+f,t},ic.rotateX=function(t,e,r){var n=-e[0],i=-e[1],s=-e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=o*a+c*n+l*s-u*i,p=l*a+c*i+u*n-o*s,f=u*a+c*s+o*i-l*n,d=c*a-o*n-l*i-u*s;return oc.rotateX(t,e,r),t[4]=h*(a=t[3])+d*(n=t[0])+p*(s=t[2])-f*(i=t[1]),t[5]=p*a+d*i+f*n-h*s,t[6]=f*a+d*s+h*i-p*n,t[7]=d*a-h*n-p*i-f*s,t},ic.rotateY=function(t,e,r){var n=-e[0],i=-e[1],s=-e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=o*a+c*n+l*s-u*i,p=l*a+c*i+u*n-o*s,f=u*a+c*s+o*i-l*n,d=c*a-o*n-l*i-u*s;return oc.rotateY(t,e,r),t[4]=h*(a=t[3])+d*(n=t[0])+p*(s=t[2])-f*(i=t[1]),t[5]=p*a+d*i+f*n-h*s,t[6]=f*a+d*s+h*i-p*n,t[7]=d*a-h*n-p*i-f*s,t},ic.rotateZ=function(t,e,r){var n=-e[0],i=-e[1],s=-e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=o*a+c*n+l*s-u*i,p=l*a+c*i+u*n-o*s,f=u*a+c*s+o*i-l*n,d=c*a-o*n-l*i-u*s;return oc.rotateZ(t,e,r),t[4]=h*(a=t[3])+d*(n=t[0])+p*(s=t[2])-f*(i=t[1]),t[5]=p*a+d*i+f*n-h*s,t[6]=f*a+d*s+h*i-p*n,t[7]=d*a-h*n-p*i-f*s,t},ic.rotateByQuatAppend=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=e[3];return t[0]=o*a+c*n+l*s-u*i,t[1]=l*a+c*i+u*n-o*s,t[2]=u*a+c*s+o*i-l*n,t[3]=c*a-o*n-l*i-u*s,t[4]=(o=e[4])*a+(c=e[7])*n+(l=e[5])*s-(u=e[6])*i,t[5]=l*a+c*i+u*n-o*s,t[6]=u*a+c*s+o*i-l*n,t[7]=c*a-o*n-l*i-u*s,t},ic.rotateByQuatPrepend=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=r[0],l=r[1],u=r[2],c=r[3];return t[0]=n*c+a*o+i*u-s*l,t[1]=i*c+a*l+s*o-n*u,t[2]=s*c+a*u+n*l-i*o,t[3]=a*c-n*o-i*l-s*u,t[4]=n*(c=r[7])+a*(o=r[4])+i*(u=r[6])-s*(l=r[5]),t[5]=i*c+a*l+s*o-n*u,t[6]=s*c+a*u+n*l-i*o,t[7]=a*c-n*o-i*l-s*u,t},ic.rotateAroundAxis=function(t,e,r,n){if(Math.abs(n)0){r=Math.sqrt(r);var n=e[0]/r,i=e[1]/r,s=e[2]/r,a=e[3]/r,o=e[4],l=e[5],u=e[6],c=e[7],h=n*o+i*l+s*u+a*c;t[0]=n,t[1]=i,t[2]=s,t[3]=a,t[4]=(o-n*h)/r,t[5]=(l-i*h)/r,t[6]=(u-s*h)/r,t[7]=(c-a*h)/r;}return t},ic.str=function(t){return \"quat2(\"+t[0]+\", \"+t[1]+\", \"+t[2]+\", \"+t[3]+\", \"+t[4]+\", \"+t[5]+\", \"+t[6]+\", \"+t[7]+\")\"},ic.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]},ic.equals=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=e[0],h=e[1],p=e[2],f=e[3],d=e[4],m=e[5],y=e[6],g=e[7];return Math.abs(r-c)<=ac.EPSILON*Math.max(1,Math.abs(r),Math.abs(c))&&Math.abs(n-h)<=ac.EPSILON*Math.max(1,Math.abs(n),Math.abs(h))&&Math.abs(i-p)<=ac.EPSILON*Math.max(1,Math.abs(i),Math.abs(p))&&Math.abs(s-f)<=ac.EPSILON*Math.max(1,Math.abs(s),Math.abs(f))&&Math.abs(a-d)<=ac.EPSILON*Math.max(1,Math.abs(a),Math.abs(d))&&Math.abs(o-m)<=ac.EPSILON*Math.max(1,Math.abs(o),Math.abs(m))&&Math.abs(l-y)<=ac.EPSILON*Math.max(1,Math.abs(l),Math.abs(y))&&Math.abs(u-g)<=ac.EPSILON*Math.max(1,Math.abs(u),Math.abs(g))},ic.sqrLen=ic.squaredLength=ic.len=ic.length=ic.dot=ic.mul=ic.setReal=ic.getReal=void 0;var ac=cc(_l),oc=cc(eu),lc=cc(ql);function uc(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (uc=function(t){return t?r:e})(t)}function cc(t,e){if(!e&&t&&t.__esModule)return t;if(null===t||\"object\"!==sc(t)&&\"function\"!=typeof t)return {default:t};var r=uc(e);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}function hc(t,e,r){var n=.5*r[0],i=.5*r[1],s=.5*r[2],a=e[0],o=e[1],l=e[2],u=e[3];return t[0]=a,t[1]=o,t[2]=l,t[3]=u,t[4]=n*u+i*l-s*o,t[5]=i*u+s*a-n*l,t[6]=s*u+n*o-i*a,t[7]=-n*a-i*o-s*l,t}function pc(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t}function fc(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=r[4],l=r[5],u=r[6],c=r[7],h=e[4],p=e[5],f=e[6],d=e[7],m=r[0],y=r[1],g=r[2],x=r[3];return t[0]=n*x+a*m+i*g-s*y,t[1]=i*x+a*y+s*m-n*g,t[2]=s*x+a*g+n*y-i*m,t[3]=a*x-n*m-i*y-s*g,t[4]=n*c+a*o+i*u-s*l+h*x+d*m+p*g-f*y,t[5]=i*c+a*l+s*o-n*u+p*x+d*y+f*m-h*g,t[6]=s*c+a*u+n*l-i*o+f*x+d*g+h*y-p*m,t[7]=a*c-n*o-i*l-s*u+d*x-h*m-p*y-f*g,t}ic.getReal=oc.copy,ic.setReal=oc.copy,ic.mul=fc;var dc=oc.dot;ic.dot=dc;var mc=oc.length;ic.length=mc,ic.len=mc;var yc=oc.squaredLength;ic.squaredLength=yc,ic.sqrLen=yc;var gc={};function xc(t){return xc=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t},xc(t)}Object.defineProperty(gc,\"__esModule\",{value:!0}),gc.create=_c,gc.clone=function(t){var e=new vc.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},gc.fromValues=function(t,e){var r=new vc.ARRAY_TYPE(2);return r[0]=t,r[1]=e,r},gc.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},gc.set=function(t,e,r){return t[0]=e,t[1]=r,t},gc.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t},gc.subtract=wc,gc.multiply=Mc,gc.divide=Ac,gc.ceil=function(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t},gc.floor=function(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t},gc.min=function(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t},gc.max=function(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t},gc.round=function(t,e){return t[0]=Math.round(e[0]),t[1]=Math.round(e[1]),t},gc.scale=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},gc.scaleAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t},gc.distance=Sc,gc.squaredDistance=Ic,gc.length=kc,gc.squaredLength=Tc,gc.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},gc.inverse=function(t,e){return t[0]=1/e[0],t[1]=1/e[1],t},gc.normalize=function(t,e){var r=e[0],n=e[1],i=r*r+n*n;return i>0&&(i=1/Math.sqrt(i)),t[0]=e[0]*i,t[1]=e[1]*i,t},gc.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},gc.cross=function(t,e,r){var n=e[0]*r[1]-e[1]*r[0];return t[0]=t[1]=0,t[2]=n,t},gc.lerp=function(t,e,r,n){var i=e[0],s=e[1];return t[0]=i+n*(r[0]-i),t[1]=s+n*(r[1]-s),t},gc.random=function(t,e){e=e||1;var r=2*vc.RANDOM()*Math.PI;return t[0]=Math.cos(r)*e,t[1]=Math.sin(r)*e,t},gc.transformMat2=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[2]*i,t[1]=r[1]*n+r[3]*i,t},gc.transformMat2d=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[2]*i+r[4],t[1]=r[1]*n+r[3]*i+r[5],t},gc.transformMat3=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[3]*i+r[6],t[1]=r[1]*n+r[4]*i+r[7],t},gc.transformMat4=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},gc.rotate=function(t,e,r,n){var i=e[0]-r[0],s=e[1]-r[1],a=Math.sin(n),o=Math.cos(n);return t[0]=i*o-s*a+r[0],t[1]=i*a+s*o+r[1],t},gc.angle=function(t,e){var r=t[0],n=t[1],i=e[0],s=e[1],a=Math.sqrt(r*r+n*n)*Math.sqrt(i*i+s*s);return Math.acos(Math.min(Math.max(a&&(r*i+n*s)/a,-1),1))},gc.zero=function(t){return t[0]=0,t[1]=0,t},gc.str=function(t){return \"vec2(\"+t[0]+\", \"+t[1]+\")\"},gc.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]},gc.equals=function(t,e){var r=t[0],n=t[1],i=e[0],s=e[1];return Math.abs(r-i)<=vc.EPSILON*Math.max(1,Math.abs(r),Math.abs(i))&&Math.abs(n-s)<=vc.EPSILON*Math.max(1,Math.abs(n),Math.abs(s))},gc.forEach=gc.sqrLen=gc.sqrDist=gc.dist=gc.div=gc.mul=gc.sub=gc.len=void 0;var vc=function(t,e){if(t&&t.__esModule)return t;if(null===t||\"object\"!==xc(t)&&\"function\"!=typeof t)return {default:t};var r=bc(void 0);if(r&&r.has(t))return r.get(t);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(\"default\"!==s&&Object.prototype.hasOwnProperty.call(t,s)){var a=i?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=t[s];}return n.default=t,r&&r.set(t,n),n}(_l);function bc(t){if(\"function\"!=typeof WeakMap)return null;var e=new WeakMap,r=new WeakMap;return (bc=function(t){return t?r:e})(t)}function _c(){var t=new vc.ARRAY_TYPE(2);return vc.ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0),t}function wc(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t}function Mc(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t}function Ac(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t}function Sc(t,e){return Math.hypot(e[0]-t[0],e[1]-t[1])}function Ic(t,e){var r=e[0]-t[0],n=e[1]-t[1];return r*r+n*n}function kc(t){return Math.hypot(t[0],t[1])}function Tc(t){var e=t[0],r=t[1];return e*e+r*r}gc.len=kc,gc.sub=wc,gc.mul=Mc,gc.div=Ac,gc.dist=Sc,gc.sqrDist=Ic,gc.sqrLen=Tc;var Pc=function(){var t=_c();return function(e,r,n,i,s,a){var o,l;for(r||(r=2),n||(n=0),l=i?Math.min(i*r+n,e.length):e.length,o=n;o0;s--)n=1<this.canonical.z?new Hc(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Hc(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e=!0){if(this.overscaledZ===t&&e)return this.key;if(t>this.canonical.z)return Jc(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y);{const r=this.canonical.z-t;return Jc(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new Hc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new Hc(e,this.wrap,e,r,n),new Hc(e,this.wrap,e,r+1,n),new Hc(e,this.wrap,e,r,n+1),new Hc(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y{let e=t.canonical.x-1,r=t.wrap;return e<0&&(e=(1<{let e=t.canonical.x+1,r=t.wrap;return e===1<new Hc(t.overscaledZ,t.wrap,t.canonical.z,t.canonical.x,(0===t.canonical.y?1<new Hc(t.overscaledZ,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y===(1<=0;if(0===a)return 0;a!==r.length&&(n=!1);}return n?2:1}function ih(t,e){for(const r of t.projections){const n=rh(e,t.points[0],r.axis);if(r.projection[1]n[1])return 0}return 1}function sh(e,r){let n=0;const i=[0,0,0,0];for(let s=0;s=0&&n++;return n}class ah{constructor(e,r){this.points=e||new Array(8).fill([0,0,0]),this.planes=r||new Array(6).fill([0,0,0,0]),this.bounds=oh.fromPoints(this.points),this.projections=[],this.frustumEdges=[t.v.sub([],this.points[2],this.points[3]),t.v.sub([],this.points[0],this.points[3]),t.v.sub([],this.points[4],this.points[0]),t.v.sub([],this.points[5],this.points[1]),t.v.sub([],this.points[6],this.points[2]),t.v.sub([],this.points[7],this.points[3])];for(const t of this.frustumEdges){const e=[0,-t[2],t[1]],r=[t[2],0,-t[0]];this.projections.push({axis:e,projection:rh(this.points,this.points[0],e)}),this.projections.push({axis:r,projection:rh(this.points,this.points[0],r)});}}static fromInvProjectionMatrix(e,r,n,i){const s=Math.pow(2,n),a=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((n=>{const a=t.e.transformMat4([],n,e),o=1/a[3]/r*s;return t.e.mul(a,a,[o,o,i?1/a[3]:o,o])})),o=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((e=>{const r=t.v.sub([],a[e[0]],a[e[1]]),n=t.v.sub([],a[e[2]],a[e[1]]),i=t.v.normalize([],t.v.cross([],r,n)),s=-t.v.dot(i,a[e[1]]);return i.concat(s)})),l=[];for(let t=0;to[1]||o[0]>a[1])return 0}return 1}}class oh{static fromPoints(e){const r=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(const i of e)t.v.min(r,r,i),t.v.max(n,n,i);return new oh(r,n)}static fromTileIdAndHeight(t,e,r){const n=1<t.max[e]||t.min[e]>this.max[e])return !1;return !0}intersectsAabbXY(t){return !(this.min[0]>t.max[0]||t.min[0]>this.max[0]||this.min[1]>t.max[1]||t.min[1]>this.max[1])}encapsulate(t){for(let e=0;e<3;e++)this.min[e]=Math.min(this.min[e],t.min[e]),this.max[e]=Math.max(this.max[e],t.max[e]);}encapsulatePoint(t){for(let e=0;e<3;e++)this.min[e]=Math.min(this.min[e],t[e]),this.max[e]=Math.max(this.max[e],t[e]);}closestPoint(t){return [Math.max(Math.min(this.max[0],t[0]),this.min[0]),Math.max(Math.min(this.max[1],t[1]),this.min[1]),Math.max(Math.min(this.max[2],t[2]),this.min[2])]}}Ks(oh,\"Aabb\");const lh=5,uh=6,ch=Cr/Math.PI/2,hh=16383,ph=64,fh=[ph,32,16],dh=-ch,mh=ch,yh=[new oh([dh,dh,dh],[mh,mh,mh]),new oh([dh,dh,dh],[0,0,mh]),new oh([0,dh,dh],[mh,0,mh]),new oh([dh,0,dh],[0,mh,mh]),new oh([0,0,dh],[mh,mh,mh])];function gh(t){return t*ch/qh}function xh(e,r,n,i=!0){const s=t.v.scale([],e._camera.position,e.worldSize),a=[r,n,1,1];t.e.transformMat4(a,a,e.pixelMatrixInverse),t.e.scale(a,a,1/a[3]);const o=t.v.sub([],a,s),l=t.v.normalize([],o),u=e.globeMatrix,c=[u[12],u[13],u[14]],h=t.v.sub([],c,s),p=t.v.length(h),f=t.v.normalize([],h),d=e.worldSize/(2*Math.PI),m=t.v.dot(f,l),y=Math.asin(d/p);if(y1?null:function(t,e,r,n){const i=Math.sin(r);return t*(Math.sin((1-n)*r)/i)+e*(Math.sin(n*r)/i)}(t.a[e],t.b[e],t.angle,k(r,0,1))+t.center[e]}function _h(t){if(t.z<=1)return yh[t.z+2*t.y+t.x];const e=kh(Ih(t));return oh.fromPoints(e)}function wh(e,r,n){return t.v.scale(e,e,1-n),t.v.scaleAndAdd(e,e,r,n)}function Mh(e,r){const n=Oh(r.zoom);if(0===n)return _h(e);const i=Ih(e),s=kh(i),a=Hh(i.getWest())*r.worldSize,o=Hh(i.getEast())*r.worldSize,l=Jh(i.getNorth())*r.worldSize,u=Jh(i.getSouth())*r.worldSize,c=[a,l,0],h=[o,l,0],p=[a,u,0],f=[o,u,0],d=t.m.invert([],r.globeMatrix);return t.v.transformMat4(c,c,d),t.v.transformMat4(h,h,d),t.v.transformMat4(p,p,d),t.v.transformMat4(f,f,d),s[0]=wh(s[0],p,n),s[1]=wh(s[1],f,n),s[2]=wh(s[2],h,n),s[3]=wh(s[3],c,n),oh.fromPoints(s)}function Ah(e,r,n){for(const i of e)t.v.transformMat4(i,i,r),t.v.scale(i,i,n);}function Sh(e,r,n,i){const s=r/e.worldSize,a=e.globeMatrix;if(n.z<=1){const t=_h(n).getCorners();return Ah(t,a,s),oh.fromPoints(t)}const o=Ih(n,i),l=kh(o);Ah(l,a,s);const u=Number.MAX_VALUE,c=[-u,-u,-u],h=[u,u,u];if(o.contains(e.center)){for(const e of l)t.v.min(h,h,e),t.v.max(c,c,e);c[2]=0;const r=e.point,n=[r.x*s,r.y*s,0];return t.v.min(h,h,n),t.v.max(c,c,n),new oh(h,c)}const p=[a[12]*s,a[13]*s,a[14]*s],f=o.getCenter(),d=k(e.center.lat,-np,np),m=k(f.lat,-np,np),y=Hh(e.center.lng),g=Jh(d);let x=y-Hh(f.lng);const v=g-Jh(m);x>.5?x-=1:x<-.5&&(x+=1);let b=0;if(Math.abs(x)>Math.abs(v))b=x>=0?1:3;else {b=v>=0?0:2;const e=[a[4]*s,a[5]*s,a[6]*s],r=-Math.sin(_(v>=0?o.getSouth():o.getNorth()))*ch;t.v.scaleAndAdd(p,p,e,r);}const w=l[b],M=l[(b+1)%4],A=new vh(w,M,p),S=[bh(A,0)||w[0],bh(A,1)||w[1],bh(A,2)||w[2]],I=Oh(e.zoom);if(I>0){const i=function({x:t,y:e,z:r},n,i,s,a){const o=1/(1<.5?p=-1:f<-.5&&(p=1),l=((l+p)*n-(s*=n))*i+s,u=((u+p)*n-s)*i+s,c=(c*n-(a*=n))*i+a,h=(h*n-a)*i+a,[[l,h,0],[u,h,0],[u,c,0],[l,c,0]]}(n,r,e._pixelsPerMercatorPixel,y,g);for(let t=0;tMath.PI/2*1.01}const Uh=_(85),Nh=Math.cos(Uh),$h=Math.sin(Uh),qh=6371008.8,Gh=2*Math.PI*qh;class Yh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error(\"Invalid LngLat latitude value: must be between -90 and 90\")}wrap(){return new Yh(P(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return qh*Math.acos(Math.min(i,1))}toBounds(t=0){const e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new vl(new Yh(this.lng-r,this.lat-e),new Yh(this.lng+r,this.lat+e))}toEcef(t){const e=gh(t);return Ph(this.lat,this.lng,ch+e)}static convert(t){if(t instanceof Yh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Yh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&\"object\"==typeof t&&null!==t)return new Yh(Number(\"lng\"in t?t.lng:t.lon),Number(t.lat));throw new Error(\"`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]\")}}var Zh=Yh;const Xh=0,Kh=25.5;function Wh(t){return Gh*Math.cos(t*Math.PI/180)}function Hh(t){return (180+t)/360}function Jh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Qh(t,e){return t/Wh(e)}function tp(t){return 360*t-180}function ep(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function rp(t,e){return t*Wh(ep(e))}const np=85.051129;function ip(t){return Math.cos(_(k(t,-np,np)))}function sp(t,e){const r=k(e,Xh,Kh),n=Math.pow(2,r);return ip(t)*Gh/(512*n)}function ap(t){return 1/Math.cos(t*Math.PI/180)}function op(t,e=0){const r=Math.exp(Math.PI*(1-(t.y+e/Cr)/(1<=l?(up(t,e,r,u,c,s,h,o,l),up(t,u,c,n,i,h,a,o,l)):t.push(a);}function cp(t,e,r){let n=t[0],i=n.x,s=n.y;e(n);const a=[n];for(let o=1;ot.x+1||nt.y+1)&&q(\"Geometry exceeds allowed extent, reduce your vector tile buffer size\"),t}function yp(t,e,r){const n=t.loadGeometry(),i=t.extent,s=Cr/i;if(e&&r&&r.projection.isReprojectedInTileSpace){const s=1<{const r=tp((e.x+t.x/i)/s),n=ep((e.y+t.y/i)/s),c=u.project(r,n);t.x=(c.x*a-o)*i,t.y=(c.y*a-l)*i;};for(let e=0;e=i||r.y<0||r.y>=i||(c(r),t.push(r));n[e]=t;}}for(const t of n)for(const e of t)mp(e,s);return n}function gp(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?yp(t):[]}}function xp(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}function vp(t,e,r){const n=16384;t.emplaceBack(e.x,e.y,e.z,r[0]*n,r[1]*n,r[2]*n);}class bp{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.fqid)),this.index=t.index,this.hasPattern=!1,this.projection=t.projection,this.layoutVertexArray=new $a,this.indexArray=new ao,this.segments=new Do,this.programConfigurations=new fl(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r,n){const i=this.layers[0],s=[];let a=null;\"circle\"===i.type&&(a=i.layout.get(\"circle-sort-key\"));for(const{feature:e,id:i,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=gp(e,t);if(!this.layers[0]._featureFilter.filter(new _a(this.zoom),u,r))continue;const c=a?a.evaluate(u,{},r):void 0,h={id:i,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:yp(e,r,n),patterns:{},sortKey:c};s.push(h);}a&&s.sort(((t,e)=>t.sortKey-e.sortKey));let o=null;\"globe\"===n.projection.name&&(this.globeExtVertexArray=new Ha,o=n.projection);for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n,l=t[s].feature;this.addFeature(n,i,s,e.availableImages,r,o,e.brightness),e.featureIndex.insert(l,i,s,a,this.index);}}update(t,e,r,n,i){const s=0!==Object.keys(t).length;s&&!this.stateDependentLayers.length||this.programConfigurations.updatePaintArrays(t,e,s?this.stateDependentLayers:this.layers,r,n,i);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Eo.members),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=t.createVertexBuffer(this.globeExtVertexArray,Bo.members))),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy());}addFeature(t,e,r,n,i,s,a){for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=Cr||n<0||n>=Cr)continue;if(s){const t=s.projectTilePoint(r,n,i),e=s.upVector(i,r,n),a=this.globeExtVertexArray;vp(a,t,e),vp(a,t,e),vp(a,t,e),vp(a,t,e);}const a=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),o=a.vertexLength;xp(this.layoutVertexArray,r,n,-1,-1),xp(this.layoutVertexArray,r,n,1,-1),xp(this.layoutVertexArray,r,n,1,1),xp(this.layoutVertexArray,r,n,-1,1),this.indexArray.emplaceBack(o,o+1,o+2),this.indexArray.emplaceBack(o,o+2,o+3),a.vertexLength+=4,a.primitiveLength+=2;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n,i,a);}}function _p(t,e){for(let r=0;r1){if(Sp(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Pp(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function zp(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Ep(t,e,r,n,i){for(const s of t)if(e<=s.x&&r<=s.y&&n>=s.x&&i>=s.y)return !0;const s=[new x(e,r),new x(e,i),new x(n,i),new x(n,r)];if(t.length>2)for(const e of s)if(zp(t,e))return !0;for(let e=0;ei.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function Dp(t,e,r,n,i,s){let a=e.y-t.y,o=t.x-e.x;if(s=s||0){const t=a*a+o*o;if(0===t)return !0;const e=Math.sqrt(t);a/=e,o/=e;}return !((r.x-t.x)*a+(r.y-t.y)*o-s<0||(n.x-t.x)*a+(n.y-t.y)*o-s<0||(i.x-t.x)*a+(i.y-t.y)*o-s<0)}function Cp(t,e,r,n,i,s,a){return !(Dp(t,e,n,i,s,a)||Dp(e,r,n,i,s,a)||Dp(r,t,n,i,s,a)||Dp(n,i,t,e,r,a)||Dp(i,s,t,e,r,a)||Dp(s,n,t,e,r,a))}function Rp(t,e,r){const n=e.paint.get(t).value;return \"constant\"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Lp(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Vp(t,e,r,n,i){if(!e[0]&&!e[1])return t;const s=x.convert(e)._mult(i);\"viewport\"===r&&s._rotate(-n);const a=[];for(let e=0;e{const e=[];return \"map\"===t.paint.get(\"circle-pitch-alignment\")&&e.push(\"PITCH_WITH_MAP\"),\"map\"===t.paint.get(\"circle-pitch-scale\")&&e.push(\"SCALE_WITH_MAP\"),e};function $p(e,r,n,i,s,a,o,l,u){if(a&&e.queryGeometry.isAboveHorizon)return !1;a&&(u*=e.pixelToTileUnitsFactor);const c=e.tileID.canonical,h=n.projection.upVectorScale(c,n.center.lat,n.worldSize).metersToTile;for(const p of r)for(const r of p){const p=r.add(l),f=s&&n.elevation?n.elevation.exaggeration()*s.getElevationAt(p.x,p.y,!0):0,d=n.projection.projectTilePoint(p.x,p.y,c);if(f>0){const t=n.projection.upVector(c,p.x,p.y);d.x+=t[0]*h*f,d.y+=t[1]*h*f,d.z+=t[2]*h*f;}const m=a?p:qp(d.x,d.y,d.z,i),y=a?e.tilespaceRays.map((t=>Zp(t,f))):e.queryGeometry.screenGeometry,g=t.e.transformMat4([],[d.x,d.y,d.z,1],i);if(!o&&a?u*=g[3]/n.cameraToCenterDistance:o&&!a&&(u*=n.cameraToCenterDistance/g[3]),a){const t=ep((r.y/Cr+c.y)/(1<t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError(\"out of range source coordinates for image copy\");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError(\"out of range destination coordinates for image copy\");const o=t.data,l=e.data,u=4===s&&a;for(let a=0;a{e[t.evaluationKey]=s;const a=t.expression.evaluate(e);a&&(i.data[r+n+0]=Math.floor(255*a.r/a.a),i.data[r+n+1]=Math.floor(255*a.g/a.a),i.data[r+n+2]=Math.floor(255*a.b/a.a),i.data[r+n+3]=Math.floor(255*a.a));};if(t.clips)for(let e=0,i=0;e80*r){n=s=t[0],i=a=t[1];for(var d=r;ds&&(s=o),l>a&&(a=l);u=0!==(u=Math.max(s-n,a-i))?32767/u:0;}return ff(p,f,r,n,i,u,0),f}function hf(t,e,r,n,i){var s,a;if(i===Rf(t,e,r,n)>0)for(s=e;s=e;s-=n)a=Bf(s,t[s],t[s+1],a);return a&&If(a,a.next)&&(Df(a),a=a.next),a}function pf(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!If(n,n.next)&&0!==Sf(n.prev,n,n.next))n=n.next;else {if(Df(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function ff(t,e,r,n,i,s,a){if(t){!a&&s&&function(t,e,r,n){var i=t;do{0===i.z&&(i.z=_f(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,s,a,o,l,u=1;do{for(r=t,t=null,s=null,a=0;r;){for(a++,n=r,o=0,e=0;e0||l>0&&n;)0!==o&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,o--):(i=n,n=n.nextZ,l--),s?s.nextZ=i:t=i,i.prevZ=s,s=i;r=n;}s.nextZ=null,u*=2;}while(a>1)}(i);}(t,n,i,s);for(var o,l,u=t;t.prev!==t.next;)if(o=t.prev,l=t.next,s?mf(t,n,i,s):df(t))e.push(o.i/r|0),e.push(t.i/r|0),e.push(l.i/r|0),Df(t),t=l.next,u=l.next;else if((t=l)===u){a?1===a?ff(t=yf(pf(t),e,r),e,r,n,i,s,2):2===a&&gf(t,e,r,n,i,s):ff(pf(t),e,r,n,i,s,1);break}}}function df(t){var e=t.prev,r=t,n=t.next;if(Sf(e,r,n)>=0)return !1;for(var i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=is?i>a?i:a:s>a?s:a,f=o>l?o>u?o:u:l>u?l:u,d=n.next;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Mf(i,o,s,l,a,u,d.x,d.y)&&Sf(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function mf(t,e,r,n){var i=t.prev,s=t,a=t.next;if(Sf(i,s,a)>=0)return !1;for(var o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=ol?o>u?o:u:l>u?l:u,y=c>h?c>p?c:p:h>p?h:p,g=_f(f,d,e,r,n),x=_f(m,y,e,r,n),v=t.prevZ,b=t.nextZ;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=m&&v.y>=d&&v.y<=y&&v!==i&&v!==a&&Mf(o,c,l,h,u,p,v.x,v.y)&&Sf(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=m&&b.y>=d&&b.y<=y&&b!==i&&b!==a&&Mf(o,c,l,h,u,p,b.x,b.y)&&Sf(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=m&&v.y>=d&&v.y<=y&&v!==i&&v!==a&&Mf(o,c,l,h,u,p,v.x,v.y)&&Sf(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=m&&b.y>=d&&b.y<=y&&b!==i&&b!==a&&Mf(o,c,l,h,u,p,b.x,b.y)&&Sf(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function yf(t,e,r){var n=t;do{var i=n.prev,s=n.next.next;!If(i,s)&&kf(i,n,n.next,s)&&zf(i,s)&&zf(s,i)&&(e.push(i.i/r|0),e.push(n.i/r|0),e.push(s.i/r|0),Df(n),Df(n.next),n=t=s),n=n.next;}while(n!==t);return pf(n)}function gf(t,e,r,n,i,s){var a=t;do{for(var o=a.next.next;o!==a.prev;){if(a.i!==o.i&&Af(a,o)){var l=Ef(a,o);return a=pf(a,a.next),l=pf(l,l.next),ff(a,e,r,n,i,s,0),void ff(l,e,r,n,i,s,0)}o=o.next;}a=a.next;}while(a!==t)}function xf(t,e){return t.x-e.x}function vf(t,e){var r=function(t,e){var r,n=e,i=t.x,s=t.y,a=-1/0;do{if(s<=n.y&&s>=n.next.y&&n.next.y!==n.y){var o=n.x+(s-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(o<=i&&o>a&&(a=o,r=n.x=n.x&&n.x>=c&&i!==n.x&&Mf(sr.x||n.x===r.x&&bf(r,n)))&&(r=n,p=l)),n=n.next;}while(n!==u);return r}(t,e);if(!r)return e;var n=Ef(r,t);return pf(n,n.next),pf(r,r.next)}function bf(t,e){return Sf(t.prev,t,e.prev)<0&&Sf(e.next,t,t.next)<0}function _f(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function wf(t){var e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Af(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&kf(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(zf(t,e)&&zf(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Sf(t.prev,t,e.prev)||Sf(t,e.prev,e))||If(t,e)&&Sf(t.prev,t,t.next)>0&&Sf(e.prev,e,e.next)>0)}function Sf(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function If(t,e){return t.x===e.x&&t.y===e.y}function kf(t,e,r,n){var i=Pf(Sf(t,e,r)),s=Pf(Sf(t,e,n)),a=Pf(Sf(r,n,t)),o=Pf(Sf(r,n,e));return i!==s&&a!==o||!(0!==i||!Tf(t,r,e))||!(0!==s||!Tf(t,n,e))||!(0!==a||!Tf(r,t,n))||!(0!==o||!Tf(r,e,n))}function Tf(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Pf(t){return t>0?1:t<0?-1:0}function zf(t,e){return Sf(t.prev,t,t.next)<0?Sf(t,e,t.next)>=0&&Sf(t,t.prev,e)>=0:Sf(t,e,t.prev)<0||Sf(t,t.next,e)<0}function Ef(t,e){var r=new Cf(t.i,t.x,t.y),n=new Cf(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Bf(t,e,r,n){var i=new Cf(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Df(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 Cf(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Rf(t,e,r,n){for(var i=0,s=e,a=r-n;s0&&r.holes.push(n+=t[i-1].length);}return r};var Lf=p(uf.exports);function Vf(t,e){const r=t.length;if(r<=1)return [t];const n=[];let i,s;for(let e=0;e1)for(let t=0;tt.fqid)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new $a,this.indexArray=new ao,this.indexArray2=new eo,this.programConfigurations=new fl(t.layers,t.zoom),this.segments=new Do,this.segments2=new Do,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.projection=t.projection;}populate(t,e,r,n){this.hasPattern=Ff(\"fill\",this.layers,e);const i=this.layers[0].layout.get(\"fill-sort-key\"),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=gp(a,t);if(!this.layers[0]._featureFilter.filter(new _a(this.zoom),c,r))continue;const h=i?i.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:yp(a,r,n),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=jf(\"fill\",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.availableImages,e.brightness);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r,n,i){const s=0!==Object.keys(t).length;s&&!this.stateDependentLayers.length||this.programConfigurations.updatePaintArrays(t,e,s?this.stateDependentLayers:this.layers,r,n,i);}addFeatures(t,e,r,n,i,s){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,r,n,s);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,lf),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s=[],a){for(const t of Vf(e,500)){let e=0;for(const r of t)e+=r.length;const r=this.segments.prepareSegment(e,this.layoutVertexArray,this.indexArray),n=r.vertexLength,i=[],s=[];for(const e of t){if(0===e.length)continue;e!==t[0]&&s.push(i.length/2);const r=this.segments2.prepareSegment(e.length,this.layoutVertexArray,this.indexArray2),n=r.vertexLength;this.layoutVertexArray.emplaceBack(e[0].x,e[0].y),this.indexArray2.emplaceBack(n+e.length-1,n),i.push(e[0].x),i.push(e[0].y);for(let t=1;t>3;}if(i--,1===n||2===n)s+=t.readSVarint(),a+=t.readSVarint(),1===n&&(e&&o.push(e),e=[]),e.push(new Hf(s,a));else {if(7!==n)throw new Error(\"unknown command \"+n);e&&e.push(e[0].clone());}}return e&&o.push(e),o},Qf.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())o&&(o=i),(s+=t.readSVarint())u&&(u=s);else if(7!==r)throw new Error(\"unknown command \"+r)}return [a,l,o,u]},Qf.prototype.toGeoJSON=function(t,e,r){var n,i,s=this.extent*Math.pow(2,r),a=this.extent*t,o=this.extent*e,l=this.loadGeometry(),u=Qf.types[this.type];function c(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}id.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error(\"feature index out of bounds\");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new rd(this._pbf,e,this.extent,this._keys,this._values)};var ad=nd;function od(t,e,r){if(3===t){var n=new ad(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}var ld=Wf.VectorTile=function(t,e){this.layers=t.readFields(od,{},e);},ud=Wf.VectorTileFeature=Jf;function cd(t,e,r,n){const i=[],s=0===n?(t,e,r,n,i,s)=>{t.push(new x(s,r+(s-e)/(n-e)*(i-r)));}:(t,e,r,n,i,s)=>{t.push(new x(e+(s-r)/(i-r)*(n-e),s));};for(const a of t){const t=[];for(const i of a){if(i.length<=2)continue;const a=[];for(let t=0;te&&s(a,o,l,u,c,e):h>r?p=e&&s(a,o,l,u,c,e),p>r&&h<=r&&s(a,o,l,u,c,r);}let o=i[i.length-1];const l=0===n?o.x:o.y;l>=e&&l<=r&&a.push(o),a.length&&(o=a[a.length-1],a[0].x===o.x&&a[0].y===o.y||a.push(a[0]),t.push(a));}t.length&&i.push(t);}return i}Wf.VectorTileLayer=nd;class hd{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e */\nread:function(t,e,r,n,i){var s,a,o=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,f=t[e+h];for(h+=p,s=f&(1<<-c)-1,f>>=-c,c+=o;c>0;s=256*s+t[e+h],h+=p,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+t[e+h],h+=p,c-=8);if(0===s)s=1-u;else {if(s===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=u;}return (f?-1:1)*a*Math.pow(2,s-n)},write:function(t,e,r,n,i,s){var a,o,l,u=8*s-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+h>=1?p/l:p*Math.pow(2,1-h))*l>=2&&(a++,l/=2),a+h>=c?(o=0,a=c):a+h>=1?(o=(e*l-1)*Math.pow(2,i),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&o,f+=d,o/=256,i-=8);for(a=a<0;t[r+f]=255&a,f+=d,a/=256,u-=8);t[r+f-d]|=128*m;}},fd=md,dd=pd;function md(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}md.Varint=0,md.Fixed64=1,md.Bytes=2,md.Fixed32=5;var yd=4294967296,gd=1/yd,xd=\"undefined\"==typeof TextDecoder?null:new TextDecoder(\"utf8\");function vd(t){return t.type===md.Bytes?t.readVarint()+t.pos:t.pos+1}function bd(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function _d(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function wd(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function Dd(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}md.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,s=this.pos;this.type=7&n,t(i,e,this),this.pos===s&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=Ed(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=Dd(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=Ed(this.buf,this.pos)+Ed(this.buf,this.pos+4)*yd;return this.pos+=8,t},readSFixed64:function(){var t=Ed(this.buf,this.pos)+Dd(this.buf,this.pos+4)*yd;return this.pos+=8,t},readFloat:function(){var t=dd.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=dd.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,s=r.buf;if(n=(112&(i=s[r.pos++]))>>4,i<128)return bd(t,n,e);if(n|=(127&(i=s[r.pos++]))<<3,i<128)return bd(t,n,e);if(n|=(127&(i=s[r.pos++]))<<10,i<128)return bd(t,n,e);if(n|=(127&(i=s[r.pos++]))<<17,i<128)return bd(t,n,e);if(n|=(127&(i=s[r.pos++]))<<24,i<128)return bd(t,n,e);if(n|=(1&(i=s[r.pos++]))<<31,i<128)return bd(t,n,e);throw new Error(\"Expected varint not more than 10 bytes\")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&xd?function(t,e,r){return xd.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n=\"\",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(s=t[i+1]))&&(u=(31&l)<<6|63&s)<=127&&(u=null):3===c?(a=t[i+2],128==(192&(s=t[i+1]))&&128==(192&a)&&((u=(15&l)<<12|(63&s)<<6|63&a)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+2],o=t[i+3],128==(192&(s=t[i+1]))&&128==(192&a)&&128==(192&o)&&((u=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&o)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==md.Bytes)return t.push(this.readVarint(e));var r=vd(this);for(t=t||[];this.pos127;);else if(e===md.Bytes)this.pos=this.readVarint()+this.pos;else if(e===md.Fixed32)this.pos+=4;else {if(e!==md.Fixed64)throw new Error(\"Unimplemented type: \"+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error(\"Given varint doesn't fit into 10 bytes\");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&_d(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),dd.write(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),dd.write(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&_d(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,md.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,wd,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,Md,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,Id,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,Ad,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,Sd,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,kd,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,Td,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,Pd,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,zd,e);},writeBytesField:function(t,e){this.writeTag(t,md.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,md.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,md.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,md.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,md.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,md.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,md.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,md.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,md.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,md.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var Cd=p(fd);const Rd=[\"tile\",\"layer\",\"source\",\"sourceLayer\",\"state\"];class Ld{constructor(t,e,r,n,i){this.type=\"Feature\",this._vectorTileFeature=t,this._z=e,this._x=r,this._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={type:\"Feature\",state:void 0,geometry:this.geometry,properties:this.properties};void 0!==this.id&&(t.id=this.id);for(const e of Rd)void 0!==this[e]&&(t[e]=this[e]);return t}}class Vd{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(t,e,r){const n=String(e);if(this.stateChanges[t]=this.stateChanges[t]||{},this.stateChanges[t][n]=this.stateChanges[t][n]||{},B(this.stateChanges[t][n],r),null===this.deletedStates[t]){this.deletedStates[t]={};for(const e in this.state[t])e!==n&&(this.deletedStates[t][e]=null);}else if(this.deletedStates[t]&&null===this.deletedStates[t][n]){this.deletedStates[t][n]={};for(const e in this.state[t][n])r[e]||(this.deletedStates[t][n][e]=null);}else for(const e in r)this.deletedStates[t]&&this.deletedStates[t][n]&&null===this.deletedStates[t][n][e]&&delete this.deletedStates[t][n][e];}removeFeatureState(t,e,r){if(null===this.deletedStates[t])return;const n=String(e);if(this.deletedStates[t]=this.deletedStates[t]||{},r&&void 0!==e)null!==this.deletedStates[t][n]&&(this.deletedStates[t][n]=this.deletedStates[t][n]||{},this.deletedStates[t][n][r]=null);else if(void 0!==e)if(this.stateChanges[t]&&this.stateChanges[t][n])for(r in this.deletedStates[t][n]={},this.stateChanges[t][n])this.deletedStates[t][n][r]=null;else this.deletedStates[t][n]=null;else this.deletedStates[t]=null;}getState(t,e){const r=String(e),n=B({},(this.state[t]||{})[r],(this.stateChanges[t]||{})[r]);if(null===this.deletedStates[t])return {};if(this.deletedStates[t]){const r=this.deletedStates[t][e];if(null===r)return {};for(const t in r)delete n[t];}return n}initializeTileState(t,e){t.setFeatureState(this.state,e);}coalesceChanges(t,e){const r={};for(const t in this.stateChanges){this.state[t]=this.state[t]||{};const e={};for(const r in this.stateChanges[t])this.state[t][r]||(this.state[t][r]={}),B(this.state[t][r],this.stateChanges[t][r]),e[r]=this.state[t][r];r[t]=e;}for(const t in this.deletedStates){this.state[t]=this.state[t]||{};const e={};if(null===this.deletedStates[t])for(const r in this.state[t])e[r]={},this.state[t][r]={};else for(const r in this.deletedStates[t]){if(null===this.deletedStates[t][r])this.state[t][r]={};else if(this.state[t][r])for(const e of Object.keys(this.deletedStates[t][r]))delete this.state[t][r][e];e[r]=this.state[t][r];}r[t]=r[t]||{},B(r[t],e);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(const n in t)t[n].setFeatureState(r,e);}}class Od{constructor(t){this.size=t,this.minimums=[],this.maximums=[],this.leaves=[];}getElevation(t,e){const r=this.toIdx(t,e);return {min:this.minimums[r],max:this.maximums[r]}}isLeaf(t,e){return this.leaves[this.toIdx(t,e)]}toIdx(t,e){return e*this.size+t}}function Fd(t,e,r,n){let i=0,s=Number.MAX_VALUE;for(let a=0;a<3;a++)if(Math.abs(n[a])<1e-15){if(r[a]e[a])return null}else {const o=1/n[a];let l=(t[a]-r[a])*o,u=(e[a]-r[a])*o;if(l>u){const t=l;l=u,u=t;}if(l>i&&(i=l),us)return null}return i}function jd(t,e,r,n,i,s,a,o,l,u,c){const h=n-t,p=i-e,f=s-r,d=a-t,m=o-e,y=l-r,g=c[1]*y-c[2]*m,x=c[2]*d-c[0]*y,v=c[0]*m-c[1]*d,b=h*g+p*x+f*v;if(Math.abs(b)<1e-15)return null;const _=1/b,w=u[0]-t,M=u[1]-e,A=u[2]-r,S=(w*g+M*x+A*v)*_;if(S<0||S>1)return null;const I=M*f-A*p,k=A*h-w*f,T=w*p-M*h,P=(c[0]*I+c[1]*k+c[2]*T)*_;return P<0||S+P>1?null:(d*I+m*k+y*T)*_}function Ud(t,e,r){return (t-e)/(r-e)}function Nd(t,e,r,n,i,s,a,o,l){const u=1<{const s=n?1:0,a=(t+1)*r-s,o=e*r,l=(e+1)*r-s;i[0]=t*r,i[1]=o,i[2]=a,i[3]=l;};let a=new Od(n);const o=[];for(let e=0;e=1;n/=2){const t=r[r.length-1];a=new Od(n);for(let e=0;e0;){const{idx:l,t:d,nodex:m,nodey:y,depth:g}=f.pop();if(this.leaves[l]){Nd(m,y,g,e,r,n,i,h,p);const l=1<=e[2])return d}continue}let x=0;for(let t=0;t=u[c[n]]&&(c.splice(n,0,t),r=!0);r||(c[x]=t),x++;}}for(let t=0;t=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError(\"out of range source coordinates for DEM data\");return (e+1)*this.stride+(t+1)}static pack(t,e){const r=[0,0,0,0],n=Kd.getUnpackVector(e);let i=Math.floor((t+n[3])/n[2]);return r[2]=i%256,i=Math.floor(i/256),r[1]=i%256,i=Math.floor(i/256),r[0]=i,r}getPixels(){return new tf({width:this.stride,height:this.stride},this.pixels)}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error(\"dem dimension mismatch\");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new ld(new Cd(this.rawTileData)).layers,this.sourceLayerCoder=new hd(this.vtLayers?Object.keys(this.vtLayers).sort():[\"_geojsonTileLayer\"]),this.vtFeatures={};for(const t in this.vtLayers)this.vtFeatures[t]=[];}return this.vtLayers}query(t,e,r,n){this.loadVTLayers();const i=t.params||{},s=ls(i.filter),a=t.tileResult,o=t.transform,l=a.bufferedTilespaceBounds,u=this.grid.query(l.min.x,l.min.y,l.max.x,l.max.y,((t,e,r,n)=>Ep(a.bufferedTilespaceGeometry,t,e,r,n)));u.sort(Qd);let c=null;o.elevation&&u.length>0&&(c=Wd.create(o.elevation,this.tileID));const h={};let p;for(let o=0;o(d||(d=yp(e,this.tileID.canonical,t.tileTransform)),r.queryIntersectsFeature(a,e,n,d,this.z,t.transform,t.pixelPosMatrix,c,i))));}return h}loadMatchingFeature(t,e,r,n,i,s,a,o,l){const{featureIndex:u,bucketIndex:c,sourceLayerIndex:h,layoutVertexArrayOffset:p}=e,f=this.bucketLayerIDs[c];if(n&&!function(t,e){for(let r=0;r=0)return !0;return !1}(n,f))return;const d=this.sourceLayerCoder.decode(h),m=this.vtLayers[d].feature(u);if(r.needGeometry){const t=gp(m,!0);if(!r.filter(new _a(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!r.filter(new _a(this.tileID.overscaledZ),m))return;const y=this.getId(m,d);for(let e=0;e{const a=e instanceof Pa?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function Qd(t,e){return e-t}Ks(Hd,\"FeatureIndex\",{omit:[\"rawTileData\",\"sourceLayerCoder\"]});const tm=Ua([{name:\"a_pos_offset\",components:4,type:\"Int16\"},{name:\"a_tex_size\",components:4,type:\"Uint16\"},{name:\"a_pixeloffset\",components:4,type:\"Int16\"}],4),em=Ua([{name:\"a_globe_anchor\",components:3,type:\"Int16\"},{name:\"a_globe_normal\",components:3,type:\"Float32\"}],4),rm=Ua([{name:\"a_projected_pos\",components:4,type:\"Float32\"}],4);Ua([{name:\"a_fade_opacity\",components:1,type:\"Uint32\"}],4);const nm=Ua([{name:\"a_z_offset\",components:1,type:\"Float32\"}],4),im=Ua([{name:\"a_texb\",components:2,type:\"Uint16\"}]),sm=Ua([{name:\"a_placed\",components:2,type:\"Uint8\"},{name:\"a_shift\",components:2,type:\"Float32\"}]),am=Ua([{name:\"a_size_scale\",components:1,type:\"Float32\"},{name:\"a_padding\",components:2,type:\"Float32\"},{name:\"a_z_offset\",components:1,type:\"Float32\"}]);Ua([{type:\"Int16\",name:\"projectedAnchorX\"},{type:\"Int16\",name:\"projectedAnchorY\"},{type:\"Int16\",name:\"projectedAnchorZ\"},{type:\"Int16\",name:\"tileAnchorX\"},{type:\"Int16\",name:\"tileAnchorY\"},{type:\"Float32\",name:\"x1\"},{type:\"Float32\",name:\"y1\"},{type:\"Float32\",name:\"x2\"},{type:\"Float32\",name:\"y2\"},{type:\"Int16\",name:\"padding\"},{type:\"Uint32\",name:\"featureIndex\"},{type:\"Uint16\",name:\"sourceLayerIndex\"},{type:\"Uint16\",name:\"bucketIndex\"}]);const om=Ua([{name:\"a_pos\",components:3,type:\"Int16\"},{name:\"a_anchor_pos\",components:2,type:\"Int16\"},{name:\"a_extrude\",components:2,type:\"Int16\"}],4),lm=Ua([{name:\"a_pos_2f\",components:2,type:\"Float32\"},{name:\"a_radius\",components:1,type:\"Float32\"},{name:\"a_flags\",components:2,type:\"Int16\"}],4);Ua([{name:\"triangle\",components:3,type:\"Uint16\"}]),Ua([{type:\"Int16\",name:\"projectedAnchorX\"},{type:\"Int16\",name:\"projectedAnchorY\"},{type:\"Int16\",name:\"projectedAnchorZ\"},{type:\"Float32\",name:\"tileAnchorX\"},{type:\"Float32\",name:\"tileAnchorY\"},{type:\"Uint16\",name:\"glyphStartIndex\"},{type:\"Uint16\",name:\"numGlyphs\"},{type:\"Uint32\",name:\"vertexStartIndex\"},{type:\"Uint32\",name:\"lineStartIndex\"},{type:\"Uint32\",name:\"lineLength\"},{type:\"Uint16\",name:\"segment\"},{type:\"Uint16\",name:\"lowerSize\"},{type:\"Uint16\",name:\"upperSize\"},{type:\"Float32\",name:\"lineOffsetX\"},{type:\"Float32\",name:\"lineOffsetY\"},{type:\"Uint8\",name:\"writingMode\"},{type:\"Uint8\",name:\"placedOrientation\"},{type:\"Uint8\",name:\"hidden\"},{type:\"Uint32\",name:\"crossTileID\"},{type:\"Int16\",name:\"associatedIconIndex\"},{type:\"Uint8\",name:\"flipState\"}]),Ua([{type:\"Float32\",name:\"tileAnchorX\"},{type:\"Float32\",name:\"tileAnchorY\"},{type:\"Int16\",name:\"projectedAnchorX\"},{type:\"Int16\",name:\"projectedAnchorY\"},{type:\"Int16\",name:\"projectedAnchorZ\"},{type:\"Int16\",name:\"rightJustifiedTextSymbolIndex\"},{type:\"Int16\",name:\"centerJustifiedTextSymbolIndex\"},{type:\"Int16\",name:\"leftJustifiedTextSymbolIndex\"},{type:\"Int16\",name:\"verticalPlacedTextSymbolIndex\"},{type:\"Int16\",name:\"placedIconSymbolIndex\"},{type:\"Int16\",name:\"verticalPlacedIconSymbolIndex\"},{type:\"Uint16\",name:\"key\"},{type:\"Uint16\",name:\"textBoxStartIndex\"},{type:\"Uint16\",name:\"textBoxEndIndex\"},{type:\"Uint16\",name:\"verticalTextBoxStartIndex\"},{type:\"Uint16\",name:\"verticalTextBoxEndIndex\"},{type:\"Uint16\",name:\"iconBoxStartIndex\"},{type:\"Uint16\",name:\"iconBoxEndIndex\"},{type:\"Uint16\",name:\"verticalIconBoxStartIndex\"},{type:\"Uint16\",name:\"verticalIconBoxEndIndex\"},{type:\"Uint16\",name:\"featureIndex\"},{type:\"Uint16\",name:\"numHorizontalGlyphVertices\"},{type:\"Uint16\",name:\"numVerticalGlyphVertices\"},{type:\"Uint16\",name:\"numIconVertices\"},{type:\"Uint16\",name:\"numVerticalIconVertices\"},{type:\"Uint16\",name:\"useRuntimeCollisionCircles\"},{type:\"Uint32\",name:\"crossTileID\"},{type:\"Float32\",components:2,name:\"textOffset\"},{type:\"Float32\",name:\"collisionCircleDiameter\"},{type:\"Float32\",name:\"zOffset\"},{type:\"Uint8\",name:\"hasIconTextFit\"}]),Ua([{type:\"Float32\",name:\"offsetX\"}]),Ua([{type:\"Int16\",name:\"x\"},{type:\"Int16\",name:\"y\"}]);var um=24;const cm=128;function hm(t,e){const{expression:r}=e;if(\"constant\"===r.kind)return {kind:\"constant\",layoutSize:r.evaluate(new _a(t+1))};if(\"source\"===r.kind)return {kind:\"source\"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;i{t.text=function(t,e,r){const n=e.layout.get(\"text-transform\").evaluate(r,{});return \"uppercase\"===n?t=t.toLocaleUpperCase():\"lowercase\"===n&&(t=t.toLocaleLowerCase()),ba.applyArabicShaping&&(t=ba.applyArabicShaping(t)),t}(t.text,e,r);})),t}const ym={\"!\":\"︕\",\"#\":\"#\",$:\"$\",\"%\":\"%\",\"&\":\"&\",\"(\":\"︵\",\")\":\"︶\",\"*\":\"*\",\"+\":\"+\",\",\":\"︐\",\"-\":\"︲\",\".\":\"・\",\"/\":\"/\",\":\":\"︓\",\";\":\"︔\",\"<\":\"︿\",\"=\":\"=\",\">\":\"﹀\",\"?\":\"︖\",\"@\":\"@\",\"[\":\"﹇\",\"\\\\\":\"\\",\"]\":\"﹈\",\"^\":\"^\",_:\"︳\",\"`\":\"`\",\"{\":\"︷\",\"|\":\"―\",\"}\":\"︸\",\"~\":\"~\",\"¢\":\"¢\",\"£\":\"£\",\"¥\":\"¥\",\"¦\":\"¦\",\"¬\":\"¬\",\"¯\":\" ̄\",\"–\":\"︲\",\"—\":\"︱\",\"‘\":\"﹃\",\"’\":\"﹄\",\"“\":\"﹁\",\"”\":\"﹂\",\"…\":\"︙\",\"‧\":\"・\",\"₩\":\"₩\",\"、\":\"︑\",\"。\":\"︒\",\"〈\":\"︿\",\"〉\":\"﹀\",\"《\":\"︽\",\"》\":\"︾\",\"「\":\"﹁\",\"」\":\"﹂\",\"『\":\"﹃\",\"』\":\"﹄\",\"【\":\"︻\",\"】\":\"︼\",\"〔\":\"︹\",\"〕\":\"︺\",\"〖\":\"︗\",\"〗\":\"︘\",\"!\":\"︕\",\"(\":\"︵\",\")\":\"︶\",\",\":\"︐\",\"-\":\"︲\",\".\":\"・\",\":\":\"︓\",\";\":\"︔\",\"<\":\"︿\",\">\":\"﹀\",\"?\":\"︖\",\"[\":\"﹇\",\"]\":\"﹈\",\"_\":\"︳\",\"{\":\"︷\",\"|\":\"―\",\"}\":\"︸\",\"⦅\":\"︵\",\"⦆\":\"︶\",\"。\":\"︒\",\"「\":\"﹁\",\"」\":\"﹂\",\"←\":\"↑\",\"→\":\"↓\"};function gm(t){return \"︶\"===t||\"﹈\"===t||\"︸\"===t||\"﹄\"===t||\"﹂\"===t||\"︾\"===t||\"︼\"===t||\"︺\"===t||\"︘\"===t||\"﹀\"===t||\"︐\"===t||\"︓\"===t||\"︔\"===t||\"`\"===t||\" ̄\"===t||\"︑\"===t||\"︒\"===t}function xm(t){return \"︵\"===t||\"﹇\"===t||\"︷\"===t||\"﹃\"===t||\"﹁\"===t||\"︽\"===t||\"︻\"===t||\"︹\"===t||\"︗\"===t||\"︿\"===t}const vm=3;function bm(t,e,r){e.glyphs=[],1===t&&r.readMessage(_m,e);}function _m(t,e,r){if(3===t){const{id:t,bitmap:n,width:i,height:s,left:a,top:o,advance:l}=r.readMessage(wm,{});e.glyphs.push({id:t,bitmap:new Jp({width:i+2*vm,height:s+2*vm},n),metrics:{width:i,height:s,left:a,top:o,advance:l}});}else 4===t?e.ascender=r.readSVarint():5===t&&(e.descender=r.readSVarint());}function wm(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}const Mm=vm,Am={horizontal:1,vertical:2,horizontalOnly:3},Sm=-17;class Im{constructor(){this.scale=1,this.fontStack=\"\",this.imageName=null;}static forText(t,e){const r=new Im;return r.scale=t||1,r.fontStack=e,r}static forImage(t){const e=new Im;return e.imageName=t,e}}class km{constructor(){this.text=\"\",this.sectionIndex=[],this.sections=[],this.imageSectionID=null;}static fromFeature(t,e){const r=new km;for(let n=0;n=0&&r>=t&&Pm[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new km;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}addTextSection(t,e){this.text+=t.text,this.sections.push(Im.forText(t.scale,t.fontStack||e));const r=this.sections.length-1;for(let e=0;e=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Tm(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d){const m=km.fromFeature(t,i);h===Am.vertical&&m.verticalizePunctuation(p);let y=[];const g=function(t,e,r,n,i,s){if(!t)return [];const a=[],o=function(t,e,r,n,i,s){let a=0;for(let r=0;r=0;let u=0;for(let r=0;r0&&s>_&&(_=s);}else {const t=r[o.fontStack];if(!t)continue;t[m]&&(A=t[m]);const n=e[o.fontStack];if(!n)continue;const s=n.glyphs[m];if(!s)continue;if(v=s.metrics,I=8203!==m?um:0,y){const t=void 0!==n.ascender?Math.abs(n.ascender):0,e=void 0!==n.descender?Math.abs(n.descender):0,r=(t+e)*g;w-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Nm(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=Mn(n.x,i.x,c),p=Mn(n.y,i.y,c),f=new jm(h,p,0,i.angleTo(n),r);return !a||Um(t,f,o,a,e)?f:void 0}l+=s;}}function Ym(t,e,r,n,i,s,a,o,l){const u=$m(n,s,a),c=qm(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new jm(g,x,0,m,e);n&&!Um(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Zm(t,h/2,r,n,i,s,a,!0,l)),f}function Xm(t,e,r,n,i){const s=[];for(let a=0;a=n&&u.x>=n||(a.x>=n?a=new x(n,a.y+(n-a.x)/(u.x-a.x)*(u.y-a.y))._round():u.x>=n&&(u=new x(n,a.y+(n-a.x)/(u.x-a.x)*(u.y-a.y))._round()),a.y>=i&&u.y>=i||(a.y>=i?a=new x(a.x+(i-a.y)/(u.y-a.y)*(u.x-a.x),i)._round():u.y>=i&&(u=new x(a.x+(i-a.y)/(u.y-a.y)*(u.x-a.x),i)._round()),l&&a.equals(l[l.length-1])||(l=[a],s.push(l)),l.push(u)))));}}return s}function Km(t){let e=0,r=0;for(const n of t)e+=n.w*n.h,r=Math.max(r,n.w);t.sort(((t,e)=>e.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();tt.hasImage(e,r))),t.dispatchRenderCallbacks(this.haveRenderCallbacks,r);for(const n in t.getUpdatedImages(r))this.patchUpdatedImage(this.iconPositions[n],t.getImage(n,r),e),this.patchUpdatedImage(this.patternPositions[n],t.getImage(n,r),e);}patchUpdatedImage(t,e,r){if(!t||!e)return;if(t.version===e.version)return;t.version=e.version;const[n,i]=t.tl,s=!!Object.keys(this.patternPositions).length;r.update(e.data,{useMipmap:s},{x:n,y:i});}}Ks(Hm,\"ImagePosition\"),Ks(Jm,\"ImageAtlas\");const Qm=1e20;function ty(t,e,r,n,i,s,a,o,l){for(let u=e;u-1);l++,s[l]=o,a[l]=u,a[l+1]=Qm;}for(let o=0,l=0;o{let n=this.entries[t];n||(n=this.entries[t]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let i=n.glyphs[e];if(void 0!==i)return void r(null,{stack:t,id:e,glyph:i});if(i=this._tinySDF(n,t,e),i)return n.glyphs[e]=i,void r(null,{stack:t,id:e,glyph:i});const a=Math.floor(e/256);if(256*a>65535)return void r(new Error(\"glyphs > 65535 not supported\"));if(n.ranges[a])return void r(null,{stack:t,id:e,glyph:i});let o=n.requests[a];o||(o=n.requests[a]=[],iy.loadGlyphRange(t,a,s,this.requestManager,((t,e)=>{if(e){n.ascender=e.ascender,n.descender=e.descender;for(const t in e.glyphs)this._doesCharSupportLocalGlyph(+t)||(n.glyphs[+t]=e.glyphs[+t]);n.ranges[a]=!0;}for(const r of o)r(t,e);delete n.requests[a];}))),o.push(((n,i)=>{n?r(n):i&&r(null,{stack:t,id:e,glyph:i.glyphs[e]||null});}));}),((t,e)=>{if(t)r(t);else if(e){const t={};for(const{stack:r,id:n,glyph:i}of e)void 0===t[r]&&(t[r]={}),void 0===t[r].glyphs&&(t[r].glyphs={}),t[r].glyphs[n]=i&&{id:i.id,bitmap:i.bitmap.clone(),metrics:i.metrics},t[r].ascender=this.entries[r].ascender,t[r].descender=this.entries[r].descender;r(null,t);}}));}_doesCharSupportLocalGlyph(t){return this.localGlyphMode!==ny.none&&(this.localGlyphMode===ny.all?!!this.localFontFamily:!!this.localFontFamily&&(ta[\"CJK Unified Ideographs\"](t)||ta[\"Hangul Syllables\"](t)||ta.Hiragana(t)||ta.Katakana(t)||ta[\"CJK Symbols and Punctuation\"](t)||ta[\"CJK Unified Ideographs Extension A\"](t)||ta[\"CJK Unified Ideographs Extension B\"](t)))}_tinySDF(t,e,r){const n=this.localFontFamily;if(!n||!this._doesCharSupportLocalGlyph(r))return;let i=t.tinySDF;if(!i){let r=\"400\";/bold/i.test(e)?r=\"900\":/medium/i.test(e)?r=\"500\":/light/i.test(e)&&(r=\"200\"),i=t.tinySDF=new iy.TinySDF({fontFamily:n,fontWeight:r,fontSize:24*ry,buffer:3*ry,radius:8*ry}),i.fontWeight=r;}if(this.localGlyphs[i.fontWeight][r])return this.localGlyphs[i.fontWeight][r];const s=String.fromCodePoint(r),{data:a,width:o,height:l,glyphWidth:u,glyphHeight:c,glyphLeft:h,glyphTop:p,glyphAdvance:f}=i.draw(s);return this.localGlyphs[i.fontWeight][r]={id:r,bitmap:new Jp({width:o,height:l},a),metrics:{width:u/ry,height:c/ry,left:h/ry,top:p/ry-27,advance:f/ry,localGlyph:!0}}}}iy.loadGlyphRange=function(t,e,r,n,i){const s=256*e,a=s+255,o=n.transformRequest(n.normalizeGlyphsURL(r).replace(\"{fontstack}\",t).replace(\"{range}\",`${s}-${a}`),ct.Glyphs);dt(o,((t,e)=>{if(t)i(t);else if(e){const t={},r=function(t){return new Cd(t).readFields(bm,{})}(e);for(const e of r.glyphs)t[e.id]=e;i(null,{glyphs:t,ascender:r.ascender,descender:r.descender});}}));},iy.TinySDF=class{constructor({fontSize:t=24,buffer:e=3,radius:r=8,cutoff:n=.25,fontFamily:i=\"sans-serif\",fontWeight:s=\"normal\",fontStyle:a=\"normal\"}={}){this.buffer=e,this.cutoff=n,this.radius=r;const o=this.size=t+4*e,l=this._createCanvas(o),u=this.ctx=l.getContext(\"2d\",{willReadFrequently:!0});u.font=`${a} ${s} ${t}px ${i}`,u.textBaseline=\"alphabetic\",u.textAlign=\"left\",u.fillStyle=\"black\",this.gridOuter=new Float64Array(o*o),this.gridInner=new Float64Array(o*o),this.f=new Float64Array(o),this.z=new Float64Array(o+1),this.v=new Uint16Array(o);}_createCanvas(t){const e=document.createElement(\"canvas\");return e.width=e.height=t,e}draw(t){const{width:e,actualBoundingBoxAscent:r,actualBoundingBoxDescent:n,actualBoundingBoxLeft:i,actualBoundingBoxRight:s}=this.ctx.measureText(t),a=Math.ceil(r),o=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(s-i))),l=Math.min(this.size-this.buffer,a+Math.ceil(n)),u=o+2*this.buffer,c=l+2*this.buffer,h=Math.max(u*c,0),p=new Uint8ClampedArray(h),f={data:p,width:u,height:c,glyphWidth:o,glyphHeight:l,glyphTop:a,glyphLeft:0,glyphAdvance:e};if(0===o||0===l)return f;const{ctx:d,buffer:m,gridInner:y,gridOuter:g}=this;d.clearRect(m,m,o,l),d.fillText(t,m,m+a);const x=d.getImageData(m,m,o,l);g.fill(Qm,0,h),y.fill(0,0,h);for(let t=0;t0?t*t:0,y[n]=t<0?t*t:0;}}ty(g,0,0,u,c,u,this.f,this.v,this.z),ty(y,m,m,o,l,u,this.f,this.v,this.z);for(let t=0;tt+e[1]-e[0],d=h.reduce(f,0),m=p.reduce(f,0),y=o-d,g=l-m;let v=0,b=d,_=0,w=m,M=0,A=y,S=0,I=g;if(s.content&&n){const t=s.content;v=oy(h,0,t[0]),_=oy(p,0,t[1]),b=oy(h,t[0],t[2]),w=oy(p,t[1],t[3]),M=t[0]-v,S=t[1]-_,A=t[2]-t[0]-b,I=t[3]-t[1]-w;}const k=(n,i,o,l)=>{const h=uy(n.stretch-v,b,u,t.left),p=cy(n.fixed-M,A,n.stretch,d),f=uy(i.stretch-_,w,c,t.top),y=cy(i.fixed-S,I,i.stretch,m),g=uy(o.stretch-v,b,u,t.left),k=cy(o.fixed-M,A,o.stretch,d),T=uy(l.stretch-_,w,c,t.top),P=cy(l.fixed-S,I,l.stretch,m),z=new x(h,f),E=new x(g,f),B=new x(g,T),D=new x(h,T),C=new x(p/a,y/a),R=new x(k/a,P/a),L=e*Math.PI/180;if(L){const t=Math.sin(L),e=Math.cos(L),r=[e,-t,t,e];z._matMult(r),E._matMult(r),D._matMult(r),B._matMult(r);}const V=n.stretch+n.fixed,O=o.stretch+o.fixed,F=i.stretch+i.fixed,j=l.stretch+l.fixed,U=t.imageSecondary;return {tl:z,tr:E,bl:D,br:B,texPrimary:{x:s.paddedRect.x+sy+V,y:s.paddedRect.y+sy+F,w:O-V,h:j-F},texSecondary:U?{x:U.paddedRect.x+sy+V,y:U.paddedRect.y+sy+F,w:O-V,h:j-F}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:C,pixelOffsetBR:R,minFontScaleX:A/a/u,minFontScaleY:I/a/c,isSDF:r}};if(n&&(s.stretchX||s.stretchY)){const t=ly(h,y,d),e=ly(p,g,m);for(let r=0;rs)&&(s=e.x),(!t||e.y>a)&&(a=e.y);}const l=Math.min(s-n,a-i);let u=l/2;const c=new Dr([],fy);if(0===l)return new x(n,i);for(let e=n;eh.d||!h.d)&&(h=n,r&&console.log(\"found best %d after %d probes\",Math.round(1e4*n.d)/1e4,p)),n.max-h.d<=e||(u=n.h/2,c.push(new dy(n.p.x-u,n.p.y-u,u,t)),c.push(new dy(n.p.x+u,n.p.y-u,u,t)),c.push(new dy(n.p.x-u,n.p.y+u,u,t)),c.push(new dy(n.p.x+u,n.p.y+u,u,t)),p+=4);}return r&&(console.log(`num probes: ${p}`),console.log(`best distance: ${h.d}`)),h.p}function fy(t,e){return e.max-t.max}class dy{constructor(t,e,r,n){this.p=new x(t,e),this.h=r,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Tp(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}}const my=7,yy=Number.POSITIVE_INFINITY,gy=Math.sqrt(2);function xy(t,[e,r]){let n=0,i=0;if(r===yy){e<0&&(e=0);const r=e/gy;switch(t){case\"top-right\":case\"top-left\":i=r-my;break;case\"bottom-right\":case\"bottom-left\":i=-r+my;break;case\"bottom\":i=-e+my;break;case\"top\":i=e-my;}switch(t){case\"top-right\":case\"bottom-right\":n=-r;break;case\"top-left\":case\"bottom-left\":n=r;break;case\"left\":n=e;break;case\"right\":n=-e;}}else {switch(e=Math.abs(e),r=Math.abs(r),t){case\"top-right\":case\"top-left\":case\"top\":i=r-my;break;case\"bottom-right\":case\"bottom-left\":case\"bottom\":i=-r+my;}switch(t){case\"top-right\":case\"bottom-right\":case\"right\":n=-e;break;case\"top-left\":case\"bottom-left\":case\"left\":n=e;}}return [n,i]}function vy(t,e,r,n,i,s,a,o,l,u,c){t.createArrays(),t.tilePixelRatio=Cr/(512*t.overscaling),t.compareText={},t.iconsNeedLinear=!1;const h=t.layers[0].layout,p=t.layers[0]._unevaluatedLayout._values,f={};if(\"composite\"===t.textSizeData.kind){const{minZoom:e,maxZoom:r}=t.textSizeData;f.compositeTextSizes=[p[\"text-size\"].possiblyEvaluate(new _a(e),o),p[\"text-size\"].possiblyEvaluate(new _a(r),o)];}if(\"composite\"===t.iconSizeData.kind){const{minZoom:e,maxZoom:r}=t.iconSizeData;f.compositeIconSizes=[p[\"icon-size\"].possiblyEvaluate(new _a(e),o),p[\"icon-size\"].possiblyEvaluate(new _a(r),o)];}f.layoutTextSize=p[\"text-size\"].possiblyEvaluate(new _a(l+1),o),f.layoutIconSize=p[\"icon-size\"].possiblyEvaluate(new _a(l+1),o),f.textMaxSize=p[\"text-size\"].possiblyEvaluate(new _a(18),o);const d=\"map\"===h.get(\"text-rotation-alignment\")&&\"point\"!==h.get(\"symbol-placement\"),m=h.get(\"text-size\");let y=!1;for(const e of t.features)if(e.icon&&e.icon.nameSecondary){y=!0;break}for(const s of t.features){const l=h.get(\"text-font\").evaluate(s,{},o).join(\",\"),p=m.evaluate(s,{},o),g=f.layoutTextSize.evaluate(s,{},o),x=(f.layoutIconSize.evaluate(s,{},o),{horizontal:{},vertical:void 0}),v=s.text;let b,_=[0,0];if(v){const n=v.toString(),a=h.get(\"text-letter-spacing\").evaluate(s,{},o)*um,u=h.get(\"text-line-height\").evaluate(s,{},o)*um,c=ra(n)?a:0,f=h.get(\"text-anchor\").evaluate(s,{},o),m=h.get(\"text-variable-anchor\");if(!m){const t=h.get(\"text-radial-offset\").evaluate(s,{},o);_=t?xy(f,[t*um,yy]):h.get(\"text-offset\").evaluate(s,{},o).map((t=>t*um));}let y=d?\"center\":h.get(\"text-justify\").evaluate(s,{},o);const b=\"point\"===h.get(\"symbol-placement\"),w=b?h.get(\"text-max-width\").evaluate(s,{},o)*um:1/0,M=s=>{t.allowVerticalPlacement&&ea(n)&&(x.vertical=Tm(v,e,r,i,l,w,u,f,s,c,_,Am.vertical,!0,g,p));};if(!d&&m){const t=\"auto\"===y?m.map((t=>by(t))):[y];let n=!1;for(let s=0;s=0||!ea(n)){const t=Tm(v,e,r,i,l,w,u,f,y,c,_,Am.horizontal,!1,g,p);t&&(x.horizontal[y]=t);}M(b?\"left\":y);}}let w=!1;if(s.icon&&s.icon.namePrimary){const e=n[s.icon.namePrimary];e&&(b=Om(i[s.icon.namePrimary],s.icon.nameSecondary?i[s.icon.nameSecondary]:void 0,h.get(\"icon-offset\").evaluate(s,{},o),h.get(\"icon-anchor\").evaluate(s,{},o)),w=e.sdf,void 0===t.sdfIcons?t.sdfIcons=e.sdf:t.sdfIcons!==e.sdf&&q(\"Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer\"),(e.pixelRatio!==t.pixelRatio||0!==h.get(\"icon-rotate\").constantOr(1))&&(t.iconsNeedLinear=!0));}const M=Sy(x.horizontal)||x.vertical;t.iconsInText||(t.iconsInText=!!M&&M.iconsInText),(M||b)&&_y(t,s,x,b,n,f,g,0,_,w,a,o,u,c,y);}s&&t.generateCollisionDebugBuffers(l,t.collisionBoxArray);}function by(t){switch(t){case\"right\":case\"top-right\":case\"bottom-right\":return \"right\";case\"left\":case\"top-left\":case\"bottom-left\":return \"left\"}return \"center\"}function _y(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d){let m=s.textMaxSize.evaluate(e,{},h);void 0===m&&(m=a);const y=t.layers[0].layout,g=y.get(\"icon-offset\").evaluate(e,{},h),x=Sy(r.horizontal)||r.vertical,v=\"globe\"===p.name,b=um,w=a/b,M=t.tilePixelRatio*m/b,A=(B=t.overscaling,t.zoom>18&&B>2&&(B>>=1),Math.max(Cr/(512*B),1)*y.get(\"symbol-spacing\")),S=y.get(\"text-padding\")*t.tilePixelRatio,I=y.get(\"icon-padding\")*t.tilePixelRatio,k=_(y.get(\"text-max-angle\")),T=\"map\"===y.get(\"text-rotation-alignment\")&&\"point\"!==y.get(\"symbol-placement\"),P=\"map\"===y.get(\"icon-rotation-alignment\")&&\"point\"!==y.get(\"symbol-placement\"),z=y.get(\"symbol-placement\"),E=A/2;var B;const D=y.get(\"icon-text-fit\").evaluate(e,{},h),C=y.get(\"icon-text-fit-padding\").evaluate(e,{},h),R=\"none\"!==D;let L;!1===t.hasAnyIconTextFit&&R&&(t.hasAnyIconTextFit=!0),n&&R&&(t.allowVerticalPlacement&&r.vertical&&(L=Fm(n,r.vertical,D,C,g,w)),x&&(n=Fm(n,x,D,C,g,w)));const V=(a,o,m)=>{if(o.x<0||o.x>=Cr||o.y<0||o.y>=Cr)return;let y=null;if(v){const{x:t,y:e,z:r}=p.projectTilePoint(o.x,o.y,m);y={anchor:new jm(t,e,r,0,void 0),up:p.upVector(m,o.x,o.y)};}!function(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g,x,v,b,_,w,M,A,S,I){const k=t.addToLineVertexArray(e,n);let T,P,z,E,B,D,C,R=0,L=0,V=0,O=0,F=-1,j=-1;const U={};let N=$o(\"\");const $=r?r.anchor:e,G=\"none\"!==l.layout.get(\"icon-text-fit\").evaluate(b,{},A);let Y=0,Z=0;if(void 0===l._unevaluatedLayout.getValue(\"text-radial-offset\")?[Y,Z]=l.layout.get(\"text-offset\").evaluate(b,{},A).map((t=>t*um)):(Y=l.layout.get(\"text-radial-offset\").evaluate(b,{},A)*um,Z=yy),t.allowVerticalPlacement&&i.vertical){const t=i.vertical;if(d)D=ky(t),o&&(C=ky(o));else {const r=l.layout.get(\"text-rotate\").evaluate(b,{},A)+90;z=Iy(u,$,e,c,h,p,t,f,r,m),o&&(E=Iy(u,$,e,c,h,p,o,g,r));}}if(s){const n=l.layout.get(\"icon-rotate\").evaluate(b,{},A),i=ay(s,n,w,G),a=o?ay(o,n,w,G):void 0;P=Iy(u,$,e,c,h,p,s,g,n),R=4*i.length;const f=t.iconSizeData;let d=null;\"source\"===f.kind?(d=[cm*l.layout.get(\"icon-size\").evaluate(b,{},A)],d[0]>My&&q(`${t.layerIds[0]}: Value for \"icon-size\" is >= ${wy}. Reduce your \"icon-size\".`)):\"composite\"===f.kind&&(d=[cm*_.compositeIconSizes[0].evaluate(b,{},A),cm*_.compositeIconSizes[1].evaluate(b,{},A)],(d[0]>My||d[1]>My)&&q(`${t.layerIds[0]}: Value for \"icon-size\" is >= ${wy}. Reduce your \"icon-size\".`)),t.addSymbols(t.icon,i,d,v,x,b,!1,r,e,k.lineStartIndex,k.lineLength,-1,M,A,S,I),F=t.icon.placedSymbolArray.length-1,a&&(L=4*a.length,t.addSymbols(t.icon,a,d,v,x,b,Am.vertical,r,e,k.lineStartIndex,k.lineLength,-1,M,A,S,I),j=t.icon.placedSymbolArray.length-1);}for(const n in i.horizontal){const s=i.horizontal[n];T||(N=$o(s.text),d?B=ky(s):T=Iy(u,$,e,c,h,p,s,f,l.layout.get(\"text-rotate\").evaluate(b,{},A),m));const o=1===s.positionedLines.length;if(V+=Ay(t,r,e,s,a,l,d,b,m,k,i.vertical?Am.horizontal:Am.horizontalOnly,o?Object.keys(i.horizontal):[n],U,F,_,M,A,S),o)break}i.vertical&&(O+=Ay(t,r,e,i.vertical,a,l,d,b,m,k,Am.vertical,[\"vertical\"],U,j,_,M,A,S));let X=-1;const K=(t,e)=>t?Math.max(t,e):e;X=K(B,X),X=K(D,X),X=K(C,X);const W=X>-1?1:0;t.glyphOffsetArray.length>=fg.MAX_GLYPHS&&q(\"Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907\"),void 0!==b.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,b.sortKey),t.symbolInstances.emplaceBack(e.x,e.y,$.x,$.y,$.z,U.right>=0?U.right:-1,U.center>=0?U.center:-1,U.left>=0?U.left:-1,U.vertical>=0?U.vertical:-1,F,j,N,void 0!==T?T:t.collisionBoxArray.length,void 0!==T?T+1:t.collisionBoxArray.length,void 0!==z?z:t.collisionBoxArray.length,void 0!==z?z+1:t.collisionBoxArray.length,void 0!==P?P:t.collisionBoxArray.length,void 0!==P?P+1:t.collisionBoxArray.length,E||t.collisionBoxArray.length,E?E+1:t.collisionBoxArray.length,c,V,O,R,L,W,0,Y,Z,X,0,G?1:0);}(t,o,y,a,r,n,i,L,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,S,T,l,0,I,P,g,e,s,u,c,h,f,d);};if(\"line\"===z)for(const i of Xm(e.geometry,0,0,Cr,Cr)){const e=Ym(i,A,k,r.vertical||x,n,b,M,t.overscaling,Cr);for(const r of e)x&&Ty(t,x.text,E,r)||V(i,r,h);}else if(\"line-center\"===z){for(const t of e.geometry)if(t.length>1){const e=Gm(t,k,r.vertical||x,n,b,M);e&&V(t,e,h);}}else if(\"Polygon\"===e.type)for(const t of Vf(e.geometry,0)){const e=py(t,16);V(t[0],new jm(e.x,e.y,0,0,void 0),h);}else if(\"LineString\"===e.type)for(const t of e.geometry)V(t,new jm(t[0].x,t[0].y,0,0,void 0),h);else if(\"Point\"===e.type)for(const t of e.geometry)for(const e of t)V([e],new jm(e.x,e.y,0,0,void 0),h);}const wy=255,My=wy*cm;function Ay(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m,y,g){const v=function(t,e,r,n,i,s,a,o){const l=[];if(0===e.positionedLines.length)return l;const u=n.layout.get(\"text-rotate\").evaluate(s,{})*Math.PI/180,c=function(t){const e=t[0],r=t[1],n=e*r;return n>0?[e,-r]:n<0?[-e,r]:0===e?[r,e]:[r,-e]}(r);let h=Math.abs(e.top-e.bottom);for(const t of e.positionedLines)h-=t.lineOffset;const p=e.positionedLines.length,f=h/p;let d=e.top-r[1];for(let t=0;tMy&&q(`${t.layerIds[0]}: Value for \"text-size\" is >= ${wy}. Reduce your \"text-size\".`)):\"composite\"===b.kind&&(_=[cm*d.compositeTextSizes[0].evaluate(o,{},y),cm*d.compositeTextSizes[1].evaluate(o,{},y)],(_[0]>My||_[1]>My)&&q(`${t.layerIds[0]}: Value for \"text-size\" is >= ${wy}. Reduce your \"text-size\".`)),t.addSymbols(t.text,v,_,l,a,o,c,e,r,u.lineStartIndex,u.lineLength,f,m,y,g,!1);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*v.length}function Sy(t){for(const e in t)return t[e];return null}function Iy(t,e,r,n,i,s,a,o,l,u){let c=a.top,h=a.bottom,p=a.left,f=a.right;const d=a.collisionPadding;if(d&&(p-=d[0],c-=d[1],f+=d[2],h+=d[3]),l){const t=new x(p,c),e=new x(f,c),r=new x(p,h),n=new x(f,h),i=_(l);let s=new x(0,0);u&&(s=new x(u[0],u[1])),t._rotateAround(i,s),e._rotateAround(i,s),r._rotateAround(i,s),n._rotateAround(i,s),p=Math.min(t.x,e.x,r.x,n.x),f=Math.max(t.x,e.x,r.x,n.x),c=Math.min(t.y,e.y,r.y,n.y),h=Math.max(t.y,e.y,r.y,n.y);}return t.emplaceBack(e.x,e.y,e.z,r.x,r.y,p,c,f,h,o,n,i,s),t.length-1}function ky(t){t.collisionPadding&&(t.top-=t.collisionPadding[1],t.bottom+=t.collisionPadding[3]);const e=t.bottom-t.top;return e>0?Math.max(10,e):null}function Ty(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])v&&(b(t,u,n,i,o,l),b(u,r,o,l,s,a));}b(h,p,n,s,i,s),b(p,f,i,s,i,a),b(f,d,i,a,n,a),b(d,h,n,a,n,s),m-=v,y-=v,g+=v,x+=v;const _=1/Math.max(g-m,x-y);return {scale:_,x:m*_,y:y*_,x2:g*_,y2:x*_,projection:e}}function Ey(t,{x:e,y:r},n=0){return new x(((e-n)*t.scale-t.x)*Cr,(r*t.scale-t.y)*Cr)}const By=t.m.identity(new Float32Array(16));class Dy{constructor(t){this.spec=t,this.name=t.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit=\"meters\",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=[\"custom\"],this.center=[0,0],this.range=[3.5,7];}project(t,e){return {x:0,y:0,z:0}}unproject(t,e){return new Zh(0,0)}projectTilePoint(t,e,r){return {x:t,y:e,z:0}}locationPoint(t,e,r=!0){return t._coordinatePoint(t.locationCoordinate(e),r)}pixelsPerMeter(t,e){return Qh(1,t)*e}pixelSpaceConversion(t,e,r){return 1}farthestPixelDistance(t){return Py(t,t.pixelsPerMeter)}pointCoordinate(t,e,r,n){const i=t.horizonLineFromTop(!1),s=new x(e,Math.max(i,r));return t.rayIntersectionCoordinate(t.pointRayIntersection(s,n))}pointCoordinate3D(t,e,r){const n=new x(e,r);if(t.elevation)return t.elevation.pointCoordinate(n);{const e=this.pointCoordinate(t,n.x,n.y,0);return [e.x,e.y,e.z]}}isPointAboveHorizon(t,e){if(t.elevation)return !this.pointCoordinate3D(t,e.x,e.y);const r=t.horizonLineFromTop();return e.y0?e<-Ny+r&&(e=-Ny+r):e>Ny-r&&(e=Ny-r);const s=i/Math.pow($y(e),n);let a=s*Math.sin(n*t),o=i-s*Math.cos(n*t);return a=.5*(a/Math.PI+.5),o=.5*(o/Math.PI+.5),{x:a,y:this.southernCenter?o:1-o,z:0}}unproject(t,e){t=(2*t-.5)*Math.PI,this.southernCenter&&(e=1-e),e=(2*(1-e)-.5)*Math.PI;const{n:r,f:n}=this,i=n-e,s=Math.sign(i),a=Math.sign(r)*Math.sqrt(t*t+i*i);let o=Math.atan2(t,Math.abs(i))*s;i*r<0&&(o-=Math.PI*Math.sign(t)*s);const l=k(w(o/r)+this.center[0],-180,180),u=k(w(2*Math.atan(Math.pow(n/a,1/r))-Ny),-np,np);return new Zh(l,this.southernCenter?-u:u)}}class Gy extends Dy{constructor(t){super(t),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null;}project(t,e){return {x:Hh(t),y:Jh(e),z:0}}unproject(t,e){const r=tp(t),n=ep(e);return new Zh(r,n)}}const Yy=_(np);class Zy extends Dy{project(t,e){const r=(e=_(e))*e,n=r*r;return {x:.5*((t=_(t))*(.8707-.131979*r+n*(n*(.003971*r-.001529*n)-.013791))/Math.PI+.5),y:1-.5*(e*(1.007226+r*(.015085+n*(.028874*r-.044475-.005916*n)))/Math.PI+1),z:0}}unproject(t,e){t=(2*t-.5)*Math.PI;let r=e=(2*(1-e)-1)*Math.PI,n=25,i=0,s=r*r;do{s=r*r;const t=s*s;i=(r*(1.007226+s*(.015085+t*(.028874*s-.044475-.005916*t)))-e)/(1.007226+s*(.045255+t*(.259866*s-.311325-.005916*11*t))),r=k(r-i,-Yy,Yy);}while(Math.abs(i)>1e-6&&--n>0);s=r*r;const a=k(w(t/(.8707+s*(s*(s*s*s*(.003971-.001529*s)-.013791)-.131979))),-180,180),o=w(r);return new Zh(a,o)}}const Xy=_(np);class Ky extends Dy{project(t,e){e=_(e),t=_(t);const r=Math.cos(e),n=2/Math.PI,i=Math.acos(r*Math.cos(t/2)),s=Math.sin(i)/i,a=.5*(t*n+2*r*Math.sin(t/2)/s)||0,o=.5*(e+Math.sin(e)/s)||0;return {x:.5*(a/Math.PI+.5),y:1-.5*(o/Math.PI+1),z:0}}unproject(t,e){let r=t=(2*t-.5)*Math.PI,n=e=(2*(1-e)-1)*Math.PI,i=25;const s=1e-6;let a=0,o=0;do{const i=Math.cos(n),s=Math.sin(n),l=2*s*i,u=s*s,c=i*i,h=Math.cos(r/2),p=Math.sin(r/2),f=2*h*p,d=p*p,m=1-c*h*h,y=m?1/m:0,g=m?Math.acos(i*h)*Math.sqrt(1/m):0,x=.5*(2*g*i*p+2*r/Math.PI)-t,v=.5*(g*s+n)-e,b=.5*y*(c*d+g*i*h*u)+1/Math.PI,_=y*(f*l/4-g*s*p),w=.125*y*(l*p-g*s*c*f),M=.5*y*(u*h+g*d*i)+.5,A=_*w-M*b;a=(v*_-x*M)/A,o=(x*w-v*b)/A,r=k(r-a,-Math.PI,Math.PI),n=k(n-o,-Xy,Xy);}while((Math.abs(a)>s||Math.abs(o)>s)&&--i>0);return new Zh(w(r),w(n))}}class Wy extends Dy{constructor(t){super(t),this.center=t.center||[0,0],this.parallels=t.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(_(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0;}project(t,e){const{scale:r,cosPhi:n}=this;return {x:_(t)*n*r+.5,y:-Math.sin(_(e))/n*r+.5,z:0}}unproject(t,e){const{scale:r,cosPhi:n}=this,i=-(e-.5)/r,s=k(w((t-.5)/r)/n,-180,180),a=Math.asin(k(i*n,-1,1)),o=k(w(a),-np,np);return new Zh(s,o)}}class Hy extends Gy{constructor(t){super(t),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit=\"pixels\",this.unsupportedLayers=[\"debug\"],this.range=[3,5];}projectTilePoint(e,r,n){const i=zh(e,r,n),s=Dh(_h(n));return t.v.transformMat4(i,i,s),{x:i[0],y:i[1],z:i[2]}}locationPoint(e,r){const n=Ph(r.lat,r.lng),i=t.v.normalize([],n),s=e.elevation?e.elevation.getAtPointOrZero(e.locationCoordinate(r),e._centerAltitude):e._centerAltitude,a=Qh(1,0)*Cr*s;t.v.scaleAndAdd(n,n,i,a);const o=t.m.identity(new Float64Array(16));return t.m.multiply(o,e.pixelMatrix,e.globeMatrix),t.v.transformMat4(n,n,o),new x(n[0],n[1])}pixelsPerMeter(t,e){return Qh(1,0)*e}pixelSpaceConversion(t,e,r){const n=Qh(1,t)*e,i=Mn(Qh(1,45)*e,n,r);return this.pixelsPerMeter(t,e)/i}createTileMatrix(e,r,n){const i=Ch(_h(n.canonical));return t.m.multiply(new Float64Array(16),e.globeMatrix,i)}createInversionMatrix(e,r){const{center:n}=e,i=Dh(_h(r));return t.m.rotateY(i,i,_(n.lng)),t.m.rotateX(i,i,_(n.lat)),t.m.scale(i,i,[e._pixelsPerMercatorPixel,e._pixelsPerMercatorPixel,1]),Float32Array.from(i)}pointCoordinate(t,e,r,n){return xh(t,e,r,!0)||new lp(0,0)}pointCoordinate3D(t,e,r){const n=this.pointCoordinate(t,e,r,0);return [n.x,n.y,n.z]}isPointAboveHorizon(t,e){return !xh(t,e.x,e.y,!1)}farthestPixelDistance(e){const r=function(e,r){const n=e.cameraToCenterDistance,i=e._centerAltitude*r,s=e._camera,a=e._camera.forward(),o=t.v.add([],t.v.scale([],a,-n),[0,0,i]),l=e.worldSize/(2*Math.PI),u=[0,0,-l],c=e.width/e.height,h=Math.tan(e.fovAboveCenter),p=t.v.scale([],s.up(),h),f=t.v.scale([],s.right(),h*c),d=t.v.normalize([],t.v.add([],t.v.add([],a,p),f)),m=[];let y;if(new th(o,d).closestPointOnSphere(u,l,m)){const r=t.v.add([],m,u),n=t.v.sub([],r,o);y=Math.cos(e.fovAboveCenter)*t.v.length(n);}else {const e=t.v.sub([],o,u),r=t.v.sub([],u,o);t.v.normalize(r,r);const n=t.v.length(e)-l;y=Math.sqrt(n*(n+2*l));const i=Math.acos(y/(l+n))-Math.acos(t.v.dot(a,r));y*=Math.cos(i);}return 1.01*y}(e,this.pixelsPerMeter(e.center.lat,e.worldSize)),n=Oh(e.zoom);if(n>0){const t=Py(e,Qh(1,e.center.lat)*e.worldSize),i=e.worldSize/(2*Math.PI),s=Math.max(e.width,e.height)/e.worldSize*Math.PI;return Mn(r,t+i*(1-Math.cos(s)),Math.pow(n,10))}return r}upVector(t,e,r){return zh(e,r,t,1)}upVectorScale(t){return {metersToTile:gh(Eh(_h(t)))}}}function Jy(t){const e=t.parallels,r=!!e&&Math.abs(e[0]+e[1])<.01;switch(t.name){case\"mercator\":return new Gy(t);case\"equirectangular\":return new Uy(t);case\"naturalEarth\":return new Zy(t);case\"equalEarth\":return new jy(t);case\"winkelTripel\":return new Ky(t);case\"albers\":return r?new Wy(t):new Cy(t);case\"lambertConformalConic\":return r?new Wy(t):new qy(t);case\"globe\":return new Hy(t)}throw new Error(`Invalid projection name: ${t.name}`)}const Qy=new Da({\"symbol-placement\":new za(re.layout_symbol[\"symbol-placement\"]),\"symbol-spacing\":new za(re.layout_symbol[\"symbol-spacing\"]),\"symbol-avoid-edges\":new za(re.layout_symbol[\"symbol-avoid-edges\"]),\"symbol-sort-key\":new Ea(re.layout_symbol[\"symbol-sort-key\"]),\"symbol-z-order\":new za(re.layout_symbol[\"symbol-z-order\"]),\"symbol-z-elevate\":new za(re.layout_symbol[\"symbol-z-elevate\"]),\"icon-allow-overlap\":new za(re.layout_symbol[\"icon-allow-overlap\"]),\"icon-ignore-placement\":new za(re.layout_symbol[\"icon-ignore-placement\"]),\"icon-optional\":new za(re.layout_symbol[\"icon-optional\"]),\"icon-rotation-alignment\":new za(re.layout_symbol[\"icon-rotation-alignment\"]),\"icon-size\":new Ea(re.layout_symbol[\"icon-size\"]),\"icon-text-fit\":new Ea(re.layout_symbol[\"icon-text-fit\"]),\"icon-text-fit-padding\":new Ea(re.layout_symbol[\"icon-text-fit-padding\"]),\"icon-image\":new Ea(re.layout_symbol[\"icon-image\"]),\"icon-rotate\":new Ea(re.layout_symbol[\"icon-rotate\"]),\"icon-padding\":new za(re.layout_symbol[\"icon-padding\"]),\"icon-keep-upright\":new za(re.layout_symbol[\"icon-keep-upright\"]),\"icon-offset\":new Ea(re.layout_symbol[\"icon-offset\"]),\"icon-anchor\":new Ea(re.layout_symbol[\"icon-anchor\"]),\"icon-pitch-alignment\":new za(re.layout_symbol[\"icon-pitch-alignment\"]),\"text-pitch-alignment\":new za(re.layout_symbol[\"text-pitch-alignment\"]),\"text-rotation-alignment\":new za(re.layout_symbol[\"text-rotation-alignment\"]),\"text-field\":new Ea(re.layout_symbol[\"text-field\"]),\"text-font\":new Ea(re.layout_symbol[\"text-font\"]),\"text-size\":new Ea(re.layout_symbol[\"text-size\"]),\"text-max-width\":new Ea(re.layout_symbol[\"text-max-width\"]),\"text-line-height\":new Ea(re.layout_symbol[\"text-line-height\"]),\"text-letter-spacing\":new Ea(re.layout_symbol[\"text-letter-spacing\"]),\"text-justify\":new Ea(re.layout_symbol[\"text-justify\"]),\"text-radial-offset\":new Ea(re.layout_symbol[\"text-radial-offset\"]),\"text-variable-anchor\":new za(re.layout_symbol[\"text-variable-anchor\"]),\"text-anchor\":new Ea(re.layout_symbol[\"text-anchor\"]),\"text-max-angle\":new za(re.layout_symbol[\"text-max-angle\"]),\"text-writing-mode\":new za(re.layout_symbol[\"text-writing-mode\"]),\"text-rotate\":new Ea(re.layout_symbol[\"text-rotate\"]),\"text-padding\":new za(re.layout_symbol[\"text-padding\"]),\"text-keep-upright\":new za(re.layout_symbol[\"text-keep-upright\"]),\"text-transform\":new Ea(re.layout_symbol[\"text-transform\"]),\"text-offset\":new Ea(re.layout_symbol[\"text-offset\"]),\"text-allow-overlap\":new za(re.layout_symbol[\"text-allow-overlap\"]),\"text-ignore-placement\":new za(re.layout_symbol[\"text-ignore-placement\"]),\"text-optional\":new za(re.layout_symbol[\"text-optional\"]),visibility:new za(re.layout_symbol.visibility)});var tg={paint:new Da({\"icon-opacity\":new Ea(re.paint_symbol[\"icon-opacity\"]),\"icon-emissive-strength\":new Ea(re.paint_symbol[\"icon-emissive-strength\"]),\"text-emissive-strength\":new Ea(re.paint_symbol[\"text-emissive-strength\"]),\"icon-color\":new Ea(re.paint_symbol[\"icon-color\"]),\"icon-halo-color\":new Ea(re.paint_symbol[\"icon-halo-color\"]),\"icon-halo-width\":new Ea(re.paint_symbol[\"icon-halo-width\"]),\"icon-halo-blur\":new Ea(re.paint_symbol[\"icon-halo-blur\"]),\"icon-translate\":new za(re.paint_symbol[\"icon-translate\"]),\"icon-translate-anchor\":new za(re.paint_symbol[\"icon-translate-anchor\"]),\"icon-image-cross-fade\":new Ea(re.paint_symbol[\"icon-image-cross-fade\"]),\"text-opacity\":new Ea(re.paint_symbol[\"text-opacity\"]),\"text-color\":new Ea(re.paint_symbol[\"text-color\"],{runtimeType:ye,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),\"text-halo-color\":new Ea(re.paint_symbol[\"text-halo-color\"]),\"text-halo-width\":new Ea(re.paint_symbol[\"text-halo-width\"]),\"text-halo-blur\":new Ea(re.paint_symbol[\"text-halo-blur\"]),\"text-translate\":new za(re.paint_symbol[\"text-translate\"]),\"text-translate-anchor\":new za(re.paint_symbol[\"text-translate-anchor\"]),\"icon-color-saturation\":new za(re.paint_symbol[\"icon-color-saturation\"])}),layout:Qy};class eg{constructor(t){this.type=t.property.overrides?t.property.overrides.runtimeType:pe,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}Ks(eg,\"FormatSectionOverride\",{omit:[\"defaultValue\"]});class rg extends Va{constructor(t,e,r){super(t,tg,e,r);}recalculate(t,e){super.recalculate(t,e),\"auto\"===this.layout.get(\"icon-rotation-alignment\")&&(this.layout._values[\"icon-rotation-alignment\"]=\"point\"!==this.layout.get(\"symbol-placement\")?\"map\":\"viewport\"),\"auto\"===this.layout.get(\"text-rotation-alignment\")&&(this.layout._values[\"text-rotation-alignment\"]=\"point\"!==this.layout.get(\"symbol-placement\")?\"map\":\"viewport\"),\"auto\"===this.layout.get(\"text-pitch-alignment\")&&(this.layout._values[\"text-pitch-alignment\"]=this.layout.get(\"text-rotation-alignment\")),\"auto\"===this.layout.get(\"icon-pitch-alignment\")&&(this.layout._values[\"icon-pitch-alignment\"]=this.layout.get(\"icon-rotation-alignment\"));const r=this.layout.get(\"text-writing-mode\");if(r){const t=[];for(const e of r)t.indexOf(e)<0&&t.push(e);this.layout._values[\"text-writing-mode\"]=t;}else this.layout._values[\"text-writing-mode\"]=\"point\"===this.layout.get(\"symbol-placement\")?[\"horizontal\"]:[\"horizontal\",\"vertical\"];this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||Zi(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>r in t?String(t[r]):\"\"))}(e.properties,i)}createBucket(t){return new fg(t)}queryRadius(){return 0}queryIntersectsFeature(){return !1}_setPaintOverrides(){for(const t of tg.paint.overridableProperties){if(!rg.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new eg(e),n=new Yi(r,e.property.specification,this.scope,this.options);let i=null;i=\"constant\"===e.value.kind||\"source\"===e.value.kind?new Ki(\"source\",n):new Wi(\"composite\",n,e.value.zoomStops,e.value._interpolationType),this.paint._values[t]=new Ta(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&rg.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get(\"text-field\"),n=tg.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if(\"constant\"===r.value.kind&&r.value.value instanceof Oe)s(r.value.value.sections);else if(\"source\"===r.value.kind){const t=e=>{i||(e instanceof Ge&&Ne(e.value)===be?s(e.value.sections):e instanceof We?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}getProgramIds(){const t=0!==this.paint.get(\"icon-opacity\").constantOr(1),e=0!==this.paint.get(\"text-opacity\").constantOr(1),r=[];return t&&r.push(\"symbolIcon\"),e&&r.push(\"symbolSDF\"),r}getDefaultProgramParams(t,e){return {config:new pl(this,e),overrideFog:!1}}}const ng=ud.types,ig=[{name:\"a_fade_opacity\",components:1,type:\"Uint8\",offset:0}];function sg(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=o?Math.min(My,Math.round(o[0])):0,d=o?Math.min(My,Math.round(o[1])):0;t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),s,a,(f<<1)+(l?1:0),d,16*u,16*c,256*h,256*p);}function ag(t,e,r){t.emplaceBack(e,r);}function og(t,e,r,n,i,s,a){t.emplaceBack(e,r,n,i,s,a);}function lg(t,e,r,n,i){t.emplaceBack(e,r,n,i),t.emplaceBack(e,r,n,i),t.emplaceBack(e,r,n,i),t.emplaceBack(e,r,n,i);}function ug(t){for(const e of t.sections)if(la(e.text))return !0;return !1}class cg{constructor(t){this.layoutVertexArray=new Ja,this.indexArray=new ao,this.programConfigurations=t,this.segments=new Do,this.dynamicLayoutVertexArray=new Xa,this.opacityVertexArray=new to,this.placedSymbolArray=new Mo,this.iconTransitioningVertexArray=new eo,this.globeExtVertexArray=new Qa,this.zOffsetVertexArray=new uo;}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.indexArray.length&&0===this.dynamicLayoutVertexArray.length&&0===this.opacityVertexArray.length&&0===this.iconTransitioningVertexArray.length}upload(t,e,r,n,i){this.isEmpty()||(r&&(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,tm.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,rm.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,ig,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=t.createVertexBuffer(this.iconTransitioningVertexArray,im.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=t.createVertexBuffer(this.globeExtVertexArray,em.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||i)&&(this.zOffsetVertexBuffer=t.createVertexBuffer(this.zOffsetVertexArray,nm.members,!0)),this.opacityVertexBuffer.itemSize=1),(r||n)&&this.programConfigurations.upload(t));}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy());}}Ks(cg,\"SymbolBuffers\");class hg{constructor(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new Do,this.collisionVertexArray=new so,this.collisionVertexArrayExt=new Xa;}upload(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,sm.members,!0),this.collisionVertexBufferExt=t.createVertexBuffer(this.collisionVertexArrayExt,am.members,!0);}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy());}}Ks(hg,\"CollisionBuffers\");class pg{constructor(e){this.collisionBoxArray=e.collisionBoxArray,this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((t=>t.fqid)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=t.m.identity([]),this.placementViewportMatrix=t.m.identity([]);const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=hm(this.zoom,r[\"text-size\"]),this.iconSizeData=hm(this.zoom,r[\"icon-size\"]);const n=this.layers[0].layout,i=n.get(\"symbol-sort-key\"),s=n.get(\"symbol-z-order\");this.canOverlap=n.get(\"text-allow-overlap\")||n.get(\"icon-allow-overlap\")||n.get(\"text-ignore-placement\")||n.get(\"icon-ignore-placement\"),this.sortFeaturesByKey=\"viewport-y\"!==s&&void 0!==i.constantOr(1),this.sortFeaturesByY=(\"viewport-y\"===s||\"auto\"===s&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=n.get(\"text-writing-mode\").map((t=>Am[t])),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID,this.projection=e.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=n.get(\"symbol-z-elevate\");}createArrays(){this.text=new cg(new fl(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new cg(new fl(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new Io,this.lineVertexArray=new ko,this.symbolInstances=new So;}calculateGlyphDependencies(t,e,r,n,i){for(let r=0;r0)&&(\"constant\"!==l.value.kind||l.value.value.length>0),p=\"constant\"!==c.value.kind||!!c.value.value||Object.keys(c.parameters).length>0,f=a.get(\"symbol-sort-key\");if(this.features=[],!h&&!p)return;const d=r.iconDependencies,m=r.glyphDependencies,y=r.availableImages,g=new _a(this.zoom);for(const{feature:r,id:u,index:c,sourceLayerIndex:x}of e){const e=s._featureFilter.needGeometry,v=gp(r,e);if(!s._featureFilter.filter(g,v,n))continue;if(e||(v.geometry=yp(r,n,i)),o&&1!==r.type&&n.z<=5){const e=v.geometry,r=.98078528056,i=(e,i)=>{const s=zh(e.x,e.y,n,1),a=zh(i.x,i.y,n,1);return t.v.dot(s,a)=0;for(const r of b.sections)if(r.image)d[r.image.namePrimary]=!0;else {const n=ea(b.toString()),i=r.fontStack||t,s=m[i]=m[i]||{};this.calculateGlyphDependencies(r.text,s,e,this.allowVerticalPlacement,n);}}}\"line\"===a.get(\"symbol-placement\")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r,n,i){const s=0!==Object.keys(t).length;if(s&&!this.stateDependentLayers.length)return;const a=s?this.stateDependentLayers:this.layers;this.text.programConfigurations.updatePaintArrays(t,e,a,r,n,i),this.icon.programConfigurations.updatePaintArrays(t,e,a,r,n,i);}updateZOffset(){const t=(t,e,n)=>{r+=e,r>t.length&&t.resize(r);for(let i=-e;i<0;i++)t.emplace(i+r,n);},e=(t,e,r)=>{n+=e,n>t.length&&t.resize(n);for(let i=-e;i<0;i++)t.emplace(i+n,r);};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let r=0,n=0;for(let r=0;r0;if((i>0||s>0)&&(t(this.text.zOffsetVertexArray,i,o),t(this.text.zOffsetVertexArray,s,o)),l){const{placedIconSymbolIndex:t,verticalPlacedIconSymbolIndex:r}=n;t>=0&&e(this.icon.zOffsetVertexArray,a,o),r>=0&&e(this.icon.zOffsetVertexArray,n.numVerticalIconVertices,o);}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray);}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}getProjection(){return this.projectionInstance||(this.projectionInstance=Jy(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment)for(const{x:t,y:r}of e)this.lineVertexArray.emplaceBack(t,r);return {lineStartIndex:r,lineLength:this.lineVertexArray.length-r}}addSymbols(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,m){const y=t.indexArray,g=t.layoutVertexArray,x=t.globeExtVertexArray,v=t.segments.prepareSegment(4*e.length,g,y,this.canOverlap?s.sortKey:void 0),b=this.glyphOffsetArray.length,_=v.vertexLength,w=this.allowVerticalPlacement&&a===Am.vertical?Math.PI/2:0,M=s.text&&s.text.sections;for(let n=0;n=0?e.rightJustifiedTextSymbolIndex:e.centerJustifiedTextSymbolIndex>=0?e.centerJustifiedTextSymbolIndex:e.leftJustifiedTextSymbolIndex>=0?e.leftJustifiedTextSymbolIndex:e.verticalPlacedTextSymbolIndex>=0?e.verticalPlacedTextSymbolIndex:n),s=pm(this.textSizeData,t,i)/um;return this.tilePixelRatio*s}getSymbolInstanceIconSize(t,e,r){const n=this.icon.placedSymbolArray.get(r),i=pm(this.iconSizeData,t,n);return this.tilePixelRatio*i}_commitDebugCollisionVertexUpdate(t,e,r,n){t.emplaceBack(e,-r,-r,n),t.emplaceBack(e,r,-r,n),t.emplaceBack(e,r,r,n),t.emplaceBack(e,-r,r,n);}_updateTextDebugCollisionBoxes(t,e,r,n,i,s){for(let a=n;a0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let t=0;tthis.symbolInstances.get(e).zOffset-this.symbolInstances.get(t).zOffset))}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex);const{rightJustifiedTextSymbolIndex:r,centerJustifiedTextSymbolIndex:n,leftJustifiedTextSymbolIndex:i,verticalPlacedTextSymbolIndex:s,placedIconSymbolIndex:a,verticalPlacedIconSymbolIndex:o}=e;r>=0&&this.addIndicesForPlacedSymbol(this.text,r),n>=0&&n!==r&&this.addIndicesForPlacedSymbol(this.text,n),i>=0&&i!==n&&i!==r&&this.addIndicesForPlacedSymbol(this.text,i),s>=0&&this.addIndicesForPlacedSymbol(this.text,s),a>=0&&this.addIndicesForPlacedSymbol(this.icon,a),o>=0&&this.addIndicesForPlacedSymbol(this.icon,o);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}Ks(pg,\"SymbolBucket\",{omit:[\"layers\",\"collisionBoxArray\",\"features\",\"compareText\"]}),pg.MAX_GLYPHS=65535,pg.addDynamicAttributes=lg;var fg=pg;const dg=Ua([{name:\"a_pos_normal\",components:2,type:\"Int16\"},{name:\"a_data\",components:4,type:\"Uint8\"},{name:\"a_linesofar\",components:1,type:\"Float32\"}],4),{members:mg}=dg,yg=Ua([{name:\"a_packed\",components:4,type:\"Float32\"}]),{members:gg}=yg,xg=ud.types,vg=Math.cos(Math.PI/180*37.5);class bg{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.fqid)),this.index=t.index,this.projection=t.projection,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Za,this.layoutVertexArray2=new Xa,this.indexArray=new ao,this.programConfigurations=new fl(t.layers,t.zoom),this.segments=new Do,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r,n){this.hasPattern=Ff(\"line\",this.layers,e);const i=this.layers[0].layout.get(\"line-sort-key\"),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=gp(e,t);if(!this.layers[0]._featureFilter.filter(new _a(this.zoom),u,r))continue;const c=i?i.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:yp(e,r,n),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));const{lineAtlas:a,featureIndex:o}=e,l=this.addConstantDashes(a);for(const n of s){const{geometry:i,index:s,sourceLayerIndex:u}=n;if(l&&this.addFeatureDashes(n,a),this.hasPattern){const t=jf(\"line\",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,a.positions,e.availableImages,e.brightness);o.insert(t[s].feature,i,s,u,this.index);}}addConstantDashes(t){let e=!1;for(const r of this.layers){const n=r.paint.get(\"line-dasharray\").value,i=r.layout.get(\"line-cap\").value;if(\"constant\"!==n.kind||\"constant\"!==i.kind)e=!0;else {const e=i.value,r=n.value;if(!r)continue;t.addDash(r,e);}}return e}addFeatureDashes(t,e){const r=this.zoom;for(const n of this.layers){const i=n.paint.get(\"line-dasharray\").value,s=n.layout.get(\"line-cap\").value;if(\"constant\"===i.kind&&\"constant\"===s.kind)continue;let a,o;if(\"constant\"===i.kind){if(a=i.value,!a)continue}else a=i.evaluate({zoom:r},t);o=\"constant\"===s.kind?s.value:s.evaluate({zoom:r},t),e.addDash(a,o),t.patterns[n.id]=e.getKey(a,o);}}update(t,e,r,n,i){const s=0!==Object.keys(t).length;s&&!this.stateDependentLayers.length||this.programConfigurations.updatePaintArrays(t,e,s?this.stateDependentLayers:this.layers,r,n,i);}addFeatures(t,e,r,n,i,s){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,r,n,s);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,gg)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,mg),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&t.properties.hasOwnProperty(\"mapbox_clip_start\")&&t.properties.hasOwnProperty(\"mapbox_clip_end\"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s,a){const o=this.layers[0].layout,l=o.get(\"line-join\").evaluate(t,{}),u=o.get(\"line-cap\").evaluate(t,{}),c=o.get(\"line-miter-limit\"),h=o.get(\"line-round-limit\");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,l,u,c,h);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,s,n,a);}addLine(t,e,r,n,i,s){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,this.lineSoFar=0,this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[o-1].equals(t[o-2]);)o--;let l=0;for(;l0;if(_&&e>l){const t=h.dist(p);if(t>2*u){const e=h.sub(h.sub(p)._mult(u/t)._round());this.updateDistance(p,e),this.addCurrentVertex(e,d,0,0,c),p=e;}}const M=p&&f;let A=M?r:a?\"butt\":n;if(M&&\"round\"===A&&(vi&&(A=\"bevel\"),\"bevel\"===A&&(v>2&&(A=\"flipbevel\"),v100)y=m.mult(-1);else {const t=v*d.add(m).mag()/d.sub(m).mag();y._perp()._mult(t*(w?-1:1));}this.addCurrentVertex(h,y,0,0,c),this.addCurrentVertex(h,y.mult(-1),0,0,c);}else if(\"bevel\"===A||\"fakeround\"===A){const t=-Math.sqrt(v*v-1),e=w?t:0,r=w?0:t;if(p&&this.addCurrentVertex(h,d,e,r,c),\"fakeround\"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*u){const e=h.add(f.sub(h)._mult(u/t)._round());this.updateDistance(h,e),this.addCurrentVertex(e,m,0,0,c),h=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i);}addHalfVertex({x:t,y:e},r,n,i,s,a,o){this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1),0,this.lineSoFar),this.lineClips&&this.layoutVertexArray2.emplaceBack(this.scaledDistance,this.lineClipsArray.length,this.lineClips.start,this.lineClips.end);const l=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,l),o.primitiveLength++),s?this.e2=l:this.e1=l;}updateScaledDistance(){if(this.lineClips){const t=this.totalDistance/(this.lineClips.end-this.lineClips.start);this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=t*this.lineClips.start+this.distance;}else this.lineSoFar=this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}Ks(bg,\"LineBucket\",{omit:[\"layers\",\"patternFeatures\"]});class _g{constructor(t,e,r,n){this.context=t,this.format=r,this.texture=t.gl.createTexture(),this.update(e,n);}update(t,e,r){const{width:n,height:i}=t,{context:s}=this,{gl:a}=s;if(a.bindTexture(a.TEXTURE_2D,this.texture),s.pixelStoreUnpackFlipY.set(!1),s.pixelStoreUnpack.set(1),s.pixelStoreUnpackPremultiplyAlpha.set(this.format===a.RGBA&&(!e||!1!==e.premultiply)),r||this.size&&this.size[0]===n&&this.size[1]===i){const{x:e,y:s}=r||{x:0,y:0};if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData||ImageBitmap&&t instanceof ImageBitmap)a.texSubImage2D(a.TEXTURE_2D,0,e,s,a.RGBA,a.UNSIGNED_BYTE,t);else {let r=this.format,o=a.UNSIGNED_BYTE;this.format===a.R32F&&(r=a.RED,o=a.FLOAT),a.texSubImage2D(a.TEXTURE_2D,0,e,s,n,i,r,o,t.data);}}else if(this.size=[n,i],t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData||ImageBitmap&&t instanceof ImageBitmap){let e=this.format;this.format===a.R8&&(e=a.RED),a.texImage2D(a.TEXTURE_2D,0,this.format,e,a.UNSIGNED_BYTE,t);}else {let e=this.format,r=this.format,s=a.UNSIGNED_BYTE;this.format===a.DEPTH_COMPONENT&&(e=a.DEPTH_COMPONENT16,s=a.UNSIGNED_SHORT),this.format===a.R8&&(r=a.RED),this.format===a.R32F&&(s=a.FLOAT,r=a.RED),a.texImage2D(a.TEXTURE_2D,0,e,n,i,0,r,s,t.data);}this.useMipmap=Boolean(e&&e.useMipmap),this.useMipmap&&a.generateMipmap(a.TEXTURE_2D);}bind(t,e,r=!1){const{context:n}=this,{gl:i}=n;i.bindTexture(i.TEXTURE_2D,this.texture),t!==this.minFilter&&(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,this.useMipmap&&!r?t===i.NEAREST?i.NEAREST_MIPMAP_NEAREST:i.LINEAR_MIPMAP_LINEAR:t),this.minFilter=t),e!==this.wrapS&&(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,e),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,e),this.wrapS=e);}bindExtraParam(t,e,r,n){const{context:i}=this,{gl:s}=i;s.bindTexture(s.TEXTURE_2D,this.texture),e!==this.magFilter&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,e),this.magFilter=e),t!==this.minFilter&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,this.useMipmap?t===s.NEAREST?s.NEAREST_MIPMAP_NEAREST:s.LINEAR_MIPMAP_LINEAR:t),this.minFilter=t),r!==this.wrapS&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,r),this.wrapS=r),n!==this.wrapT&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,n),this.wrapT=n);}destroy(){const{gl:t}=this.context;t.deleteTexture(this.texture),this.texture=null;}}class wg{constructor(t,e){this.context=t,this.texture=e;}bind(t,e){const{context:r}=this,{gl:n}=r;n.bindTexture(n.TEXTURE_2D,this.texture),t!==this.minFilter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,t),this.minFilter=t),e!==this.wrapS&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrapS=e);}}const Mg=32,Ag=33,Sg=new Uint16Array(8184);for(let t=0;t<2046;t++){let e=t+2,r=0,n=0,i=0,s=0,a=0,o=0;for(1&e?i=s=a=Mg:r=n=o=Mg;(e>>=1)>1;){const t=r+i>>1,l=n+s>>1;1&e?(i=r,s=n,r=a,n=o):(r=i,n=s,i=a,s=o),a=t,o=l;}const l=4*t;Sg[l+0]=r,Sg[l+1]=n,Sg[l+2]=i,Sg[l+3]=s;}const Ig=new Uint16Array(2178),kg=new Uint8Array(1089),Tg=new Uint16Array(1089);function Pg(t){return 0===t?-.03125:32===t?.03125:0}var zg=Ua([{name:\"a_pos\",type:\"Int16\",components:2},{name:\"a_texture_pos\",type:\"Int16\",components:2}]);const Eg={type:2,extent:Cr,loadGeometry:()=>[[new x(0,0),new x(Cr+1,0),new x(Cr+1,Cr+1),new x(0,Cr+1),new x(0,0)]]};class Bg{constructor(t,e,r,n,i){this.tileID=t,this.uid=C(),this.uses=0,this.tileSize=e,this.tileZoom=r,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.isRaster=i,n&&n.style&&(this._lastUpdatedBrightness=n.style.getBrightness()),this.expiredRequestCount=0,this.state=\"loading\",n&&n.transform&&(this.projection=n.transform.projection);}registerFadeDuration(t){const e=t+this.timeAdded;ee.getLayer(t))).filter(Boolean);if(0!==t.length){n.layers=t,n.stateDependentLayerIds&&(n.stateDependentLayers=n.stateDependentLayerIds.map((e=>t.filter((t=>t.id===e))[0])));for(const e of t)r[e.fqid]=n;}}return r}(t.buckets,e.style),this.hasSymbolBuckets=!1;for(const t in this.buckets){const e=this.buckets[t];if(e instanceof fg){if(this.hasSymbolBuckets=!0,!r)break;e.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const t in this.buckets){const e=this.buckets[t];if(e instanceof fg&&e.hasRTLText){this.hasRTLText=!0,ba.isLoading()||ba.isLoaded()||\"deferred\"!==xa()||va();break}}this.queryPadding=0;for(const t in this.buckets){const r=this.buckets[t],n=e.style.getOwnLayer(t);if(!n)continue;const i=n.queryRadius(r);this.queryPadding=Math.max(this.queryPadding,i);}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage),t.lineAtlas&&(this.lineAtlas=t.lineAtlas),this._lastUpdatedBrightness=t.brightness;}else this.collisionBoxArray=new _o;}unloadVectorData(){if(this.hasData()){for(const t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state=\"unloaded\";}}getBucket(t){return this.buckets[t.fqid]}upload(t){for(const e in this.buckets){const r=this.buckets[e];r.uploadPending()&&r.upload(t);}const e=t.gl,r=this.imageAtlas;if(r&&!r.uploaded){const n=!!Object.keys(r.patternPositions).length;this.imageAtlasTexture=new _g(t,r.image,e.RGBA,{useMipmap:n}),this.imageAtlas.uploaded=!0;}this.glyphAtlasImage&&(this.glyphAtlasTexture=new _g(t,this.glyphAtlasImage,e.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new _g(t,this.lineAtlas.image,e.R8),this.lineAtlas.uploaded=!0);}prepare(t,e,r){if(this.imageAtlas&&this.imageAtlasTexture&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture,r),!e||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const n=e.style.getBrightness();(this._lastUpdatedBrightness||n)&&(this._lastUpdatedBrightness&&n&&Math.abs(this._lastUpdatedBrightness-n)<.001||(this._lastUpdatedBrightness=n,this.updateBuckets(void 0,e)));}queryRenderedFeatures(t,e,r,n,i,s,a,o){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({tileResult:n,pixelPosMatrix:a,transform:s,params:i,tileTransform:this.tileTransform},t,e,r):{}}querySourceFeatures(t,e){const r=this.latestFeatureIndex;if(!r||!r.rawTileData)return;const n=r.loadVTLayers(),i=e?e.sourceLayer:\"\",s=n._geojsonTileLayer||n[i];if(!s)return;const a=ls(e&&e.filter),{z:o,x:l,y:u}=this.tileID.canonical,c={z:o,x:l,y:u};for(let e=0;et)r=!1;else if(e)if(this.expirationTime=0;t--){const e=4*t,r=Sg[e+0],n=Sg[e+1],i=Sg[e+2],s=Sg[e+3],a=r+i>>1,o=n+s>>1,l=a+o-n,u=o+r-a,c=n*Ag+r,h=s*Ag+i,p=o*Ag+a,f=Math.hypot((Ig[2*c+0]+Ig[2*h+0])/2-Ig[2*p+0],(Ig[2*c+1]+Ig[2*h+1])/2-Ig[2*p+1])>=16;kg[p]=kg[p]||(f?1:0),t<1022&&(kg[p]=kg[p]||kg[(n+u>>1)*Ag+(r+l>>1)]||kg[(s+u>>1)*Ag+(i+l>>1)]);}const i=new Ga,s=new ao;let a=0;function o(t,e){const r=e*Ag+t;return 0===Tg[r]&&(i.emplaceBack(Ig[2*r+0],Ig[2*r+1],t*Cr/Mg,e*Cr/Mg),Tg[r]=++a),Tg[r]-1}function l(t,e,r,n,i,a){const u=t+r>>1,c=e+n>>1;if(Math.abs(t-i)+Math.abs(e-a)>1&&kg[c*Ag+u])l(i,a,t,e,u,c),l(r,n,i,a,u,c);else {const l=o(t,e),u=o(r,n),c=o(i,a);s.emplaceBack(l,u,c);}}return l(0,0,Mg,Mg,Mg,0),l(Mg,Mg,0,0,0,Mg),{vertices:i,indices:s}}(this.tileID.canonical,e);n=t.vertices,i=t.indices;}else {n=new Ga,i=new ao;for(const{x:t,y:e}of r)n.emplaceBack(t,e,0,0);const t=Lf(n.int16,void 0,4);for(let e=0;e0&&(o=t.m.invert(new Float64Array(16),r.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(e,i,r,s,o,a),this._makeGlobeTileDebugTextBuffer(e,i,r,s,o,a);}_globePoint(e,r,n,i,s,a,o){let l=zh(e,r,n);if(a){const s=1<.5?p=-1:h<-.5&&(p=1);let f=(e/Cr+n.x)/s+p,d=(r/Cr+n.y)/s;f=(f-u)*i._pixelsPerMercatorPixel+u,d=(d-c)*i._pixelsPerMercatorPixel+c;const m=[f*i.worldSize,d*i.worldSize,0];t.v.transformMat4(m,m,a),l=wh(l,m,o);}return t.v.transformMat4(l,l,s)}_makeGlobeTileDebugBorderBuffer(t,e,r,n,i,s){const a=new $a,o=new fo,l=new qa,u=(t,u,c,h,p)=>{const f=(c-t)/(p-1),d=(h-u)/(p-1),m=a.length;for(let c=0;cc*t+e;for(let t=0;t{this.remove(t,i);}),r)),this.data[n].push(i),this.order.push(n),this.order.length>this.max){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t);}return this}has(t){return t.wrapped().key in this.data}getAndRemove(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null}_getAndRemoveByKey(t){const e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value}getByKey(t){const e=this.data[t];return e?e[0].value:null}get(t){return this.has(t)?this.data[t.wrapped().key][0].value:null}remove(t,e){if(!this.has(t))return this;const r=t.wrapped().key,n=void 0===e?0:this.data[r].indexOf(e),i=this.data[r][n];return this.data[r].splice(n,1),i.timeout&&clearTimeout(i.timeout),0===this.data[r].length&&delete this.data[r],this.onRemove(i.value),this.order.splice(this.order.indexOf(r),1),this}setMaxSize(t){for(this.max=t;this.order.length>this.max;){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t);}return this}filter(t){const e=[];for(const r in this.data)for(const n of this.data[r])t(n.value)||e.push(n);for(const t of e)this.remove(t.value.tileID,t);}}class Cg{constructor(t,e,r,n){this.id=Cg.uniqueIdxCounter,Cg.uniqueIdxCounter++,this.context=t;const i=t.gl;this.buffer=i.createBuffer(),this.dynamicDraw=Boolean(r),this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),i.bufferData(i.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||n||e.destroy();}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(t){this.id=Cg.uniqueIdxCounter,Cg.uniqueIdxCounter++;const e=this.context.gl;this.context.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}Cg.uniqueIdxCounter=0;class Rg{constructor(t,e,r){this.func=t,this.mask=e,this.range=r;}}Rg.ReadOnly=!1,Rg.ReadWrite=!0,Rg.disabled=new Rg(519,Rg.ReadOnly,[0,1]);const Lg=7680;class Vg{constructor(t,e,r,n,i,s){this.test=t,this.ref=e,this.mask=r,this.fail=n,this.depthFail=i,this.pass=s;}}Vg.disabled=new Vg({func:519,mask:0},0,0,Lg,Lg,Lg);class Og{constructor(t,e,r,n){this.blendFunction=t,this.blendColor=e,this.mask=r,this.blendEquation=n;}}Og.Replace=[1,0,1,0],Og.disabled=new Og(Og.Replace,Re.transparent,[!1,!1,!1,!1]),Og.unblended=new Og(Og.Replace,Re.transparent,[!0,!0,!0,!0]),Og.alphaBlended=new Og([1,771,1,771],Re.transparent,[!0,!0,!0,!0]),Og.multiply=new Og([774,0,774,0],Re.transparent,[!0,!0,!0,!0]);const Fg=1029,jg=2305;class Ug{constructor(t,e,r){this.enable=t,this.mode=e,this.frontFace=r;}}Ug.disabled=new Ug(!1,Fg,jg),Ug.backCCW=new Ug(!0,Fg,jg),Ug.backCW=new Ug(!0,Fg,2304),Ug.frontCW=new Ug(!0,1028,2304),Ug.frontCCW=new Ug(!0,1028,jg);class Ng extends ee{constructor(t,e,r){super(),this.id=t,this._onlySymbols=r,e.on(\"data\",(t=>{\"source\"===t.dataType&&\"metadata\"===t.sourceDataType&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&\"source\"===t.dataType&&\"content\"===t.sourceDataType&&(this.reload(),this.transform&&this.update(this.transform));})),e.on(\"error\",(()=>{this._sourceErrored=!0;})),this._source=e,this._tiles={},this._cache=new Dg(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=e.minTileCacheSize,this._maxTileCacheSize=e.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Vd,this._isRaster=\"raster\"===this._source.type||\"raster-dem\"===this._source.type||\"custom\"===this._source.type&&\"raster\"===this._source._dataType;}onAdd(t){this.map=t,this._minTileCacheSize=void 0===this._minTileCacheSize&&t?t._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=void 0===this._maxTileCacheSize&&t?t._maxTileCacheSize:this._maxTileCacheSize;}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;for(const t in this._tiles){const e=this._tiles[t];if(\"errored\"!==e.state&&(\"loaded\"!==e.state||!e.bucketsLoaded()))return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform);}_loadTile(t,e){return t.isSymbolTile=this._onlySymbols,t.isExtraShadowCaster=this._shadowCasterTiles[t.tileID.key],this._source.loadTile(t,e)}_unloadTile(t){if(this._source.unloadTile)return this._source.unloadTile(t,(()=>{}))}_abortTile(t){if(this._source.abortTile)return this._source.abortTile(t,(()=>{}))}serialize(){return this._source.serialize()}prepare(t){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const e in this._tiles){const r=this._tiles[e];r.upload(t),r.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope);}}getIds(){return E(this._tiles).map((t=>t.tileID)).sort($g).map((t=>t.key))}getRenderableIds(t,e){const r=[];for(const n in this._tiles)this._isIdRenderable(+n,t,e)&&r.push(this._tiles[n]);return t?r.sort(((t,e)=>{const r=t.tileID,n=e.tileID,i=new x(r.canonical.x,r.canonical.y)._rotate(this.transform.angle),s=new x(n.canonical.x,n.canonical.y)._rotate(this.transform.angle);return r.overscaledZ-n.overscaledZ||s.y-i.y||s.x-i.x})).map((t=>t.tileID.key)):r.map((t=>t.tileID)).sort($g).map((t=>t.key))}hasRenderableParent(t){const e=this.findLoadedParent(t,0);return !!e&&this._isIdRenderable(e.tileID.key)}_isIdRenderable(t,e,r){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]&&(e||!this._tiles[t].holdingForFade())&&(r||!this._shadowCasterTiles[t])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)\"errored\"!==this._tiles[t].state&&this._reloadTile(+t,\"reloading\");}}_reloadTile(t,e){const r=this._tiles[t];r&&(\"loading\"!==r.state&&(r.state=e),this._loadTile(r,this._tileLoaded.bind(this,r,t,e)));}_tileLoaded(t,e,r,n){if(n)if(t.state=\"errored\",404!==n.status)this._source.fire(new te(n,{tile:t}));else {if(!(t.tileID.key in this._loadedParentTiles))return void this._source.fire(new Qt(\"data\",{dataType:\"source\",sourceDataType:\"error\",sourceId:this._source.id}));if(\"raster-dem\"===this._source.type&&this.usedForTerrain&&this.map.painter.terrain){const t=this.map.painter.terrain;this.update(this.transform,t.getScaledDemTileSize(),!0),t.resetTileLookupCache(this.id);}else this.update(this.transform);}else t.timeAdded=Wt.now(),\"expired\"===r&&(t.refreshedUponExpiration=!0),this._setTileReloadTimer(e,t),\"raster-dem\"===this._source.type&&t.dem&&this._backfillDEM(t),this._state.initializeTileState(t,this.map?this.map.painter:null),this._source.fire(new Qt(\"data\",{dataType:\"source\",tile:t,coord:t.tileID,sourceCacheId:this.id}));}_backfillDEM(t){const e=this.getRenderableIds();for(let n=0;n1||(Math.abs(r)>1&&(1===Math.abs(r+i)?r+=i:1===Math.abs(r-i)&&(r-=i)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,r,n),t.neighboringTiles&&t.neighboringTiles[s]&&(t.neighboringTiles[s].backfilled=!0)));}}getTile(t){return this.getTileByID(t.key)}getTileByID(t){return this._tiles[t]}_retainLoadedChildren(t,e,r,n){for(const i in this._tiles){let s=this._tiles[i];if(n[i]||!s.hasData()||s.tileID.overscaledZ<=e||s.tileID.overscaledZ>r)continue;let a=s.tileID;for(;s&&s.tileID.overscaledZ>e+1;){const t=s.tileID.scaledTo(s.tileID.overscaledZ-1);s=this._tiles[t.key],s&&s.hasData()&&(a=t);}let o=a;for(;o.overscaledZ>e;)if(o=o.scaledTo(o.overscaledZ-1),t[o.key]){n[a.key]=a;break}}}findLoadedParent(t,e){if(t.key in this._loadedParentTiles){const r=this._loadedParentTiles[t.key];return r&&r.tileID.overscaledZ>=e?r:null}for(let r=t.overscaledZ-1;r>=e;r--){const e=t.scaledTo(r),n=this._getLoadedTile(e);if(n)return n}}_getLoadedTile(t){const e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(this._source.reparseOverscaled?t.wrapped().key:t.canonical.key)}updateCacheSize(t,e){e=e||this._source.tileSize;const r=Math.ceil(t.width/e)+1,n=Math.ceil(t.height/e)+1,i=Math.floor(r*n*5),s=\"number\"==typeof this._minTileCacheSize?Math.max(this._minTileCacheSize,i):i,a=\"number\"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,s):s;this._cache.setMaxSize(a);}handleWrapJump(t){const e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){const t={};for(const r in this._tiles){const n=this._tiles[r];n.tileID=n.tileID.unwrapTo(n.tileID.wrap+e),t[n.tileID.key]=n;}this._tiles=t;for(const t in this._timers)clearTimeout(this._timers[t]),delete this._timers[t];for(const t in this._tiles)this._setTileReloadTimer(+t,this._tiles[t]);}}update(t,e,r,n){if(this.transform=t,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage)return;if(this.usedForTerrain&&!r)return;let i;if(this.updateCacheSize(t,e),\"globe\"!==this.transform.projection.name&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?i=t.getVisibleUnwrappedCoordinates(this._source.tileID).map((t=>new Hc(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y))):(i=t.coveringTiles({tileSize:e||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!r,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain}),this._source.hasTile&&(i=i.filter((t=>this._source.hasTile(t))))):i=[],i.length>0&&this.castsShadows&&n&&\"globe\"!==this.transform.projection.name&&!this.usedForTerrain&&!qg(this._source.type)){const s=t.coveringZoomLevel({tileSize:e||this._source.tileSize,roundZoom:this._source.roundZoom&&!r}),a=Math.min(s,this._source.maxzoom),o=t.extendTileCoverForShadows(i,n,a);for(const t of o)this._shadowCasterTiles[t.key]=!0,i.push(t);}const s=this._updateRetainedTiles(i);if(qg(this._source.type)&&0!==i.length){const t={},e={},r=Object.keys(s);for(const n of r){const r=s[n],i=this._tiles[n];if(!i||i.fadeEndTime&&i.fadeEndTime<=Wt.now())continue;const a=this.findLoadedParent(r,Math.max(r.overscaledZ-Ng.maxOverzooming,this._source.minzoom));a&&(this._addTile(a.tileID),t[a.tileID.key]=a.tileID),e[n]=r;}const n=i[i.length-1].overscaledZ;for(const t in this._tiles){const r=this._tiles[t];if(s[t]||!r.hasData())continue;let i=r.tileID;for(;i.overscaledZ>n;){i=i.scaledTo(i.overscaledZ-1);const n=this._tiles[i.key];if(n&&n.hasData()&&e[i.key]){s[t]=r.tileID;break}}}for(const e in t)s[e]||(this._coveredTiles[e]=!0,s[e]=t[e]);}for(const t in s)this._tiles[t].clearFadeHold();const a=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r}(this._tiles,s);for(const t of a){const e=this._tiles[t];e.hasSymbolBuckets&&!e.holdingForFade()?e.setHoldDuration(this.map._fadeDuration):e.hasSymbolBuckets&&!e.symbolFadeFinished()||this._removeTile(+t);}this._updateLoadedParentTileCache(),this._onlySymbols&&this._source.afterUpdate&&this._source.afterUpdate();}releaseSymbolFadeTiles(){for(const t in this._tiles)this._tiles[t].holdingForFade()&&this._removeTile(+t);}_updateRetainedTiles(t){const e={};if(0===t.length)return e;const r={},n=t.reduce(((t,e)=>Math.min(t,e.overscaledZ)),1/0),i=t[0].overscaledZ,s=Math.max(i-Ng.maxOverzooming,this._source.minzoom),a=Math.max(i+Ng.maxUnderzooming,this._source.minzoom),o={};for(const r of t){const t=this._addTile(r);e[r.key]=r,t.hasData()||n=this._source.maxzoom){const t=n.children(this._source.maxzoom)[0],r=this.getTile(t);if(r&&r.hasData()){e[t.key]=t;continue}}else {const t=n.children(this._source.maxzoom);if(e[t[0].key]&&e[t[1].key]&&e[t[2].key]&&e[t[3].key])continue}let i=t.wasRequested();for(let a=n.overscaledZ-1;a>=s;--a){const s=n.scaledTo(a);if(r[s.key])break;if(r[s.key]=!0,t=this.getTile(s),!t&&i&&(t=this._addTile(s)),t&&(e[s.key]=s,i=t.wasRequested(),t.hasData()))break}}return e}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const t in this._tiles){const e=[];let r,n=this._tiles[t].tileID;for(;n.overscaledZ>0;){if(n.key in this._loadedParentTiles){r=this._loadedParentTiles[n.key];break}e.push(n.key);const t=n.scaledTo(n.overscaledZ-1);if(r=this._getLoadedTile(t),r)break;n=t;}for(const t of e)this._loadedParentTiles[t]=r;}}_addTile(t){let e=this._tiles[t.key];if(e)return !0!==e.isExtraShadowCaster||!!this._shadowCasterTiles[t.key]||this._reloadTile(t.key,\"reloading\"),e;e=this._cache.getAndRemove(t),e&&(this._setTileReloadTimer(t.key,e),e.tileID=t,this._state.initializeTileState(e,this.map?this.map.painter:null),this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,e)));const r=Boolean(e);if(!r){const r=this.map?this.map.painter:null;e=new Bg(t,this._source.tileSize*t.overscaleFactor(),this.transform.tileZoom,r,this._isRaster),this._loadTile(e,this._tileLoaded.bind(this,e,t.key,e.state));}return e?(e.uses++,this._tiles[t.key]=e,r||this._source.fire(new Qt(\"dataloading\",{tile:e,coord:e.tileID,dataType:\"source\"})),e):null}_setTileReloadTimer(t,e){t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);const r=e.getExpiryTimeout();r&&(this._timers[t]=setTimeout((()=>{this._reloadTile(t,\"expired\"),delete this._timers[t];}),r));}_removeTile(t){const e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()&&\"reloading\"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const t in this._tiles)this._removeTile(+t);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id);}tilesIn(t,e,r){const n=[],i=this.transform;if(!i)return n;const s=\"globe\"===i.projection.name,a=Hh(i.center.lng);for(const o in this._tiles){const l=this._tiles[o];if(r&&l.clearQueryDebugViz(),l.holdingForFade())continue;let u;if(s){const t=l.tileID.canonical;if(0===t.z){const e=[Math.abs(k(a,...Gg(t,-1))-a),Math.abs(k(a,...Gg(t,1))-a)];u=[0,2*e.indexOf(Math.min(...e))-1];}else {const e=[Math.abs(k(a,...Gg(t,-1))-a),Math.abs(k(a,...Gg(t,0))-a),Math.abs(k(a,...Gg(t,1))-a)];u=[e.indexOf(Math.min(...e))-1];}}else u=[0];for(const r of u){const s=t.containsTile(l,i,e,r);s&&n.push(s);}}return n}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(t){return this._getRenderableCoordinates(t)}_getRenderableCoordinates(t,e){const r=this.getRenderableIds(t,e).map((t=>this._tiles[t].tileID)),n=\"globe\"===this.transform.projection.name;for(const t of r)t.projMatrix=this.transform.calculateProjMatrix(t.toUnwrapped()),t.expandedProjMatrix=n?this.transform.calculateProjMatrix(t.toUnwrapped(),!1,!0):t.projMatrix;return r}sortCoordinatesByDistance(t){const e=t.slice(),r=this.transform._camera.position,n=this.transform._camera.forward(),i={};for(const t of e){const e=1/(1<i[t.key]-i[e.key])),e}hasTransition(){if(this._source.hasTransition())return !0;if(qg(this._source.type))for(const t in this._tiles){const e=this._tiles[t];if(void 0!==e.fadeEndTime&&e.fadeEndTime>=Wt.now())return !0}return !1}setFeatureState(t,e,r){this._state.updateState(t=t||\"_geojsonTileLayer\",e,r);}removeFeatureState(t,e,r){this._state.removeFeatureState(t=t||\"_geojsonTileLayer\",e,r);}getFeatureState(t,e){return this._state.getState(t=t||\"_geojsonTileLayer\",e)}setDependencies(t,e,r){const n=this._tiles[t];n&&n.setDependencies(e,r);}reloadTilesForDependencies(t,e){for(const r in this._tiles)this._tiles[r].hasDependency(t,e)&&this._reloadTile(+r,\"reloading\");this._cache.filter((r=>!r.hasDependency(t,e)));}_preloadTiles(t,e){if(!this._sourceLoaded){const r=()=>{this._sourceLoaded&&(this._source.off(\"data\",r),this._preloadTiles(t,e));};return void this._source.on(\"data\",r)}const r=new Map,n=Array.isArray(t)?t:[t],i=this.map.painter.terrain,s=this.usedForTerrain&&i?i.getScaledDemTileSize():this._source.tileSize;for(const t of n){const e=t.coveringTiles({tileSize:s,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const t of e)r.set(t.key,t);this.usedForTerrain&&t.updateElevation(!1);}z(Array.from(r.values()),((t,e)=>{const r=new Bg(t,this._source.tileSize*t.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster);this._loadTile(r,(t=>{\"raster-dem\"===this._source.type&&r.dem&&this._backfillDEM(r),e(t,r);}));}),e);}}function $g(t,e){const r=Math.abs(2*t.wrap)-+(t.wrap<0),n=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||n-r||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function qg(t){return \"raster\"===t||\"image\"===t||\"video\"===t||\"custom\"===t}function Gg(t,e){const r=1<0){const n=function(e,r){const n=r.worldSize,i=Qh(1,0)*n*sp(r.center.lat,r.zoom)/Rh(n),s=Qh(1,r.center.lat)*n,a=t.m.identity([]);return t.m.rotateY(a,a,_(r.center.lng)),t.m.rotateX(a,a,_(r.center.lat)),t.m.translate(a,a,[0,0,ch]),t.m.scale(a,a,[i,i,i*s]),t.m.translate(a,a,[r.point.x-.5*n,r.point.y-.5*n,0]),t.m.multiply(a,a,e),t.m.multiply(a,r.globeMatrix,a)}(e,r);return function(e,r,n){const i=(e,r,n)=>{const i=t.v.length(e),s=t.v.length(r),a=wh(e,r,n);return t.v.scale(a,a,1/t.v.length(a)*Mn(i,s,n))},s=i([e[0],e[1],e[2]],[r[0],r[1],r[2]],n),a=i([e[4],e[5],e[6]],[r[4],r[5],r[6]],n),o=i([e[8],e[9],e[10]],[r[8],r[9],r[10]],n),l=wh([e[12],e[13],e[14]],[r[12],r[13],r[14]],n);return [s[0],s[1],s[2],0,a[0],a[1],a[2],0,o[0],o[1],o[2],0,l[0],l[1],l[2],1]}(s,n,i)}return s}const ux=64,cx={CoordinateSpaceTile:1,CoordinateSpaceYUp:2,HasMapboxMeshFeatures:4};function hx(t,e,r=!1){t.uploaded||(t.gfxTexture=new _g(e,t.image,r?e.gl.R8:e.gl.RGBA,{useMipmap:t.sampler.minFilter>=e.gl.NEAREST_MIPMAP_NEAREST}),t.uploaded=!0,t.image=null);}function px(t,e,r){t.indexBuffer=e.createIndexBuffer(t.indexArray,!1,!0),t.vertexBuffer=e.createVertexBuffer(t.vertexArray,Yg.members,!1,!0),t.normalArray&&(t.normalBuffer=e.createVertexBuffer(t.normalArray,Wg.members,!1,!0)),t.texcoordArray&&(t.texcoordBuffer=e.createVertexBuffer(t.texcoordArray,Kg.members,!1,!0)),t.colorArray&&(t.colorBuffer=e.createVertexBuffer(t.colorArray,(12===t.colorArray.bytesPerElement?Zg:Xg).members,!1,!0)),t.featureArray&&(t.pbrBuffer=e.createVertexBuffer(t.featureArray,Jg.members,!0)),t.segments=Do.simpleSegment(0,0,t.vertexArray.length,t.indexArray.length);const n=t.material;n.pbrMetallicRoughness.baseColorTexture&&hx(n.pbrMetallicRoughness.baseColorTexture,e),n.pbrMetallicRoughness.metallicRoughnessTexture&&hx(n.pbrMetallicRoughness.metallicRoughnessTexture,e),n.normalTexture&&hx(n.normalTexture,e),n.occlusionTexture&&hx(n.occlusionTexture,e,r),n.emissionTexture&&hx(n.emissionTexture,e);}function fx(t,e,r){if(t.meshes)for(const n of t.meshes)px(n,e,r);if(t.children)for(const n of t.children)fx(n,e,r);}function dx(t){if(t.meshes)for(const e of t.meshes)e.indexArray.destroy(),e.vertexArray.destroy(),e.colorArray&&e.colorArray.destroy(),e.normalArray&&e.normalArray.destroy(),e.texcoordArray&&e.texcoordArray.destroy(),e.featureArray&&e.featureArray.destroy();if(t.children)for(const e of t.children)dx(e);}function mx(t){if(t.meshes)for(const r of t.meshes)r.vertexBuffer&&(r.vertexBuffer.destroy(),r.indexBuffer.destroy(),r.normalBuffer&&r.normalBuffer.destroy(),r.texcoordBuffer&&r.texcoordBuffer.destroy(),r.colorBuffer&&r.colorBuffer.destroy(),r.pbrBuffer&&r.pbrBuffer.destroy(),r.segments.destroy(),r.material&&((e=r.material).pbrMetallicRoughness.baseColorTexture&&e.pbrMetallicRoughness.baseColorTexture.gfxTexture&&e.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),e.pbrMetallicRoughness.metallicRoughnessTexture&&e.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&e.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),e.normalTexture&&e.normalTexture.gfxTexture&&e.normalTexture.gfxTexture.destroy(),e.emissionTexture&&e.emissionTexture.gfxTexture&&e.emissionTexture.gfxTexture.destroy(),e.occlusionTexture&&e.occlusionTexture.gfxTexture&&e.occlusionTexture.gfxTexture.destroy()));var e;if(t.children)for(const e of t.children)mx(e);}class yx{constructor(t,e){this.feature=t,this.instancedDataOffset=e,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0];}}class gx{constructor(){this.instancedDataArray=new go,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={};}}class xx{constructor(t){this.zoom=t.zoom,this.canonical=t.canonical,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.fqid)),this.projection=t.projection,this.index=t.index,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0};}populate(t,e,r,n){this.tileToMeter=op(r);const i=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);for(const{feature:s,id:a,index:o,sourceLayerIndex:l}of t){const t=gp(s,i);if(!this.layers[0]._featureFilter.filter(new _a(this.zoom),t,r))continue;const u={id:a,sourceLayerIndex:l,index:o,geometry:i?t.geometry:yp(s,r,n),properties:s.properties,type:s.type,patterns:{}},c=this.addFeature(u,u.geometry,t);c&&e.featureIndex.insert(s,u.geometry,o,l,this.index,this.instancesPerModel[c].instancedDataArray.length);}this.lookup=null;}update(t,e,r,n){for(const e in this.instancesPerModel){const r=this.instancesPerModel[e];for(const e in t)r.idToFeaturesIndex.hasOwnProperty(e)&&this.evaluate(r.features[r.idToFeaturesIndex[e]],t[e],r,!0);}this.maxHeight=0;}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return !1;let e=!1;for(const r in this.instancesPerModel){const n=this.instancesPerModel[r];for(const r of n.features){const i=this.layers[0],s=r.feature,a=this.canonical,o=i.paint.get(\"model-rotation\").evaluate(s,{},a),l=i.paint.get(\"model-scale\").evaluate(s,{},a),u=i.paint.get(\"model-translation\").evaluate(s,{},a);t.v.exactEquals(r.rotation,o)&&t.v.exactEquals(r.scale,l)&&t.v.exactEquals(r.translation,u)||(this.evaluate(r,r.featureStates,n,!0),e=!0);}}return e}isEmpty(){for(const t in this.instancesPerModel)if(0!==this.instancesPerModel[t].instancedDataArray.length)return !1;return !0}uploadPending(){return !this.uploaded}upload(t){if(!this.uploaded)for(const e in this.instancesPerModel){const r=this.instancesPerModel[e];r.instancedDataArray.length<0||0===r.instancedDataArray.length||(r.instancedDataBuffer?r.instancedDataBuffer.updateData(r.instancedDataArray):r.instancedDataBuffer=t.createVertexBuffer(r.instancedDataArray,Hg.members,!0,void 0,this.instanceCount));}this.uploaded=!0;}destroy(){for(const t in this.instancesPerModel){const e=this.instancesPerModel[t];0!==e.instancedDataArray.length&&e.instancedDataBuffer&&e.instancedDataBuffer.destroy();}}addFeature(t,e,r){const n=this.layers[0],i=n.layout.get(\"model-id\").evaluate(r,{},this.canonical);if(!i)return q(`modelId is not evaluated for layer ${n.id} and it is not going to get rendered.`),i;this.instancesPerModel[i]||(this.instancesPerModel[i]=new gx);const s=this.instancesPerModel[i],a=s.instancedDataArray,o=new yx(r,a.length);for(const t of e)for(const e of t){if(e.x<0||e.x>=Cr||e.y<0||e.y>=Cr)continue;const t=(this.lookupDim-1)/Cr,r=this.lookupDim*(e.y*t|0)+e.x*t|0;if(this.lookup){if(0!==this.lookup[r])continue;this.lookup[r]=1;}this.instanceCount++;const n=a.length;a.resize(n+1),s.instancesEvaluatedElevation.push(0),a.float32[16*n]=e.x,a.float32[16*n+1]=e.y;}return o.instancedDataCount=s.instancedDataArray.length-o.instancedDataOffset,o.instancedDataCount>0&&(t.id&&(s.idToFeaturesIndex[t.id]=s.features.length),s.features.push(o),this.evaluate(o,{},s,!1)),i}evaluate(t,e,r,n){const i=this.layers[0],s=t.feature,a=this.canonical,o=t.rotation=i.paint.get(\"model-rotation\").evaluate(s,e,a),l=t.scale=i.paint.get(\"model-scale\").evaluate(s,e,a),u=t.translation=i.paint.get(\"model-translation\").evaluate(s,e,a),c=i.paint.get(\"model-color\").evaluate(s,e,a);c.a=i.paint.get(\"model-color-mix-intensity\").evaluate(s,e,a);const h=[];this.maxVerticalOffset10?this.tileToMeter:op(a,f)),o[s+4]=u[0],o[s+5]=u[1],o[s+6]=u[2]+l,o[s+7]=h[0],o[s+8]=h[1],o[s+9]=h[2],o[s+10]=h[4],o[s+11]=h[5],o[s+12]=h[6],o[s+13]=h[8],o[s+14]=h[9],o[s+15]=h[10],r.instancesEvaluatedElevation[i]=u[2];}}}Ks(xx,\"ModelBucket\",{omit:[\"layers\"]}),Ks(gx,\"PerModelAttributes\"),Ks(yx,\"ModelFeature\");const vx=new Da({visibility:new za(re.layout_model.visibility),\"model-id\":new Ea(re.layout_model[\"model-id\"])});var bx={paint:new Da({\"model-opacity\":new za(re.paint_model[\"model-opacity\"]),\"model-rotation\":new Ea(re.paint_model[\"model-rotation\"]),\"model-scale\":new Ea(re.paint_model[\"model-scale\"]),\"model-translation\":new Ea(re.paint_model[\"model-translation\"]),\"model-color\":new Ea(re.paint_model[\"model-color\"]),\"model-color-mix-intensity\":new Ea(re.paint_model[\"model-color-mix-intensity\"]),\"model-type\":new za(re.paint_model[\"model-type\"]),\"model-cast-shadows\":new za(re.paint_model[\"model-cast-shadows\"]),\"model-receive-shadows\":new za(re.paint_model[\"model-receive-shadows\"]),\"model-ambient-occlusion-intensity\":new za(re.paint_model[\"model-ambient-occlusion-intensity\"]),\"model-emissive-strength\":new Ea(re.paint_model[\"model-emissive-strength\"]),\"model-roughness\":new Ea(re.paint_model[\"model-roughness\"]),\"model-height-based-emissive-strength-multiplier\":new Ea(re.paint_model[\"model-height-based-emissive-strength-multiplier\"]),\"model-cutoff-fade-range\":new za(re.paint_model[\"model-cutoff-fade-range\"])}),layout:vx};const _x=new Float32Array(262144),wx=new Uint8Array(262144);function Mx(t){let e=0;if(t.meshes)for(const r of t.meshes)e=Math.max(e,r.aabb.max[2]);if(t.children)for(const r of t.children)e=Math.max(e,Mx(r));return e}const Ax=[\"\",\"wall\",\"door\",\"roof\",\"window\",\"lamp\",\"logo\"];class Sx{constructor(t){this.node=t,this.evaluatedRMEA=[[1,0,0,1],[1,0,0,1],[1,0,0,1],[1,0,0,1],[.4,1,0,1],[1,0,0,1],[1,0,0,1]],this.hiddenByReplacement=!1,this.evaluatedScale=[1,1,1],this.evaluatedColor=[],this.emissionHeightBasedParams=[],this.feature={type:\"Point\",id:t.id,geometry:[],properties:{height:Mx(t)}};}}class Ix{constructor(t,e,r,n){this.nodes=t,this.id=e,this.modelTraits|=cx.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,r&&(this.modelTraits|=cx.HasMapboxMeshFeatures),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:\"mercator\"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=n,this.dirty=!0,this.needsUpload=!1;}update(){console.log(\"Update 3D model bucket\");}populate(){console.log(\"populate 3D model bucket\");}uploadPending(){return !this.uploaded||this.needsUpload}upload(t){if(!this.needsUpload)return;const e=this.getNodesInfo();for(const r of e){const e=r.node;this.uploaded?this.updatePbrBuffer(e):fx(e,t,!0);}for(const t of e)dx(t.node);this.uploaded=!0,this.needsUpload=!1;}updatePbrBuffer(t){let e=!1;if(!t.meshes)return e;for(const r of t.meshes)r.pbrBuffer&&(r.pbrBuffer.updateData(r.featureArray),e=!0);return e}needsReEvaluation(t,e,r){const n=t.transform.projectionOptions,i=t.style.getBrightness(),s=this.brightness!==i;return !!(!this.uploaded||this.dirty||n.name!==this.projection.name||kx(r.paint.get(\"model-color\").value,s)||kx(r.paint.get(\"model-color-mix-intensity\").value,s)||kx(r.paint.get(\"model-roughness\").value,s)||kx(r.paint.get(\"model-emissive-strength\").value,s)||kx(r.paint.get(\"model-height-based-emissive-strength-multiplier\").value,s))&&(this.projection=n,this.brightness=i,!0)}evaluateScale(t,e){if(t.transform.zoom===this.zoom)return;this.zoom=t.transform.zoom;const r=this.getNodesInfo(),n=this.id.canonical;for(const t of r){const r=t.feature;t.evaluatedScale=e.paint.get(\"model-scale\").evaluate(r,{},n);}}evaluate(t){const e=this.getNodesInfo();for(const r of e){if(!r.node.meshes)continue;const e=r.feature,n=r.node.meshes&&r.node.meshes[0].featureData,i=r.evaluatedColor[2],s=r.evaluatedRMEA[2],a=this.id.canonical;if(r.hasTranslucentParts=!1,n){for(let n=0;n=t)continue;const h=_x[u],p=Math.abs(h);p>o&&(a=h,o=p,l=i,c=e);}if(o>.1){const s=1-(t+.5*Math.abs(l*c))/u;let o=e._dem.get(n,r)+a*s;const h=e._dem.get(n+l,r+c),p=e._dem.get(n-l,r-c,!0);(o-h)*(o-p)>0&&(o=(h+p)/2),_x[i]=e._dem.set(n,r,o),wx[i]=t;}}}}}a&&(e._demTile.needsDEMTextureUpload=!0,e._dem._timestamp=Wt.now());}getNodesInfo(){if(!this.nodesInfo){this.nodesInfo=[];for(const t of this.nodes)this.nodesInfo.push(new Sx(t));this.freeNodes();}return this.nodesInfo}freeNodes(){if(this.nodes){for(const t of this.nodes)mx(t);this.nodes.splice(0,this.nodes.length);}}destroy(){this.freeNodes();const t=this.getNodesInfo();for(const e of t)dx(e.node),mx(e.node);}isEmpty(){return !this.nodes.length}updateReplacement(t,e){if(e.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=e.updateTime;const r=e.getReplacementRegionsForTile(t.toUnwrapped()),n=this.getNodesInfo();for(let t=0;tt.footprint===e.footprint));}}getHeightAtTileCoord(t,e){const r=this.getNodesInfo(),n=[];for(let i=0;ia.aabb.max[0]||e>a.aabb.max[1])continue;const o=(t-a.aabb.min[0])/(a.aabb.max[0]-a.aabb.min[0])*ux|0,l=Math.min(63,(e-a.aabb.min[1])/(a.aabb.max[1]-a.aabb.min[1])*ux|0)*ux+Math.min(63,o);if(!(a.heightmap[l]<0&&s.node.footprint)){if(s.hiddenByReplacement)return;return {height:a.heightmap[l],maxHeight:s.feature.properties.height,hidden:!1,verticalScale:s.evaluatedScale[2]}}if(s.node.footprint.grid.query(new x(t,e),new x(t,e),n),n.length>0)return {height:void 0,maxHeight:s.feature.properties.height,hidden:s.hiddenByReplacement,verticalScale:s.evaluatedScale[2]}}}}function kx(t,e){return !t.isLightConstant&&e}function Tx(t,e,r,n,i,s,a,o){let l=(61440&e|(61440&e)>>4)>>8,u=(3840&e|(3840&e)>>4)>>4,c=240&e|(240&e)>>4;r[3]>0&&(l=Mn(l,255*r[0],r[3]),u=Mn(u,255*r[1],r[3]),c=Mn(c,255*r[2],r[3]));const h=l<<8|u,p=c<<8|Math.floor(255*n[3]),f=function(t){const e=k(t,0,2);return Math.min(Math.round(.5*e*255),255)}(n[2])<<8|15*n[0]<<4|15*n[1],d=k(i[0],0,1),m=k(i[1],0,1),y=k(i[2],0,1),g=k(i[3],0,1);let x,v,b,_;if(d!==m&&a!==s&&m!==d){const t=a-s;v=1/(t*(m-d)),b=-(s+t*d)/(t*(m-d));const e=k(i[4],-1,1);_=Math.pow(10,e),x=255*y<<8|255*g;}else x=65535,v=0,b=1,_=1;if(t.emplaceBack(h,p,f,x,v,b,_),o){const t=o.length;o.clear();for(let e=0;e>16&65535,u=t.evaluatedRMEA[o],c=t.evaluatedColor[o],h=t.emissionHeightBasedParams[o];if(s&&2===o&&r.lights&&(n=new xo,n.resize(10*r.lights.length)),Tx(i.featureArray,l,c,u,h,i.aabb.min[2],i.aabb.max[2],n),n&&s){s=!1;const t=r.meshes[r.lightMeshIndex];t.featureArray=n,t.featureArray._trim();}}i.featureArray._trim(),n++;}}function zx(t,e){return t.x-e.x||t.y-e.y}function Ex(t,e){return 0===zx(t.min,e.min)&&0===zx(t.max,e.max)}function Bx(t,e){return !(t.min.x>e.max.x||t.max.xe.max.y||t.max.ynew x(t.x*s.x*Cr*o-a.x*Cr,t.y*s.y*Cr*o-a.y*Cr)));}return Rx(r,i,t.indices,0,t.indices.length,0,0)}Ks(Ix,\"Tiled3dModelBucket\",{omit:[\"layers\"]}),Ks(Sx,\"Tiled3dModelFeature\");const Vx=ud.types,Ox=[\"fill-extrusion-base\",\"fill-extrusion-height\",\"fill-extrusion-color\",\"fill-extrusion-pattern\",\"fill-extrusion-flood-light-wall-radius\"],Fx=[\"fill-extrusion-flood-light-ground-radius\"],jx=Math.pow(2,13),Ux=Math.pow(2,15)-1,Nx=new x(0,1),$x=2147483648;function qx(t,e,r,n,i,s,a,o){t.emplaceBack((e<<1)+a,(r<<1)+s,(Math.floor(n*jx)<<1)+i,Math.round(o));}function Gx(t,e,r,n,i,s){t.emplaceBack(e.x,e.y,(r.x<<1)+n,(r.y<<1)+i,s);}function Yx(t,e,r){const n=16384;t.emplaceBack(e.x,e.y,e.z,r[0]*n,r[1]*n,r[2]*n);}class Zx{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0;}}class Xx{constructor(){this.centroidXY=new x(0,0),this.vertexArrayOffset=0,this.vertexCount=0,this.groundVertexArrayOffset=0,this.groundVertexCount=0,this.flags=0,this.footprintSegIdx=-1,this.footprintSegLen=0,this.polygonSegIdx=-1,this.polygonSegLen=0,this.min=new x(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new x(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0;}span(){return new x(this.max.x-this.min.x,this.max.y-this.min.y)}}class Kx{constructor(){this.acc=new x(0,0),this.accCount=0,this.centroidDataIndex=0;}startRing(t,e){t.min.x===Number.MAX_VALUE&&(t.min.x=t.max.x=e.x,t.min.y=t.max.y=e.y);}appendEdge(t,e,r){this.accCount++,this.acc._add(e);let n=!!this.borders;e.xt.max.x&&(t.max.x=e.x,n=!0),e.yt.max.y&&(t.max.y=e.y,n=!0),((0===e.x||e.x===Cr)&&e.x===r.x)!=((0===e.y||e.y===Cr)&&e.y===r.y)&&this.processBorderOverlap(e,r),n&&this.checkBorderIntersection(e,r);}checkBorderIntersection(t,e){e.x<0!=t.x<0&&this.addBorderIntersection(0,Mn(e.y,t.y,(0-e.x)/(t.x-e.x))),e.x>Cr!=t.x>Cr&&this.addBorderIntersection(1,Mn(e.y,t.y,(Cr-e.x)/(t.x-e.x))),e.y<0!=t.y<0&&this.addBorderIntersection(2,Mn(e.x,t.x,(0-e.y)/(t.y-e.y))),e.y>Cr!=t.y>Cr&&this.addBorderIntersection(3,Mn(e.x,t.x,(Cr-e.y)/(t.y-e.y)));}addBorderIntersection(t,e){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const r=this.borders[t];er[1]&&(r[1]=e);}processBorderOverlap(t,e){if(t.x===e.x){if(t.y===e.y)return;const r=0===t.x?0:1;this.addBorderIntersection(r,e.y),this.addBorderIntersection(r,t.y);}else {const r=0===t.y?2:3;this.addBorderIntersection(r,e.x),this.addBorderIntersection(r,t.x);}}centroid(){return 0===this.accCount?new x(0,0):new x(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce(((t,e)=>t+ +(e[0]!==Number.MAX_VALUE)),0):0}}function Wx(t,e){const r=t.add(e)._unit(),n=k(t.x*r.x+t.y*r.y,-1,1);var i,s,a;return i=Math.acos(n),Math.min(4,Math.max(-4,Math.tan(i)))/4*Ux*((s=t).x*(a=e).y-s.y*a.x<0?-1:1)}const Hx=[t=>t.x<0,t=>t.x>Cr,t=>t.y<0,t=>t.y>Cr];function Jx(t,e,r,n){const i=[4];if(0===n)return i;r._mult(n);const s=t.sub(r),a=e.sub(r),o=[t,e,s,a];for(let t=0;t<4;t++)for(const e of o)if(Hx[t](e)){i.push(t);break}return i}class Qx{constructor(t){this.vertexArray=new Ya,this.indexArray=new ao,this.programConfigurations=new fl(t.layers,t.zoom,(t=>Fx.includes(t))),this._segments=new Do,this.hiddenByLandmarkVertexArray=new vo,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Do;}getDefaultSegment(){return this.regionSegments[4]}hasData(){return 0!==this.vertexArray.length}addData(t,e,r,n=!1){const i=t.length;if(i>2){let s=Math.max(0,this._segments.get().length-1);const a=this._segments._prepareSegment(4*i,this.vertexArray.length,2*this._segmentToGroundQuads[s].length);let o;s!==this._segments.get().length-1&&(s++,this._segmentToGroundQuads[s]=[],this._segmentToRegionTriCounts[s]=[0,0,0,0,0]);{const e=t[0],r=t[1];o=Wx(e.sub(t[i-1])._perp()._unit(),r.sub(e)._perp()._unit());}for(let l=0;lt.region-e.region));for(let r=0;rt+e),0);let s=0;for(let t=0;t<=4;t++){const e=i[t];if(0!==e){let r=this.regionSegments[t];r||(r=this.regionSegments[t]=new Do);const i={vertexOffset:n.vertexOffset,primitiveOffset:n.primitiveOffset+s,vertexLength:n.vertexLength,primitiveLength:e};r.get().push(i);}s+=e;}for(let t=0;t0?this.hiddenByLandmarkVertexBuffer=t.createVertexBuffer(this.hiddenByLandmarkVertexArray,Zf.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1);}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let t=0;t<=4;t++){const e=this.regionSegments[t];e&&e.destroy();}}}}class tv{constructor(t){this.zoom=t.zoom,this.canonical=t.canonical,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.fqid)),this.index=t.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=t.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new ao,this.footprintVertices=new $a,this.footprintSegments=[],this.layoutVertexArray=new Ga,this.centroidVertexArray=new zo,this.indexArray=new ao,this.programConfigurations=new fl(t.layers,t.zoom,(t=>Ox.includes(t))),this.segments=new Do,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.groundEffect=new Qx(t),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[];}populate(t,e,r,n){this.features=[],this.hasPattern=Ff(\"fill-extrusion\",this.layers,e),this.featuresOnBorder=[],this.borderFeatureIndices=[[],[],[],[]],this.borderDoneWithNeighborZ=[-1,-1,-1,-1],this.tileToMeter=op(r),this.edgeRadius=this.layers[0].layout.get(\"fill-extrusion-edge-radius\")/this.tileToMeter;for(const{feature:i,id:s,index:a,sourceLayerIndex:o}of t){const t=this.layers[0]._featureFilter.needGeometry,l=gp(i,t);if(!this.layers[0]._featureFilter.filter(new _a(this.zoom),l,r))continue;const u={id:s,sourceLayerIndex:o,index:a,geometry:t?l.geometry:yp(i,r,n),properties:i.properties,type:i.type,patterns:{}},c=this.layoutVertexArray.length;this.hasPattern?this.features.push(jf(\"fill-extrusion\",this.layers,u,this.zoom,e)):this.addFeature(u,u.geometry,a,r,{},e.availableImages,n,e.brightness),e.featureIndex.insert(i,u.geometry,a,o,this.index,c);}this.sortBorders(),\"mercator\"===this.projection.name&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0;}addFeatures(t,e,r,n,i,s){for(const t of this.features){const{geometry:a}=t;this.addFeature(t,a,t.index,e,r,n,i,s);}this.sortBorders(),\"mercator\"===this.projection.name&&this.splitToSubtiles();}update(t,e,r,n,i){const s=0!==Object.keys(t).length;if(s&&!this.stateDependentLayers.length)return;const a=s?this.stateDependentLayers:this.layers;this.programConfigurations.updatePaintArrays(t,e,a,r,n,i),this.groundEffect.update(t,e,a,r,n,i);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Kf),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=t.createVertexBuffer(this.layoutVertexExtArray,Xf.members,!0)),this.groundEffect.upload(t)),this.groundEffect.uploadPaintProperties(t),this.programConfigurations.upload(t),this.uploaded=!0;}uploadCentroid(t){this.groundEffect.uploadHiddenByLandmark(t),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,Yf.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1);}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i,s,a,o){const l=this.layers[0].paint.get(\"fill-extrusion-flood-light-ground-radius\").evaluate(t,{})/this.tileToMeter,u=[new x(0,0),new x(Cr,Cr)],c=a.projection,h=\"globe\"===c.name,p=\"Polygon\"===Vx[t.type],f=new Kx;f.centroidDataIndex=this.centroidData.length;const d=new Xx,m=this.layers[0].paint.get(\"fill-extrusion-base\").evaluate(t,{},n)<=0,y=this.layers[0].paint.get(\"fill-extrusion-height\").evaluate(t,{},n);d.height=y,d.vertexArrayOffset=this.layoutVertexArray.length,d.groundVertexArrayOffset=this.groundEffect.vertexArray.length,h&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new Ha);const g=Vf(e,500);for(let t=g.length-1;t>=0;t--){const e=g[t];(0===e.length||(v=e[0]).every((t=>t.x<=0))||v.every((t=>t.x>=Cr))||v.every((t=>t.y<=0))||v.every((t=>t.y>=Cr)))&&g.splice(t,1);}var v;let b;if(h)b=uv(g,u,n);else {b=[];for(const t of g)b.push({polygon:t,bounds:u});}const _=p?this.edgeRadius:0,w=_>0&&this.zoom<17,M=(t,e)=>{if(0===t.length)return !1;const r=t[t.length-1];return e.x===r.x&&e.y===r.y};for(const{polygon:t,bounds:e}of b){let r=0,i=0;for(const e of t)p&&!e[0].equals(e[e.length-1])&&e.push(e[0]),i+=p?e.length-1:e.length;const s=this.segments.prepareSegment((p?5:4)*i,this.layoutVertexArray,this.indexArray);d.footprintSegIdx<0&&(d.footprintSegIdx=this.footprintSegments.length),d.polygonSegIdx<0&&(d.polygonSegIdx=this.polygonSegments.length);const a={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},o=new Zx;if(o.vertexOffset=this.footprintVertices.length,o.indexOffset=3*this.footprintIndices.length,o.ringIndices=[],p){const i=[],a=[];r=s.vertexLength;for(let r=0;r4&&av(a[a.length-2],a[0],a[1]),u=_?rv(a[a.length-2],a[0],a[1],_):0;const y=[];let g,x,v;x=a[1].sub(a[0])._perp()._unit();let b=!0;for(let t=1,i=0;t0?1:0,k=l.dist(p);if(i+k>32768&&(i=0),_){v=w.sub(p)._perp()._unit();let t=nv(l,p,w,ev(x,v),_);isNaN(t)&&(t=0);const e=p.sub(l)._unit();l=l.add(e.mult(u))._round(),p=p.add(e.mult(-t))._round(),u=t,x=v,m&&this.zoom>=17&&(M(y,l)||y.push(l),M(y,p)||y.push(p));}const T=s.vertexLength,P=a.length>4&&av(l,p,w);let z=ov(i,o,b);if(qx(this.layoutVertexArray,l.x,l.y,S,I,0,0,z),qx(this.layoutVertexArray,l.x,l.y,S,I,0,1,z),i+=k,z=ov(i,P,!b),o=P,qx(this.layoutVertexArray,p.x,p.y,S,I,0,0,z),qx(this.layoutVertexArray,p.x,p.y,S,I,0,1,z),s.vertexLength+=4,this.indexArray.emplaceBack(T+0,T+1,T+2),this.indexArray.emplaceBack(T+1,T+3,T+2),s.primitiveLength+=2,_){const n=r+(1===t?a.length-2:t-2),i=1===t?r:n+1;if(this.indexArray.emplaceBack(T+1,n,T+3),this.indexArray.emplaceBack(n,i,T+3),s.primitiveLength+=2,void 0===g&&(g=T),!iv(w,a[t],e)){const e=t===a.length-1?g:s.vertexLength;this.indexArray.emplaceBack(T+2,T+3,e),this.indexArray.emplaceBack(T+3,e+1,e),this.indexArray.emplaceBack(T+3,i,e+1),s.primitiveLength+=3;}b=!b;}if(h){const t=this.layoutVertexExtArray,e=c.projectTilePoint(l.x,l.y,n),r=c.projectTilePoint(p.x,p.y,n),i=c.upVector(n,l.x,l.y),s=c.upVector(n,p.x,p.y);Yx(t,e,i),Yx(t,e,i),Yx(t,r,s),Yx(t,r,s);}}p&&(r+=a.length-1),m&&_&&this.zoom>=17&&(0!==y.length&&M(y,y[0])&&y.pop(),this.groundEffect.addData(y,e,l,_>0));}this.footprintSegments.push(o),a.triangleCount=this.indexArray.length-a.triangleArrayOffset,this.polygonSegments.push(a),++d.footprintSegLen,++d.polygonSegLen;}if(d.vertexCount=this.layoutVertexArray.length-d.vertexArrayOffset,d.groundVertexCount=this.groundEffect.vertexArray.length-d.groundVertexArrayOffset,0!==d.vertexCount){if(d.centroidXY=f.borders?Nx:this.encodeCentroid(f,d),this.centroidData.push(d),f.borders){this.featuresOnBorder.push(f);const t=this.featuresOnBorder.length-1;for(let e=0;ethis.featuresOnBorder[e].borders[t][0]-this.featuresOnBorder[r].borders[t][0]));}splitToSubtiles(){const t=[];for(let e=0;eCr),i=2*n+(+(r.min.x+r.max.x>Cr)^n);for(let n=0;nt.triangleSegmentIdx===e.triangleSegmentIdx?t.subtile-e.subtile:t.triangleSegmentIdx-e.triangleSegmentIdx));let r=0,n=0,i=0;for(const e of t){if(e.triangleSegmentIdx!==r)break;i++;}const s=t.length;for(;n!==t.length;){r=t[n].triangleSegmentIdx;let a=0,o=n,l=n;for(let e=o;e0&&this.triangleSubSegments.push({segment:c,min:s,max:u}),o=l;for(let e=o;e[t[0]*(1-r[0])+e[0]*r[0],t[1]*(1-r[1])+e[1]*r[1]],p=[],f=[];for(const t of this.triangleSubSegments){p[0]=t.min.x/Cr,p[1]=t.min.y/Cr,f[0]=t.max.x/Cr,f[1]=t.max.y/Cr;const e=h(l,u,p),s=h(l,u,f);if(0===new oh([e[0],e[1],n],[s[0],s[1],i]).intersectsPrecise(r)){o&&(c.segments.push(o),o=void 0);continue}const a=t.segment;o&&o.vertexOffset!==a.vertexOffset&&(c.segments.push(o),o=void 0),o?(o.vertexLength+=a.vertexLength,o.primitiveLength+=a.primitiveLength):o={vertexOffset:a.vertexOffset,primitiveLength:a.primitiveLength,vertexLength:a.vertexLength,primitiveOffset:a.primitiveOffset,sortKey:void 0,vaos:{}};}return o&&c.segments.push(o),c}encodeCentroid(t,e){const r=t.centroid(),n=e.span(),i=Math.min(7,Math.round(n.x*this.tileToMeter/10)),s=Math.min(7,Math.round(n.y*this.tileToMeter/10));return new x(k(r.x,1,Cr-1)<<3|i,k(r.y,1,Cr-1)<<3|s)}encodeBorderCentroid(t){if(!t.borders)return new x(0,0);const e=t.borders,r=Number.MAX_VALUE;if(e[0][0]!==r||e[1][0]!==r){const t=e[0][0]!==r?0:1;return new x(6|(e[0][0]!==r?0:65528),((e[t][0]+e[t][1])/2|0)<<3|6)}{const t=e[2][0]!==r?2:3;return new x(((e[t][0]+e[t][1])/2|0)<<3|6,6|(e[2][0]!==r?0:65528))}}showCentroid(t){const e=this.centroidData[t.centroidDataIndex];e.flags&=$x,e.centroidXY.x=0,e.centroidXY.y=0,this.writeCentroidToBuffer(e);}writeCentroidToBuffer(t){this.groundEffect.updateHiddenByLandmark(t);const e=t.vertexArrayOffset,r=t.vertexCount+t.vertexArrayOffset,n=t.flags&$x?Nx:t.centroidXY,i=this.centroidVertexArray.geta_centroid_pos0(e);if(this.centroidVertexArray.geta_centroid_pos1(e)!==n.y||i!==n.x){for(let t=e;ti.max.x||i.min.x>e.max.x||e.min.y>i.max.y||i.min.y>e.max.y))for(let s=0;se!=l>e&&t<(this.footprintVertices.int16[2*(o+s.vertexOffset)+0]-r)*(e-a)/(l-a)+r&&(n=!n);}a=r;}}return n}getHeightAtTileCoord(t,e){let r=Number.NEGATIVE_INFINITY,n=!0;const i=4*(t+Cr)*Cr+(e+Cr);if(this.partLookup.hasOwnProperty(i)){const t=this.partLookup[i];return t?{height:t.height,hidden:!!(t.flags&$x)}:void 0}for(const s of this.centroidData)t>s.max.x||s.min.x>t||e>s.max.y||s.min.y>e||this.footprintContainsPoint(t,e,s)&&s&&s.height>r&&(r=s.height,this.partLookup[i]=s,n=!!(s.flags&$x));if(r!==Number.NEGATIVE_INFINITY)return {height:r,hidden:n};this.partLookup[i]=void 0;}}function ev(t,e){const r=t.add(e)._unit();return t.x*r.x+t.y*r.y}function rv(t,e,r,n){const i=e.sub(t)._perp()._unit(),s=r.sub(e)._perp()._unit();return nv(t,e,r,ev(i,s),n)}function nv(t,e,r,n,i){const s=Math.sqrt(1-n*n);return Math.min(t.dist(e)/3,e.dist(r)/3,i*s/n)}function iv(t,e,r){return t.xr[1].x&&e.x>r[1].x||t.yr[1].y&&e.y>r[1].y}function sv(t,e){return t.xe[1].x||t.ye[1].y}function av(t,e,r){if(t.x<0||t.x>=Cr||e.x<0||e.x>=Cr||r.x<0||r.x>=Cr)return !1;const n=r.sub(e),i=n.perp(),s=t.sub(e);return (n.x*s.x+n.y*s.y)/Math.sqrt((n.x*n.x+n.y*n.y)*(s.x*s.x+s.y*s.y))>-.866&&i.x*s.x+i.y*s.y<0}function ov(t,e,r){const n=e?2|t:-3&t;return r?1|n:-2&n}function lv(){const t=Math.PI/32,e=Math.tan(t),r=qh;return r*Math.sqrt(1+2*e*e)-r}function uv(t,e,r){const n=1<{for(const r of t)a.push({polygon:r,bounds:e});},l=Math.ceil(Math.log2(r)),u=Math.ceil(Math.log2(n)),c=l-u,h=[];for(let t=0;t0?0:1);for(let t=0;te+1?f.push({polygons:p,bounds:t,depth:e+1}):o(p,t);}if(d.length){const t=[new x(0===r?c:n.x,1===r?c:n.y),a];h.length>e+1?f.push({polygons:d,bounds:t,depth:e+1}):o(d,t);}}return a}(t,e,Math.ceil((s-i)/11.25),Math.ceil((a-o)/11.25),1,((t,e,i)=>{if(0===t)return .5*(e+i);{const t=ep((r.y+e/Cr)/n);return (Jh(.5*(ep((r.y+i/Cr)/n)+t))*n-r.y)*Cr}}))}function cv(t,e,r,n,i,s){const a=Math.pow(2,n.z-i.z);for(let o=0;o{const e=[];wv(t)&&e.push(\"RENDER_LINE_DASH\"),t.paint.get(\"line-gradient\")&&e.push(\"RENDER_LINE_GRADIENT\");const r=t.paint.get(\"line-trim-offset\");return 0===r[0]&&0===r[1]||e.push(\"RENDER_LINE_TRIM_OFFSET\"),0!==t.paint.get(\"line-border-width\").constantOr(1)&&e.push(\"RENDER_LINE_BORDER\"),e};function wv(t){const e=t.paint.get(\"line-dasharray\").value;return e.value||\"constant\"!==e.kind}const Mv=new class extends Ea{possiblyEvaluate(t,e){return e=new _a(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=B({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}(xv.paint.properties[\"line-width\"].specification);function Av(t,e){return e>0?e+2*t:t}Mv.useIntegerZoom=!0;const Sv=new Da({visibility:new za(re.layout_background.visibility)});var Iv={paint:new Da({\"background-color\":new za(re.paint_background[\"background-color\"]),\"background-pattern\":new za(re.paint_background[\"background-pattern\"]),\"background-opacity\":new za(re.paint_background[\"background-opacity\"]),\"background-emissive-strength\":new za(re.paint_background[\"background-emissive-strength\"])}),layout:Sv};const kv=new Da({visibility:new za(re.layout_raster.visibility)});var Tv={paint:new Da({\"raster-opacity\":new za(re.paint_raster[\"raster-opacity\"]),\"raster-color\":new Ba(re.paint_raster[\"raster-color\"]),\"raster-color-mix\":new za(re.paint_raster[\"raster-color-mix\"]),\"raster-color-range\":new za(re.paint_raster[\"raster-color-range\"]),\"raster-hue-rotate\":new za(re.paint_raster[\"raster-hue-rotate\"]),\"raster-brightness-min\":new za(re.paint_raster[\"raster-brightness-min\"]),\"raster-brightness-max\":new za(re.paint_raster[\"raster-brightness-max\"]),\"raster-saturation\":new za(re.paint_raster[\"raster-saturation\"]),\"raster-contrast\":new za(re.paint_raster[\"raster-contrast\"]),\"raster-resampling\":new za(re.paint_raster[\"raster-resampling\"]),\"raster-fade-duration\":new za(re.paint_raster[\"raster-fade-duration\"]),\"raster-emissive-strength\":new za(re.paint_raster[\"raster-emissive-strength\"]),\"raster-array-band\":new za(re.paint_raster[\"raster-array-band\"]),\"raster-elevation\":new za(re.paint_raster[\"raster-elevation\"])}),layout:kv};function Pv(e,r,n,i,s,a,o,l){const u=[e,r,1,n,i,1,s,a,1],c=[o,l,1],h=t.bx.adjoint([],u),[p,f,d]=t.v.transformMat3(c,c,h);return t.bx.multiply(u,u,[p,0,0,0,f,0,0,0,d])}function zv(e,r,n,i,s,a,o,l){const u=function(e,r,n,i,s,a,o,l){const u=Pv(0,0,1,0,1,1,0,1),c=Pv(e,r,n,i,s,a,o,l),h=t.bx.adjoint([],u);return t.bx.multiply(c,c,h)}(e,r,n,i,s,a,o,l);return [u[2]/u[8]/Cr,u[5]/u[8]/Cr]}function Ev(t){return [t[0],Math.min(Math.max(t[1],-np),np)]}class Bv extends ee{constructor(t,e,r,n){super(),this.id=t,this.dispatcher=r,this.coordinates=e.coordinates,this.type=\"image\",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(n),this.options=e,this._dirty=!1;}load(t,e){if(this._loaded=e||!1,this.fire(new Qt(\"dataloading\",{dataType:\"source\"})),this.url=this.options.url,!this.url)return t&&(this.coordinates=t),this._loaded=!0,void this._finishLoading();this._imageRequest=vt(this.map._requestManager.transformRequest(this.url,ct.Image),((e,r)=>{this._imageRequest=null,this._loaded=!0,e?this.fire(new te(e)):r&&(this.image=r instanceof HTMLImageElement?Wt.getImageData(r):r,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,t&&(this.coordinates=t),this._finishLoading());}));}loaded(){return this._loaded}updateImage(t){return t.url?(this._imageRequest&&t.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=t.url,this.load(t.coordinates,this._loaded),this):this}setTexture(t){if(!(t.handle instanceof WebGLTexture))throw new Error(\"The provided handle is not a WebGLTexture instance\");return this.texture=new wg(this.map.painter.context,t.handle),this.width=t.dimensions[0],this.height=t.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Qt(\"data\",{dataType:\"source\",sourceDataType:\"metadata\"})));}onAdd(t){this.map=t,this.load();}onRemove(){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof wg||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy());}setCoordinates(t){if(this.coordinates=t,this._boundsArray=void 0,this._unsupportedCoords=!1,!t.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let e=t[0][1],r=t[0][1];for(const n of t)n[1]>r&&(r=n[1]),n[1]np?this.onNorthPole=!0:n<-np&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const e=t.map(lp.fromLngLat);this.tileID=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);const s=Math.max(n-e,i-r),a=Math.max(0,Math.floor(-Math.log(s)/Math.LN2)),o=Math.pow(2,a);let l=Math.floor((e+n)/2*o);return l>1&&(l-=1),new Kc(a,l,Math.floor((r+i)/2*o))}(e),this.minzoom=this.maxzoom=this.tileID.z;}return this.fire(new Qt(\"data\",{dataType:\"source\",sourceDataType:\"content\"})),this}_clear(){this._boundsArray=void 0,this._unsupportedCoords=!1;}_prepareData(e){for(const t in this.tiles){const e=this.tiles[t];\"loaded\"!==e.state&&(e.state=\"loaded\",e.texture=this.texture);}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const r=zy(new Kc(0,0,0),this.map.transform.projection),n=[r.projection.project(this.coordinates[0][0],this.coordinates[0][1]),r.projection.project(this.coordinates[1][0],this.coordinates[1][1]),r.projection.project(this.coordinates[2][0],this.coordinates[2][1]),r.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(t){const e=t[1].x-t[0].x,r=t[1].y-t[0].y,n=t[2].x-t[1].x,i=t[2].y-t[1].y,s=t[3].x-t[2].x,a=t[3].y-t[2].y,o=t[0].x-t[3].x,l=t[0].y-t[3].y,u=e*i-n*r,c=n*a-s*i,h=s*l-o*a,p=o*r-e*l;return u>0&&c>0&&h>0&&p>0||u<0&&c<0&&h<0&&p<0}(n))return console.warn(\"Image source coordinates are defining non-convex area in the Mercator projection\"),void(this._unsupportedCoords=!0);const i=zy(this.tileID,this.map.transform.projection),[s,a,o,l]=this.coordinates.map((t=>{const e=i.projection.project(t[0],t[1]);return Ey(i,e)._round()}));this.perspectiveTransform=zv(s.x,s.y,a.x,a.y,o.x,o.y,l.x,l.y);const u=this._boundsArray=new Ga;u.emplaceBack(s.x,s.y,0,0),u.emplaceBack(a.x,a.y,Cr,0),u.emplaceBack(l.x,l.y,0,Cr),u.emplaceBack(o.x,o.y,Cr,Cr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=e.createVertexBuffer(u,zg.members),this.boundsSegments=Do.simpleSegment(0,0,4,2);const c=[],h=function(t){return [Ev(t[0]),Ev(t[1]),Ev(t[2]),Ev(t[3])]}(this.coordinates),[p,f,d,m]=function(t){let e=t[0][0],r=e,n=t[0][1],i=n;for(let s=1;sr&&(r=t[s][0]),t[s][1]i&&(i=t[s][1]);return [e,n,r-e,i-n]}(h);{const i=new Ga,[s,a,o,l]=function(t){let e=t[0].x,r=e,n=t[0].y,i=n;for(let s=1;sr&&(r=t[s].x),t[s].yi&&(i=t[s].y);return [e,n,r-e,i-n]}(n),u=t=>[(t.x-s)/o,(t.y-a)/l],[h,y,g,x]=n.map(u),v=function(e,r,n,i,s,a,o,l){const u=Pv(0,0,1,0,1,1,0,1),c=Pv(e,r,n,i,s,a,o,l),h=t.bx.adjoint([],c);return t.bx.multiply(u,u,h)}(h[0],h[1],y[0],y[1],g[0],g[1],x[0],x[1]);this.elevatedGlobePerspectiveTransform=zv(h[0],h[1],y[0],y[1],g[0],g[1],x[0],x[1]);const b=(e,r)=>{c.push(e.lng);const n=Math.round((e.lng-p)/d*Cr),s=Math.round((e.lat-f)/m*Cr),a=u(r),o=t.v.transformMat3([],[a[0],a[1],1],v),l=Math.round(o[0]/o[2]*Cr),h=Math.round(o[1]/o[2]*Cr);i.emplaceBack(n,s,l,h);},_=n[3].x-n[0].x,w=n[3].y-n[0].y,M=n[2].x-n[1].x,A=n[2].y-n[1].y;for(let t=0;t<65;t++){const e=t/64,i=[n[0].x+e*_,n[0].y+e*w],s=[n[1].x+e*M,n[1].y+e*A],a=s[0]-i[0],o=s[1]-i[1];for(let t=0;t<65;t++){const e=t/64,n={x:i[0]+a*e,y:i[1]+o*e,z:0};b(r.projection.unproject(n.x,n.y),n);}}this.elevatedGlobeVertexBuffer=e.createVertexBuffer(i,zg.members);}{this.maxLongitudeTriangleSize=0;let t=[],r=new ao;const n=(e,n,i)=>{r.emplaceBack(e,n,i);const s=c[e],a=c[n],o=c[i],l=Math.min(Math.min(s,a),o),u=Math.max(Math.max(s,a),o)-l;u>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=u),t.push(l+u/2);};for(let t=0;t<64;t++)for(let e=0;e<64;e++){const r=65*t+e,i=r+1,s=r+65,a=s+1;n(r,s,i),n(i,s,a);}[t,r]=function(t,e){const r=Array.from({length:t.length},((t,e)=>e));r.sort(((e,r)=>t[e]-t[r]));const n=[],i=new ao;for(let s=0;st+360*Math.round((e-t)/360))(t+180,r[0]);const i=new Do,s=(t,r)=>{i.segments.push({vertexOffset:0,primitiveOffset:t,vertexLength:e.segments[0].vertexLength,primitiveLength:r,sortKey:void 0,vaos:{}});},a=.51*this.maxLongitudeTriangleSize;if(Math.abs(r[0]-n)<=a){const t=tt(r,0,r.length,n+a);return t===r.length||s(t,Q(r,t+1,r.length,n+360-a)-t),i}nt.polygon)).flat());const g=d?l:null,[v,b]=function(e,r,n,i,s,a,o,l,u,c,h){return \"globe\"===e.projection.name?function(e,r,n,i,s,a,o,l,u,c,h){const p=[],f=[],d=e.projection.upVectorScale(h,e.center.lat,e.worldSize).metersToTile,m=[0,0,0,1],y=[0,0,0,1],g=(t,e,r,n)=>{t[0]=e,t[1]=r,t[2]=n,t[3]=1;},x=lv();n>0&&(n+=x),i+=x;for(const x of r){const r=[],v=[];for(const p of x){const f=p.x+s.x,x=p.y+s.y,b=e.projection.projectTilePoint(f,x,h),_=e.projection.upVector(h,p.x,p.y);let w=n,M=i;if(o){const t=yv(f,x,n,i,o,l,u,c);w+=t.base,M+=t.top;}0!==n?g(m,b.x+_[0]*d*w,b.y+_[1]*d*w,b.z+_[2]*d*w):g(m,b.x,b.y,b.z),g(y,b.x+_[0]*d*M,b.y+_[1]*d*M,b.z+_[2]*d*M),t.v.transformMat4(m,m,a),t.v.transformMat4(y,y,a),r.push(new fv(m[0],m[1],m[2])),v.push(new fv(y[0],y[1],y[2]));}p.push(r),f.push(v);}return [p,f]}(e,r,n,i,s,a,o,l,u,c,h):o?function(e,r,n,i,s,a,o,l,u){const c=[],h=[],p=[0,0,0,1];for(const f of e){const e=[],d=[];for(const c of f){const h=c.x+i.x,f=c.y+i.y,m=yv(h,f,r,n,a,o,l,u);p[0]=h,p[1]=f,p[2]=m.base,p[3]=1,t.e.transformMat4(p,p,s),p[3]=Math.max(p[3],1e-5);const y=new fv(p[0]/p[3],p[1]/p[3],p[2]/p[3]);p[0]=h,p[1]=f,p[2]=m.top,p[3]=1,t.e.transformMat4(p,p,s),p[3]=Math.max(p[3],1e-5);const g=new fv(p[0]/p[3],p[1]/p[3],p[2]/p[3]);e.push(y),d.push(g);}c.push(e),h.push(d);}return [c,h]}(r,n,i,s,a,o,l,u,c):function(t,e,r,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*r,p=i[9]*r,f=i[10]*r,d=i[11]*r;for(const e of t){const t=[],r=[];for(const s of e){const e=s.x+n.x,a=s.y+n.y,m=i[0]*e+i[4]*a+i[12],y=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=m+o,b=y+l,_=g+u,w=Math.max(x+c,1e-5),M=m+h,A=y+p,S=g+f,I=Math.max(x+d,1e-5);t.push(new fv(v/w,b/w,_/w)),r.push(new fv(M/I,A/I,S/I));}s.push(t),a.push(r);}return [s,a]}(r,n,i,s,a)}(a,i,p,h,c,o,g,f,m,a.center.lat,e.tileID.canonical),_=e.queryGeometry;return function(t,e,r){let n=1/0;Mp(r,e)&&(n=mv(r,e[0]));for(let i=0;i=3)for(let e=0;e{this._triggered=!1,this._callback();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._callback();}),0));}remove(){this._channel=void 0,this._callback=()=>{};}}class jv{constructor(){this.tasks={},this.taskQueue=[],O([\"process\"],this),this.invoker=new Fv(this.process),this.nextId=0;}add(t,e){const r=this.nextId++,n=function({type:t,isSymbolTile:e,zoom:r}){return r=r||0,\"message\"===t?0:\"maybePrepare\"!==t||e?\"parseTile\"!==t||e?\"parseTile\"===t&&e?300-r:\"maybePrepare\"===t&&e?400-r:500:200-r:100-r}(e);if(0===n){X();try{t();}finally{}return null}return this.tasks[r]={fn:t,metadata:e,priority:n,id:r},this.taskQueue.push(r),this.invoker.trigger(),{cancel:()=>{delete this.tasks[r];}}}process(){X();try{if(this.taskQueue=this.taskQueue.filter((t=>!!this.tasks[t])),!this.taskQueue.length)return;const t=this.pick();if(null===t)return;const e=this.tasks[t];if(delete this.tasks[t],this.taskQueue.length&&this.invoker.trigger(),!e)return;e.fn();}finally{}}pick(){let t=null,e=1/0;for(let r=0;r{r&&delete this.callbacks[a],this.target.postMessage({id:a,type:\"\",targetMapId:n,sourceMapId:this.mapId});}}}receive(t){const e=t.data,r=e.id;if(r&&(!e.targetMapId||this.mapId===e.targetMapId))if(\"\"===e.type){const t=this.cancelCallbacks[r];delete this.cancelCallbacks[r],t&&t.cancel();}else if(e.mustQueue||X()){const t=this.callbacks[r],n=this.scheduler.add((()=>this.processTask(r,e)),t&&t.metadata||{type:\"message\"});n&&(this.cancelCallbacks[r]=n);}else this.processTask(r,e);}processTask(t,e){if(delete this.cancelCallbacks[t],\"\"===e.type){const r=this.callbacks[t];delete this.callbacks[t],r&&(e.error?r(Qs(e.error)):r(null,Qs(e.data)));}else {const r=new Set,n=e.hasCallback?(e,n)=>{this.target.postMessage({id:t,type:\"\",sourceMapId:this.mapId,error:e?Js(e):null,data:Js(n,r)},r);}:t=>{},i=Qs(e.data);if(this.parent[e.type])this.parent[e.type](e.sourceMapId,i,n);else if(this.parent.getWorkerSource){const t=e.type.split(\".\");this.parent.getWorkerSource(e.sourceMapId,t[0],i.source,i.scope)[t[1]](i,n);}else n(new Error(`Could not find function ${e.type}`));}}remove(){this.scheduler.remove(),this.target.removeEventListener(\"message\",this.receive,!1);}}class Nv{constructor(t,e){this.workerPool=t,this.actors=[],this.currentActor=0,this.id=C();const r=this.workerPool.acquire(this.id);for(let t=0;t{this.ready=!0;}));}broadcast(t,e,r){z(this.actors,((r,n)=>{r.send(t,e,n);}),r=r||function(){});}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach((t=>{t.remove();})),this.actors=[],this.workerPool.release(this.id);}}Nv.Actor=Uv;class $v{constructor(t,e){this.width=t,this.height=e,this.nextRow=0,this.image=new Jp({width:t,height:e}),this.positions={},this.uploaded=!1;}getDash(t,e){const r=this.getKey(t,e);return this.positions[r]}trim(){const t=this.width,e=this.height=L(this.nextRow);this.image.resize({width:t,height:e});}getKey(t,e){return t.join(\",\")+e}getDashRanges(t,e,r){const n=[];let i=t.length%2==1?-t[t.length-1]*r:0,s=t[0]*r,a=!0;n.push({left:i,right:s,isDash:a,zeroLength:0===t[0]});let o=t[0];for(let e=1;e1&&(a=t[++s]);const l=Math.abs(o-a.left),u=Math.abs(o-a.right),c=Math.min(l,u);let h;const p=e/r*(n+1);if(a.isDash){const t=n-Math.abs(p);h=Math.sqrt(c*c+t*t);}else h=n-Math.sqrt(c*c+p*p);this.image.data[i+o]=Math.max(0,Math.min(255,h+128));}}}addRegularDash(t,e){for(let e=t.length-1;e>=0;--e){const r=t[e],n=t[e+1];r.zeroLength?t.splice(e,1):n&&n.isDash===r.isDash&&(n.left=r.left,t.splice(e,1));}const r=t[0],n=t[t.length-1];r.isDash===n.isDash&&(r.left=n.left-this.width,n.right=r.right+this.width);const i=this.width*this.nextRow;let s=0,a=t[s];for(let r=0;r1&&(a=t[++s]);const n=Math.abs(r-a.left),o=Math.abs(r-a.right),l=Math.min(n,o);this.image.data[i+r]=Math.max(0,Math.min(255,(a.isDash?l:-l)+e+128));}}addDash(t,e){const r=this.getKey(t,e);if(this.positions[r])return this.positions[r];const n=\"round\"===e,i=n?7:0,s=2*i+1;if(this.nextRow+s>this.height)return q(\"LineAtlas out of space\"),null;0===t.length&&t.push(1);let a=0;for(let e=0;e=e.maxzoom||\"none\"!==e.visibility&&(Zv(t,this.zoom,u.brightness,r),(o[e.id]=e.createBucket({index:a.bucketLayerIDs.length,layers:t,zoom:this.zoom,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:p,sourceID:this.source,projection:this.projection.spec})).populate(f,u,this.tileID.canonical,this.tileTransform),a.bucketLayerIDs.push(t.map((t=>t.id)))));}}let h,p,f,d;l.trim();const m={type:\"maybePrepare\",isSymbolTile:this.isSymbolTile,zoom:this.zoom},y=()=>{if(h)return this.status=\"done\",i(h);if(this.extraShadowCaster)this.status=\"done\",i(null,{buckets:E(o).filter((t=>!t.isEmpty())),featureIndex:a,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:u.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(p&&f&&d){const t=new Gv(p),e=new Jm(f,d);for(const n in o){const i=o[n];i instanceof fg?(Zv(i.layers,this.zoom,u.brightness,r),vy(i,p,t.positions,f,e.iconPositions,this.showCollisionBoxes,r,this.tileID.canonical,this.tileZoom,this.projection,this.brightness)):i.hasPattern&&(i instanceof bg||i instanceof Uf||i instanceof tv)&&(Zv(i.layers,this.zoom,u.brightness,r),i.addFeatures(u,this.tileID.canonical,e.patternPositions,r,this.tileTransform,this.brightness));}this.status=\"done\",i(null,{buckets:E(o).filter((t=>!t.isEmpty())),featureIndex:a,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,lineAtlas:l,imageAtlas:e,brightness:u.brightness});}};if(!this.extraShadowCaster){const t=j(u.glyphDependencies,(t=>Object.keys(t).map(Number)));Object.keys(t).length?n.send(\"getGlyphs\",{uid:this.uid,stacks:t,scope:this.scope},((t,e)=>{h||(h=t,p=e,y());}),void 0,!1,m):p={};const e=Object.keys(u.iconDependencies);e.length?n.send(\"getImages\",{icons:e,source:this.source,scope:this.scope,tileID:this.tileID,type:\"icons\"},((t,e)=>{h||(h=t,f=e,y());}),void 0,!1,m):f={};const r=Object.keys(u.patternDependencies);r.length?n.send(\"getImages\",{icons:r,source:this.source,scope:this.scope,tileID:this.tileID,type:\"patterns\"},((t,e)=>{h||(h=t,d=e,y());}),void 0,!1,m):d={};}y();}}function Zv(t,e,r,n){const i=new _a(e,{brightness:r});for(const e of t)e.recalculate(i,n);}class Xv{constructor(t){this.entries={},this.scheduler=t;}request(t,e,r,n){const i=this.entries[t]=this.entries[t]||{callbacks:[]};if(i.result){const[t,r]=i.result;return this.scheduler?this.scheduler.add((()=>{n(t,r);}),e):n(t,r),()=>{}}return i.callbacks.push(n),i.cancel||(i.cancel=r(((r,n)=>{i.result=[r,n];for(const t of i.callbacks)this.scheduler?this.scheduler.add((()=>{t(r,n);}),e):t(r,n);setTimeout((()=>delete this.entries[t]),3e3);}))),()=>{i.result||(i.callbacks=i.callbacks.filter((t=>t!==n)),i.callbacks.length||(i.cancel(),delete this.entries[t]));}}}function Kv(t,e,r){const n=JSON.stringify(t.request);return t.data&&(this.deduped.entries[n]={result:[null,t.data]}),this.deduped.request(n,{type:\"parseTile\",isSymbolTile:t.isSymbolTile,zoom:t.tileZoom},(e=>{const n=dt(t.request,((t,n,i,s)=>{t?e(t):n&&e(null,{vectorTile:r?void 0:new ld(new Cd(n)),rawData:n,cacheControl:i,expires:s});}));return ()=>{n.cancel(),e();}}),e)}var Wv={workerUrl:\"\",workerClass:null,workerParams:void 0};function Hv(){return null!=Wv.workerClass?new Wv.workerClass:new self.Worker(Wv.workerUrl,Wv.workerParams)}const Jv=\"mapboxgl_preloaded_worker_pool\";class Qv{constructor(){this.active={};}acquire(t){if(!this.workers)for(this.workers=[];this.workers.length{t.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[Jv]}numActive(){return Object.keys(this.active).length}}let tb;function eb(){return tb||(tb=new Qv),tb}Qv.workerCount=2;let rb,nb,ib,sb=null;function ab(){return X()&&self.worker&&self.worker.dracoUrl?self.worker.dracoUrl:nb||n.DRACO_URL}const ob=5123,lb=5126,ub={5120:Int8Array,5121:Uint8Array,5122:Int16Array,[ob]:Uint16Array,5125:Uint32Array,[lb]:Float32Array},cb={5120:\"DT_INT8\",5121:\"DT_UINT8\",5122:\"DT_INT16\",[ob]:\"DT_UINT16\",5125:\"DT_UINT32\",[lb]:\"DT_FLOAT32\"},hb={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function pb(t,e,r){const n=r.json.bufferViews.length,i=r.buffers.length;e.bufferView=n,r.json.bufferViews[n]={buffer:i,byteLength:t.byteLength},r.buffers[i]=t;}const fb=\"KHR_draco_mesh_compression\";function db(t,e){const r=t.extensions&&t.extensions[fb];if(!r)return;const n=new ib.Decoder,i=vb(e,r.bufferView),s=new ib.Mesh;if(!n.DecodeArrayToMesh(i,i.byteLength,s))throw new Error(\"Failed to decode Draco mesh\");const a=e.json.accessors[t.indices],o=ub[a.componentType],l=a.count*o.BYTES_PER_ELEMENT,u=ib._malloc(l);o===Uint16Array?n.GetTrianglesUInt16Array(s,l,u):n.GetTrianglesUInt32Array(s,l,u),pb(ib.memory.buffer.slice(u,u+l),a,e),ib._free(u);for(const i of Object.keys(r.attributes)){const a=n.GetAttributeByUniqueId(s,r.attributes[i]),o=e.json.accessors[t.attributes[i]],l=cb[o.componentType],u=o.count*hb[o.type]*ub[o.componentType].BYTES_PER_ELEMENT,c=ib._malloc(u);n.GetAttributeDataArrayForAllPoints(s,a,ib[l],u,c),pb(ib.memory.buffer.slice(c,c+u),o,e),ib._free(c);}n.destroy(),s.destroy(),delete t.extensions[fb];}const mb=1179937895,yb=new TextDecoder(\"utf8\");function gb(t,e){return new URL(t,e).href}function xb(t,e,r,n){return fetch(gb(t.uri,n)).then((t=>t.arrayBuffer())).then((t=>{e.buffers[r]=t;}))}function vb(t,e){const r=t.json.bufferViews[e];return new Uint8Array(t.buffers[r.buffer],r.byteOffset||0,r.byteLength)}function bb(t,e,r,n){if(t.uri){const i=gb(t.uri,n);return fetch(i).then((t=>t.blob())).then((t=>createImageBitmap(t))).then((t=>{e.images[r]=t;}))}if(void 0!==t.bufferView){const n=vb(e,t.bufferView),i=new Blob([n],{type:t.mimeType});return createImageBitmap(i).then((t=>{e.images[r]=t;}))}}function _b(t,e=0,r){const n={json:null,images:[],buffers:[]};if(new Uint32Array(t,e,1)[0]===mb){const r=new Uint32Array(t,e);let i=2;const s=(r[i++]>>2)-3,a=r[i++]>>2;if(i++,n.json=JSON.parse(yb.decode(r.subarray(i,i+a))),i+=a,i{const t=[],e=o&&o.includes(fb);if(e&&t.push(function(){if(!ib)return rb||(rb=function(t){let e,r=null;function n(){e=new Uint8Array(r.buffer);}function i(){throw new Error(\"Unexpected Draco error.\")}const s={a:{a:i,d:function(t,r,n){return e.copyWithin(t,r,r+n)},c:function(t){const i=e.length,s=Math.max(t>>>0,Math.ceil(1.2*i)),a=Math.ceil((s-i)/65536);try{return r.grow(a),n(),!0}catch(t){return !1}},b:i}};return (WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(t,s):t.then((t=>t.arrayBuffer())).then((t=>WebAssembly.instantiate(t,s)))).then((t=>{const{Rb:i,Qb:s,P:a,T:o,X:l,Ja:u,La:c,Qa:h,Va:p,Wa:f,eb:d,jb:m,f:y,e:g,yb:x,zb:v,Ab:b,Bb:_,Db:w,Gb:M}=t.instance.exports;r=g;const A=(()=>{let t=0,r=0,n=0,a=0;return o=>{n&&(i(a),i(t),r+=n,n=t=0),t||(r+=128,t=s(r));const l=o.length+7&-8;let u=t;l>=r&&(n=l,u=a=s(l));for(let t=0;t{ib=t,rb=void 0;})))}()),s)for(let e=0;e{if(e&&a)for(const{primitives:t}of a)for(const e of t)db(e,n);return n}))}))}class wb{constructor(t,e,r){if(this.triangleCount=e.length/3,this.min=new x(0,0),this.max=new x(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],0===this.triangleCount||0===t.length||0===r)return;const n=t.map((t=>t.x)),i=t.map((t=>t.y));this.min=new x(Math.min(...n),Math.min(...i)),this.max=new x(Math.max(...n),Math.max(...i));const s=this.max.sub(this.min);s.x=Math.max(s.x,1),s.y=Math.max(s.y,1);const a=Math.max(s.x,s.y)/r;this.cellsX=Math.max(1,Math.ceil(s.x/a)),this.cellsY=Math.max(1,Math.ceil(s.y/a)),this.xScale=1/a,this.yScale=1/a;const o=[];for(let r=0;rt.cellIdx-e.cellIdx||t.triIdx-e.triIdx));let l=0;for(;lthis.max.x||this.min.x>e.x)return;if(t.y>this.max.y||this.min.y>e.y)return;this.lookup||(this.lookup=new Uint8Array(Math.ceil(this.triangleCount/8)));for(let t=0;t0){for(let i=0;i0){s.texcoordArray=new yo;const t=e.json.accessors[i.TEXCOORD_0];s.texcoordArray.reserve(t.count);const r=Ab(e,t);for(let e=0;e1&&n[n.length-1].equals(n[0])&&n.pop();let i=0;for(let t=0;t0&&n.reverse();const s=Lf(n.flatMap((t=>[t.x,t.y])),[]);return 0===s.length?null:{vertices:n,indices:s}}function Pb(t){const e=[],r=[];let n=0;for(const i of t){n=e.length;const t=i.vertexArray.float32,s=i.indexArray.uint16;for(let r=0;r0&&([r[t+1],r[t+2]]=[r[t+2],r[t+1]]);}return {vertices:e,indices:r}}function zb(t){const e=function(t,e){const r=[],n=WebGL2RenderingContext;if(t.json.textures)for(const i of t.json.textures){const s={magFilter:n.LINEAR,minFilter:n.NEAREST,wrapS:n.REPEAT,wrapT:n.REPEAT};void 0!==i.sampler&&Object.assign(s,t.json.samplers[i.sampler]),r.push({image:e[i.source],sampler:s,uploaded:!1});}return r}(t,t.images),r=function(t,e){const r=[];for(const n of t.json.meshes){const i=[];for(const r of n.primitives)i.push(Sb(r,t,e));r.push(i);}return r}(t,e),{scenes:n,scene:i,nodes:s}=t.json,a=n?n[i||0].nodes:s,o=[];for(const e of a)o.push(Ib(s[e],t,r));return function(t,e,r){const n={},i=new Set;for(let s=0;s0){const e=Array.from(i.values()).sort(((t,e)=>t-e));for(let r=e.length-1;r>=0;r--)t.splice(e[r],1);}}(o,a,t.json.nodes),o}function Eb(t){t.heightmap=new Float32Array(4096),t.heightmap.fill(-1);const e=t.vertexArray.float32,r=t.aabb.min[0]-1,n=t.aabb.min[1]-1,i=ux/(t.aabb.max[0]-r+2),s=ux/(t.aabb.max[1]-n+2);for(let a=0;at.heightmap[u*ux+l]&&(t.heightmap[u*ux+l]=o);}}function Bb(e,r){const n={};n.indexArray=new ao,n.indexArray.reserve(4*e.length),n.vertexArray=new mo,n.vertexArray.reserve(10*e.length),n.colorArray=new Xa,n.vertexArray.reserve(10*e.length);let i=0;for(const s of e){const e=Math.min(10,Math.max(4,1.3*s.height))*r,a=[-s.normal[1],s.normal[0],0],o=Math.min(.29,.1*s.width/s.depth),l=s.width-2*s.depth*r*(o+.01),u=t.v.scaleAndAdd([],s.pos,a,l/2),c=t.v.scaleAndAdd([],s.pos,a,-l/2),h=[u[0],u[1],u[2]+s.height],p=[c[0],c[1],c[2]+s.height],f=t.v.scaleAndAdd([],s.normal,a,o);t.v.scale(f,f,e);const d=t.v.scaleAndAdd([],s.normal,a,-o);t.v.scale(d,d,e),t.v.add(f,u,f),t.v.add(d,c,d),u[2]+=.1,c[2]+=.1,n.vertexArray.emplaceBack(f[0],f[1],f[2]),n.vertexArray.emplaceBack(d[0],d[1],d[2]),n.vertexArray.emplaceBack(u[0],u[1],u[2]),n.vertexArray.emplaceBack(c[0],c[1],c[2]),n.vertexArray.emplaceBack(h[0],h[1],h[2]),n.vertexArray.emplaceBack(p[0],p[1],p[2]),n.vertexArray.emplaceBack(u[0],u[1],u[2]),n.vertexArray.emplaceBack(c[0],c[1],c[2]),n.vertexArray.emplaceBack(f[0],f[1],f[2]),n.vertexArray.emplaceBack(d[0],d[1],d[2]);const m=l/e/2;n.colorArray.emplaceBack(-m-o,-1,m,.8),n.colorArray.emplaceBack(m+o,-1,m,.8),n.colorArray.emplaceBack(-m,0,m,1.3),n.colorArray.emplaceBack(m,0,m,1.3),n.colorArray.emplaceBack(m+o,-.8,m,.7),n.colorArray.emplaceBack(m+o,-.8,m,.7),n.colorArray.emplaceBack(0,0,m,1.3),n.colorArray.emplaceBack(0,0,m,1.3),n.colorArray.emplaceBack(m+o,-1.2,m,.8),n.colorArray.emplaceBack(m+o,-1.2,m,.8),n.indexArray.emplaceBack(6+i,4+i,8+i),n.indexArray.emplaceBack(7+i,9+i,5+i),n.indexArray.emplaceBack(0+i,1+i,2+i),n.indexArray.emplaceBack(1+i,3+i,2+i),i+=10;}const s={defined:!0,emissiveFactor:[0,0,0]},a={};return a.baseColorFactor=Re.white,s.pbrMetallicRoughness=a,n.material=s,n.aabb=new oh([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),n}Ks(wb,\"TriangleGridIndex\");const Db=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class Cb{static from(t){if(!(t instanceof ArrayBuffer))throw new Error(\"Data must be an instance of ArrayBuffer.\");const[e,r]=new Uint8Array(t,0,2);if(219!==e)throw new Error(\"Data does not appear to be in a KDBush format.\");const n=r>>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=Db[15&r];if(!i)throw new Error(\"Unrecognized array type.\");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new Cb(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=Db.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return Rb(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error(\"Data not yet indexed - call index.finish().\");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error(\"Data not yet indexed - call index.finish().\");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)Fb(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];Fb(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function Rb(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;Lb(t,e,a,n,i,s),Rb(t,e,r,n,a-1,1-s),Rb(t,e,r,a+1,i,1-s);}function Lb(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);Lb(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(Vb(t,e,n,r),e[2*i+s]>a&&Vb(t,e,n,i);oa;)l--;}e[2*n+s]===a?Vb(t,e,n,l):(l++,Vb(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function Vb(t,e,r,n){Ob(t,r,n),Ob(e,2*r,2*n),Ob(e,2*r+1,2*n+1);}function Ob(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Fb(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}t.$=45,t.A=np,t.B=function(e){const r=t.m.identity(new Float64Array(16));t.m.multiply(r,e.pixelMatrix,e.globeMatrix);const n=[0,dh,0],i=[0,mh,0];return t.v.transformMat4(n,n,r),t.v.transformMat4(i,i,r),[n[0]>0&&n[0]<=e.width&&n[1]>0&&n[1]<=e.height&&!jh(e,new Zh(e.center.lat,90)),i[0]>0&&i[0]<=e.width&&i[1]>0&&i[1]<=e.height&&!jh(e,new Zh(e.center.lat,-90))]},t.C=Re,t.D=vl,t.E=Hh,t.F=ah,t.G=uh,t.H=Jh,t.I=Cg,t.J=Cr,t.K=function(e,r){const{scale:n}=e.tileTransform,i=n*Cr/(e.tileSize*Math.pow(2,r.zoom-e.tileID.overscaledZ+e.tileID.canonical.z));return t.h.scale(new Float32Array(4),r.inverseAdjustmentMatrix,[i,i])},t.L=Zh,t.M=lp,t.N=ex,t.O=Hc,t.P=x,t.Q=Qg,t.R=th,t.S=function(e){const r=Qg(e,!0);return t.h.invert([],[r[0],r[1],r[4],r[5]])},t.T=eh,t.U=Wc,t.V=function(t){const{x:e,y:r}=t.point,{lng:n,lat:i}=t._center;return Vh(e,r,t.worldSize,n,i)},t.W=Am,t.X=q,t.Y=w,t.Z=lh,t._=function(t){const e=Math.round((t+45+360)%360/90)%4;return M[e]},t.a=Og,t.a$=Ko,t.a0=Wh,t.a1=function(t,e){return ft(B(t,{type:\"json\"}),e)},t.a2=ct,t.a3=vt,t.a4=Wt,t.a5=Qp,t.a6=ee,t.a7=te,t.a8=Qt,t.a9=_g,t.aA=zp,t.aB=cp,t.aC=ch,t.aD=Xv,t.aE=Ra,t.aF=Kv,t.aG=function(t){ut++,ut>nt&&(t.getActor().send(\"enforceCacheSizeLimit\",rt),ut=0);},t.aH=Dt,t.aI=Kt,t.aJ=function(t){return t<=1?1:Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},t.aK=Bv,t.aL=function(t,e){const r=document.createElement(\"video\");r.muted=!0,r.onloadstart=function(){e(null,r);};for(let e=0;e{}}},t.aM=ne,t.aN=wg,t.aO=function(t){return fetch(t).then((t=>t.arrayBuffer())).then((e=>_b(e,0,t)))},t.aP=zb,t.aQ=class{constructor(t,e,r,n){this.id=t,this.position=null!=e?new Zh(e[0],e[1]):new Zh(0,0),this.orientation=null!=r?r:[0,0,0],this.nodes=n,this.uploaded=!1,this.aabb=new oh([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),this.matrix=[];}_applyTransformations(e,r){if(t.m.multiply(e.matrix,r,e.matrix),e.meshes)for(const t of e.meshes){const r=oh.applyTransform(t.aabb,e.matrix);this.aabb.encapsulate(r);}if(e.children)for(const t of e.children)this._applyTransformations(t,e.matrix);}computeBoundsAndApplyParent(){const e=t.m.identity([]);for(const t of this.nodes)this._applyTransformations(t,e);}_positionModelOnTerrain(e,r){const n=e.elevation;if(!n)return 0;const i=oh.projectAabbCorners(this.aabb,this.matrix),s=Qh(1,this.position.lat)*e.worldSize,a=function(e,r){const n=[0,0,1],i=[{corners:[0,1,3,2],dotProductWithUp:0},{corners:[1,5,2,6],dotProductWithUp:0},{corners:[0,4,1,5],dotProductWithUp:0},{corners:[2,6,3,7],dotProductWithUp:0},{corners:[4,7,5,6],dotProductWithUp:0},{corners:[0,3,4,7],dotProductWithUp:0}];for(const s of i){const i=e[s.corners[0]],a=e[s.corners[1]],o=e[s.corners[2]],l=[a[0]-i[0],a[1]-i[1],r*(a[2]-i[2])],u=t.v.cross(l,l,[o[0]-i[0],o[1]-i[1],r*(o[2]-i[2])]);t.v.normalize(u,u),s.dotProductWithUp=t.v.dot(u,n);}return i.sort(((t,e)=>t.dotProductWithUp-e.dotProductWithUp)),i[0].corners}(i,s),o=i[a[0]],l=i[a[1]],u=i[a[2]],c=i[a[3]],h=n.getAtPointOrZero(new lp(o[0]/e.worldSize,o[1]/e.worldSize),0),p=n.getAtPointOrZero(new lp(l[0]/e.worldSize,l[1]/e.worldSize),0),f=n.getAtPointOrZero(new lp(u[0]/e.worldSize,u[1]/e.worldSize),0),d=n.getAtPointOrZero(new lp(c[0]/e.worldSize,c[1]/e.worldSize),0),m=(h+d)/2,y=(p+f)/2;return m>y?pNs(Es(t)),t.ai=$s,t.aj=Fs,t.ak=B,t.al=_a,t.am=Wi,t.an=T,t.ao=Oh,t.ap=t=>Ns(Cs(t)),t.aq=An,t.ar=Pa,t.as=class{constructor(t){this.specification=t;}possiblyEvaluate(t,e){return function([t,e]){const r=Z([1,t,e]);return {x:r.x,y:r.y,z:r.z}}(t.expression.evaluate(e))}interpolate(t,e,r){return {x:Mn(t.x,e.x,r),y:Mn(t.y,e.y,r),z:Mn(t.z,e.z,r)}}},t.at=function(t,e,r=0,n=!0){const i=new x(r,r),s=t.sub(i),a=e.add(i),o=[s,new x(a.x,s.y),a,new x(s.x,a.y)];return n&&o.push(s.clone()),o},t.au=function(t,e){const r=[];for(let n=0;n0?Math.acos(r/n)*b:0;let s=0!==t||0!==e?Math.atan2(-e,-t)*b+90:0;return s<0&&(s+=360),[n,s,i]},t.b4=Rg,t.b5=Ug,t.b6=Vg,t.b7=Jo,t.b8=class extends Xo{constructor(t){super(t),this.current=nl;}set(t,e,r){if(this.fetchUniformLocation(t,e))for(let t=0;t<9;t++)if(r[t]!==this.current[t]){this.current=r,this.gl.uniformMatrix3fv(this.location,!1,r);break}}},t.b9=Qo,t.bA=function(e,r){const n=[0,0,0],i=Dh(_h(r.canonical));return t.v.transformMat4(n,n,i),t.v.transformMat4(n,n,e),n},t.bB=t=>({u_camera_to_center_distance:new Wo(t),u_extrude_scale:new sl(t),u_device_pixel_ratio:new Wo(t),u_matrix:new rl(t),u_inv_rot_matrix:new rl(t),u_merc_center:new Ho(t),u_tile_id:new Jo(t),u_zoom_transition:new Wo(t),u_up_dir:new Jo(t),u_emissive_strength:new Wo(t)}),t.bC=t=>({u_matrix:new rl(t),u_pixels_to_tile_units:new sl(t),u_device_pixel_ratio:new Wo(t),u_units_to_pixels:new Ho(t),u_dash_image:new Ko(t),u_gradient_image:new Ko(t),u_image_height:new Wo(t),u_texsize:new Ho(t),u_tile_units_to_pixels:new Wo(t),u_alpha_discard_threshold:new Wo(t),u_trim_offset:new Ho(t),u_emissive_strength:new Wo(t)}),t.bD=t=>({u_matrix:new rl(t),u_texsize:new Ho(t),u_pixels_to_tile_units:new sl(t),u_device_pixel_ratio:new Wo(t),u_image:new Ko(t),u_units_to_pixels:new Ho(t),u_tile_units_to_pixels:new Wo(t),u_alpha_discard_threshold:new Wo(t)}),t.bE=io,t.bF=lm,t.bG=dm,t.bH=Np,t.bI=(t,e,r,n,i,s)=>{const a=t.transform,o=\"globe\"===a.projection.name;let l;if(\"map\"===s.paint.get(\"circle-pitch-alignment\"))if(o){const t=Lh(a.zoom,e.canonical)*a._pixelsPerMercatorPixel;l=Float32Array.from([t,0,0,t]);}else l=a.calculatePixelsToTileUnitsMatrix(r);else l=new Float32Array([a.pixelsToGLUnits[0],0,0,a.pixelsToGLUnits[1]]);const u={u_camera_to_center_distance:t.transform.getCameraToCenterDistance(a.projection),u_matrix:t.translatePosMatrix(e.projMatrix,r,s.paint.get(\"circle-translate\"),s.paint.get(\"circle-translate-anchor\")),u_device_pixel_ratio:Wt.devicePixelRatio,u_extrude_scale:l,u_inv_rot_matrix:Up,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:s.paint.get(\"circle-emissive-strength\")};if(o){u.u_inv_rot_matrix=n,u.u_merc_center=i,u.u_tile_id=[e.canonical.x,e.canonical.y,1<{const s=t.transform;return {u_matrix:bv(t,e,r,n),u_texsize:e.imageAtlasTexture?e.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:s.calculatePixelsToTileUnitsMatrix(e),u_device_pixel_ratio:i,u_image:0,u_tile_units_to_pixels:vv(e,s),u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]],u_alpha_discard_threshold:0}},t.bL=(t,e,r,n,i,s,a)=>{const o=t.transform,l=o.calculatePixelsToTileUnitsMatrix(e);return {u_matrix:bv(t,e,r,n),u_pixels_to_tile_units:l,u_device_pixel_ratio:s,u_units_to_pixels:[1/o.pixelsToGLUnits[0],1/o.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:i,u_texsize:wv(r)&&e.lineAtlasTexture?e.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:vv(e,t.transform),u_alpha_discard_threshold:0,u_trim_offset:a,u_emissive_strength:r.paint.get(\"line-emissive-strength\")}},t.bM=L,t.bN=nf,t.bO=lv,t.bP=Qc,t.bQ=tv,t.bR=$x,t.bS=450,t.bT=7,t.bU=Mh,t.bV=Ch,t.bW=Ua,t.bX=mo,t.bY=co,t.bZ=1,t.b_=771,t.ba=A,t.bb=function(t,e,r){const n=Oh(r.zoom),i=t.style.map._antialias,s=e.options.extStandardDerivativesForceOff||t.terrain&&t.terrain.exaggeration()>0;return 0===n&&!i&&!s},t.bc=function(e){const r=e.pixelsPerMeter,n=r/Qh(1,e.center.lat),i=t.m.identity(new Float64Array(16));return t.m.translate(i,i,[e.point.x,e.point.y,0]),t.m.scale(i,i,[n,n,r]),Float32Array.from(i)},t.bd=se,t.be=Ih,t.bf=function(t){const e=np-5;t=k(t,-e,e)/e*90;const r=Math.pow(Math.abs(Math.sin(_(t))),3);return Math.round(r*(fh.length-1))},t.bg=function(e,r,n,i){const s=r.getNorth(),a=r.getSouth(),o=r.getWest(),l=r.getEast(),u=1<0){const e=180/i;t.bx.multiply(d,d,[e/c+1,0,0,0,e/h+1,0,-.5*e/p,.5*e/f,1]);}return d[2]=u,d[5]=e.x,d[8]=e.y,d},t.bh=Dh,t.bi=_h,t.bj=function(e,r,n){const i=t.m.identity(new Float64Array(16)),s=(r/(1<1)return !1;const r=e.getSource().maxzoom,n=1<1)return e;const i=n.getSource().maxzoom,s=1<{const a=this.getAtTileOffset(e,s.x,s.y),o=i.upVector(e.canonical,s.x,s.y),l=i.upVectorScale(e.canonical,r,n).metersToTile;return t.v.scale(o,o,a*l),o}}getForTilePoints(t,e,r,n){if(this.isUsingMockSource())return !1;const i=Wd.create(this,t,n);return !!i&&(e.forEach((t=>{t[2]=this.exaggeration()*i.getElevationAt(t[0],t[1],r);})),!0)}getMinMaxForTile(t){if(this.isUsingMockSource())return null;const e=this.findDEMTileFor(t);if(!e||!e.dem)return null;const r=e.dem.tree,n=e.tileID,i=1<Ns(Ds(t)),t.cC=ga,t.cD=ft,t.cE=S,t.cF=function(){return !!document.fullscreenElement||!!document.webkitFullscreenElement},t.cG=I,t.cH=ap,t.cI=Ph,t.cJ=function([t,e,r]){const n=Math.hypot(t,e,r),i=Math.atan2(t,r),s=.5*Math.PI-Math.acos(-e/n);return new Zh(w(i),w(s))},t.cK=tp,t.cL=qh,t.cM=n,t.cN=jh,t.cO=Fh,t.cP=function(e){const r=[0,0,0],n=t.m.identity(new Float64Array(16));return t.m.multiply(n,e.pixelMatrix,e.globeMatrix),t.v.transformMat4(r,r,n),new x(r[0],r[1])},t.cQ=function(t){const e=t.navigator?t.navigator.userAgent:null;return !!function(t){if(null==W){const e=t.navigator?t.navigator.userAgent:null;W=!!t.safari||!(!e||!(/\\b(iPad|iPhone|iPod)\\b/.test(e)||e.match(\"Safari\")&&!e.match(\"Chrome\")));}return W}(t)&&e&&(e.match(\"Version/15.4\")||e.match(\"Version/15.5\")||e.match(/CPU (OS|iPhone OS) (15_4|15_5) like Mac OS X/))},t.cR=C,t.cS=class{constructor(t,e,r){this._transformRequestFn=t,this._customAccessToken=e,this._silenceAuthErrors=!!r,this._createSkuToken();}_createSkuToken(){const t=function(){let t=\"\";for(let e=0;e<10;e++)t+=\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"[Math.floor(62*Math.random())];return {token:[\"1\",h,t].join(\"\"),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=t.token,this._skuTokenExpiresAt=t.tokenExpiresAt;}_isSkuTokenExpired(){return Date.now()>this._skuTokenExpiresAt}transformRequest(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}}normalizeStyleURL(t,r){if(!_t(t))return t;const n=kt(t);return n.params.push(`sdk=js-${e}`),n.path=`/styles/v1${n.path}`,this._makeAPIURL(n,this._customAccessToken||r)}normalizeGlyphsURL(t,e){if(!_t(t))return t;const r=kt(t);return r.path=`/fonts/v1${r.path}`,this._makeAPIURL(r,this._customAccessToken||e)}normalizeModelURL(t,e){if(!_t(t))return t;const r=kt(t);return r.path=`/models/v1${r.path}`,this._makeAPIURL(r,this._customAccessToken||e)}normalizeSourceURL(t,e,r,n){if(!_t(t))return t;const i=kt(t);return i.path=`/v4/${i.authority}.json`,i.params.push(\"secure\"),r&&i.params.push(`language=${r}`),n&&i.params.push(`worldview=${n}`),this._makeAPIURL(i,this._customAccessToken||e)}normalizeSpriteURL(t,e,r,n){const i=kt(t);return _t(t)?(i.path=`/styles/v1${i.path}/sprite${e}${r}`,this._makeAPIURL(i,this._customAccessToken||n)):(i.path+=`${e}${r}`,Tt(i))}normalizeTileURL(t,e,r){if(this._isSkuTokenExpired()&&this._createSkuToken(),t&&!_t(t))return t;const s=kt(t);s.path=s.path.replace(/(\\.(png|jpg)\\d*)(?=$)/,`${e||r&&\"raster\"!==s.authority&&512===r?\"@2x\":\"\"}${i.supported?\".webp\":\"$1\"}`),\"raster\"===s.authority?s.path=`/${n.RASTER_URL_PREFIX}${s.path}`:(s.path=s.path.replace(/^.+\\/v4\\//,\"/\"),s.path=`/${n.TILE_URL_VERSION}${s.path}`);const a=this._customAccessToken||function(t){for(const e of t){const t=e.match(/^access_token=(.*)$/);if(t)return t[1]}return null}(s.params)||n.ACCESS_TOKEN;return n.REQUIRE_ACCESS_TOKEN&&a&&this._skuToken&&s.params.push(`sku=${this._skuToken}`),this._makeAPIURL(s,a)}canonicalizeTileURL(t,e){const r=kt(t);if(!r.path.match(/^(\\/v4\\/|\\/raster\\/v1\\/)/)||!r.path.match(/\\.[\\w]+$/))return t;let i=\"mapbox://\";r.path.match(/^\\/raster\\/v1\\//)?i+=`raster/${r.path.replace(`/${n.RASTER_URL_PREFIX}/`,\"\")}`:i+=`tiles/${r.path.replace(`/${n.TILE_URL_VERSION}/`,\"\")}`;let s=r.params;return e&&(s=s.filter((t=>!t.match(/^access_token=/)))),s.length&&(i+=`?${s.join(\"&\")}`),i}canonicalizeTileset(t,e){const r=!!e&&_t(e),n=[];for(const e of t.tiles||[])wt(e)?n.push(this.canonicalizeTileURL(e,r)):n.push(e);return n}_makeAPIURL(t,e){const r=\"See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes\",i=kt(n.API_URL);if(t.protocol=i.protocol,t.authority=i.authority,\"http\"===t.protocol){const e=t.params.indexOf(\"secure\");e>=0&&t.params.splice(e,1);}if(\"/\"!==i.path&&(t.path=`${i.path}${t.path}`),!n.REQUIRE_ACCESS_TOKEN)return Tt(t);if(e=e||n.ACCESS_TOKEN,!this._silenceAuthErrors){if(!e)throw new Error(`An API access token is required to use Mapbox GL. ${r}`);if(\"s\"===e[0])throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${r}`)}return t.params=t.params.filter((t=>-1===t.indexOf(\"access_token\"))),t.params.push(`access_token=${e||\"\"}`),Tt(t)}},t.cT=function(t,e){e?jt.add(t):jt.delete(t);},t.cU=i,t.cV=Vt,t.cW=Ft,t.cX=bt,t.cY=Rt,t.cZ=function(t){jt.delete(t);},t.c_=z,t.ca=class{constructor(){this._updateTime=0,this._sourceIds=[],this._activeRegions=[],this._prevRegions=[];}clear(){this._activeRegions.length>0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[];}get updateTime(){return this._updateTime}getReplacementRegionsForTile(t){const e=Dx(new x(0,0),new x(Cr,Cr),t),r=[];for(const n of this._activeRegions){if(n.hiddenByOverlap)continue;if(!Bx(e,n))continue;const i=Cx(n.min,n.max,t);r.push({min:i.min,max:i.max,sourceId:this._sourceIds[n.priority],footprint:n.footprint,footprintTileId:n.tileId});}return r}setSources(t){this._setSources(t.map((t=>({getSourceId:()=>t.cache.id,getFootprints:()=>{const e=[];for(const r of t.cache.getVisibleCoordinates()){const n=t.cache.getTile(r).buckets[t.layer];if(n)for(const t of n.getNodesInfo()){const n=t.node;n.footprint&&e.push({footprint:n.footprint,id:r.toUnwrapped()});}}return e}}))));}_addSource(t){const e=t.getFootprints();if(0!==e.length){for(const t of e){if(!t.footprint)continue;const e=Dx(t.footprint.min,t.footprint.max,t.id);this._activeRegions.push({min:e.min,max:e.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:t.id,footprint:t.footprint});}this._sourceIds.push(t.getSourceId());}}_computeReplacement(){this._activeRegions.sort(((t,e)=>t.priority-e.priority||zx(t.min,e.min)||zx(t.max,e.max)));let t=this._activeRegions.length!==this._prevRegions.length;if(!t){let e=0,r=0;for(;!t&&e!==this._activeRegions.length;){const n=this._activeRegions[e],i=this._prevRegions[r];t=n.priority!==i.priority||!Ex(n,i),++e,++r;}}if(t){++this._updateTime;const t=t=>{const e=this._activeRegions;if(t>=e.length)return t;const r=e[t].priority;for(;t1){let e=0,r=t(e);for(;e!==r;){let n=e;const i=e;for(;n!==r;){const t=this._activeRegions[n];t.hiddenByOverlap=!1;for(let e=0;e=0;e--)this._addSource(t[e]);this._computeReplacement();}},t.cb=Ga,t.cc=zg,t.cd=fo,t.ce=class{constructor(t){this._createGrid(t),this._createPoles(t);}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const t of this._poleSegments)t.destroy();for(const t of this._gridSegments)t.withSkirts.destroy(),t.withoutSkirts.destroy();}_fillGridMeshWithLods(t,e){const r=new $a,n=new ao,i=[],s=t+1+2,a=e[0]+1,o=e[0]+1+(1+e.length),l=(t,e,r)=>{let n=t===s-1?t-2:0===t?t:t-1;return n+=r?24575:0,[n,e]};for(let t=0;t=0?t.slice(0,e):t},t.cr=t=>Ns(zs(t)),t.cs=t=>Ns(Ts(t)),t.ct=t=>Ns(Bs(t)),t.cu=function(t){return t.indexOf(Ca)>=0},t.cv=function(t){const e=t.indexOf(Ca);return e>=0?t.slice(e+1):\"\"},t.cw=Xi,t.cx=function(t){const e=[],r=t.id;return void 0===r&&e.push({message:`layers.${r}: missing required property \"id\"`}),void 0===t.render&&e.push({message:`layers.${r}: missing required method \"render\"`}),t.renderingMode&&\"2d\"!==t.renderingMode&&\"3d\"!==t.renderingMode&&e.push({message:`layers.${r}: property \"renderingMode\" must be either \"2d\" or \"3d\"`}),e},t.cy=t=>Ns(Ss(t)),t.cz=t=>Ns(bs(t)),t.d=_,t.d0=function(t,e){rt=t,nt=e;},t.d1=function(t,e,r=!1){if(fa===ua||fa===ca||fa===ha)throw new Error(\"setRTLTextPlugin cannot be called multiple times.\");da=Wt.resolveURL(t),fa=ua,pa=e,ya(),r||va();},t.d2=xa,t.d3=function(){eb().acquire(Jv);},t.d4=function(){const t=tb;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(Jv),tb=null):console.warn(\"Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()\"));},t.d5=Qv,t.d6=function(t){const e=at();if(!e)return;const r=e.delete(et);t&&r.catch(t).then((()=>t()));},t.d7=Wv,t.d8=ab,t.d9=function(t){nb=Wt.resolveURL(t),sb||(sb=new Nv(eb(),new ee)),sb.broadcast(\"setDracoUrl\",nb);},t.da=E,t.db=Kd,t.dc=p,t.dd=ud,t.de=Wf,t.df=y,t.dg=fd,t.dh=class extends ee{constructor(t,e,r,n,i,s){super(),this.actor=t,this.layerIndex=e,this.availableImages=r,this.loadVectorData=i||Kv,this.loading={},this.loaded={},this.deduped=new Xv(t.scheduler),this.isSpriteLoaded=n,this.scheduler=t.scheduler,this.brightness=s;}loadTile(t,e){const r=t.uid,n=t&&t.request,i=n&&n.collectResourceTiming,s=this.loading[r]=new Yv(t);s.abort=this.loadVectorData(t,((a,o)=>{const l=!this.loading[r];if(delete this.loading[r],l||a||!o)return s.status=\"done\",l||(this.loaded[r]=s),e(a);const u=o.rawData,c={};o.expires&&(c.expires=o.expires),o.cacheControl&&(c.cacheControl=o.cacheControl),s.vectorTile=o.vectorTile||new ld(new Cd(u));const h=()=>{s.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,((t,r)=>{if(t||!r)return e(t);const s={};if(i){const t=$t(n);t.length>0&&(s.resourceTiming=JSON.parse(JSON.stringify(t)));}e(null,B({rawTileData:u.slice(0)},r,c,s));}));};this.isSpriteLoaded?h():this.once(\"isSpriteLoaded\",(()=>{this.scheduler?this.scheduler.add(h,{type:\"parseTile\",isSymbolTile:t.isSymbolTile,zoom:t.tileZoom}):h();})),this.loaded=this.loaded||{},this.loaded[r]=s;}));}reloadTile(t,e){const r=this.loaded,n=t.uid,i=this;if(r&&r[n]){const s=r[n];s.showCollisionBoxes=t.showCollisionBoxes,s.projection=t.projection,s.brightness=t.brightness,s.tileTransform=zy(t.tileID.canonical,t.projection),s.extraShadowCaster=t.extraShadowCaster;const a=(t,r)=>{const n=s.reloadCallback;n&&(delete s.reloadCallback,s.parse(s.vectorTile,i.layerIndex,this.availableImages,i.actor,n)),e(t,r);};\"parsing\"===s.status?s.reloadCallback=a:\"done\"===s.status&&(s.vectorTile?s.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,a):a());}else e(null,void 0);}abortTile(t,e){const r=t.uid,n=this.loading[r];n&&(n.abort&&n.abort(),delete this.loading[r]),e();}removeTile(t,e){const r=this.loaded,n=t.uid;r&&r[n]&&delete r[n],e();}},t.di=$t,t.dj=dt,t.dk=Hd,t.dl=function(t){let e=0;if(new Uint32Array(t,0,1)[0]!==mb){const r=new Uint32Array(t,0,7),[,,n,i,s,a]=r;e=r.byteLength+i+s+a+s,(n!==t.byteLength||e>=t.byteLength)&&q(\"Invalid b3dm header information.\");}return _b(t,e)},t.dm=function(t,e){const r=zb(t);for(const t of r){for(const e of t.meshes)Eb(e);t.lights&&(t.lightMeshIndex=t.meshes.length,t.meshes.push(Bb(t.lights,e)));}return r},t.dn=Ix,t.dp=Uv,t.dq=ba,t.dr=function(t){ot(),it&&it.then((e=>{e.keys().then((r=>{for(let n=0;ns&&(n+=(t[i]-s)*(t[i]-s)),e[i]this._layers[e.id])),r=t[0];if(\"none\"===r.visibility)continue;const o=r.source||\"\";let i=this.familiesBySource[o];i||(i=this.familiesBySource[o]={});const s=r.sourceLayer||\"_geojsonTileLayer\";let n=i[s];n||(n=i[s]=[]),n.push(t);}}}class i{loadTile(t,r){const{uid:o,encoding:i,rawImageData:s,padding:n}=t,a=ImageBitmap&&s instanceof ImageBitmap?this.getImageData(s,n):s;r(null,new e.db(o,a,i,n<1));}getImageData(e,t){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(e.width,e.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext(\"2d\",{willReadFrequently:!0})),this.offscreenCanvas.width=e.width,this.offscreenCanvas.height=e.height,this.offscreenCanvasContext.drawImage(e,0,0,e.width,e.height);const r=this.offscreenCanvasContext.getImageData(-t,-t,e.width+2*t,e.height+2*t);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),r}}function s(e,t){if(0!==e.length){n(e[0],t);for(var r=1;r=Math.abs(a)?r-l+a:a-l+r,r=l;}r+o>=0!=!!t&&e.reverse();}var a=e.dc((function e(t,r){var o,i=t&&t.type;if(\"FeatureCollection\"===i)for(o=0;o>31}function b(e,t){for(var r=e.loadGeometry(),o=e.type,i=0,s=0,n=r.length,a=0;ae},_=Math.fround||(L=new Float32Array(1),e=>(L[0]=+e,L[0]));var L;const T=3,C=5,O=6;class j{constructor(e){this.options=Object.assign(Object.create(P),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:r,maxZoom:o}=this.options;t&&console.time(\"total time\");const i=`prepare ${e.length} points`;t&&console.time(i),this.points=e;const s=[];for(let t=0;t=r;e--){const r=+Date.now();n=this.trees[e]=this._createTree(this._cluster(n,e)),t&&console.log(\"z%d: %d clusters in %dms\",e,n.numItems,+Date.now()-r);}return t&&console.timeEnd(\"total time\"),this}getClusters(e,t){let r=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let i=180===e[2]?180:((e[2]+180)%360+360)%360-180;const s=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,i=180;else if(r>i){const e=this.getClusters([r,o,180,s],t),n=this.getClusters([-180,o,i,s],t);return e.concat(n)}const n=this.trees[this._limitZoom(t)],a=n.range(z(r),D(s),z(i),D(o)),l=n.data,h=[];for(const e of a){const t=this.stride*e;h.push(l[t+C]>1?Z(l,t,this.clusterProps):this.points[l[t+T]]);}return h}getChildren(e){const t=this._getOriginId(e),r=this._getOriginZoom(e),o=\"No cluster with the specified id.\",i=this.trees[r];if(!i)throw new Error(o);const s=i.data;if(t*this.stride>=s.length)throw new Error(o);const n=this.options.radius/(this.options.extent*Math.pow(2,r-1)),a=i.within(s[t*this.stride],s[t*this.stride+1],n),l=[];for(const t of a){const r=t*this.stride;s[r+4]===e&&l.push(s[r+C]>1?Z(s,r,this.clusterProps):this.points[s[r+T]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,r){const o=[];return this._appendLeaves(o,e,t=t||10,r=r||0,0),o}getTile(e,t,r){const o=this.trees[this._limitZoom(e)],i=Math.pow(2,e),{extent:s,radius:n}=this.options,a=n/s,l=(r-a)/i,h=(r+1+a)/i,u={features:[]};return this._addTileFeatures(o.range((t-a)/i,l,(t+1+a)/i,h),o.data,t,r,i,u),0===t&&this._addTileFeatures(o.range(1-a/i,l,1,h),o.data,i,r,i,u),t===i-1&&this._addTileFeatures(o.range(0,l,a/i,h),o.data,-1,r,i,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const r=this.getChildren(e);if(t++,1!==r.length)break;e=r[0].properties.cluster_id;}return t}_appendLeaves(e,t,r,o,i){const s=this.getChildren(t);for(const t of s){const s=t.properties;if(s&&s.cluster?i+s.point_count<=o?i+=s.point_count:i=this._appendLeaves(e,s.cluster_id,r,o,i):i1;let l,h,u;if(a)l=F(t,e,this.clusterProps),h=t[e],u=t[e+1];else {const r=this.points[t[e+T]];l=r.properties;const[o,i]=r.geometry.coordinates;h=z(o),u=D(i);}const c={type:1,geometry:[[Math.round(this.options.extent*(h*i-r)),Math.round(this.options.extent*(u*i-o))]],tags:l};let d;d=a||this.options.generateId?t[e+T]:this.points[t[e+T]].id,void 0!==d&&(c.id=d),s.features.push(c);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:r,extent:o,reduce:i,minPoints:s}=this.options,n=r/(o*Math.pow(2,t)),a=e.data,l=[],h=this.stride;for(let r=0;rt&&(f+=a[r+C]);}if(f>d&&f>=s){let e,s=o*d,n=u*d,p=-1;const g=((r/h|0)<<5)+(t+1)+this.points.length;for(const o of c){const l=o*h;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+C];s+=a[l]*u,n+=a[l+1]*u,a[l+4]=g,i&&(e||(e=this._map(a,r,!0),p=this.clusterProps.length,this.clusterProps.push(e)),i(e,this._map(a,l)));}a[r+4]=g,l.push(s/f,n/f,1/0,g,-1,f),i&&l.push(p);}else {for(let e=0;e1)for(const e of c){const r=e*h;if(!(a[r+2]<=t)){a[r+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,r){if(e[t+C]>1){const o=this.clusterProps[e[t+O]];return r?Object.assign({},o):o}const o=this.points[e[t+T]].properties,i=this.options.map(o);return r&&i===o?Object.assign({},i):i}}function Z(e,t,r){return {type:\"Feature\",id:e[t+T],properties:F(e,t,r),geometry:{type:\"Point\",coordinates:[(o=e[t],360*(o-.5)),E(e[t+1])]}};var o;}function F(e,t,r){const o=e[t+C],i=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+\"k\":o,s=e[t+O],n=-1===s?{}:Object.assign({},r[s]);return Object.assign(n,{cluster:!0,cluster_id:e[t+T],point_count:o,point_count_abbreviated:i})}function z(e){return e/360+.5}function D(e){const t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function E(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}var J={exports:{}};J.exports=function(){function e(r,o,i,s){for(var n,a=s,l=i-o>>1,h=i-o,u=r[o],c=r[o+1],d=r[i],f=r[i+1],p=o+3;pa)n=p,a=g;else if(g===a){var m=Math.abs(p-l);ms&&(n-o>3&&e(r,o,n,s),r[n+2]=a,i-n>3&&e(r,n,i,s));}function t(e,t,r,o,i,s){var n=i-r,a=s-o;if(0!==n||0!==a){var l=((e-r)*n+(t-o)*a)/(n*n+a*a);l>1?(r=i,o=s):l>0&&(r+=n*l,o+=a*l);}return (n=e-r)*n+(a=t-o)*a}function r(e,t,r,i){var s={id:void 0===e?null:e,type:t,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,r=e.type;if(\"Point\"===r||\"MultiPoint\"===r||\"LineString\"===r)o(e,t);else if(\"Polygon\"===r||\"MultiLineString\"===r)for(var i=0;i0&&(a+=i?(s*d-c*n)/2:Math.sqrt(Math.pow(c-s,2)+Math.pow(d-n,2))),s=c,n=d;}var f=r.length-3;r[2]=1,e(r,0,f,o),r[f+2]=1,r.size=Math.abs(a),r.start=0,r.end=r.size;}function a(e,t,r,o){for(var i=0;i1?1:r}function u(e,t,o,i,s,n,a,l){if(i/=t,n>=(o/=t)&&a=i)return null;for(var h=[],u=0;u=o&&v=i)){var w=[];if(\"Point\"===m||\"MultiPoint\"===m)c(g,w,o,i,s);else if(\"LineString\"===m)d(g,w,o,i,s,!1,l.lineMetrics);else if(\"MultiLineString\"===m)p(g,w,o,i,s,!1);else if(\"Polygon\"===m)p(g,w,o,i,s,!0);else if(\"MultiPolygon\"===m)for(var x=0;x=r&&n<=o&&(t.push(e[s]),t.push(e[s+1]),t.push(e[s+2]));}}function d(e,t,r,o,i,s,n){for(var a,l,h=f(e),u=0===i?m:y,c=e.start,d=0;dr&&(l=u(h,p,v,x,S,r),n&&(h.start=c+a*l)):M>o?b=r&&(l=u(h,p,v,x,S,r),I=!0),b>o&&M<=o&&(l=u(h,p,v,x,S,o),I=!0),!s&&I&&(n&&(h.end=c+a*l),t.push(h),h=f(e)),n&&(c+=a);}var k=e.length-3;p=e[k],v=e[k+1],w=e[k+2],(M=0===i?p:v)>=r&&M<=o&&g(h,p,v,w),k=h.length-3,s&&k>=3&&(h[k]!==h[0]||h[k+1]!==h[1])&&g(h,h[0],h[1],h[2]),h.length&&t.push(h);}function f(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function p(e,t,r,o,i,s){for(var n=0;nn.maxX&&(n.maxX=u),c>n.maxY&&(n.maxY=c);}return n}function b(e,t,r,o){var i=t.geometry,s=t.type,n=[];if(\"Point\"===s||\"MultiPoint\"===s)for(var a=0;a0&&t.size<(i?n:o))r.numPoints+=t.length/3;else {for(var a=[],l=0;ln)&&(r.numSimplified++,a.push(t[l]),a.push(t[l+1])),r.numPoints++;i&&function(e,t){for(var r=0,o=0,i=e.length,s=i-2;o0===t)for(o=0,i=e.length;o24)throw new Error(\"maxZoom should be in the 0-24 range\");if(t.promoteId&&t.generateId)throw new Error(\"promoteId and generateId cannot be used together.\");var o=function(e,t){var r=[];if(\"FeatureCollection\"===e.type)for(var o=0;o1&&console.time(\"creation\"),f=this.tiles[d]=M(e,t,r,o,l),this.tileCoords.push({z:t,x:r,y:o}),h)){h>1&&(console.log(\"tile z%d-%d-%d (features: %d, points: %d, simplified: %d)\",t,r,o,f.numFeatures,f.numPoints,f.numSimplified),console.timeEnd(\"creation\"));var p=\"z\"+t;this.stats[p]=(this.stats[p]||0)+1,this.total++;}if(f.source=e,i){if(t===l.maxZoom||t===i)continue;var g=1<1&&console.time(\"clipping\");var m,y,v,w,x,S,b=.5*l.buffer/l.extent,I=.5-b,k=.5+b,_=1+b;m=y=v=w=null,x=u(e,c,r-b,r+k,0,f.minX,f.maxX,l),S=u(e,c,r+I,r+_,0,f.minX,f.maxX,l),e=null,x&&(m=u(x,c,o-b,o+k,1,f.minY,f.maxY,l),y=u(x,c,o+I,o+_,1,f.minY,f.maxY,l),x=null),S&&(v=u(S,c,o-b,o+k,1,f.minY,f.maxY,l),w=u(S,c,o+I,o+_,1,f.minY,f.maxY,l),S=null),h>1&&console.timeEnd(\"clipping\"),a.push(m||[],t+1,2*r,2*o),a.push(y||[],t+1,2*r,2*o+1),a.push(v||[],t+1,2*r+1,2*o),a.push(w||[],t+1,2*r+1,2*o+1);}}},k.prototype.getTile=function(e,t,r){var o=this.options,i=o.extent,s=o.debug;if(e<0||e>24)return null;var n=1<1&&console.log(\"drilling down to z%d-%d-%d\",e,t,r);for(var l,h=e,u=t,c=r;!l&&h>0;)h--,u=Math.floor(u/2),c=Math.floor(c/2),l=this.tiles[P(h,u,c)];return l&&l.source?(s>1&&console.log(\"found parent tile z%d-%d-%d\",h,u,c),s>1&&console.time(\"drilling down\"),this.splitTile(l.source,h,u,c,e,t,r),s>1&&console.timeEnd(\"drilling down\"),this.tiles[a]?x(this.tiles[a],i):null):null},function(e,t){return new k(e,t)}}();var N=e.dc(J.exports);function Y(t,r){const o=t.tileID.canonical;if(!this._geoJSONIndex)return r(null,null);const i=this._geoJSONIndex.getTile(o.z,o.x,o.y);if(!i)return r(null,null);const s=new class{constructor(t){this.layers={_geojsonTileLayer:this},this.name=\"_geojsonTileLayer\",this.extent=e.J,this.length=t.length,this._features=t;}feature(t){return new class{constructor(t){this._feature=t,this.extent=e.J,this.type=t.type,this.properties=t.tags,\"id\"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));}loadGeometry(){if(1===this._feature.type){const t=[];for(const r of this._feature.geometry)t.push([new e.P(r[0],r[1])]);return t}{const t=[];for(const r of this._feature.geometry){const o=[];for(const t of r)o.push(new e.P(t[0],t[1]));t.push(o);}return t}}toGeoJSON(e,t,r){return l.call(this,e,t,r)}}(this._features[t])}}(i.features);let n=k(s);0===n.byteOffset&&n.byteLength===n.buffer.byteLength||(n=new Uint8Array(n)),r(null,{vectorTile:s,rawData:n.buffer});}class G extends e.dh{constructor(e,t,r,o,i,s){super(e,t,r,o,Y,s),i&&(this.loadGeoJSON=i);}loadData(t,r){const o=t&&t.request,i=o&&o.collectResourceTiming;this.loadGeoJSON(t,((s,n)=>{if(s||!n)return r(s);if(\"object\"!=typeof n)return r(new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`));{a(n,!0);try{if(t.filter){const r=e.cw(t.filter,{type:\"boolean\",\"property-type\":\"data-driven\",overridable:!1,transition:!1});if(\"error\"===r.result)throw new Error(r.value.map((e=>`${e.key}: ${e.message}`)).join(\", \"));const o=n.features.filter((e=>r.value.evaluate({zoom:0},e)));n={type:\"FeatureCollection\",features:o};}this._geoJSONIndex=t.cluster?new j(function({superclusterOptions:t,clusterProperties:r}){if(!r||!t)return t;const o={},i={},s={accumulated:null,zoom:0},n={properties:null},a=Object.keys(r);for(const t of a){const[s,n]=r[t],a=e.cw(n),l=e.cw(\"string\"==typeof s?[s,[\"accumulated\"],[\"get\",t]]:s);o[t]=a.value,i[t]=l.value;}return t.map=e=>{n.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(s,n);return t},t.reduce=(e,t)=>{n.properties=t;for(const t of a)s.accumulated=e[t],e[t]=i[t].evaluate(s,n);},t}(t)).load(n.features):N(n,t.geojsonVtOptions);}catch(s){return r(s)}this.loaded={};const l={};if(i){const r=e.di(o);r&&(l.resourceTiming={},l.resourceTiming[t.source]=JSON.parse(JSON.stringify(r)));}r(null,l);}}));}reloadTile(e,t){const r=this.loaded;return r&&r[e.uid]?super.reloadTile(e,t):this.loadTile(e,t)}loadGeoJSON(t,r){if(t.request)e.a1(t.request,r);else {if(\"string\"!=typeof t.data)return r(new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`));try{return r(null,JSON.parse(t.data))}catch(e){return r(new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`))}}}getClusterExpansionZoom(e,t){try{t(null,this._geoJSONIndex.getClusterExpansionZoom(e.clusterId));}catch(e){t(e);}}getClusterChildren(e,t){try{t(null,this._geoJSONIndex.getChildren(e.clusterId));}catch(e){t(e);}}getClusterLeaves(e,t){try{t(null,this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset));}catch(e){t(e);}}}class W{constructor(t,r){this.tileID=new e.O(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.tileZoom=t.tileZoom,this.uid=t.uid,this.zoom=t.zoom,this.canonical=t.tileID.canonical,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=t.projection,this.brightness=r;}parse(t,r,o,i){this.status=\"parsing\";const s=new e.O(o.tileID.overscaledZ,o.tileID.wrap,o.tileID.canonical.z,o.tileID.canonical.x,o.tileID.canonical.y),n={},a=r.familiesBySource[o.source],l=new e.dk(s,o.promoteId);return l.bucketLayerIDs=[],e.dl(t).then((t=>{if(!t)return i(new Error(\"Could not parse tile\"));const r=e.dm(t,1/e.cg(o.tileID.canonical)),h=t.json.extensionsUsed&&t.json.extensionsUsed.includes(\"MAPBOX_mesh_features\"),u=new e.al(this.zoom,{brightness:this.brightness});for(const o in a)for(const i of a[o]){const o=i[0],a=t.json.extensionsUsed;o.recalculate(u,[]);const l=new e.dn(r,s,a&&a.includes(\"MAPBOX_mesh_features\"),this.brightness);h||(l.needsUpload=!0),n[o.fqid]=l,l.evaluate(o);}this.status=\"done\",i(null,{buckets:n,featureIndex:l});})).catch((e=>i(new Error(e.message))))}}class X{constructor(e,t,r,o,i,s){this.actor=e,this.layerIndex=t,this.brightness=s,this.loading={},this.loaded={};}loadTile(t,r){const o=t.uid,i=this.loading[o]=new W(t,this.brightness);e.dj(t.request,((e,s)=>{const n=!this.loading[o];return delete this.loading[o],n||e?(i.status=\"done\",n||(this.loaded[o]=i),r(e)):s&&0!==s.byteLength?void i.parse(s,this.layerIndex,t,((e,t)=>{i.status=\"done\",this.loaded=this.loaded||{},this.loaded[o]=i,e||!t?r(e):r(null,t);})):(i.status=\"done\",this.loaded[o]=i,r())}));}reloadTile(e,t){const r=this.loaded,o=e.uid;if(r&&r[o]){const i=r[o];i.projection=e.projection,i.brightness=e.brightness;const s=(r,o)=>{i.reloadCallback&&(delete i.reloadCallback,this.loadTile(e,t)),t(r,o);};\"parsing\"===i.status?i.reloadCallback=s:\"done\"===i.status&&this.loadTile(e,t);}}abortTile(e,t){const r=e.uid;this.loading[r]&&delete this.loading[r],t();}removeTile(e,t){const r=this.loaded,o=e.uid;r&&r[o]&&delete r[o],t();}}class q{constructor(t){this.self=t,this.actor=new e.dp(t,this),this.layerIndexes={},this.availableImages={},this.isSpriteLoaded={},this.projections={},this.defaultProjection=e.o({name:\"mercator\"}),this.workerSourceTypes={vector:e.dh,geojson:G,\"batched-model\":X},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=(e,t)=>{if(this.workerSourceTypes[e])throw new Error(`Worker source with name \"${e}\" already registered.`);this.workerSourceTypes[e]=t;},this.self.registerRTLTextPlugin=t=>{if(e.dq.isParsed())throw new Error(\"RTL text plugin already registered.\");e.dq.applyArabicShaping=t.applyArabicShaping,e.dq.processBidirectionalText=t.processBidirectionalText,e.dq.processStyledBidirectionalText=t.processStyledBidirectionalText;};}clearCaches(e,t,r){delete this.layerIndexes[e],delete this.availableImages[e],delete this.workerSources[e],delete this.demWorkerSources[e],r();}checkIfReady(e,t,r){r();}setReferrer(e,t){this.referrer=t;}spriteLoaded(t,{scope:r,isLoaded:o}){if(this.isSpriteLoaded[t]||(this.isSpriteLoaded[t]={}),this.isSpriteLoaded[t][r]=o,this.workerSources[t]&&this.workerSources[t][r])for(const i in this.workerSources[t][r]){const s=this.workerSources[t][r][i];for(const t in s)s[t]instanceof e.dh&&(s[t].isSpriteLoaded=o,s[t].fire(new e.a8(\"isSpriteLoaded\")));}}setImages(e,{scope:t,images:r},o){if(this.availableImages[e]||(this.availableImages[e]={}),this.availableImages[e][t]=r,this.workerSources[e]&&this.workerSources[e][t]){for(const o in this.workerSources[e][t]){const i=this.workerSources[e][t][o];for(const e in i)i[e].availableImages=r;}o();}else o();}setProjection(t,r){this.projections[t]=e.o(r);}setBrightness(e,t,r){this.brightness=t,r();}setLayers(e,t,r){this.getLayerIndex(e,t.scope).replace(t.layers,t.options),r();}updateLayers(e,t,r){this.getLayerIndex(e,t.scope).update(t.layers,t.removedIds,t.options),r();}loadTile(e,t,r){t.projection=this.projections[e]||this.defaultProjection,this.getWorkerSource(e,t.type,t.source,t.scope).loadTile(t,r);}loadDEMTile(e,t,r){this.getDEMWorkerSource(e,t.source,t.scope).loadTile(t,r);}reloadTile(e,t,r){t.projection=this.projections[e]||this.defaultProjection,this.getWorkerSource(e,t.type,t.source,t.scope).reloadTile(t,r);}abortTile(e,t,r){this.getWorkerSource(e,t.type,t.source,t.scope).abortTile(t,r);}removeTile(e,t,r){this.getWorkerSource(e,t.type,t.source,t.scope).removeTile(t,r);}removeSource(e,t,r){if(!(this.workerSources[e]&&this.workerSources[e][t.scope]&&this.workerSources[e][t.scope][t.type]&&this.workerSources[e][t.scope][t.type][t.source]))return;const o=this.workerSources[e][t.scope][t.type][t.source];delete this.workerSources[e][t.scope][t.type][t.source],void 0!==o.removeSource?o.removeSource(t,r):r();}loadWorkerSource(e,t,r){try{this.self.importScripts(t.url),r();}catch(e){r(e.toString());}}syncRTLPluginState(t,r,o){try{e.dq.setState(r);const t=e.dq.getPluginURL();if(e.dq.isLoaded()&&!e.dq.isParsed()&&null!=t){this.self.importScripts(t);const r=e.dq.isParsed();o(r?void 0:new Error(`RTL Text Plugin failed to import scripts from ${t}`),r);}}catch(e){o(e.toString());}}setDracoUrl(e,t){this.dracoUrl=t;}getAvailableImages(e,t){this.availableImages[e]||(this.availableImages[e]={});let r=this.availableImages[e][t];return r||(r=[]),r}getLayerIndex(e,t){this.layerIndexes[e]||(this.layerIndexes[e]={});let r=this.layerIndexes[e][t];return r||(r=this.layerIndexes[e][t]=new o,r.scope=t),r}getWorkerSource(e,t,r,o){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][o]||(this.workerSources[e][o]={}),this.workerSources[e][o][t]||(this.workerSources[e][o][t]={}),this.isSpriteLoaded[e]||(this.isSpriteLoaded[e]={}),!this.workerSources[e][o][t][r]){const i={send:(t,r,o,i,s,n)=>{this.actor.send(t,r,o,e,s,n);},scheduler:this.actor.scheduler};this.workerSources[e][o][t][r]=new this.workerSourceTypes[t](i,this.getLayerIndex(e,o),this.getAvailableImages(e,o),this.isSpriteLoaded[e][o],void 0,this.brightness);}return this.workerSources[e][o][t][r]}getDEMWorkerSource(e,t,r){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][r]||(this.demWorkerSources[e][r]={}),this.demWorkerSources[e][r][t]||(this.demWorkerSources[e][r][t]=new i),this.demWorkerSources[e][r][t]}enforceCacheSizeLimit(t,r){e.dr(r);}getWorkerPerformanceMetrics(e,t,r){r(void 0,void 0);}}return \"undefined\"!=typeof WorkerGlobalScope&&\"undefined\"!=typeof self&&self instanceof WorkerGlobalScope&&(self.worker=new q(self)),q}));\n\ndefine([\"./shared\"],(function(e){\"use strict\";function t(e,i){if(Array.isArray(e)){if(!Array.isArray(i)||e.length!==i.length)return !1;for(let o=0;o{window.removeEventListener(\"click\",d,!0);}),0);}function p(e,t){const i=e.getBoundingClientRect();return g(e,i,t)}function m(e,t){const i=e.getBoundingClientRect(),o=[];for(let r=0;r=0?0:e.button}function g(t,i,o){const r=t.offsetWidth===i.width?1:t.offsetWidth/i.width;return new e.P((o.clientX-i.left)*r,(o.clientY-i.top)*r)}class v{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages=new Set;}isDirty(){return this._changed}setDirty(){this._changed=!0;}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(e,t){this._updatedSourceCaches[e]=t,this.setDirty();}discardSourceCacheUpdate(e){delete this._updatedSourceCaches[e];}updateLayer(e){const t=e.scope;this._updatedLayers[t]=this._updatedLayers[t]||new Set,this._updatedLayers[t].add(e.id),this.setDirty();}removeLayer(e){const t=e.scope;this._removedLayers[t]=this._removedLayers[t]||{},this._updatedLayers[t]=this._updatedLayers[t]||new Set,this._removedLayers[t][e.id]=e,this._updatedLayers[t].delete(e.id),this._updatedPaintProps.delete(e.fqid),this.setDirty();}getRemovedLayer(e){return this._removedLayers[e.scope]?this._removedLayers[e.scope][e.id]:null}discardLayerRemoval(e){this._removedLayers[e.scope]&&delete this._removedLayers[e.scope][e.id];}getLayerUpdatesByScope(){const e={};for(const t in this._updatedLayers)e[t]=e[t]||{},e[t].updatedIds=Array.from(this._updatedLayers[t].values());for(const t in this._removedLayers)e[t]=e[t]||{},e[t].removedIds=Object.keys(this._removedLayers[t]);return e}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(e){this._updatedPaintProps.add(e.fqid),this.setDirty();}getUpdatedImages(){return Array.from(this._updatedImages.values())}updateImage(e){this._updatedImages.add(e),this.setDirty();}resetUpdatedImages(){this._updatedImages.clear();}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages.clear();}}const x={Int8:\"BYTE\",Uint8:\"UNSIGNED_BYTE\",Int16:\"SHORT\",Uint16:\"UNSIGNED_SHORT\",Int32:\"INT\",Uint32:\"UNSIGNED_INT\",Float32:\"FLOAT\"};class y{constructor(e,t,i,o,r,s){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.instanceCount=s,this.context=e;const n=e.gl;this.buffer=n.createBuffer(),e.bindVertexBuffer.set(this.buffer),n.bufferData(n.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||r||t.destroy();}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&e.vertexAttribDivisor(r,i);}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}class b{constructor(e){this.gl=e.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1;}get(){return this.current}set(e){}getDefault(){return this.default}setDefault(){this.set(this.default);}}class w extends b{getDefault(){return e.C.transparent}set(e){const t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.clearColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1);}}class T extends b{getDefault(){return 1}set(e){(e!==this.current||this.dirty)&&(this.gl.clearDepth(e),this.current=e,this.dirty=!1);}}class E extends b{getDefault(){return 0}set(e){(e!==this.current||this.dirty)&&(this.gl.clearStencil(e),this.current=e,this.dirty=!1);}}class C extends b{getDefault(){return [!0,!0,!0,!0]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.colorMask(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1);}}class I extends b{getDefault(){return !0}set(e){(e!==this.current||this.dirty)&&(this.gl.depthMask(e),this.current=e,this.dirty=!1);}}class S extends b{getDefault(){return 255}set(e){(e!==this.current||this.dirty)&&(this.gl.stencilMask(e),this.current=e,this.dirty=!1);}}class M extends b{getDefault(){return {func:this.gl.ALWAYS,ref:0,mask:255}}set(e){const t=this.current;(e.func!==t.func||e.ref!==t.ref||e.mask!==t.mask||this.dirty)&&(this.gl.stencilFunc(e.func,e.ref,e.mask),this.current=e,this.dirty=!1);}}class L extends b{getDefault(){const e=this.gl;return [e.KEEP,e.KEEP,e.KEEP]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||this.dirty)&&(this.gl.stencilOp(e[0],e[1],e[2]),this.current=e,this.dirty=!1);}}class P extends b{getDefault(){return !1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.current=e,this.dirty=!1;}}class D extends b{getDefault(){return [0,1]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.depthRange(e[0],e[1]),this.current=e,this.dirty=!1);}}class A extends b{getDefault(){return !1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.current=e,this.dirty=!1;}}class R extends b{getDefault(){return this.gl.LESS}set(e){(e!==this.current||this.dirty)&&(this.gl.depthFunc(e),this.current=e,this.dirty=!1);}}class z extends b{getDefault(){return !1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.current=e,this.dirty=!1;}}class O extends b{getDefault(){const e=this.gl;return [e.ONE,e.ZERO,e.ONE,e.ZERO]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.blendFuncSeparate(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1);}}class F extends b{getDefault(){return e.C.transparent}set(e){const t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.blendColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1);}}class B extends b{getDefault(){return this.gl.FUNC_ADD}set(e){(e!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(e,e),this.current=e,this.dirty=!1);}}class k extends b{getDefault(){return !1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),this.current=e,this.dirty=!1;}}class N extends b{getDefault(){return this.gl.BACK}set(e){(e!==this.current||this.dirty)&&(this.gl.cullFace(e),this.current=e,this.dirty=!1);}}class U extends b{getDefault(){return this.gl.CCW}set(e){(e!==this.current||this.dirty)&&(this.gl.frontFace(e),this.current=e,this.dirty=!1);}}let G=class extends b{getDefault(){return null}set(e){(e!==this.current||this.dirty)&&(this.gl.useProgram(e),this.current=e,this.dirty=!1);}};class j extends b{getDefault(){return this.gl.TEXTURE0}set(e){(e!==this.current||this.dirty)&&(this.gl.activeTexture(e),this.current=e,this.dirty=!1);}}class V extends b{getDefault(){const e=this.gl;return [0,0,e.drawingBufferWidth,e.drawingBufferHeight]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.viewport(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1);}}class Z extends b{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.current=e,this.dirty=!1;}}class W extends b{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindRenderbuffer(t.RENDERBUFFER,e),this.current=e,this.dirty=!1;}}class H extends b{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindTexture(t.TEXTURE_2D,e),this.current=e,this.dirty=!1;}}class q extends b{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindBuffer(t.ARRAY_BUFFER,e),this.current=e,this.dirty=!1;}}class $ extends b{getDefault(){return null}set(e){const t=this.gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e),this.current=e,this.dirty=!1;}}class X extends b{getDefault(){return null}set(e){this.gl&&(e!==this.current||this.dirty)&&(this.gl.bindVertexArray(e),this.current=e,this.dirty=!1);}}class J extends b{getDefault(){return 4}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_ALIGNMENT,e),this.current=e,this.dirty=!1;}}class Y extends b{getDefault(){return !1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e),this.current=e,this.dirty=!1;}}class K extends b{getDefault(){return !1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e),this.current=e,this.dirty=!1;}}class Q extends b{constructor(e,t){super(e),this.context=e,this.parent=t;}getDefault(){return null}}class ee extends Q{setDirty(){this.dirty=!0;}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1;}}class te extends Q{attachment(){return this.gl.DEPTH_ATTACHMENT}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,this.attachment(),t.RENDERBUFFER,e),this.current=e,this.dirty=!1;}}class ie extends Q{attachment(){return this.gl.DEPTH_ATTACHMENT}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,this.attachment(),t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1;}}class oe extends te{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}class re{constructor(e,t,i,o,r){this.context=e,this.width=t,this.height=i;const s=this.framebuffer=e.gl.createFramebuffer();o&&(this.colorAttachment=new ee(e,s)),r&&(this.depthAttachmentType=r,this.depthAttachment=\"renderbuffer\"===r?new te(e,s):new ie(e,s));}destroy(){const e=this.context.gl;if(this.colorAttachment){const t=this.colorAttachment.get();t&&e.deleteTexture(t);}if(this.depthAttachment&&this.depthAttachmentType)if(\"renderbuffer\"===this.depthAttachmentType){const t=this.depthAttachment.get();t&&e.deleteRenderbuffer(t);}else {const t=this.depthAttachment.get();t&&e.deleteTexture(t);}e.deleteFramebuffer(this.framebuffer);}}class se{constructor(e,t){this.gl=e,this.clearColor=new w(this),this.clearDepth=new T(this),this.clearStencil=new E(this),this.colorMask=new C(this),this.depthMask=new I(this),this.stencilMask=new S(this),this.stencilFunc=new M(this),this.stencilOp=new L(this),this.stencilTest=new P(this),this.depthRange=new D(this),this.depthTest=new A(this),this.depthFunc=new R(this),this.blend=new z(this),this.blendFunc=new O(this),this.blendColor=new F(this),this.blendEquation=new B(this),this.cullFace=new k(this),this.cullFaceSide=new N(this),this.frontFace=new U(this),this.program=new G(this),this.activeTexture=new j(this),this.viewport=new V(this),this.bindFramebuffer=new Z(this),this.bindRenderbuffer=new W(this),this.bindTexture=new H(this),this.bindVertexBuffer=new q(this),this.bindElementBuffer=new $(this),this.bindVertexArrayOES=new X(this),this.pixelStoreUnpack=new J(this),this.pixelStoreUnpackPremultiplyAlpha=new Y(this),this.pixelStoreUnpackFlipY=new K(this),this.options=t?{...t}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=e.getExtension(\"EXT_texture_filter_anisotropic\")||e.getExtension(\"MOZ_EXT_texture_filter_anisotropic\")||e.getExtension(\"WEBKIT_EXT_texture_filter_anisotropic\"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=e.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=e.getExtension(\"WEBGL_debug_renderer_info\"),this.extDebugRendererInfo&&(this.renderer=e.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=e.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=e.getExtension(\"OES_texture_float_linear\")),this.extRenderToTextureHalfFloat=e.getExtension(\"EXT_color_buffer_half_float\"),this.extTimerQuery=e.getExtension(\"EXT_disjoint_timer_query_webgl2\"),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE);}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault();}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0;}createIndexBuffer(t,i,o){return new e.I(this,t,i,o)}createVertexBuffer(e,t,i,o,r){return new y(this,e,t,i,o,r)}createRenderbuffer(e,t,i){const o=this.gl,r=o.createRenderbuffer();return this.bindRenderbuffer.set(r),o.renderbufferStorage(o.RENDERBUFFER,e,t,i),this.bindRenderbuffer.set(null),r}createFramebuffer(e,t,i,o){return new re(this,e,t,i,o)}clear({color:e,depth:t,stencil:i,colorMask:o}){const r=this.gl;let s=0;e&&(s|=r.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set(o||[!0,!0,!0,!0])),void 0!==t&&(s|=r.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(t),this.depthMask.set(!0)),void 0!==i&&(s|=r.STENCIL_BUFFER_BIT,this.clearStencil.set(i),this.stencilMask.set(255)),r.clear(s);}setCullFace(e){!1===e.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(e.mode),this.frontFace.set(e.frontFace));}setDepthMode(e){e.func!==this.gl.ALWAYS||e.mask?(this.depthTest.set(!0),this.depthFunc.set(e.func),this.depthMask.set(e.mask),this.depthRange.set(e.range)):this.depthTest.set(!1);}setStencilMode(e){e.test.func!==this.gl.ALWAYS||e.mask?(this.stencilTest.set(!0),this.stencilMask.set(e.mask),this.stencilOp.set([e.fail,e.depthFail,e.pass]),this.stencilFunc.set({func:e.test.func,ref:e.ref,mask:e.test.mask})):this.stencilTest.set(!1);}setColorMode(i){t(i.blendFunction,e.a.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(i.blendFunction),this.blendColor.set(i.blendColor),i.blendEquation?this.blendEquation.set(i.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(i.mask);}unbindVAO(){this.bindVertexArrayOES.set(null);}}class ne{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error(\"Invalid value for edge-insets, top, bottom, left and right must all be numbers\");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(t,i,o){return null!=i.top&&null!=t.top&&(this.top=e.n(t.top,i.top,o)),null!=i.bottom&&null!=t.bottom&&(this.bottom=e.n(t.bottom,i.bottom,o)),null!=i.left&&null!=t.left&&(this.left=e.n(t.left,i.left,o)),null!=i.right&&null!=t.right&&(this.right=e.n(t.right,i.right,o)),this}getCenter(t,i){const o=e.c((this.left+t-this.right)/2,0,t),r=e.c((this.top+i-this.bottom)/2,0,i);return new e.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new ne(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function ae(t,i){const o=e.g(t,3);e.m.fromQuat(t,i),e.s(t,3,o);}function le(t,i){const o=e.q.identity([]);return e.q.rotateZ(o,o,-i),e.q.rotateX(o,o,-t),o}function ce(t,i){const o=[t[0],t[1],0],r=[i[0],i[1],0];if(e.v.length(o)>=1e-15){const t=e.v.normalize([],o);e.v.scale(r,t,e.v.dot(r,t)),i[0]=r[0],i[1]=r[1];}const s=e.v.cross([],i,t);if(e.v.len(s)<1e-15)return null;const n=Math.atan2(-s[1],s[0]);return le(Math.atan2(Math.sqrt(t[0]*t[0]+t[1]*t[1]),-t[2]),n)}class he{constructor(e,t){this.position=e,this.orientation=t;}get position(){return this._position}set position(t){if(t){const i=t instanceof e.M?t:new e.M(t[0],t[1],t[2]);this._renderWorldCopies&&(i.x=e.w(i.x,0,1)),this._position=i;}else this._position=null;}lookAtPoint(t,i){if(this.orientation=null,!this.position)return;const o=this.position,r=this._elevation?this._elevation.getAtPointOrZero(e.M.fromLngLat(t)):0,s=e.M.fromLngLat(t,r),n=[s.x-o.x,s.y-o.y,s.z-o.z];i||(i=[0,0,1]),i[2]=Math.abs(i[2]),this.orientation=ce(n,i);}setPitchBearing(t,i){this.orientation=le(e.d(t),e.d(-i));}}class _e{constructor(t,i){this._transform=e.m.identity([]),this.orientation=i,this.position=t;}get mercatorPosition(){const t=this.position;return new e.M(t[0],t[1],t[2])}get position(){const t=e.g(this._transform,3);return [t[0],t[1],t[2]]}set position(t){var i;t&&e.s(this._transform,3,[(i=t)[0],i[1],i[2],1]);}get orientation(){return this._orientation}set orientation(t){this._orientation=t||e.q.identity([]),t&&ae(this._transform,this._orientation);}getPitchBearing(){const e=this.forward(),t=this.right();return {bearing:Math.atan2(-t[1],t[0]),pitch:Math.atan2(Math.sqrt(e[0]*e[0]+e[1]*e[1]),-e[2])}}setPitchBearing(e,t){this._orientation=le(e,t),ae(this._transform,this._orientation);}forward(){const t=e.g(this._transform,2);return [-t[0],-t[1],-t[2]]}up(){const t=e.g(this._transform,1);return [-t[0],-t[1],-t[2]]}right(){const t=e.g(this._transform,0);return [t[0],t[1],t[2]]}getCameraToWorld(t,i){const o=new Float64Array(16);return e.m.invert(o,this.getWorldToCamera(t,i)),o}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(t,i,o){const r=this.position;e.v.scale(r,r,-t);const s=new Float64Array(16);return e.m.fromScaling(s,[o,o,o]),e.m.translate(s,s,r),s[10]*=i,s}getWorldToCamera(t,i){const o=new Float64Array(16),r=new Float64Array(4),s=this.position;return e.q.conjugate(r,this._orientation),e.v.scale(s,s,-t),e.m.fromQuat(o,r),e.m.translate(o,o,s),o[1]*=-1,o[5]*=-1,o[9]*=-1,o[13]*=-1,o[8]*=i,o[9]*=i,o[10]*=i,o[11]*=i,o}getCameraToClipPerspective(t,i,o,r){const s=new Float64Array(16);return e.m.perspective(s,t,i,o,r),s}getCameraToClipOrthographic(t,i,o,r,s,n){const a=new Float64Array(16);return e.m.ortho(a,t,i,o,r,s,n),a}getDistanceToElevation(t,i=!1){const o=0===t?0:e.b(t,i?e.l(this.position[1]):this.position[1]),r=this.forward();return (o-this.position[2])/r[2]}clone(){return new _e([...this.position],[...this.orientation])}}const de={unknown:0,flipRequired:1,flipNotRequired:2},ue=Math.tan(85*Math.PI/180);function pe(t,i,o,r,s,n,a){const l=e.m.create();if(o)if(\"globe\"===n.name){const t=e.f(s,i);e.m.multiply(l,l,t);}else {const t=e.h.invert([],a);l[0]=t[0],l[1]=t[1],l[4]=t[2],l[5]=t[3],r||e.m.rotateZ(l,l,s.angle);}else e.m.multiply(l,s.labelPlaneMatrix,t);return l}function me(e,t,i,o,r,s,n){const a=pe(e,t,i,o,r,s,n);return \"globe\"===s.name&&i||(a[2]=a[6]=a[10]=a[14]=0),a}function fe(t,i,o,r,s,n,a){if(o){if(\"globe\"===n.name){const l=pe(t,i,o,r,s,n,a);return e.m.invert(l,l),e.m.multiply(l,t,l),l}{const i=e.m.clone(t),o=e.m.identity([]);return o[0]=a[0],o[1]=a[1],o[4]=a[2],o[5]=a[3],e.m.multiply(i,i,o),r||e.m.rotateZ(i,i,-s.angle),i}}return s.glCoordMatrix}function ge(t,i,o,r){const s=[t,i,o,1];o?e.e.transformMat4(s,s,r):Me(s,s,r);const n=s[3];return s[0]/=n,s[1]/=n,s[2]/=n,s}function ve(e,t){return Math.min(.5+e/t*.5,1.5)}function xe(e,t){const i=e[0]/e[3],o=e[1]/e[3];return i>=-t[0]&&i<=t[0]&&o>=-t[1]&&o<=t[1]}function ye(t,i,o,r,s,n,a,l,c,h){const _=o.transform,d=r?t.textSizeData:t.iconSizeData,u=e.i(d,o.transform.zoom),p=\"globe\"===_.projection.name,m=[256/o.width*2+1,256/o.height*2+1],f=r?t.text.dynamicLayoutVertexArray:t.icon.dynamicLayoutVertexArray;f.clear();let g=null;p&&(g=r?t.text.globeExtVertexArray:t.icon.globeExtVertexArray);const v=t.lineVertexArray,x=r?t.text.placedSymbolArray:t.icon.placedSymbolArray,y=o.transform.width/o.transform.height;let b,w=!1;for(let r=0;rMath.abs(o)?{useVertical:!0}:t===e.W.vertical?r>0?{needsFlipping:!0}:null:i!==de.unknown&&function(e,t){return 0===e||Math.abs(t/e)>ue}(o,r)?i===de.flipRequired?{needsFlipping:!0}:null:o<0?{needsFlipping:!0}:null}function Te(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f,g,v,x){const y=i/24,b=t.lineOffsetX*y,w=t.lineOffsetY*y,{lineStartIndex:T,glyphStartIndex:E,numGlyphs:C,segment:I,writingMode:S,flipState:M}=t,L=T+t.lineLength,P=t=>{if(_){const[i,o,r]=t.up,s=h.length;e.u(_,s+0,i,o,r),e.u(_,s+1,i,o,r),e.u(_,s+2,i,o,r),e.u(_,s+3,i,o,r);}const[i,o,r]=t.point;e.k(h,i,o,r,t.angle);};if(C>1){const e=be(y,l,b,w,o,d,u,t,c,n,p,f,!1,g,v,x);if(!e)return {notEnoughRoom:!0};if(r&&!o){let[i,o,r]=e.first.point,[s,n,l]=e.last.point;[i,o]=ge(i,o,r,a),[s,n]=ge(s,n,l,a);const c=we(S,M,(s-i)*m,n-o);if(t.flipState=c&&c.needsFlipping?de.flipRequired:de.flipNotRequired,c)return c}P(e.first);for(let e=E+1;e0?n:Ce(u,r,i,1,s,void 0,g,v.canonical),l=we(S,M,(a[0]-i[0])*m,a[1]-i[1]);if(t.flipState=l&&l.needsFlipping?de.flipRequired:de.flipNotRequired,l)return l}const i=Ie(y*l.getoffsetX(E),b,w,o,d,u,I,T,L,c,n,p,f,!1,!1,g,v,x);if(!i)return {notEnoughRoom:!0};P(i);}return {}}function Ee(e,t,i,o,r){const{x:s,y:n,z:a}=o.projectTilePoint(e.x,e.y,t);if(!r)return ge(s,n,a,i);const[l,c,h]=r(e);return ge(s+l,n+c,a+h,i)}function Ce(t,i,o,r,s,n,a,l){const c=Ee(t.sub(i)._unit()._add(t),l,s,a,n);return e.v.sub(c,o,c),e.v.normalize(c,c),e.v.scaleAndAdd(c,o,c,r)}function Ie(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f,g,v){const x=r?t-i:t+i;let y=x>0?1:-1,b=0;r&&(y*=-1,b=Math.PI),y<0&&(b+=Math.PI);let w=l+a+(y>0?0:1)|0,T=s,E=s,C=0,I=0;const S=Math.abs(x),M=[],L=[];let P=n,D=P;const A=()=>Ce(D,P,E,S-C+1,_,u,f,g.canonical);for(;C+I<=S;){if(w+=y,w=c)return null;if(E=T,D=P,M.push(E),p&&L.push(D),P=new e.P(h.getx(w),h.gety(w)),T=d[w],!T){const e=Ee(P,g.canonical,_,f,u);T=e[3]>0?d[w]=e:A();}C+=I,I=e.v.distance(E,T);}m&&u&&(d[w]&&(T=A(),I=e.v.distance(E,T)),d[w]=T);const R=(S-C)/I,z=P.sub(D)._mult(R)._add(D),O=e.v.sub([],T,E),F=e.v.scaleAndAdd([],E,O,R);let B=[0,0,1],k=O[0],N=O[1];if(v&&(B=f.upVector(g.canonical,z.x,z.y),0!==B[0]||0!==B[1]||1!==B[2])){const t=[B[2],0,-B[0]],i=e.v.cross([],B,t);e.v.normalize(t,t),e.v.normalize(i,i),k=e.v.dot(O,t),N=e.v.dot(O,i);}if(o){const t=e.v.cross([],B,O);e.v.normalize(t,t),e.v.scaleAndAdd(F,F,t,o*y);}const U=b+Math.atan2(N,k);return M.push(F),p&&L.push(z),{point:F,angle:U,path:M,tilePath:L,up:B}}function Se(e,t){const i=t.length,o=i+4*e;t.resize(o),t.float32.fill(-1/0,4*i,4*o);}function Me(e,t,i){const o=t[0],r=t[1];return e[0]=i[0]*o+i[4]*r+i[12],e[1]=i[1]*o+i[5]*r+i[13],e[3]=i[3]*o+i[7]*r+i[15],e}const Le=(e,t,i)=>(1-i)*e+i*t,Pe=e=>e*e*e*e*e;class De{constructor(t,i,o,r,s,n,a){this.tileSize=512,this._renderWorldCopies=void 0===s||s,this._minZoom=t||0,this._maxZoom=i||22,this._minPitch=null==o?0:o,this._maxPitch=null==r?60:r,this.setProjection(n),this.setMaxBounds(a),this.width=0,this.height=0,this._center=new e.L(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._unmodified=!0,this._edgeInsets=new ne,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new _e,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference=\"ground\",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1;}clone(){const e=new De(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection());return e._elevation=this._elevation,e._centerAltitude=this._centerAltitude,e._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,e.tileSize=this.tileSize,e.mercatorFromTransition=this.mercatorFromTransition,e.width=this.width,e.height=this.height,e.cameraElevationReference=this.cameraElevationReference,e._center=this._center,e._setZoom(this.zoom),e._seaLevelZoom=this._seaLevelZoom,e.angle=this.angle,e._fov=this._fov,e._pitch=this._pitch,e._nearZ=this._nearZ,e._farZ=this._farZ,e._averageElevation=this._averageElevation,e._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,e._unmodified=this._unmodified,e._edgeInsets=this._edgeInsets.clone(),e._camera=this._camera.clone(),e._calcMatrices(),e.freezeTileCoverage=this.freezeTileCoverage,e.frustumCorners=this.frustumCorners,e}get isOrthographic(){return \"globe\"!==this.projection.name&&this._orthographicProjectionAtLowPitch&&this.pitch<15}get elevation(){return this._elevation}set elevation(e){this._elevation!==e&&(this._elevation=e,this._updateCameraOnTerrain(),this._calcMatrices());}get depthOcclusionForSymbolsAndCircles(){return \"globe\"!==this.projection.name&&!this.isOrthographic}updateElevation(e,t=!1){const i=this._elevation&&this._elevation.exaggeration()!==this._centerAltitudeValidForExaggeration;(null==this._seaLevelZoom||i)&&this._updateCameraOnTerrain(),(e||i)&&this._constrainCamera(t),this._calcMatrices();}getProjection(){return e.p(this.projection,[\"name\",\"center\",\"parallels\"])}setProjection(i){this.projectionOptions=i||{name:\"mercator\"};const o=this.projection?this.getProjection():void 0;this.projection=e.o(this.projectionOptions);const r=!t(o,this.getProjection());return r&&this._calcMatrices(),this.mercatorFromTransition=!1,r}setOrthographicProjectionAtLowPitch(e){return this._orthographicProjectionAtLowPitch!==e&&(this._orthographicProjectionAtLowPitch=e,this._calcMatrices(),!0)}setMercatorFromTransition(){const t=this.projection.name;this.mercatorFromTransition=!0,this.projectionOptions={name:\"mercator\"},this.projection=e.o({name:\"mercator\"});const i=t!==this.projection.name;return i&&this._calcMatrices(),i}get minZoom(){return this._minZoom}set minZoom(e){this._minZoom!==e&&(this._minZoom=e,this.zoom=Math.max(this.zoom,e));}get maxZoom(){return this._maxZoom}set maxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.zoom=Math.min(this.zoom,e));}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch!==e&&(this._minPitch=e,this.pitch=Math.max(this.pitch,e));}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.pitch=Math.min(this.pitch,e));}get renderWorldCopies(){return this._renderWorldCopies&&!0===this.projection.supportsWorldCopies}set renderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this.tileSize*this.scale}get cameraWorldSizeForFog(){const e=Math.max(this._camera.getDistanceToElevation(this._averageElevation),Number.EPSILON);return this._worldSizeFromZoom(this._zoomFromMercatorZ(e))}get cameraWorldSize(){const e=Math.max(this._camera.getDistanceToElevation(this._averageElevation,!0),Number.EPSILON);return this._worldSizeFromZoom(this._zoomFromMercatorZ(e))}get pixelsPerMeter(){return this.projection.pixelsPerMeter(this.center.lat,this.worldSize)}get cameraPixelsPerMeter(){return e.b(1,this.center.lat)*this.cameraWorldSizeForFog}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new e.P(this.width,this.height)}get bearing(){return e.w(this.rotation,-180,180)}set bearing(e){this.rotation=e;}get rotation(){return -this.angle/Math.PI*180}set rotation(t){const i=-t*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=e.h.create(),e.h.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));}get pitch(){return this._pitch/Math.PI*180}set pitch(t){const i=e.c(t,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());}get aspect(){return this.width/this.height}get fov(){return this._fov/Math.PI*180}get fovX(){return this._fov}get fovY(){const e=1/Math.tan(.5*this.fovX);return 2*Math.atan(1/this.aspect/e)}set fov(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=e.d(t),this._calcMatrices());}get averageElevation(){return this._averageElevation}set averageElevation(e){this._averageElevation=e,this._calcFogMatrices(),this._distanceTileDataCache={};}get zoom(){return this._zoom}set zoom(e){const t=Math.min(Math.max(e,this.minZoom),this.maxZoom);this._zoom!==t&&(this._unmodified=!1,this._setZoom(t),this._updateSeaLevelZoom(),this._constrain(),this._calcMatrices());}_setZoom(e){this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom;}_updateCameraOnTerrain(){const e=this.elevation?this.elevation.getAtPoint(this.locationCoordinate(this.center),Number.NEGATIVE_INFINITY):Number.NEGATIVE_INFINITY,t=this.elevation&&e===Number.NEGATIVE_INFINITY&&this.elevation.visibleDemTiles.length>0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||e===Number.NEGATIVE_INFINITY&&(!t||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const i=this._elevation;t||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&i.exaggeration()&&this._centerAltitudeValidForExaggeration!==i.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*i.exaggeration(),this._centerAltitudeValidForExaggeration=i.exaggeration()):(this._centerAltitude=e||0,this._centerAltitudeValidForExaggeration=i.exaggeration()),this._updateSeaLevelZoom();}_updateSeaLevelZoom(){void 0!==this._centerAltitudeValidForExaggeration&&(this._seaLevelZoom=this._zoomFromMercatorZ((this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize));}sampleAverageElevation(){if(!this._elevation)return 0;const t=this._elevation,i=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],o=this.horizonLineFromTop();let r=0,s=0;for(let n=0;n0,h=t.y+10,d=o.wrap-(c?0:1),u=o.wrap+(l?0:1),p=c?t.x-1:a-1,m=l?t.x+1:0;i[0]<0?(r.push(new e.O(s,u,t.z,m,t.y)),i[1]<0&&h&&(r.push(new e.O(s,n,t.z,t.x,t.y+1)),r.push(new e.O(s,u,t.z,m,t.y+1))),i[1]>0&&_&&(r.push(new e.O(s,n,t.z,t.x,t.y-1)),r.push(new e.O(s,u,t.z,m,t.y-1)))):i[0]>0?(r.push(new e.O(s,d,t.z,p,t.y)),i[1]<0&&h&&(r.push(new e.O(s,n,t.z,t.x,t.y+1)),r.push(new e.O(s,d,t.z,p,t.y+1))),i[1]>0&&_&&(r.push(new e.O(s,n,t.z,t.x,t.y-1)),r.push(new e.O(s,d,t.z,p,t.y-1)))):i[1]<0&&h?r.push(new e.O(s,n,t.z,t.x,t.y+1)):_&&r.push(new e.O(s,n,t.z,t.x,t.y-1));}if(r.length>1){r.sort(((e,t)=>e.overscaledZ-t.overscaledZ||e.wrap-t.wrap||e.canonical.z-t.canonical.z||e.canonical.x-t.canonical.x||e.canonical.y-t.canonical.y));let e=0,t=0;for(;te.isChildOf(t)))||s.push(e);return r=s.filter((e=>!t.some((t=>!!(e.overscaledZt.maxzoom&&(i=t.maxzoom);const a=this.locationCoordinate(this.center),l=this.center.lat,c=1<{const i=1/4e4,o=new e.M(t.x+i,t.y,t.z),r=new e.M(t.x,t.y+i,t.z),s=t.toLngLat(),n=o.toLngLat(),a=r.toLngLat(),l=this.locationCoordinate(s),c=this.locationCoordinate(n),h=this.locationCoordinate(a),_=Math.hypot(c.x-l.x,c.y-l.y),d=Math.hypot(h.x-l.x,h.y-l.y);return Math.sqrt(_*d)*T/i},C=t=>{const i=b,o=w;return {aabb:e.y(this,c,0,0,0,t,o,i,this.projection),zoom:0,x:0,y:0,minZ:o,maxZ:i,wrap:t,fullyVisible:!1}},I=[];let S=[];const M=i,L=t.reparseOverscaled?o:i,P=e=>e*e,D=P((f-this._centerAltitude)*m),A=e=>{if(!this._elevation||!e.tileID||!n)return;const t=this._elevation.getMinMaxForTile(e.tileID),i=e.aabb;t?(i.min[2]=t.min,i.max[2]=t.max,i.center[2]=(i.min[2]+i.max[2])/2):(e.shouldSplit=R(e),e.shouldSplit||(i.min[2]=i.max[2]=i.center[2]=this._centerAltitude));},R=t=>{if(t.zoom=.9)return !0}else if(s&&(n=P(t.aabb.distanceZ(g)*m)),this.projection.isReprojectedInTileSpace&&o<=5){const i=Math.pow(2,t.zoom),o=E(new e.M((t.x+.5)/i,(t.y+.5)/i));a=o>.85?1:o;}const c=i*i+r*r+n,h=P((1<{if(t*P(.707)0;){const o=I.pop(),r=o.x,a=o.y;let l=o.fullyVisible;const d=()=>\"globe\"===this.projection.name&&(0===o.y||o.y===(1<>1),d={aabb:n?o.aabb.quadrant(t):e.y(this,c,o.zoom+1,i,h,o.wrap,o.minZ,o.maxZ,this.projection),zoom:o.zoom+1,x:i,y:h,wrap:o.wrap,fullyVisible:l,tileID:void 0,shouldSplit:void 0,minZ:o.minZ,maxZ:o.maxZ};s&&!_&&(d.tileID=new e.O(o.zoom+1===M?L:o.zoom+1,o.wrap,o.zoom+1,i,h),A(d)),I.push(d);}else {const s=o.zoom===M?L:o.zoom;if(t.minzoom&&t.minzoom>s)continue;if(!l){let t=v?o.aabb.intersectsPrecise(u):o.aabb.intersectsPreciseFlat(u);if(0===t&&d()){const i=new e.t(o.zoom,r,a);t=e.x(this,c,i,!0).intersectsPrecise(u);}if(0===t)continue}const n=h[0]-(.5+r+(o.wrap<{const s=[0,0,0,1],n=[e.J,e.J,0,1],a=this.calculateFogTileMatrix(r.tileID.toUnwrapped());e.e.transformMat4(s,s,a),e.e.transformMat4(n,n,a);const l=e.e.min([],s,n),c=e.e.max([],s,n),h=e.z(l,c);if(0===h)return !0;let _=!1;const d=this._elevation;if(d&&h>i&&0!==o){const i=this.calculateProjMatrix(r.tileID.toUnwrapped());let s;t.isTerrainDEM||(s=d.getMinMaxForTile(r.tileID)),s||(s={min:w,max:b});const n=e._(this.rotation),a=[n[0]*e.J,n[1]*e.J,s.max];e.v.transformMat4(a,a,i),_=(1-a[1])*this.height*.5e.distanceSq-t.distanceSq)).map((e=>e.tileID))}resize(e,t){this.width=e,this.height=t,this.pixelsToGLUnits=[2/e,-2/t],this._constrain(),this._calcMatrices();}get unmodified(){return this._unmodified}zoomScale(e){return Math.pow(2,e)}scaleZoom(e){return Math.log(e)/Math.LN2}project(t){const i=e.c(t.lat,-e.A,e.A),o=this.projection.project(t.lng,i);return new e.P(o.x*this.worldSize,o.y*this.worldSize)}unproject(e){return this.projection.unproject(e.x/this.worldSize,e.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/e.b(1,this.center.lat)/this.worldSize}setLocationAtPoint(t,i){let o,r;const s=this.centerPoint;if(\"globe\"===this.projection.name){const e=this.worldSize;o=(i.x-s.x)/e,r=(i.y-s.y)/e;}else {const e=this.pointCoordinate(i),t=this.pointCoordinate(s);o=e.x-t.x,r=e.y-t.y;}const n=this.locationCoordinate(t);this.setLocation(new e.M(n.x-o,n.y-r));}setLocation(e){this.center=this.coordinateLocation(e),this.projection.wrap&&(this.center=this.center.wrap());}locationPoint(e){return this.projection.locationPoint(this,e)}locationPoint3D(e){return this.projection.locationPoint(this,e,!0)}pointLocation(e){return this.coordinateLocation(this.pointCoordinate(e))}pointLocation3D(e){return this.coordinateLocation(this.pointCoordinate3D(e))}locationCoordinate(t,i){const o=i?e.b(i,t.lat):void 0,r=this.projection.project(t.lng,t.lat);return new e.M(r.x,r.y,o)}coordinateLocation(e){return this.projection.unproject(e.x,e.y)}pointRayIntersection(t,i){const o=null!=i?i:this._centerAltitude,r=[t.x,t.y,0,1],s=[t.x,t.y,1,1];e.e.transformMat4(r,r,this.pixelMatrixInverse),e.e.transformMat4(s,s,this.pixelMatrixInverse);const n=s[3];e.e.scale(r,r,1/r[3]),e.e.scale(s,s,1/n);const a=r[2],l=s[2];return {p0:r,p1:s,t:a===l?0:(o-a)/(l-a)}}screenPointToMercatorRay(t){const i=[t.x,t.y,0,1],o=[t.x,t.y,1,1];return e.e.transformMat4(i,i,this.pixelMatrixInverse),e.e.transformMat4(o,o,this.pixelMatrixInverse),e.e.scale(i,i,1/i[3]),e.e.scale(o,o,1/o[3]),i[2]=e.b(i[2],this._center.lat)*this.worldSize,o[2]=e.b(o[2],this._center.lat)*this.worldSize,e.e.scale(i,i,1/this.worldSize),e.e.scale(o,o,1/this.worldSize),new e.R([i[0],i[1],i[2]],e.v.normalize([],e.v.sub([],o,i)))}rayIntersectionCoordinate(t){const{p0:i,p1:o,t:r}=t,s=e.b(i[2],this._center.lat),n=e.b(o[2],this._center.lat);return new e.M(e.n(i[0],o[0],r)/this.worldSize,e.n(i[1],o[1],r)/this.worldSize,e.n(s,n,r))}pointCoordinate(e,t=this._centerAltitude){return this.projection.pointCoordinate(this,e.x,e.y,t)}pointCoordinate3D(t){if(!this.elevation)return this.pointCoordinate(t);let i=this.projection.pointCoordinate3D(this,t.x,t.y);if(i)return new e.M(i[0],i[1],i[2]);let o=0,r=this.horizonLineFromTop();if(t.y>r)return this.pointCoordinate(t);const s=.02*r,n=t.clone();for(let t=0;t<10&&r-o>s;t++){n.y=e.n(o,r,.66);const t=this.projection.pointCoordinate3D(this,n.x,n.y);t?(r=n.y,i=t):o=n.y;}return i?new e.M(i[0],i[1],i[2]):this.pointCoordinate(t)}isPointAboveHorizon(e){return this.projection.isPointAboveHorizon(this,e)}isPointOnSurface(t){if(t.y<0||t.y>this.height||t.x<0||t.x>this.width)return !1;if(this.elevation||this.zoom>=e.G)return !this.isPointAboveHorizon(t);const i=this.pointCoordinate(t);return i.y>=0&&i.y<=1}_coordinatePoint(t,i){const o=i&&this.elevation?this.elevation.getAtPointOrZero(t,this._centerAltitude):this._centerAltitude,r=[t.x*this.worldSize,t.y*this.worldSize,o+t.toAltitude(),1];return e.e.transformMat4(r,r,this.pixelMatrix),r[3]>0?new e.P(r[0]/r[3],r[1]/r[3]):new e.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:t,left:i}=this._edgeInsets,o=this.height-this._edgeInsets.bottom,r=this.width-this._edgeInsets.right,s=this.pointLocation3D(new e.P(i,t)),n=this.pointLocation3D(new e.P(r,t)),a=this.pointLocation3D(new e.P(r,o)),l=this.pointLocation3D(new e.P(i,o));let c=Math.min(s.lng,n.lng,a.lng,l.lng),h=Math.max(s.lng,n.lng,a.lng,l.lng),_=Math.min(s.lat,n.lat,a.lat,l.lat),d=Math.max(s.lat,n.lat,a.lat,l.lat);const u=Math.pow(2,-this.zoom)/16*270,p=\"globe\"===this.projection.name?1:4,m=(t,i,o,r,s)=>{const n=(t+o)/2,a=(i+r)/2,l=new e.P(n,a),{lng:f,lat:g}=this.pointLocation3D(l),v=Math.max(0,c-f,_-g,f-h,g-d);c=Math.min(c,f),h=Math.max(h,f),_=Math.min(_,g),d=Math.max(d,g),(su)&&(m(t,i,n,a,s+1),m(n,a,o,r,s+1));};if(m(i,t,r,t,1),m(r,t,r,o,1),m(r,o,i,o,1),m(i,o,i,t,1),\"globe\"===this.projection.name){const[t,i]=e.B(this);t?(d=90,h=180,c=-180):i&&(_=-90,h=180,c=-180);}return new e.D(new e.L(c,_),new e.L(h,d))}_getBoundsRectangular(t,i){const{top:o,left:r}=this._edgeInsets,s=this.height-this._edgeInsets.bottom,n=this.width-this._edgeInsets.right,a=new e.P(r,o),l=new e.P(n,o),c=new e.P(n,s),h=new e.P(r,s);let _=this.pointCoordinate(a,t),d=this.pointCoordinate(l,t);const u=this.pointCoordinate(c,i),p=this.pointCoordinate(h,i),m=(e,t)=>(t.y-e.y)/(t.x-e.x);return _.y>1&&d.y>=0?_=new e.M((1-p.y)/m(p,_)+p.x,1):_.y<0&&d.y<=1&&(_=new e.M(-p.y/m(p,_)+p.x,0)),d.y>1&&_.y>=0?d=new e.M((1-u.y)/m(u,d)+u.x,1):d.y<0&&_.y<=1&&(d=new e.M(-u.y/m(u,d)+u.x,0)),(new e.D).extend(this.coordinateLocation(_)).extend(this.coordinateLocation(d)).extend(this.coordinateLocation(p)).extend(this.coordinateLocation(u))}_getBoundsRectangularTerrain(){const e=this.elevation;if(!e.visibleDemTiles.length||e.isUsingMockSource())return this._getBoundsRectangular(0,0);const t=e.visibleDemTiles.reduce(((e,t)=>{if(t.dem){const i=t.dem.tree;e.min=Math.min(e.min,i.minimums[0]),e.max=Math.max(e.max,i.maximums[0]);}return e}),{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(t.min*e.exaggeration(),t.max*e.exaggeration())}getBounds(){return \"mercator\"===this.projection.name||\"equirectangular\"===this.projection.name?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(e=!0){const t=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,i=this.height/2-t*(1-this._horizonShift);return e?Math.max(0,i):i}getMaxBounds(){return this.maxBounds}setMaxBounds(t){this.maxBounds=t,this.minLat=-e.A,this.maxLat=e.A,this.minLng=-180,this.maxLng=180,t&&(this.minLat=t.getSouth(),this.maxLat=t.getNorth(),this.minLng=t.getWest(),this.maxLng=t.getEast(),this.maxLng_&&(a=_-c),_-ht&&(n=t-l),t-e{for(let r=0;r<16;r++)e[r]=Le(t[r],i[r],o);})(a,a,l,Pe(this.pitch>=15?1:this.pitch/15));}else a=l;const c=e.m.mul([],l,n);let h=e.m.mul([],a,n);if(this.projection.isReprojectedInTileSpace){const t=this.locationCoordinate(this.center),i=e.m.identity([]);e.m.translate(i,i,[t.x*this.worldSize,t.y*this.worldSize,0]),e.m.multiply(i,i,e.Q(this)),e.m.translate(i,i,[-t.x*this.worldSize,-t.y*this.worldSize,0]),e.m.multiply(h,h,i),e.m.multiply(c,c,i),this.inverseAdjustmentMatrix=e.S(this);}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=e.m.scale([],h,[this.worldSize,this.worldSize,this.worldSize/s,1]),this.projMatrix=h,this.invProjMatrix=e.m.invert(new Float64Array(16),this.projMatrix),i){const i=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);i[8]=2*-t.x/this.width,i[9]=2*t.y/this.height,this.expandedFarZProjMatrix=e.m.mul([],i,n);}else this.expandedFarZProjMatrix=this.projMatrix;const _=e.m.invert([],a);this.frustumCorners=e.T.fromInvProjectionMatrix(_,this.horizonLineFromTop(),this.height),this.cameraFrustum=e.F.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!i);const d=new Float32Array(16);e.m.identity(d),e.m.scale(d,d,[1,-1,1]),e.m.rotateX(d,d,this._pitch),e.m.rotateZ(d,d,this.angle);const u=e.m.perspective(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=e.m.clone(u);const p=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;u[8]=2*-t.x/this.width,u[9]=2*(t.y+p)/this.height,this.skyboxMatrix=e.m.multiply(d,u,d);const m=this.point,f=m.x,g=m.y,v=this.width%2/2,x=this.height%2/2,y=Math.cos(this.angle),b=Math.sin(this.angle),w=f-Math.round(f)+y*v+b*x,T=g-Math.round(g)+y*x+b*v,E=new Float64Array(h);if(e.m.translate(E,E,[w>.5?w-1:w,T>.5?T-1:T,0]),this.alignedProjMatrix=E,h=e.m.create(),e.m.scale(h,h,[this.width/2,-this.height/2,1]),e.m.translate(h,h,[1,-1,0]),this.labelPlaneMatrix=h,h=e.m.create(),e.m.scale(h,h,[1,-1,1]),e.m.translate(h,h,[-1,-1,0]),e.m.scale(h,h,[2/this.width,2/this.height,1]),this.glCoordMatrix=h,this.pixelMatrix=e.m.multiply(new Float64Array(16),this.labelPlaneMatrix,c),this._calcFogMatrices(),this._distanceTileDataCache={},h=e.m.invert(new Float64Array(16),this.pixelMatrix),!h)throw new Error(\"failed to invert matrix\");if(this.pixelMatrixInverse=h,\"globe\"===this.projection.name||this.mercatorFromTransition){this.globeMatrix=e.V(this);const t=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=e.v.transformMat4(t,t,n),this.globeRadius=this.worldSize/2/Math.PI-1;}else this.globeMatrix=h;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={};}_calcFogMatrices(){this._fogTileMatrixCache={};const t=this.cameraWorldSizeForFog,i=this.cameraPixelsPerMeter,o=this._camera.position,r=1/this.height/this._pixelsPerMercatorPixel,s=[t,t,i];e.v.scale(s,s,r),e.v.scale(o,o,-1),e.v.multiply(o,o,s);const n=e.m.create();e.m.translate(n,n,o),e.m.scale(n,n,s),this.mercatorFogMatrix=n,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(t,i,r);}_computeCameraPosition(e){const t=(e=e||this.pixelsPerMeter)/this.pixelsPerMeter,i=this._camera.forward(),o=this.point,r=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*t-e/this.worldSize*this._centerAltitude;return [o.x/this.worldSize-i[0]*r,o.y/this.worldSize-i[1]*r,e/this.worldSize*this._centerAltitude-i[2]*r]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition());}_translateCameraConstrained(t){const i=this._maxCameraBoundsDistance()*Math.cos(this._pitch),o=this._camera.position[2],r=t[2];let s=1;this.projection.wrap&&(this.center=this.center.wrap()),r>0&&(s=Math.min((i-o)/r,1)),this._camera.position=e.v.scaleAndAdd([],this._camera.position,t,s),this._updateStateFromCamera();}_updateStateFromCamera(){const t=this._camera.position,i=this._camera.forward(),{pitch:o,bearing:r}=this._camera.getPitchBearing(),s=e.b(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,n=this._mercatorZfromZoom(this._maxZoom)*Math.cos(e.d(this._maxPitch)),a=Math.max((t[2]-s)/Math.cos(o),n),l=this._zoomFromMercatorZ(a);e.v.scaleAndAdd(t,t,i,a),this._pitch=e.c(o,e.d(this.minPitch),e.d(this.maxPitch)),this.angle=e.w(r,-Math.PI,Math.PI),this._setZoom(e.c(l,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new e.M(t[0],t[1],t[2])),this._unmodified=!1,this._constrain(),this._calcMatrices();}_worldSizeFromZoom(e){return Math.pow(2,e)*this.tileSize}_mercatorZfromZoom(e){return this.cameraToCenterDistance/this._worldSizeFromZoom(e)}_minimumHeightOverTerrain(){const e=Math.min((null!=this._seaLevelZoom?this._seaLevelZoom:this._zoom)+4,this._maxZoom);return this._mercatorZfromZoom(e)}_zoomFromMercatorZ(e){return this.scaleZoom(this.cameraToCenterDistance/(e*this.tileSize))}zoomFromMercatorZAdjusted(t){let i=0,o=e.G,r=0,s=1/0;for(;o-i>1e-6&&o>i;){const e=i+.5*(o-i),n=this.tileSize*Math.pow(2,e),a=this.getCameraToCenterDistance(this.projection,e,n),l=this.scaleZoom(a/(t*this.tileSize)),c=Math.abs(e-l);cc||i.y>1)return !0}return !1}isHorizonVisible(){return this.pitch+e.Y(this.fovAboveCenter)>88||this.anyCornerOffEdge(new e.P(0,0),new e.P(this.width,this.height))}zoomDeltaToMovement(t,i){const o=e.v.length(e.v.sub([],this._camera.position,t)),r=this._zoomFromMercatorZ(o)+i;return o-this._mercatorZfromZoom(r)}getCameraPoint(){if(\"globe\"===this.projection.name){const t=function([t,i,o],r){const s=[t,i,o,1];e.e.transformMat4(s,s,r);const n=s[3]=Math.max(s[3],1e-6);return s[0]/=n,s[1]/=n,s[2]/=n,s}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new e.P(t[0],t[1])}{const t=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new e.P(0,t))}}getCameraToCenterDistance(t,i=this.zoom,o=this.worldSize){const r=e.N(t,i,this.width,this.height,1024),s=t.pixelSpaceConversion(this.center.lat,o,r);let n=.5/Math.tan(.5*this._fov)*this.height*s;return this.isOrthographic&&(n=Le(1,n,Pe(this.pitch>=15?1:this.pitch/15))),n}getWorldToCameraMatrix(){const t=this._camera.getWorldToCamera(this.worldSize,\"meters\"===this.projection.zAxisUnit?this.pixelsPerMeter:1);return \"globe\"===this.projection.name&&e.m.multiply(t,t,this.globeMatrix),t}getFrustum(t){return e.F.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,t,\"meters\"===this.projection.zAxisUnit)}}function Ae(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class Re extends e.a6{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded={},this.requestors=[],this.patterns={},this.atlasImage={},this.atlasTexture={},this.dirty=!0;}createScope(t){this.images[t]={},this.loaded[t]=!1,this.updatedImages[t]={},this.patterns[t]={},this.callbackDispatchedThisFrame[t]={},this.atlasImage[t]=new e.a5({width:1,height:1});}isLoaded(){for(const e in this.loaded)if(!this.loaded[e])return !1;return !0}setLoaded(e,t){if(this.loaded[t]!==e&&(this.loaded[t]=e,e)){for(const{ids:e,callback:i}of this.requestors)this._notify(e,t,i);this.requestors=[];}}hasImage(e,t){return !!this.getImage(e,t)}getImage(e,t){return this.images[t][e]}addImage(e,t,i){this._validate(e,i)&&(this.images[t][e]=i);}_validate(t,i){let o=!0;return this._validateStretch(i.stretchX,i.data&&i.data.width)||(this.fire(new e.a7(new Error(`Image \"${t}\" has invalid \"stretchX\" value`))),o=!1),this._validateStretch(i.stretchY,i.data&&i.data.height)||(this.fire(new e.a7(new Error(`Image \"${t}\" has invalid \"stretchY\" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new e.a7(new Error(`Image \"${t}\" has invalid \"content\" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]=0)r=i;else {const s=t.points[o-4];r=e.aq(s,i,s[2]/(s[2]-i[2]));}if(Ve(this.state,r[0],r[1],0,this._transform)>=Ue)return !0}return !1}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}_validate(t,i,o){return (!o||!1!==o.validate)&&e.ai(this,t.call(e.aj,e.ak({value:i,style:{glyphs:!0,sprite:!0},styleSpec:e.ae})))}}class qe extends e.a6{constructor(t,i,o,r){super(),this.scope=o,this._options=t,this.properties=new e.ar(i),this._transitionable=new e.ag(i,o,new Map(r)),this._transitionable.setTransitionOrValue(t.properties),this._transitioning=this._transitionable.untransitioned();}updateConfig(e){this._transitionable.setTransitionOrValue(this._options.properties,new Map(e));}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(e,t){this._options=e,this._transitionable.setTransitionOrValue(e.properties,t);}shadowsEnabled(){return !!this.properties&&!0===this.properties.get(\"cast-shadows\")}}const $e=new e.ac({color:new e.ad(e.ae.properties_light_ambient.color),intensity:new e.ad(e.ae.properties_light_ambient.intensity)}),Xe=new e.ac({direction:new e.as(e.ae.properties_light_directional.direction),color:new e.ad(e.ae.properties_light_directional.color),intensity:new e.ad(e.ae.properties_light_directional.intensity),\"cast-shadows\":new e.ad(e.ae.properties_light_directional[\"cast-shadows\"]),\"shadow-intensity\":new e.ad(e.ae.properties_light_directional[\"shadow-intensity\"])});class Je{constructor(e,t,i,o){this.screenBounds=e,this.cameraPoint=t,this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=i,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,o);}static createFromScreenPoints(t,i){let o,r;if(t instanceof e.P||\"number\"==typeof t[0]){const s=e.P.convert(t);o=[s],r=i.isPointAboveHorizon(s);}else {const s=e.P.convert(t[0]),n=e.P.convert(t[1]);o=[s,n],r=e.at(s,n).every((e=>i.isPointAboveHorizon(e)));}return new Je(o,i.getCameraPoint(),r,i)}isPointQuery(){return 1===this.screenBounds.length}bufferedScreenGeometry(t){return e.at(this.screenBounds[0],1===this.screenBounds.length?this.screenBounds[0]:this.screenBounds[1],t)}bufferedCameraGeometry(t){const i=this.screenBounds[0],o=1===this.screenBounds.length?this.screenBounds[0].add(new e.P(1,1)):this.screenBounds[1],r=e.at(i,o,0,!1);return this.cameraPoint.y>o.y&&(this.cameraPoint.x>i.x&&this.cameraPoint.x=o.x?r[2]=this.cameraPoint:this.cameraPoint.x<=i.x&&(r[3]=this.cameraPoint)),e.au(r,t)}bufferedCameraGeometryGlobe(t){const i=this.screenBounds[0],o=1===this.screenBounds.length?this.screenBounds[0].add(new e.P(1,1)):this.screenBounds[1],r=e.at(i,o,t),s=this.cameraPoint.clone();switch(3*((s.y>i.y)+(s.y>o.y))+((s.x>i.x)+(s.x>o.x))){case 0:r[0]=s,r[4]=s.clone();break;case 1:r.splice(1,0,s);break;case 2:r[1]=s;break;case 3:r.splice(4,0,s);break;case 5:r.splice(2,0,s);break;case 6:r[3]=s;break;case 7:r.splice(3,0,s);break;case 8:r[2]=s;}return r}containsTile(t,i,o,r=0){const s=t.queryPadding/i._pixelsPerMercatorPixel+1,n=o?this._bufferedCameraMercator(s,i):this._bufferedScreenMercator(s,i);let a=t.tileID.wrap+(n.unwrapped?r:0);const l=n.polygon.map((i=>e.av(t.tileTransform,i,a)));if(!e.aw(l,0,0,e.J,e.J))return;a=t.tileID.wrap+(this.screenGeometryMercator.unwrapped?r:0);const c=this.screenGeometryMercator.polygon.map((i=>e.ax(t.tileTransform,i,a))),h=c.map((t=>new e.P(t[0],t[1]))),_=i.getFreeCameraOptions().position||new e.M(0,0,0),d=e.ax(t.tileTransform,_,a),u=c.map((t=>{const i=e.v.sub(t,t,d);return e.v.normalize(i,i),new e.R(d,i)})),p=e.ay(t,1,i.zoom)*i._pixelsPerMercatorPixel;return {queryGeometry:this,tilespaceGeometry:h,tilespaceRays:u,bufferedTilespaceGeometry:l,bufferedTilespaceBounds:(m=e.az(l),m.min.x=e.c(m.min.x,0,e.J),m.min.y=e.c(m.min.y,0,e.J),m.max.x=e.c(m.max.x,0,e.J),m.max.y=e.c(m.max.y,0,e.J),m),tile:t,tileID:t.tileID,pixelToTileUnitsFactor:p};var m;}_bufferedScreenMercator(e,t){const i=Qe(e);if(this._screenRaycastCache[i])return this._screenRaycastCache[i];{let o;return o=\"globe\"===t.projection.name?this._projectAndResample(this.bufferedScreenGeometry(e),t):{polygon:this.bufferedScreenGeometry(e).map((e=>t.pointCoordinate3D(e))),unwrapped:!0},this._screenRaycastCache[i]=o,o}}_bufferedCameraMercator(e,t){const i=Qe(e);if(this._cameraRaycastCache[i])return this._cameraRaycastCache[i];{let o;return o=\"globe\"===t.projection.name?this._projectAndResample(this.bufferedCameraGeometryGlobe(e),t):{polygon:this.bufferedCameraGeometry(e).map((e=>t.pointCoordinate3D(e))),unwrapped:!0},this._cameraRaycastCache[i]=o,o}}_projectAndResample(t,i){const o=function(t,i){const o=e.m.multiply([],i.pixelMatrix,i.globeMatrix),r=[0,-e.aC,0,1],s=[0,e.aC,0,1],n=[0,0,0,1];e.e.transformMat4(r,r,o),e.e.transformMat4(s,s,o),e.e.transformMat4(n,n,o);const a=new e.P(r[0]/r[3],r[1]/r[3]),l=new e.P(s[0]/s[3],s[1]/s[3]),c=e.aA(t,a)&&r[3]1?Ye(t.slice(0,d),i):[],m=dnew e.P(Ke(t.x),t.y))),m=m.map((t=>new e.P(Ke(t.x),t.y)));const f=[...p];0===f.length&&f.push(m[m.length-1]);const g=e.n(f[f.length-1].y,(0===m.length?p[0]:m[0]).y,u);let v;return v=c?[new e.P(0,g),new e.P(0,0),new e.P(1,0),new e.P(1,g)]:[new e.P(1,g),new e.P(1,1),new e.P(0,1),new e.P(0,g)],f.push(...v),0===m.length?f.push(p[0]):f.push(...m),{polygon:f.map((t=>new e.M(t.x,t.y))),unwrapped:!1}}(t,i);if(o)return o;const r=function(t,i){let o=!1,r=-1/0,s=0;for(let e=0;er&&(r=t[e].x,s=e);for(let e=0;e.5&&(r.x{e.x-=1;})),{polygon:t,unwrapped:o}}(Ye(t,i).map((t=>new e.P(Ke(t.x),t.y))),i);return {polygon:r.polygon.map((t=>new e.M(t.x,t.y))),unwrapped:r.unwrapped}}}function Ye(t,i){return e.aB(t,(e=>{const t=i.pointCoordinate3D(e);e.x=t.x,e.y=t.y;}),1/256)}function Ke(e){return e<0?1+e%1:e%1}function Qe(e){return 100*e|0}function et(t,i,o,r,s){const n=function(o,r){if(o)return s(o);if(r){t.url&&r.tiles&&t.tiles&&delete t.tiles;const o=e.p(e.ak(r,t),[\"tiles\",\"minzoom\",\"maxzoom\",\"attribution\",\"mapbox_logo\",\"bounds\",\"scheme\",\"tileSize\",\"encoding\"]);r.vector_layers&&(o.vectorLayers=r.vector_layers,o.vectorLayerIds=o.vectorLayers.map((e=>e.id))),o.tiles=i.canonicalizeTileset(o,t.url),s(null,o);}};return t.url?e.a1(i.transformRequest(i.normalizeSourceURL(t.url,null,o,r),e.a2.Source),n):e.a4.frame((()=>n(null,t)))}class tt{constructor(t,i,o){this.bounds=e.D.convert(this.validateBounds(t)),this.minzoom=i||0,this.maxzoom=o||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(t){const i=Math.pow(2,t.z),o=Math.floor(e.E(this.bounds.getWest())*i),r=Math.floor(e.H(this.bounds.getNorth())*i),s=Math.ceil(e.E(this.bounds.getEast())*i),n=Math.ceil(e.H(this.bounds.getSouth())*i);return t.x>=o&&t.x=r&&t.y{this._tileJSONRequest=null,this._loaded=!0,r?(i&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${i}`),o&&2!==o.length&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${o}`),this.fire(new e.a7(r))):s&&(e.ak(this,s),s.bounds&&(this.tileBounds=new tt(s.bounds,this.minzoom,this.maxzoom)),e.aH(s.tiles,this.map._requestManager._customAccessToken),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"metadata\"})),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"content\"}))),t&&t(r);}));}loaded(){return this._loaded}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}onAdd(e){this.map=e,this.load();}reload(){this.cancelTileJSONRequest();const t=e.aE(this.id,this.scope);this.load((()=>this.map.style.clearSource(t)));}setTiles(e){return this._options.tiles=e,this.reload(),this}setUrl(e){return this.url=e,this._options.url=e,this.reload(),this}onRemove(){this.cancelTileJSONRequest();}serialize(){return e.ak({},this._options)}loadTile(t,i){const o=this.map._requestManager.normalizeTileURL(t.tileID.canonical.url(this.tiles,this.scheme)),r={request:this.map._requestManager.transformRequest(o,e.a2.Tile),data:void 0,uid:t.uid,tileID:t.tileID,tileZoom:t.tileZoom,zoom:t.tileID.overscaledZ,tileSize:this.tileSize*t.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:e.a4.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,isSymbolTile:t.isSymbolTile,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:t.isExtraShadowCaster};if(r.request.collectResourceTiming=this._collectResourceTiming,t.actor&&\"expired\"!==t.state)\"loading\"===t.state?t.reloadCallback=i:t.request=t.actor.send(\"reloadTile\",r,s.bind(this));else if(t.actor=this._tileWorkers[o]=this._tileWorkers[o]||this.dispatcher.getActor(),this.dispatcher.ready)t.request=t.actor.send(\"loadTile\",r,s.bind(this),void 0,!0);else {const i=e.aF.call({deduped:this._deduped},r,((e,i)=>{e||!i?s.call(this,e):(r.data={cacheControl:i.cacheControl,expires:i.expires,rawData:i.rawData.slice(0)},t.actor&&t.actor.send(\"loadTile\",r,s.bind(this),void 0,!0));}),!0);t.request={cancel:i};}function s(o,r){return delete t.request,t.aborted?i(null):o&&404!==o.status?i(o):(r&&r.resourceTiming&&(t.resourceTiming=r.resourceTiming),this.map._refreshExpiredTiles&&r&&t.setExpiryData(r),t.loadVectorData(r,this.map.painter),e.aG(this.dispatcher),i(null),void(t.reloadCallback&&(this.loadTile(t,t.reloadCallback),t.reloadCallback=null)))}}abortTile(e){e.request&&(e.request.cancel(),delete e.request),e.actor&&e.actor.send(\"abortTile\",{uid:e.uid,type:this.type,source:this.id,scope:this.scope});}unloadTile(e){e.actor&&e.actor.send(\"removeTile\",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy();}hasTransition(){return !1}afterUpdate(){this._tileWorkers={};}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);}}class ot extends e.a6{constructor(t,i,o,r){super(),this.id=t,this.dispatcher=o,this.setEventedParent(r),this.type=\"raster\",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme=\"xyz\",this.tileSize=512,this._loaded=!1,this._options=e.ak({type:\"raster\"},i),e.ak(this,e.p(i,[\"url\",\"scheme\",\"tileSize\"]));}load(t){this._loaded=!1,this.fire(new e.a8(\"dataloading\",{dataType:\"source\"})),this._tileJSONRequest=et(this._options,this.map._requestManager,null,null,((i,o)=>{this._tileJSONRequest=null,this._loaded=!0,i?this.fire(new e.a7(i)):o&&(e.ak(this,o),o.bounds&&(this.tileBounds=new tt(o.bounds,this.minzoom,this.maxzoom)),e.aH(o.tiles),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"metadata\"})),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"content\"}))),t&&t(i);}));}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}reload(){this.cancelTileJSONRequest();const t=e.aE(this.id,this.scope);this.load((()=>this.map.style.clearSource(t)));}setTiles(e){return this._options.tiles=e,this.reload(),this}setUrl(e){return this.url=e,this._options.url=e,this.reload(),this}onRemove(){this.cancelTileJSONRequest();}serialize(){return e.ak({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(t,i){const o=e.a4.devicePixelRatio>=2,r=this.map._requestManager.normalizeTileURL(t.tileID.canonical.url(this.tiles,this.scheme),o,this.tileSize);t.request=e.a3(this.map._requestManager.transformRequest(r,e.a2.Tile),((o,r,s,n)=>(delete t.request,t.aborted?(t.state=\"unloaded\",i(null)):o?(t.state=\"errored\",i(o)):r?(this.map._refreshExpiredTiles&&t.setExpiryData({cacheControl:s,expires:n}),t.setTexture(r,this.map.painter),t.state=\"loaded\",e.aG(this.dispatcher),void i(null)):i(null))));}abortTile(e,t){e.request&&(e.request.cancel(),delete e.request),t();}unloadTile(t,i){t.texture&&t.texture instanceof e.a9?(t.destroy(!0),t.texture&&t.texture instanceof e.a9&&this.map.painter.saveTileTexture(t.texture)):t.destroy(),i();}hasTransition(){return !1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);}}const rt={vector:it,raster:ot,\"raster-dem\":class extends ot{constructor(t,i,o,r){super(t,i,o,r),this.type=\"raster-dem\",this.maxzoom=22,this._options=e.ak({type:\"raster-dem\"},i),this.encoding=i.encoding||\"mapbox\";}loadTile(t,i){const o=this.map._requestManager.normalizeTileURL(t.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);function r(e,o){e&&(t.state=\"errored\",i(e)),o&&(t.dem=o,t.dem.onDeserialize(),t.needsHillshadePrepare=!0,t.needsDEMTextureUpload=!0,t.state=\"loaded\",i(null));}t.request=e.a3(this.map._requestManager.transformRequest(o,e.a2.Tile),function(o,s,n,a){if(delete t.request,t.aborted)t.state=\"unloaded\",i(null);else if(o)t.state=\"errored\",i(o);else if(s){this.map._refreshExpiredTiles&&t.setExpiryData({cacheControl:n,expires:a});const i=ImageBitmap&&s instanceof ImageBitmap&&e.aI(),o=1-(s.width-e.aJ(s.width))/2;o<1||t.neighboringTiles||(t.neighboringTiles=this._getNeighboringTiles(t.tileID));const l=i?s:e.a4.getImageData(s,o),c={uid:t.uid,coord:t.tileID,source:this.id,scope:this.scope,rawImageData:l,encoding:this.encoding,padding:o};t.actor&&\"expired\"!==t.state||(t.actor=this.dispatcher.getActor(),t.actor.send(\"loadDEMTile\",c,r.bind(this),void 0,!0));}}.bind(this));}_getNeighboringTiles(t){const i=t.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,s=0===i.x?t.wrap-1:t.wrap,n=(i.x+1+o)%o,a=i.x+1===o?t.wrap+1:t.wrap,l={};return l[new e.O(t.overscaledZ,s,i.z,r,i.y).key]={backfilled:!1},l[new e.O(t.overscaledZ,a,i.z,n,i.y).key]={backfilled:!1},i.y>0&&(l[new e.O(t.overscaledZ,s,i.z,r,i.y-1).key]={backfilled:!1},l[new e.O(t.overscaledZ,t.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new e.O(t.overscaledZ,a,i.z,n,i.y-1).key]={backfilled:!1}),i.y+1{if(this._loaded=!0,this._pendingLoad=null,t)this.fire(new e.a7(t));else {const t={dataType:\"source\",sourceDataType:this._metadataFired?\"content\":\"metadata\"};this._collectResourceTiming&&i&&i.resourceTiming&&i.resourceTiming[this.id]&&(t.resourceTiming=i.resourceTiming[this.id]),this.fire(new e.a8(\"data\",t)),this._metadataFired=!0;}this._coalesce&&(this._updateWorkerData(),this._coalesce=!1);}));}loaded(){return this._loaded}loadTile(t,i){const o=t.actor?\"reloadTile\":\"loadTile\";t.actor=this.actor;const r={type:this.type,uid:t.uid,tileID:t.tileID,tileZoom:t.tileZoom,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,scope:this.scope,pixelRatio:e.a4.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0};t.request=this.actor.send(o,r,((e,r)=>(delete t.request,t.destroy(),t.aborted?i(null):e?i(e):(t.loadVectorData(r,this.map.painter,\"reloadTile\"===o),i(null)))),void 0,\"loadTile\"===o);}abortTile(e){e.request&&(e.request.cancel(),delete e.request),e.aborted=!0;}unloadTile(e){this.actor.send(\"removeTile\",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy();}onRemove(){this._pendingLoad&&this._pendingLoad.cancel();}serialize(){return e.ak({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}},video:class extends e.aK{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type=\"video\",this.options=t;}load(){this._loaded=!1;const t=this.options;this.urls=[];for(const i of t.urls)this.urls.push(this.map._requestManager.transformRequest(i,e.a2.Source).url);e.aL(this.urls,((t,i)=>{this._loaded=!0,t?this.fire(new e.a7(t)):i&&(this.video=i,this.video.loop=!0,this.video.setAttribute(\"playsinline\",\"\"),this.video.addEventListener(\"playing\",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading());}));}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(t){if(this.video){const i=this.video.seekable;ti.end(0)?this.fire(new e.a7(new e.aM(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=t;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const t=this.map.painter.context,i=t.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new e.a9(t,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(t);}serialize(){return {type:\"video\",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:e.aK,model:class extends e.a6{constructor(e,t,i,o){super(),this.id=e,this.type=\"model\",this.models=[],this._loaded=!1,this._options=t;}load(){const t=[];for(const i in this._options.models){const o=this._options.models[i],r=e.aO(this.map._requestManager.transformRequest(o.uri,e.a2.Model).url).then((t=>{if(!t)return;const r=e.aP(t),s=new e.aQ(i,o.position,o.orientation,r);s.computeBoundsAndApplyParent(),this.models.push(s);})).catch((t=>{this.fire(new e.a7(new Error(`Could not load model ${i} from ${o.uri}: ${t.message}`)));}));t.push(r);}return Promise.allSettled(t).then((()=>{this._loaded=!0,this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"metadata\"}));})).catch((t=>{this.fire(new e.a7(new Error(`Could not load models: ${t.message}`)));}))}onAdd(e){this.map=e,this.load();}hasTransition(){return !1}loaded(){return this._loaded}getModels(){return this.models}loadTile(e,t){}serialize(){return {type:\"model\"}}},\"batched-model\":class extends e.a6{constructor(e,t,i,o){super(),this.type=\"batched-model\",this.id=e,this.tileSize=512,this._options=t,this.tiles=this._options.tiles,this.maxzoom=t.maxzoom||19,this.minzoom=t.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=i,this.reparseOverscaled=!1,this.scheme=\"xyz\",this._loaded=!1,this.setEventedParent(o);}onAdd(e){this.map=e,this.load();}load(t){this._loaded=!1,this.fire(new e.a8(\"dataloading\",{dataType:\"source\"}));const i=Array.isArray(this.map._language)?this.map._language.join():this.map._language,o=this.map._worldview;this._tileJSONRequest=et(this._options,this.map._requestManager,i,o,((r,s)=>{this._tileJSONRequest=null,this._loaded=!0,r?(i&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${i}`),o&&2!==o.length&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${o}`),this.fire(new e.a7(r))):s&&(e.ak(this,s),s.bounds&&(this.tileBounds=new tt(s.bounds,this.minzoom,this.maxzoom)),e.aH(s.tiles,this.map._requestManager._customAccessToken),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"metadata\"})),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"content\"}))),t&&t(r);}));}hasTransition(){return !1}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loaded(){return this._loaded}loadTile(t,i){const o=this.map._requestManager.normalizeTileURL(t.tileID.canonical.url(this.tiles,this.scheme)),r={request:this.map._requestManager.transformRequest(o,e.a2.Tile),data:void 0,uid:t.uid,tileID:t.tileID,tileZoom:t.tileZoom,zoom:t.tileID.overscaledZ,tileSize:this.tileSize*t.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,isSymbolTile:t.isSymbolTile,brightness:this.map.style&&this.map.style.getBrightness()||0};if(t.actor&&\"expired\"!==t.state)if(\"loading\"===t.state)t.reloadCallback=i;else {if(t.buckets){const e=Object.values(t.buckets);for(const t of e)t.dirty=!0;return void(t.state=\"loaded\")}t.request=t.actor.send(\"reloadTile\",r,s.bind(this));}else t.actor=this.dispatcher.getActor(),t.request=t.actor.send(\"loadTile\",r,s.bind(this),void 0,!0);function s(e,o){return t.aborted?i(null):e&&404!==e.status?i(e):(o&&(o.resourceTiming&&(t.resourceTiming=o.resourceTiming),this.map._refreshExpiredTiles&&t.setExpiryData(o),t.buckets={...t.buckets,...o.buckets}),t.state=\"loaded\",void i(null))}}serialize(){return e.ak({},this._options)}},canvas:class extends e.aK{constructor(t,i,o,r){super(t,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>\"number\"!=typeof e))))||this.fire(new e.a7(new e.aM(`sources.${t}`,null,'\"coordinates\" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new e.a7(new e.aM(`sources.${t}`,null,'missing required property \"coordinates\"'))),i.animate&&\"boolean\"!=typeof i.animate&&this.fire(new e.a7(new e.aM(`sources.${t}`,null,'optional \"animate\" property must be a boolean value'))),i.canvas?\"string\"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new e.a7(new e.aM(`sources.${t}`,null,'\"canvas\" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new e.a7(new e.aM(`sources.${t}`,null,'missing required property \"canvas\"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new e.a7(new Error(\"Canvas dimensions cannot be less than or equal to zero.\"))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context;this.texture?!t&&!this._playing||this.texture instanceof e.aN||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new e.a9(i,this.canvas,i.gl.RGBA,{premultiply:!0}),this._prepareData(i);}serialize(){return {type:\"canvas\",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}},custom:class extends e.a6{constructor(t,i,o,r){super(),this.id=t,this.type=\"custom\",this._dataType=\"raster\",this._dispatcher=o,this._implementation=i,this.setEventedParent(r),this.scheme=\"xyz\",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new e.a7(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new e.a7(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new tt(this._implementation.bounds,this.minzoom,this.maxzoom)),i.update=this._update.bind(this),i.clearTiles=this._clearTiles.bind(this),i.coveringTiles=this._coveringTiles.bind(this),e.ak(this,e.p(i,[\"dataType\",\"scheme\",\"minzoom\",\"maxzoom\",\"tileSize\",\"attribution\",\"minTileCacheSize\",\"maxTileCacheSize\"]));}serialize(){return e.p(this,[\"type\",\"scheme\",\"minzoom\",\"maxzoom\",\"tileSize\",\"attribution\"])}load(){this._loaded=!0,this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"metadata\"})),this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"content\"}));}loaded(){return this._loaded}onAdd(t){this._map=t,this._loaded=!1,this.fire(new e.a8(\"dataloading\",{dataType:\"source\"})),this._implementation.onAdd&&this._implementation.onAdd(t),this.load();}onRemove(e){this._implementation.onRemove&&this._implementation.onRemove(e);}hasTile(e){if(this._implementation.hasTile){const{x:t,y:i,z:o}=e.canonical;return this._implementation.hasTile({x:t,y:i,z:o})}return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e,t){const{x:i,y:o,z:r}=e.tileID.canonical,s=new AbortController;e.request=Promise.resolve(this._implementation.loadTile({x:i,y:o,z:r},{signal:s.signal})).then(function(i){return delete e.request,e.aborted?(e.state=\"unloaded\",t(null)):void 0===i?(e.state=\"errored\",t(null)):null===i?(this.loadTileData(e,{width:this.tileSize,height:this.tileSize,data:null}),e.state=\"loaded\",t(null)):function(e){return e instanceof ImageData||e instanceof HTMLCanvasElement||e instanceof ImageBitmap||e instanceof HTMLImageElement}(i)?(this.loadTileData(e,i),e.state=\"loaded\",void t(null)):(e.state=\"errored\",t(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}.bind(this)).catch((i=>{20!==i.code&&(e.state=\"errored\",t(i));})),e.request.cancel=()=>s.abort();}loadTileData(e,t){e.setTexture(t,this._map.painter);}unloadTile(t,i){if(t.texture&&t.texture instanceof e.a9?(t.destroy(!0),t.texture&&t.texture instanceof e.a9&&this._map.painter.saveTileTexture(t.texture)):t.destroy(),this._implementation.unloadTile){const{x:e,y:i,z:o}=t.tileID.canonical;this._implementation.unloadTile({x:e,y:i,z:o});}i();}abortTile(e,t){e.request&&e.request.cancel&&(e.request.cancel(),delete e.request),t();}hasTransition(){return !1}_coveringTiles(){return this._map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map((e=>({x:e.canonical.x,y:e.canonical.y,z:e.canonical.z})))}_clearTiles(){const t=e.aE(this.id,this.scope);this._map.style.clearSource(t);}_update(){this.fire(new e.a8(\"data\",{dataType:\"source\",sourceDataType:\"content\"}));}}},st=function(t,i,o,r){const s=new rt[i.type](t,i,o,r);if(s.id!==t)throw new Error(`Expected Source id to be ${t} instead of ${s.id}`);return e.aR([\"load\",\"abort\",\"unload\",\"serialize\",\"prepare\"],s),s};function nt(t,i){const o=e.m.identity([]);return e.m.scale(o,o,[.5*t.width,.5*-t.height,1]),e.m.translate(o,o,[1,-1,0]),e.m.multiply(o,o,t.calculateProjMatrix(i.toUnwrapped())),Float32Array.from(o)}function at(e,t,i,o,r,s,n,a=!1){const l=e.tilesIn(o,n,a);l.sort(ct);const c=[];for(const o of l)c.push({wrappedTileID:o.tile.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o,r,s,nt(e.transform,o.tile.tileID),a)});const h=function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,s=i[r]=i[r]||{};for(const i in e){const o=e[i],r=s[i]=s[i]||{},n=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,n.push(e));}}return t}(c);for(const t in h)h[t].forEach((t=>{const i=t.feature,o=i.layer;o&&\"background\"!==o.type&&\"sky\"!==o.type&&\"slot\"!==o.type&&(i.source=o.source,o[\"source-layer\"]&&(i.sourceLayer=o[\"source-layer\"]),i.state=void 0!==i.id?e.getFeatureState(o[\"source-layer\"],i.id):{});}));return h}function lt(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;e0?i.paint.get(\"fill-extrusion-vertical-scale\"):0);let s=o?o.getTile(t):null;if(!s&&o&&t.canonical.z>o.getSource().minzoom){let e=t.scaledTo(Math.min(o.getSource().maxzoom,t.overscaledZ-1));for(;e.overscaledZ>=o.getSource().minzoom&&(s=o.getTile(e),!s&&0!==e.overscaledZ);)e=e.scaledTo(e.overscaledZ-1);}this.currentBuildingBuckets.push({bucket:s?s.getBucket(i):null,tileID:s?s.tileID:t,verticalScale:r});}e.hasAnyZOffset=!1;let i=!1;for(let o=0;o{e in i&&(o[e]=i[e]);})),o}function dt(e){e=e.slice();const t=Object.create(null);for(let i=0;i0?(r-n)/a:0;return this.points[s].mult(1-l).add(this.points[i].mult(l))}}class wt{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return !r&&[];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return !0;for(let e=0;e0:n}_queryCircle(e,t,i,o,r){const s=e-i,n=e+i,a=t-i,l=t+i;if(n<0||s>this.width||l<0||a>this.height)return !o&&[];const c=[];return this._forEachCell(s,a,n,l,this._queryCellCircle,c,{hitTest:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),o?c.length>0:c}query(e,t,i,o,r){return this._query(e,t,i,o,!1,r)}hitTest(e,t,i,o,r){return this._query(e,t,i,o,!0,r)}hitTestCircle(e,t,i,o){return this._queryCircle(e,t,i,!0,o)}_queryCell(e,t,i,o,r,s,n,a){const l=n.seenUids,c=this.boxCells[r];if(null!==c){const r=this.bboxes;for(const h of c)if(!l.box[h]){l.box[h]=!0;const c=4*h;if(e<=r[c+2]&&t<=r[c+3]&&i>=r[c+0]&&o>=r[c+1]&&(!a||a(this.boxKeys[h]))){if(n.hitTest)return s.push(!0),!0;s.push({key:this.boxKeys[h],x1:r[c],y1:r[c+1],x2:r[c+2],y2:r[c+3]});}}}const h=this.circleCells[r];if(null!==h){const r=this.circles;for(const c of h)if(!l.circle[c]){l.circle[c]=!0;const h=3*c;if(this._circleAndRectCollide(r[h],r[h+1],r[h+2],e,t,i,o)&&(!a||a(this.circleKeys[c]))){if(n.hitTest)return s.push(!0),!0;{const e=r[h],t=r[h+1],i=r[h+2];s.push({key:this.circleKeys[c],x1:e-i,y1:t-i,x2:e+i,y2:t+i});}}}}}_queryCellCircle(e,t,i,o,r,s,n,a){const l=n.circle,c=n.seenUids,h=this.boxCells[r];if(null!==h){const e=this.bboxes;for(const t of h)if(!c.box[t]){c.box[t]=!0;const i=4*t;if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!a||a(this.boxKeys[t])))return s.push(!0),!0}}const _=this.circleCells[r];if(null!==_){const e=this.circles;for(const t of _)if(!c.circle[t]){c.circle[t]=!0;const i=3*t;if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!a||a(this.circleKeys[t])))return s.push(!0),!0}}}_forEachCell(e,t,i,o,r,s,n,a){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),_=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=_;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,s,n,a))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,s){const n=o-e,a=r-t,l=i+s;return l*l>n*n+a*a}_circleAndRectCollide(e,t,i,o,r,s,n){const a=(s-o)/2,l=Math.abs(e-(o+a));if(l>a+i)return !1;const c=(n-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=a||h<=c)return !0;const _=l-a,d=h-c;return _*_+d*d<=i*i}}const Tt=100;class Et{constructor(e,t,i=new wt(e.width+200,e.height+200,25),o=new wt(e.width+200,e.height+200,25)){this.transform=e,this.grid=i,this.ignoredGrid=o,this.pitchfactor=Math.cos(e._pitch)*e.cameraToCenterDistance,this.screenRightBoundary=e.width+Tt,this.screenBottomBoundary=e.height+Tt,this.gridRightBoundary=e.width+200,this.gridBottomBoundary=e.height+200,this.fogState=t;}placeCollisionBox(e,t,i,o,r,s,n,a){let l=i.projectedAnchorX,c=i.projectedAnchorY,h=i.projectedAnchorZ;const _=i.elevation,d=i.tileID,u=e.getProjection();if(_&&d){const[e,t,o]=u.upVector(d.canonical,i.tileAnchorX,i.tileAnchorY),r=u.upVectorScale(d.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;l+=e*_*r,c+=t*_*r,h+=o*_*r;}const p=this.projectAndGetPerspectiveRatio(n,l,c,h,i.tileID,\"globe\"===u.name||!!_||this.transform.pitch>0,u),m=s*p.perspectiveRatio,f=(i.x1*t+o.x-i.padding)*m+p.point.x,g=(i.y1*t+o.y-i.padding)*m+p.point.y,v=(i.x2*t+o.x+i.padding)*m+p.point.x,x=(i.y2*t+o.y+i.padding)*m+p.point.y,y=p.perspectiveRatio<=.55||p.occluded;return !this.isInsideGrid(f,g,v,x)||!r&&this.grid.hitTest(f,g,v,x,a)||y?{box:[],offscreen:!1,occluded:p.occluded}:{box:[f,g,v,x],offscreen:this.isOffscreen(f,g,v,x),occluded:!1}}placeCollisionCircles(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m){const f=[],g=this.transform.elevation,v=t.getProjection(),x=g?g.getAtTileOffsetFunc(m,this.transform.center.lat,this.transform.worldSize,v):null,y=new e.P(o.tileAnchorX,o.tileAnchorY);let{x:b,y:w,z:T}=v.projectTilePoint(y.x,y.y,m.canonical);if(x){const[e,t,i]=x(y);b+=e,w+=t,T+=i;}const E=\"globe\"===v.name,C=this.projectAndGetPerspectiveRatio(a,b,w,T,m,E||!!g||this.transform.pitch>0,v),{perspectiveRatio:I}=C,S=(_?n/I:n*I)/e.aV,M=ge(b,w,T,l),L=C.signedDistanceFromCamera>0?be(S,s,o.lineOffsetX*S,o.lineOffsetY*S,!1,M,y,o,r,l,{},g&&!_?x:null,_&&!!g,v,m,_):null;let P=!1,D=!1,A=!0;if(L&&!C.occluded){const t=.5*u*I+p,o=new e.P(-100,-100),r=new e.P(this.screenRightBoundary,this.screenBottomBoundary),s=new bt,{first:n,last:a}=L,l=n.path.length;let _=[];for(let e=l-1;e>=1;e--)_.push(n.path[e]);for(let e=1;e(x&&!E&&(i=x(oe[3]<=0))&&(_=[]));let g=[];if(_.length>0){let t=1/0,i=-1/0,s=1/0,n=-1/0;for(const e of _)t=Math.min(t,e[0]),s=Math.min(s,e[1]),i=Math.max(i,e[0]),n=Math.max(n,e[1]);i>=o.x&&t<=r.x&&n>=o.y&&s<=r.y&&(g=[_.map((t=>new e.P(t[0],t[1])))],(tr.x||sr.y)&&(g=e.aT(g,o.x,o.y,r.x,r.y)));}for(const e of g){s.reset(e,.25*t);let o=0;o=s.length<=.5*t?1:Math.ceil(s.paddedLength/m)+1;for(let e=0;e0){if(e.e.transformMat4(l,l,t),this.fogState&&s&&\"globe\"!==a.name){const t=function(t,i,o,r,s,n){const a=n.calculateFogTileMatrix(s),l=[i,o,r];return e.v.transformMat4(l,l,a),Ge(t,e.v.length(l),n.pitch,n._fov)}(this.fogState,i,o,r,s.toUnwrapped(),this.transform);c=t>.9;}}else Me(l,l,t);const h=l[3];return {point:new e.P((l[0]/h+1)/2*this.transform.width+Tt,(-l[1]/h+1)/2*this.transform.height+Tt),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(a)/h*.5,1.5),signedDistanceFromCamera:h,occluded:n&&l[2]>h||c}}isOffscreen(e,t,i,o){return i=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&te.collisionGroupID===t};}return this.collisionGroups[e]}}function zt(t,i,o,r,s){const{horizontalAlign:n,verticalAlign:a}=e.aY(t),l=-(n-.5)*i,c=-(a-.5)*o,h=e.aW(t,r);return new e.P(l+h[0]*s,c+h[1]*s)}function Ot(t,i,o,r,s){const n=new e.P(t,i);return o&&n._rotate(r?s:-s),n}class Ft{constructor(e,t,i,o,r,s){this.transform=e.clone(),this.projection=e.projection.name,this.collisionIndex=new Et(this.transform,r),this.buildingIndex=s,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=t,this.retainedQueryData={},this.collisionGroups=new Rt(i),this.collisionCircleArrays={},this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};}getBucketParts(t,i,o,r){const s=o.getBucket(i),n=o.latestFeatureIndex;if(!s||!n||i.fqid!==s.layerIds[0])return;const a=s.layers[0].layout,l=o.collisionBoxArray,c=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),h=o.tileSize/e.J,_=o.tileID.toUnwrapped();this.transform.setProjection(s.projection);const d=(u=o.tileID,p=s.getProjection(),m=this.transform,p.name===this.projection?m.calculateProjMatrix(u.toUnwrapped()):Ct(m,p,u));var u,p,m;const f=\"map\"===a.get(\"text-pitch-alignment\"),g=\"map\"===a.get(\"text-rotation-alignment\");i.compileFilter();const v=i.dynamicFilter(),x=i.dynamicFilterNeedsFeature(),y=this.transform.calculatePixelsToTileUnitsMatrix(o),b=me(d,o.tileID.canonical,f,g,this.transform,s.getProjection(),y);let w=null;if(f){const t=fe(d,o.tileID.canonical,f,g,this.transform,s.getProjection(),y);w=e.m.multiply([],this.transform.labelPlaneMatrix,t);}let T=null;v&&o.latestFeatureIndex&&(T={unwrappedTileID:_,dynamicFilter:v,dynamicFilterNeedsFeature:x,featureIndex:o.latestFeatureIndex}),this.retainedQueryData[s.bucketInstanceId]=new At(s.bucketInstanceId,n,s.sourceLayerIndex,s.index,o.tileID);const E={bucket:s,layout:a,posMatrix:d,textLabelPlaneMatrix:b,labelToScreenMatrix:w,clippingData:T,scale:c,textPixelRatio:h,holdingForFade:o.holdingForFade(),collisionBoxArray:l,partiallyEvaluatedTextSize:e.i(s.textSizeData,this.transform.zoom),partiallyEvaluatedIconSize:e.i(s.iconSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(s.sourceID)};if(r)for(const e of s.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=e;t.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:E});}else t.push({symbolInstanceStart:0,symbolInstanceEnd:s.symbolInstances.length,parameters:E});}attemptAnchorPlacement(e,t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f,g){const{textOffset0:v,textOffset1:x,crossTileID:y}=_,b=[v,x],w=zt(e,i,o,b,r),T=this.collisionIndex.placeCollisionBox(u,r,t,Ot(w.x,w.y,s,n,this.transform.angle),h,a,l,c.predicate);if(m){const e=u.getSymbolInstanceIconSize(g,this.transform.zoom,_.placedIconSymbolIndex);if(0===this.collisionIndex.placeCollisionBox(u,e,m,Ot(w.x,w.y,s,n,this.transform.angle),h,a,l,c.predicate).box.length)return}if(T.box.length>0){let t;return this.prevPlacement&&this.prevPlacement.variableOffsets[y]&&this.prevPlacement.placements[y]&&this.prevPlacement.placements[y].text&&(t=this.prevPlacement.variableOffsets[y].anchor),this.variableOffsets[y]={textOffset:b,width:i,height:o,anchor:e,textScale:r,prevAnchor:t},this.markUsedJustification(u,e,_,p),u.allowVerticalPlacement&&(this.markUsedOrientation(u,p,_),this.placedOrientations[y]=p),{shift:w,placedGlyphBoxes:T}}}placeLayerBucketPart(t,i,o,r){const{bucket:s,layout:n,posMatrix:a,textLabelPlaneMatrix:l,labelToScreenMatrix:c,clippingData:h,textPixelRatio:_,holdingForFade:d,collisionBoxArray:u,partiallyEvaluatedTextSize:p,partiallyEvaluatedIconSize:m,collisionGroup:f}=t.parameters,g=n.get(\"text-optional\"),v=n.get(\"icon-optional\"),x=n.get(\"text-allow-overlap\"),y=n.get(\"icon-allow-overlap\"),b=\"map\"===n.get(\"text-rotation-alignment\"),w=\"map\"===n.get(\"text-pitch-alignment\"),T=\"viewport-y\"===n.get(\"symbol-z-order\"),E=n.get(\"symbol-z-elevate\");this.transform.setProjection(s.projection);let C=x&&(y||!s.hasIconData()||v),I=y&&(x||!s.hasTextData()||g);!s.collisionArrays&&u&&s.deserializeCollisionBoxes(u),o&&r&&s.updateCollisionDebugBuffers(this.transform.zoom,u);const S=(t,r,u)=>{const{crossTileID:T,numVerticalGlyphVertices:E}=t;if(h){const o={zoom:this.transform.zoom,pitch:this.transform.pitch};let r=null;if(h.dynamicFilterNeedsFeature){const e=this.retainedQueryData[s.bucketInstanceId];r=h.featureIndex.loadFeature({featureIndex:t.featureIndex,bucketIndex:e.bucketIndex,sourceLayerIndex:e.sourceLayerIndex,layoutVertexArrayOffset:0});}if(!(0,h.dynamicFilter)(o,r,this.retainedQueryData[s.bucketInstanceId].tileID.canonical,new e.P(t.tileAnchorX,t.tileAnchorY),this.transform.calculateDistanceTileData(h.unwrappedTileID)))return this.placements[T]=new Pt(!1,!1,!1,!0),void i.add(T)}if(i.has(T))return;if(d)return void(this.placements[T]=new Pt(!1,!1,!1));let S=!1,M=!1,L=!0,P=!1,D=!1,A=null,R={box:null,offscreen:null,occluded:null},z={box:null,offscreen:null,occluded:null},O=null,F=null,B=null,k=0,N=0,U=0;u.textFeatureIndex?k=u.textFeatureIndex:t.useRuntimeCollisionCircles&&(k=t.featureIndex),u.verticalTextFeatureIndex&&(N=u.verticalTextFeatureIndex);const G=e=>{e.tileID=this.retainedQueryData[s.bucketInstanceId].tileID;const i=this.transform.elevation;e.elevation=t.zOffset+(i?i.getAtTileOffset(e.tileID,e.tileAnchorX,e.tileAnchorY):0);},j=u.textBox;if(j){G(j);const i=i=>{let o=e.W.horizontal;if(s.allowVerticalPlacement&&!i&&this.prevPlacement){const e=this.prevPlacement.placedOrientations[T];e&&(this.placedOrientations[T]=e,o=e,this.markUsedOrientation(s,o,t));}return o},o=(t,i)=>{if(s.allowVerticalPlacement&&E>0&&u.verticalTextBox){for(const o of s.writingModes)if(o===e.W.vertical?(R=i(),z=R):R=t(),R&&R.box&&R.box.length)break}else R=t();};if(n.get(\"text-variable-anchor\")){let l=n.get(\"text-variable-anchor\");if(this.prevPlacement&&this.prevPlacement.variableOffsets[T]){const e=this.prevPlacement.variableOffsets[T];l.indexOf(e.anchor)>0&&(l=l.filter((t=>t!==e.anchor)),l.unshift(e.anchor));}const c=(e,i,o)=>{const n=s.getSymbolInstanceTextSize(p,t,this.transform.zoom,r),c=(e.x2-e.x1)*n+2*e.padding,h=(e.y2-e.y1)*n+2*e.padding,d=t.hasIconTextFit&&!y?i:null;d&&G(d);let u={box:[],offscreen:!1,occluded:!1};const g=x?2*l.length:l.length;for(let i=0;i=l.length,t,r,s,o,d,p,m);if(g&&(u=g.placedGlyphBoxes,u&&u.box&&u.box.length)){S=!0,A=g.shift;break}}return u};o((()=>c(j,u.iconBox,e.W.horizontal)),(()=>{const t=u.verticalTextBox;return t&&G(t),s.allowVerticalPlacement&&!(R&&R.box&&R.box.length)&&E>0&&t?c(t,u.verticalIconBox,e.W.vertical):{box:null,offscreen:null,occluded:null}})),R&&(S=R.box,L=R.offscreen,P=R.occluded);const h=i(!(!R||!R.box));if(!S&&this.prevPlacement){const e=this.prevPlacement.variableOffsets[T];e&&(this.variableOffsets[T]=e,this.markUsedJustification(s,e.anchor,t,h));}}else {const n=(i,o)=>{const n=s.getSymbolInstanceTextSize(p,t,this.transform.zoom,r),l=this.collisionIndex.placeCollisionBox(s,n,i,new e.P(0,0),x,_,a,f.predicate);return l&&l.box&&l.box.length&&(this.markUsedOrientation(s,o,t),this.placedOrientations[T]=o),l};o((()=>n(j,e.W.horizontal)),(()=>{const t=u.verticalTextBox;return s.allowVerticalPlacement&&E>0&&t?(G(t),n(t,e.W.vertical)):{box:null,offscreen:null,occluded:null}})),i(!!(R&&R.box&&R.box.length));}}if(O=R,S=O&&O.box&&O.box.length>0,L=O&&O.offscreen,P=O&&O.occluded,t.useRuntimeCollisionCircles){const i=s.text.placedSymbolArray.get(t.centerJustifiedTextSymbolIndex>=0?t.centerJustifiedTextSymbolIndex:t.verticalPlacedTextSymbolIndex),r=e.j(s.textSizeData,p,i),h=n.get(\"text-padding\");F=this.collisionIndex.placeCollisionCircles(s,x,i,s.lineVertexArray,s.glyphOffsetArray,r,a,l,c,o,w,f.predicate,t.collisionCircleDiameter*r/e.aV,h,this.retainedQueryData[s.bucketInstanceId].tileID),S=x||F.circles.length>0&&!F.collisionDetected,L=L&&F.offscreen,P=F.occluded;}if(u.iconFeatureIndex&&(U=u.iconFeatureIndex),u.iconBox){const i=i=>{G(i);const o=t.hasIconTextFit&&A?Ot(A.x,A.y,b,w,this.transform.angle):new e.P(0,0),r=s.getSymbolInstanceIconSize(m,this.transform.zoom,t.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(s,r,i,o,y,_,a,f.predicate)};z&&z.box&&z.box.length&&u.verticalIconBox?(B=i(u.verticalIconBox),M=B.box.length>0):(B=i(u.iconBox),M=B.box.length>0),L=L&&B.offscreen,D=B.occluded;}const V=g||0===t.numHorizontalGlyphVertices&&0===E,Z=v||0===t.numIconVertices;if(V||Z?Z?V||(M=M&&S):S=M&&S:M=S=M&&S,S&&O&&O.box&&this.collisionIndex.insertCollisionBox(O.box,n.get(\"text-ignore-placement\"),s.bucketInstanceId,z&&z.box&&N?N:k,f.ID),M&&B&&this.collisionIndex.insertCollisionBox(B.box,n.get(\"icon-ignore-placement\"),s.bucketInstanceId,U,f.ID),F&&(S&&this.collisionIndex.insertCollisionCircles(F.circles,n.get(\"text-ignore-placement\"),s.bucketInstanceId,k,f.ID),o)){const e=s.bucketInstanceId;let t=this.collisionCircleArrays[e];void 0===t&&(t=this.collisionCircleArrays[e]=new Dt);for(let e=0;e=0;--e){const i=t[e];S(s.symbolInstances.get(i),i,s.collisionArrays[i]);}s.hasAnyZOffset&&e.X(`${s.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`);}else if(s.hasAnyZOffset){const e=s.getSortedIndexesByZOffset();for(let t=0;t=0&&(t.text.placedSymbolArray.get(s).crossTileID=_>=0&&s!==_?0:c),n>=0&&(t.text.placedSymbolArray.get(n).crossTileID=_>=0&&n!==_?0:c),a>=0&&(t.text.placedSymbolArray.get(a).crossTileID=_>=0&&a!==_?0:c),l>=0&&(t.text.placedSymbolArray.get(l).crossTileID=_>=0&&l!==_?0:c);}markUsedOrientation(t,i,o){const r=i===e.W.horizontal||i===e.W.horizontalOnly?i:0,s=i===e.W.vertical?i:0,{leftJustifiedTextSymbolIndex:n,centerJustifiedTextSymbolIndex:a,rightJustifiedTextSymbolIndex:l,verticalPlacedTextSymbolIndex:c}=o,h=t.text.placedSymbolArray;n>=0&&(h.get(n).placedOrientation=r),a>=0&&(h.get(a).placedOrientation=r),l>=0&&(h.get(l).placedOrientation=r),c>=0&&(h.get(c).placedOrientation=s);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},s=t?t.variableOffsets:{},n=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],s=r[e];s?(this.opacities[e]=new Lt(s,o,t.text,t.icon,null,t.clipped),i=i||t.text!==s.text.placed||t.icon!==s.icon.placed):(this.opacities[e]=new Lt(null,o,t.text,t.icon,t.skipFade,t.clipped),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Lt(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in s)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=s[e]);for(const e in n)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=n[e]);i?this.lastPlacementChangeTime=e:\"number\"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i=new Set;for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.fqid===t.layerIds[0]&&(this.updateBucketOpacities(t,i,o.collisionBoxArray),t.layers[0].layout.get(\"symbol-z-elevate\")&&this.buildingIndex&&(this.buildingIndex.updateZOffset(t,o.tileID),t.updateZOffset()));}}updateBucketOpacities(t,i,o){t.hasTextData()&&t.text.opacityVertexArray.clear(),t.hasIconData()&&t.icon.opacityVertexArray.clear(),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexArray.clear(),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexArray.clear();const r=t.layers[0].layout,s=!!t.layers[0].dynamicFilter(),n=new Lt(null,0,!1,!1,!0),a=r.get(\"text-allow-overlap\"),l=r.get(\"icon-allow-overlap\"),c=r.get(\"text-variable-anchor\"),h=\"map\"===r.get(\"text-rotation-alignment\"),_=\"map\"===r.get(\"text-pitch-alignment\"),d=new Lt(null,0,a&&(l||!t.hasIconData()||r.get(\"icon-optional\")),l&&(a||!t.hasTextData()||r.get(\"text-optional\")),!0);!t.collisionArrays&&o&&(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData())&&t.deserializeCollisionBoxes(o);const u=(e,t,i)=>{for(let o=0;o0||l>0,y=f>0,b=this.placedOrientations[m],w=b===e.W.vertical,T=b===e.W.horizontal||b===e.W.horizontalOnly;if(!x&&!y||v.isHidden()||p++,x){const e=Wt(v.text);u(t.text,a,w?Ht:e),u(t.text,l,T?Ht:e);const i=v.text.isHidden(),{leftJustifiedTextSymbolIndex:o,centerJustifiedTextSymbolIndex:s,rightJustifiedTextSymbolIndex:n,verticalPlacedTextSymbolIndex:c}=r,h=t.text.placedSymbolArray,_=i||w?1:0;o>=0&&(h.get(o).hidden=_),s>=0&&(h.get(s).hidden=_),n>=0&&(h.get(n).hidden=_),c>=0&&(h.get(c).hidden=i||T?1:0);const d=this.variableOffsets[m];d&&this.markUsedJustification(t,d.anchor,r,b);const p=this.placedOrientations[m];p&&(this.markUsedJustification(t,\"left\",r,p),this.markUsedOrientation(t,p,r));}if(y){const e=Wt(v.icon),{placedIconSymbolIndex:i,verticalPlacedIconSymbolIndex:o}=r,s=t.icon.placedSymbolArray,n=v.icon.isHidden()?1:0;i>=0&&(u(t.icon,f,w?Ht:e),s.get(i).hidden=n),o>=0&&(u(t.icon,r.numVerticalIconVertices,T?Ht:e),s.get(o).hidden=n);}if(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData()){const i=t.collisionArrays[o];if(i){let o=new e.P(0,0),n=!0;if(i.textBox||i.verticalTextBox){if(c){const e=this.variableOffsets[m];e?(o=zt(e.anchor,e.width,e.height,e.textOffset,e.textScale),h&&o._rotate(_?this.transform.angle:-this.transform.angle)):n=!1;}s&&(n=!v.clipped),i.textBox&&Bt(t.textCollisionBox.collisionVertexArray,v.text.placed,!n||w,o.x,o.y),i.verticalTextBox&&Bt(t.textCollisionBox.collisionVertexArray,v.text.placed,!n||T,o.x,o.y);}const a=n&&Boolean(!T&&i.verticalIconBox);i.iconBox&&Bt(t.iconCollisionBox.collisionVertexArray,v.icon.placed,a,r.hasIconTextFit?o.x:0,r.hasIconTextFit?o.y:0),i.verticalIconBox&&Bt(t.iconCollisionBox.collisionVertexArray,v.icon.placed,!a,r.hasIconTextFit?o.x:0,r.hasIconTextFit?o.y:0);}}}if(t.fullyClipped=0===p,t.sortFeatures(this.transform.angle),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexBuffer&&t.iconCollisionBox.collisionVertexBuffer.updateData(t.iconCollisionBox.collisionVertexArray),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexBuffer&&t.textCollisionBox.collisionVertexBuffer.updateData(t.textCollisionBox.collisionVertexArray),t.bucketInstanceId in this.collisionCircleArrays){const e=this.collisionCircleArrays[t.bucketInstanceId];t.placementInvProjMatrix=e.invProjMatrix,t.placementViewportMatrix=e.viewportMatrix,t.collisionCircleArray=e.circles,delete this.collisionCircleArrays[t.bucketInstanceId];}}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function Bt(e,t,i,o,r){e.emplaceBack(t?1:0,i?1:0,o||0,r||0),e.emplaceBack(t?1:0,i?1:0,o||0,r||0),e.emplaceBack(t?1:0,i?1:0,o||0,r||0),e.emplaceBack(t?1:0,i?1:0,o||0,r||0);}const kt=Math.pow(2,25),Nt=Math.pow(2,24),Ut=Math.pow(2,17),Gt=Math.pow(2,16),jt=Math.pow(2,9),Vt=Math.pow(2,8),Zt=Math.pow(2,1);function Wt(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*kt+t*Nt+i*Ut+t*Gt+i*jt+t*Vt+i*Zt+t}const Ht=0;class qt{constructor(e){this._sortAcrossTiles=\"viewport-y\"!==e.layout.get(\"symbol-z-order\")&&void 0!==e.layout.get(\"symbol-sort-key\").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[];}continuePlacement(e,t,i,o,r){const s=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex{const t=e.a4.now()-s;return !this._forceFullPlacement&&t>2};for(;this._currentPlacementIndex>=0;){const s=i[t[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if(\"symbol\"===s.type&&(!s.minzoom||s.minzoom<=a)&&(!s.maxzoom||s.maxzoom>a)){const t=s,i=t.layout.get(\"symbol-z-elevate\"),a=this._inProgressLayer=this._inProgressLayer||new qt(t),l=e.aE(s.source,s.scope);if(a.continuePlacement(i?r[l]:o[l],this.placement,this._showCollisionBoxes,s,n))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const Xt=512/e.J/2;class Jt{constructor(t,i,o){this.tileID=t,this.bucketInstanceId=o,this.index=new e.aZ(i.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const r=t.canonical.x*e.J,s=t.canonical.y*e.J;for(let e=0;ee.overscaledZ)for(const i in r){const s=r[i];s.tileID.isChildOf(e)&&s.findMatches(t.symbolInstances,e,o);}else {const s=r[e.scaledTo(Number(i)).key];s&&s.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var ei=\"\\n#define EPSILON 0.0000001\\n#define PI 3.141592653589793\\n#ifdef RENDER_CUTOFF\\nfloat cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);}\\n#endif\",ti=\"\\nout vec4 glFragColor;highp float unpack_depth(highp vec4 rgba_depth)\\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\\n#ifdef INDICATOR_CUTOUT\\nuniform vec2 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params;\\n#endif\\nvec4 applyCutout(vec4 color) {\\n#ifdef INDICATOR_CUTOUT\\nfloat holeMinOpacity=u_indicator_cutout_params.x;float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0);\\n#else\\nreturn color;\\n#endif\\n}\\n#ifdef DEBUG_WIREFRAME\\n#define HANDLE_WIREFRAME_DEBUG \\\\\\nglFragColor=vec4(0.7,0.0,0.0,0.7); \\\\\\ngl_FragDepth=gl_FragCoord.z-0.0001;\\n#else\\n#define HANDLE_WIREFRAME_DEBUG\\n#endif\\n#ifdef RENDER_CUTOFF\\nuniform highp vec4 u_cutoff_params;in float v_cutoff_opacity;\\n#endif\\nvec4 textureLodCustom(sampler2D image,vec2 pos,vec2 lod_coord) {vec2 size=vec2(textureSize(image,0));vec2 dx=dFdx(lod_coord.xy*size);vec2 dy=dFdy(lod_coord.xy*size);float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}\",ii=\"\\n#define EXTENT 8192.0\\n#define RAD_TO_DEG 180.0/PI\\n#define DEG_TO_RAD PI/180.0\\n#define GLOBE_RADIUS EXTENT/PI/2.0\\nfloat wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;}\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) {\\n#ifndef PROJECTED_POS_ON_VIEWPORT\\nfloat tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz;\\n#else\\nreturn vec3(0.0);\\n#endif\\n}vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);}\\n#endif\\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(\\nunpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);}\\n#ifdef RENDER_CUTOFF\\nuniform vec4 u_cutoff_params;out float v_cutoff_opacity;\\n#endif\\nconst vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(vec2 posWithComposedSkirt)\\n{float skirt=float(posWithComposedSkirt.x >=skirtOffset);vec2 pos=posWithComposedSkirt-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);}\",oi=\"in highp vec3 a_pos_3f;uniform lowp mat4 u_matrix;out highp vec3 v_uv;void main() {const mat3 half_neg_pi_around_x=mat3(1.0,0.0, 0.0,0.0,0.0,-1.0,0.0,1.0, 0.0);v_uv=half_neg_pi_around_x*a_pos_3f;vec4 pos=u_matrix*vec4(a_pos_3f,1.0);gl_Position=pos.xyww;}\",ri=\"\\n#define ELEVATION_SCALE 7.0\\n#define ELEVATION_OFFSET 450.0\\n#ifdef PROJECTION_GLOBE_VIEW\\nuniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;vec3 elevationVector(vec2 pos) {vec2 uv=pos/EXTENT;vec3 up=normalize(mix(\\nmix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;}\\n#else\\nvec3 elevationVector(vec2 pos) { return vec3(0,0,1); }\\n#endif\\n#ifdef TERRAIN\\nuniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;uniform sampler2D u_depth;uniform vec2 u_depth_size_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) {\\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r;\\n#else\\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\\n#endif\\n}float prevElevation(vec2 apos) {\\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r;\\n#else\\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\\n#endif\\n}\\n#ifdef TERRAIN_VERTEX_MORPHING\\nfloat elevation(vec2 apos) {\\n#ifdef ZERO_EXAGGERATION\\nreturn 0.0;\\n#endif\\nfloat nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);}\\n#else\\nfloat elevation(vec2 apos) {\\n#ifdef ZERO_EXAGGERATION\\nreturn 0.0;\\n#endif\\nreturn currentElevation(apos);}\\n#endif\\nhighp float unpack_depth(highp vec4 rgba_depth)\\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;float depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5));return coord.z > depth+0.0005;}float occlusionFade(vec4 frag) {vec3 coord=frag.xyz/frag.w;vec3 df=vec3(5.0*u_depth_size_inv,0.0);vec2 uv=0.5*coord.xy+0.5;vec4 depth=vec4(\\nunpack_depth(texture(u_depth,uv-df.xz)),unpack_depth(texture(u_depth,uv+df.xz)),unpack_depth(texture(u_depth,uv-df.zy)),unpack_depth(texture(u_depth,uv+df.zy))\\n);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z-0.001)-depth),0.0,1.0));}vec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);}\\n#else\\nfloat elevation(vec2 pos) { return 0.0; }bool isOccluded(vec4 frag) { return false; }float occlusionFade(vec4 frag) { return 1.0; }\\n#endif\",si=\"#ifdef FOG\\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump mat4 u_fog_matrix;out vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);}\\n#endif\",ni=\"highp vec3 hash(highp vec2 p) {highp vec3 p3=fract(p.xyx*vec3(443.8975,397.2973,491.1871));p3+=dot(p3,p3.yxz+19.19);return fract((p3.xxy+p3.yzz)*p3.zyx);}vec3 dither(vec3 color,highp vec2 seed) {vec3 rnd=hash(seed)+hash(seed+0.59374)-0.5;return color+rnd/255.0;}\\n#ifdef FOG\\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=gl_FragCoord.xy/u_viewport;highp vec3 ray_dir=mix(\\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {\\n#ifdef FOG_DITHERING\\nvec2 dither_seed=gl_FragCoord.xy+u_fog_temporal_offset;return dither(color,dither_seed);\\n#else\\nreturn color;\\n#endif\\n}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);}\\n#endif\",ai=\"#ifdef RASTER_ARRAY\\nuniform sampler2D u_image0;uniform sampler2D u_image1;const vec4 NODATA=vec4(1);vec4 _raTexLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return (texCoord.xxyy+vec2(1.5,0.5).xyxy)/texResolution.xxyy;}vec2 _raTexLinearMix(highp vec2 fxy,highp vec4 colorMix,highp float colorOffset,highp vec4 t00,highp vec4 t10,highp vec4 t01,highp vec4 t11) {vec2 c00=t00==NODATA ? vec2(0) : vec2(colorOffset+dot(t00,colorMix),1);vec2 c10=t10==NODATA ? vec2(0) : vec2(colorOffset+dot(t10,colorMix),1);vec2 c01=t01==NODATA ? vec2(0) : vec2(colorOffset+dot(t01,colorMix),1);vec2 c11=t11==NODATA ? vec2(0) : vec2(colorOffset+dot(t11,colorMix),1);return mix(mix(c01,c11,fxy.x),mix(c00,c10,fxy.x),fxy.y);}vec2 raTexture2D_image0_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;vec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texture(u_image0,c.yz),texture(u_image0,c.xz),texture(u_image0,c.yw),texture(u_image0,c.xw)\\n);}vec2 raTexture2D_image1_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;vec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texture(u_image1,c.yz),texture(u_image1,c.xz),texture(u_image1,c.yw),texture(u_image1,c.xw)\\n);}vec2 raTexture2D_image0_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texture(u_image0,texCoord);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}vec2 raTexture2D_image1_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texture(u_image1,texCoord);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}\\n#endif\",li=\"#ifdef RENDER_SHADOWS\\nuniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];}\\n#endif//RENDER_SHADOWS\",ci=\"#ifdef RENDER_SHADOWS\\n#ifdef DEPTH_TEXTURE\\nuniform highp sampler2D u_shadowmap_0;uniform highp sampler2D u_shadowmap_1;\\n#else\\nuniform sampler2D u_shadowmap_0;uniform sampler2D u_shadowmap_1;\\n#endif\\nuniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;highp float shadow_sample_1(highp vec2 uv,highp float compare) {highp float shadow_depth;\\n#ifdef DEPTH_TEXTURE\\nshadow_depth=texture(u_shadowmap_1,uv).r;\\n#else\\nshadow_depth=unpack_depth(texture(u_shadowmap_1,uv))*0.5+0.5;\\n#endif\\nreturn step(shadow_depth,compare);}highp float shadow_sample_0(highp vec2 uv,highp float compare) {highp float shadow_depth;\\n#ifdef DEPTH_TEXTURE\\nshadow_depth=texture(u_shadowmap_0,uv).r;\\n#else\\nshadow_depth=unpack_depth(texture(u_shadowmap_0,uv))*0.5+0.5;\\n#endif\\nreturn step(shadow_depth,compare);}float shadow_occlusion_1(highp vec4 pos,highp float bias) {highp vec2 uv=pos.xy;return shadow_sample_1(uv,pos.z-bias);}float shadow_occlusion_0(highp vec4 pos,highp float bias) {highp float compare0=pos.z-bias;\\n#ifdef NATIVE\\nhighp vec2 uv=pos.xy;highp vec4 samples=textureGather(u_shadowmap_0,uv,0);lowp vec4 stepSamples=step(samples,vec4(compare0));\\n#else\\nhighp vec2 uv00=pos.xy-vec2(0.5*u_shadow_texel_size);highp vec2 uv10=uv00+vec2(u_shadow_texel_size,0.0);highp vec2 uv01=uv00+vec2(0.0,u_shadow_texel_size);highp vec2 uv11=uv01+vec2(u_shadow_texel_size,0.0);lowp vec4 stepSamples=vec4(\\nshadow_sample_0(uv01,compare0),shadow_sample_0(uv11,compare0),shadow_sample_0(uv10,compare0),shadow_sample_0(uv00,compare0)\\n);\\n#endif\\nvec2 f=fract(pos.xy*u_shadow_map_resolution-vec2(0.5));lowp vec2 lerpx=mix(stepSamples.wx,stepSamples.zy,f.xx);return mix(lerpx.x,lerpx.y,f.y);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {\\n#ifdef SHADOWS_SINGLE_CASCADE\\nlight_view_pos0.xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;return shadow_occlusion_0(light_view_pos0,bias);\\n#else\\nlight_view_pos0.xyz/=light_view_pos0.w;light_view_pos1.xyz/=light_view_pos1.w;vec4 uv=vec4(light_view_pos0.xy,light_view_pos1.xy);vec4 abs_bounds=abs(uv);if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {light_view_pos0.xyz=light_view_pos0.xyz*0.5+0.5;return shadow_occlusion_0(light_view_pos0,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}light_view_pos1.xyz=light_view_pos1.xyz*0.5+0.5;float occlusion1=shadow_occlusion_1(light_view_pos1,bias);return mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth));\\n#endif\\n}highp float calculate_shadow_bias(float NDotL) {\\n#ifdef NORMAL_OFFSET\\nreturn 0.5*u_shadow_bias.x;\\n#else\\nreturn 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z));\\n#endif\\n}float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);}\\n#endif\";const hi=[];fi(ei,hi),fi(ii,hi),fi(ti,hi);const _i={\"_prelude_fog.vertex.glsl\":si,\"_prelude_terrain.vertex.glsl\":ri,\"_prelude_shadow.vertex.glsl\":li,\"_prelude_fog.fragment.glsl\":ni,\"_prelude_shadow.fragment.glsl\":ci,\"_prelude_lighting.glsl\":\"\\n#ifdef LIGHTING_3D_MODE\\nuniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);}\\n#endif//LIGHTING_3D_MODE\",\"_prelude_raster_array.glsl\":ai},di={};gi(\"\",ri),gi(ni,si),gi(ci,li),gi(ai,\"\");const ui=gi(ti,ii),pi=ei;var mi={background:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform vec4 u_color;uniform float u_opacity;\\n#ifdef LIGHTING_3D_MODE\\nin vec4 v_color;\\n#endif\\nvoid main() {vec4 out_color;\\n#ifdef LIGHTING_3D_MODE\\nout_color=v_color;\\n#else\\nout_color=u_color;\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nglFragColor=out_color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nin vec2 a_pos;uniform mat4 u_matrix;\\n#ifdef LIGHTING_3D_MODE\\nuniform mediump vec4 u_color;out vec4 v_color;uniform float u_emissive_strength;\\n#endif\\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0,1);\\n#ifdef LIGHTING_3D_MODE\\nv_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),backgroundPattern:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in vec2 v_pos;void main() {vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nglFragColor=out_color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_tile_units_to_pixels,a_pos);\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),circle:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nin vec3 v_data;in float v_visibility;\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define mediump float radius\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define highp vec4 stroke_color\\n#pragma mapbox: define mediump float stroke_width\\n#pragma mapbox: define lowp float stroke_opacity\\nuniform float u_emissive_strength;void main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize mediump float radius\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize highp vec4 stroke_color\\n#pragma mapbox: initialize mediump float stroke_width\\n#pragma mapbox: initialize lowp float stroke_opacity\\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(\\nantialiased_blur,0.0,extrude_length-radius/(radius+stroke_width)\\n);vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_apply_premultiplied(out_color,v_fog_pos);\\n#endif\\nglFragColor=out_color*(v_visibility*opacity_t);\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\n}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_terrain.vertex.glsl\"\\n#define NUM_VISIBILITY_RINGS 2\\n#define INV_SQRT2 0.70710678\\n#define ELEVATION_BIAS 0.0001\\n#define NUM_SAMPLES_PER_RING 16\\nuniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;in vec2 a_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\\n#endif\\nout vec3 v_data;out float v_visibility;\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define mediump float radius\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define highp vec4 stroke_color\\n#pragma mapbox: define mediump float stroke_width\\n#pragma mapbox: define lowp float stroke_opacity\\nvec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1,-1),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1,-1),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1,1),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1,1),radius,stroke_width,view_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) {\\n#if defined(TERRAIN)\\nreturn elevation(pos)+ELEVATION_BIAS;\\n#else\\nreturn 0.0;\\n#endif\\n}vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_scale);\\n#ifdef PITCH_WITH_MAP\\n#ifdef PROJECTION_GLOBE_VIEW\\nreturn u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) );\\n#else\\nreturn u_matrix*( world_center+vec4(sample_offset,0,0) );\\n#endif\\n#else\\nreturn projected_center+vec4(sample_offset,0,0);\\n#endif\\n}float get_sample_step() {\\n#ifdef PITCH_WITH_MAP\\nreturn 2.0*PI/float(NUM_SAMPLES_PER_RING);\\n#else\\nreturn PI/float(NUM_SAMPLES_PER_RING);\\n#endif\\n}void main(void) {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize mediump float radius\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize highp vec4 stroke_color\\n#pragma mapbox: initialize mediump float stroke_width\\n#pragma mapbox: initialize lowp float stroke_opacity\\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);vec4 world_center;mat3 surface_vectors;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 pos_normal_3=a_pos_normal_3/16384.0;surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*circle_elevation(circle_center);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*circle_elevation(circle_center);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1);\\n#else \\nsurface_vectors=mat3(1.0);float height=circle_elevation(circle_center);world_center=vec4(circle_center,height,1);\\n#endif\\nvec4 projected_center=u_matrix*world_center;float view_scale=0.0;\\n#ifdef PITCH_WITH_MAP\\n#ifdef SCALE_WITH_MAP\\nview_scale=1.0;\\n#else\\nview_scale=projected_center.w/u_camera_to_center_distance;\\n#endif\\n#else\\n#ifdef SCALE_WITH_MAP\\nview_scale=u_camera_to_center_distance;\\n#else\\nview_scale=projected_center.w;\\n#endif\\n#endif\\ngl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,view_scale,surface_vectors);float visibility=0.0;\\n#ifdef TERRAIN\\nfloat step=get_sample_step();vec4 occlusion_world_center;vec4 occlusion_projected_center;\\n#ifdef PITCH_WITH_MAP\\nfloat cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,view_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center;\\n#else\\nocclusion_world_center=world_center;occlusion_projected_center=projected_center;\\n#endif\\nfor(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float scale=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*scale;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,view_scale,surface_vectors);visibility+=float(!isOccluded(frag_pos));}}visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_SAMPLES_PER_RING);\\n#else\\nvisibility=1.0;\\n#endif\\n#ifdef PROJECTION_GLOBE_VIEW\\nvisibility=1.0;\\n#endif\\nv_visibility=visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);\\n#ifdef FOG\\nv_fog_pos=fog_position(world_center.xyz);\\n#endif\\n}'),clippingMask:gi(\"void main() {glFragColor=vec4(1.0);}\",\"in vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}\"),heatmap:gi('#include \"_prelude_fog.fragment.glsl\"\\nuniform highp float u_intensity;in vec2 v_extrude;\\n#pragma mapbox: define highp float weight\\n#define GAUSS_COEF 0.3989422804014327\\nvoid main() {\\n#pragma mapbox: initialize highp float weight\\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0);\\n#ifdef FOG\\nif (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_terrain.vertex.glsl\"\\n#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;in vec2 a_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\\n#endif\\nout vec2 v_extrude;\\n#pragma mapbox: define highp float weight\\n#pragma mapbox: define mediump float radius\\nconst highp float ZERO=1.0/255.0/16.0;\\n#define GAUSS_COEF 0.3989422804014327\\nvoid main(void) {\\n#pragma mapbox: initialize highp float weight\\n#pragma mapbox: initialize mediump float radius\\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(a_pos*0.5);vec3 pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 pos_normal_3=a_pos_normal_3/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\\n#else\\npos=vec3(tilePos+extrude,elevation(tilePos));\\n#endif\\ngl_Position=u_matrix*vec4(pos,1);\\n#ifdef FOG\\nv_fog_pos=fog_position(pos);\\n#endif\\n}'),heatmapTexture:gi(\"uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));glFragColor=color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(0.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}\",\"in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=a_pos*0.5+0.5;}\"),collisionBox:gi(\"in float v_placed;in float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);glFragColor =mix(red,blue,step(0.5,v_placed))*0.5;glFragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}\",'#include \"_prelude_terrain.vertex.glsl\"\\nin vec3 a_pos;in vec2 a_anchor_pos;in vec2 a_extrude;in vec2 a_placed;in vec2 a_shift;in float a_size_scale;in vec2 a_padding;in float a_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;out float v_placed;out float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_pos+elevationVector(a_anchor_pos)*(a_z_offset+elevation(a_anchor_pos)),1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(\\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(a_extrude*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}'),collisionCircle:gi(\"in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}\",\"in vec2 a_pos_2f;in float a_radius;in vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;out float v_radius;out vec2 v_extrude;out float v_perspective_ratio;out float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos_2f;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(\\nmix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(\\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}\"),debug:gi(\"uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}\",'#include \"_prelude_terrain.vertex.glsl\"\\nin vec2 a_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_pos_3;\\n#endif\\nout vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {float h=elevation(a_pos);v_uv=a_pos/8192.0;\\n#ifdef PROJECTION_GLOBE_VIEW\\ngl_Position=u_matrix*vec4(a_pos_3+elevationVector(a_pos)*h,1);\\n#else\\ngl_Position=u_matrix*vec4(a_pos*u_overlay_scale,h,1);\\n#endif\\n}'),fill:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define lowp float opacity\\nuniform float u_emissive_strength;void main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize lowp float opacity\\nvec4 out_color=color;\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nglFragColor=out_color*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nin vec2 a_pos;uniform mat4 u_matrix;\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize lowp float opacity\\ngl_Position=u_matrix*vec4(a_pos,0,1);\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),fillOutline:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nin highp vec2 v_pos;uniform float u_emissive_strength;\\n#pragma mapbox: define highp vec4 outline_color\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 outline_color\\n#pragma mapbox: initialize lowp float opacity\\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color;\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nglFragColor=out_color*(alpha*opacity);\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nin vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;out highp vec2 v_pos;\\n#pragma mapbox: define highp vec4 outline_color\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 outline_color\\n#pragma mapbox: initialize lowp float opacity\\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),fillOutlinePattern:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_emissive_strength;in highp vec2 v_pos;in highp vec2 v_pos_world;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nglFragColor=out_color*(alpha*opacity);\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos;out highp vec2 v_pos;out highp vec2 v_pos_world;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern\\n#pragma mapbox: define lowp float pixel_ratio\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern\\n#pragma mapbox: initialize lowp float pixel_ratio\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos);v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),fillPattern:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform vec2 u_texsize;uniform sampler2D u_image;in vec2 v_pos;uniform float u_emissive_strength;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nglFragColor=out_color*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp vec4 pattern\\n#pragma mapbox: define lowp float pixel_ratio\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump vec4 pattern\\n#pragma mapbox: initialize lowp float pixel_ratio\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos);\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),fillExtrusion:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_shadow.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nin vec4 v_color;in vec4 v_flat;\\n#ifdef RENDER_SHADOWS\\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth;\\n#endif\\nuniform lowp float u_opacity;\\n#ifdef FAUX_AO\\nuniform lowp vec2 u_ao;in vec2 v_ao;\\n#endif\\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\\nin vec4 v_roof_color;\\n#endif\\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\\nin highp vec3 v_normal;\\n#endif\\nuniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor;\\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\\nin float v_flood_radius;in float v_has_floodlight;\\n#endif\\nuniform float u_emissive_strength;in float v_height;void main() {\\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\\nvec3 normal=normalize(v_normal);\\n#endif\\nfloat z;vec4 color=v_color;\\n#ifdef ZERO_ROOF_RADIUS\\nz=float(normal.z > 0.00001);\\n#ifdef LIGHTING_3D_MODE\\nnormal=mix(normal,vec3(0.0,0.0,1.0),z);\\n#else\\ncolor=mix(v_color,v_roof_color,z);\\n#endif\\n#endif\\nfloat h=max(0.0,v_height);float ao_shade=1.0;\\n#ifdef FAUX_AO\\nfloat intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;\\n#ifdef ZERO_ROOF_RADIUS\\nconcave*=(1.0-z);\\n#endif\\nfloat x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave);\\n#ifdef LIGHTING_3D_MODE\\n#ifdef FLOOD_LIGHT\\ncolor.rgb*=mix(ao_shade,1.0,v_has_floodlight);\\n#else\\ncolor.rgb*=ao_shade;\\n#endif\\n#else\\ncolor.rgb*=ao_shade;\\n#endif\\n#endif\\n#ifdef LIGHTING_3D_MODE\\nfloat flood_radiance=0.0;\\n#ifdef FLOOD_LIGHT\\nflood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight;\\n#endif\\n#ifdef RENDER_SHADOWS\\n#ifdef FLOOD_LIGHT\\nfloat ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,v_depth);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance);\\n#else\\nfloat shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor);\\n#endif\\n#else\\ncolor.rgb=apply_lighting(color.rgb,normal);\\n#ifdef FLOOD_LIGHT\\ncolor.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance);\\n#endif\\n#endif\\ncolor.rgb=mix(color.rgb,v_flat.rgb,u_emissive_strength);color*=u_opacity;\\n#endif\\n#ifdef FOG\\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h));\\n#endif\\n#ifdef INDICATOR_CUTOUT\\ncolor=applyCutout(color);\\n#endif\\nglFragColor=color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_terrain.vertex.glsl\"\\n#include \"_prelude_shadow.vertex.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\\n#endif\\nuniform highp float u_vertical_scale;out vec4 v_color;out vec4 v_flat;\\n#ifdef RENDER_SHADOWS\\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth;\\n#endif\\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\\nout vec4 v_roof_color;\\n#endif\\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\\nout highp vec3 v_normal;\\n#endif\\n#ifdef FAUX_AO\\nuniform lowp vec2 u_ao;out vec2 v_ao;\\n#endif\\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\\nout float v_flood_radius;out float v_has_floodlight;\\n#endif\\nout float v_height;\\n#pragma mapbox: define highp float base\\n#pragma mapbox: define highp float height\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define highp float flood_light_wall_radius\\nvoid main() {\\n#pragma mapbox: initialize highp float base\\n#pragma mapbox: initialize highp float height\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize highp float flood_light_wall_radius\\nbase*=u_vertical_scale;height*=u_vertical_scale;vec4 pos_nx=floor(a_pos_normal_ed*0.5);vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));\\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\\nv_normal=normal;\\n#endif\\nbase=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\\n#if defined(HAS_CENTROID) || defined(TERRAIN)\\ncentroid_pos=a_centroid_pos;\\n#endif\\nfloat ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos;\\n#ifdef TERRAIN\\nbool flat_roof=centroid_pos.x !=0.0 && t > 0.0;ele=elevation(pos_nx.xy);c_ele=flat_roof ? centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos) : ele;h=flat_roof ? max(c_ele+height,ele+base+2.0) : ele+(t > 0.0 ? height : base==0.0 ?-5.0 : base);pos=vec3(pos_nx.xy,h);\\n#else\\nh=t > 0.0 ? height : base;pos=vec3(pos_nx.xy,h);\\n#endif\\n#ifdef PROJECTION_GLOBE_VIEW\\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\\n#endif\\nfloat cutoff=1.0;vec3 scaled_pos=pos;\\n#ifdef RENDER_CUTOFF\\nvec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_pos.x==0.0 ? pos.xyz : (centroid_random/8.0);vec4 ground=u_matrix*vec4(ground_pos.xy,ele,1.0);cutoff=max(0.01,cutoff_opacity(u_cutoff_params,ground.z));if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale);\\n#endif\\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff < 0.01 && centroid_pos.x !=0.0));gl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h;\\n#ifdef RENDER_SHADOWS\\nvec3 shd_pos0=pos;vec3 shd_pos1=pos;\\n#ifdef NORMAL_OFFSET\\nvec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\\n#endif\\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\\n#endif\\nfloat NdotL=0.0;float colorvalue=0.0;\\n#ifndef LIGHTING_3D_MODE\\ncolorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=(\\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\\n#endif\\n#ifdef FAUX_AO\\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\\n#ifdef TERRAIN\\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\\n#endif\\nv_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny.y)*u_ao[0]);\\n#ifdef PROJECTION_GLOBE_VIEW\\ntop_height+=u_height_lift;\\n#endif\\ngl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\\n#endif\\n#ifdef LIGHTING_3D_MODE\\n#ifdef FLOOD_LIGHT\\nfloat is_wall=1.0-float(t > 0.0 && top_up_ny.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale;\\n#endif\\nv_color=vec4(color.rgb,1.0);v_flat=vec4(linearProduct(color.rgb,vec3(calculate_NdotL(normal))),1.0);\\n#else\\nv_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity;\\n#endif\\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\\nfloat roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity;\\n#endif\\n#ifdef FOG\\nv_fog_pos=fog_position(pos);\\n#endif\\n}'),fillExtrusionDepth:gi(\"in highp float v_depth;void main() {\\n#ifndef DEPTH_TEXTURE\\nglFragColor=pack_depth(v_depth);\\n#endif\\n}\",'#include \"_prelude_terrain.vertex.glsl\"\\nuniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_vertical_scale;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\\n#pragma mapbox: define highp float base\\n#pragma mapbox: define highp float height\\nout highp float v_depth;void main() {\\n#pragma mapbox: initialize highp float base\\n#pragma mapbox: initialize highp float height\\nbase*=u_vertical_scale;height*=u_vertical_scale;vec3 pos_nx=floor(a_pos_normal_ed.xyz*0.5);mediump vec3 top_up_ny=a_pos_normal_ed.xyz-2.0*pos_nx;base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\\n#if defined(HAS_CENTROID) || defined(TERRAIN)\\ncentroid_pos=a_centroid_pos;\\n#endif\\nvec3 pos;\\n#ifdef TERRAIN\\nbool flat_roof=centroid_pos.x !=0.0 && t > 0.0;float ele=elevation(pos_nx.xy);float c_ele=flat_roof ? centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos) : ele;float h=flat_roof ? max(c_ele+height,ele+base+2.0) : ele+(t > 0.0 ? height : base);pos=vec3(pos_nx.xy,h);\\n#else\\npos=vec3(pos_nx.xy,t > 0.0 ? height : base);\\n#endif\\nfloat hidden=float(centroid_pos.x==0.0 && centroid_pos.y==1.0);gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);v_depth=gl_Position.z/gl_Position.w;}'),fillExtrusionPattern:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform vec2 u_texsize;uniform sampler2D u_image;\\n#ifdef FAUX_AO\\nuniform lowp vec2 u_ao;in vec3 v_ao;\\n#endif\\n#ifdef LIGHTING_3D_MODE\\nin vec3 v_normal;\\n#endif\\nin vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity;\\n#pragma mapbox: define highp float base\\n#pragma mapbox: define highp float height\\n#pragma mapbox: define mediump vec4 pattern\\n#pragma mapbox: define highp float pixel_ratio\\nvoid main() {\\n#pragma mapbox: initialize highp float base\\n#pragma mapbox: initialize highp float height\\n#pragma mapbox: initialize mediump vec4 pattern\\n#pragma mapbox: initialize highp float pixel_ratio\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 imagecoord=mod(v_pos,1.0);vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting(out_color,normalize(v_normal))*u_opacity;\\n#else\\nout_color=out_color*v_lighting;\\n#endif\\n#ifdef FAUX_AO\\nfloat intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade;\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\n#ifdef INDICATOR_CUTOUT\\nout_color=applyCutout(out_color);\\n#endif\\nglFragColor=out_color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_terrain.vertex.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\\n#endif\\nout vec2 v_pos;out vec4 v_lighting;\\n#ifdef FAUX_AO\\nuniform lowp vec2 u_ao;out vec3 v_ao;\\n#endif\\n#ifdef LIGHTING_3D_MODE\\nout vec3 v_normal;\\n#endif\\n#pragma mapbox: define highp float base\\n#pragma mapbox: define highp float height\\n#pragma mapbox: define mediump vec4 pattern\\n#pragma mapbox: define highp float pixel_ratio\\nvoid main() {\\n#pragma mapbox: initialize highp float base\\n#pragma mapbox: initialize highp float height\\n#pragma mapbox: initialize mediump vec4 pattern\\n#pragma mapbox: initialize highp float pixel_ratio\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec4 pos_nx=floor(a_pos_normal_ed*0.5);mediump vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;mediump vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=a_pos_normal_ed.w;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0);\\n#if defined(HAS_CENTROID) || defined(TERRAIN)\\ncentroid_pos=a_centroid_pos;\\n#endif\\nfloat ele=0.0;float h=z;vec3 p;float c_ele;\\n#ifdef TERRAIN\\nbool flat_roof=centroid_pos.x !=0.0 && t > 0.0;ele=elevation(pos_nx.xy);c_ele=flat_roof ? centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos) : ele;h=flat_roof ? max(c_ele+height,ele+base+2.0) : ele+(t > 0.0 ? height : base==0.0 ?-5.0 : base);p=vec3(pos_nx.xy,h);\\n#else\\np=vec3(pos_nx.xy,z);\\n#endif\\n#ifdef PROJECTION_GLOBE_VIEW\\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\\n#endif\\nfloat hidden=float(centroid_pos.x==0.0 && centroid_pos.y==1.0);gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0\\n? pos_nx.xy\\n: vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0;\\n#ifdef LIGHTING_3D_MODE\\nNdotL=calculate_NdotL(normal);\\n#else\\nNdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL);\\n#endif\\nif (normal.y !=0.0) {float r=0.84;\\n#ifndef LIGHTING_3D_MODE\\nr=mix(0.7,0.98,1.0-u_lightintensity);\\n#endif\\nNdotL*=(\\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\\n#ifdef FAUX_AO\\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\\n#ifdef TERRAIN\\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\\n#endif\\nv_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny.y)*u_ao[0]);\\n#ifdef PROJECTION_GLOBE_VIEW\\ntop_height+=u_height_lift;\\n#endif\\ngl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\\n#endif\\n#ifdef LIGHTING_3D_MODE\\nv_normal=normal;\\n#else\\nv_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;\\n#endif \\n#ifdef FOG\\nv_fog_pos=fog_position(p);\\n#endif\\n}'),groundShadow:gi('#include \"_prelude_shadow.fragment.glsl\"\\nprecision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;in float v_depth;\\n#ifdef FOG\\nin float v_fog_opacity;\\n#endif\\nvoid main() {float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light);\\n#ifdef RENDER_CUTOFF\\nshadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,v_depth));\\n#endif\\n#ifdef FOG\\nshadow=mix(shadow,vec3(1.0),v_fog_opacity);\\n#endif\\n#ifdef INDICATOR_CUTOUT\\nshadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0)).r);\\n#endif\\nglFragColor=vec4(shadow,1.0);}','#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in vec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1;out float v_depth;\\n#ifdef FOG\\nout float v_fog_opacity;\\n#endif\\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0);v_depth=gl_Position.w;\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);v_fog_opacity=fog(v_fog_pos);\\n#endif\\n}'),fillExtrusionGroundEffect:gi(\"uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size;\\n#ifdef SDF_SUBPASS\\nin highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);}\\n#ifdef FOG\\nin highp float v_fog;\\n#endif\\n#endif\\nvoid main() {\\n#ifdef CLEAR_SUBPASS\\nvec4 color=vec4(1.0);\\n#ifdef CLEAR_FROM_TEXTURE\\ncolor=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size));\\n#endif\\nglFragColor=color;\\n#else\\n#ifdef SDF_SUBPASS\\nhighp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0;\\n#ifdef FOG\\nfog=v_fog;\\n#endif\\n#ifdef RENDER_CUTOFF\\nfog*=v_cutoff_opacity;\\n#endif\\nglFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog));\\n#else\\nvec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass);\\n#ifdef OVERDRAW_INSPECTOR\\ncolor=vec4(1.0);\\n#endif\\nglFragColor=color;HANDLE_WIREFRAME_DEBUG;\\n#endif\\n#endif\\n}\",'#include \"_prelude_fog.vertex.glsl\"\\nin highp vec4 a_pos_end;in highp float a_angular_offset_factor;in highp float a_hidden_by_landmark;\\n#ifdef SDF_SUBPASS\\nout highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao;\\n#ifdef FOG\\nout highp float v_fog;\\n#endif\\n#endif\\nuniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp vec2 u_ao;\\n#pragma mapbox: define highp float flood_light_ground_radius\\nconst float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() {\\n#pragma mapbox: initialize highp float flood_light_ground_radius\\nvec2 p=a_pos_end.xy;vec2 q=floor(a_pos_end.zw*0.5);vec2 start_bottom=a_pos_end.zw-q*2.0;float fl_ground_radius=flood_light_ground_radius;fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=a_angular_offset_factor/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(1.0,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp;\\n#ifdef SDF_SUBPASS\\nv_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius);\\n#ifdef FOG\\nv_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos);\\n#endif\\n#endif\\nfloat hidden_by_landmark=0.0;\\n#ifdef HAS_CENTROID\\nhidden_by_landmark=a_hidden_by_landmark;\\n#endif\\nfloat isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0));\\n#ifdef RENDER_CUTOFF\\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\\n#endif\\n}'),hillshadePrepare:gi(\"precision highp float;uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2(\\n(c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c)\\n)/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4(\\nderiv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}\",\"uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}\"),hillshade:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);glFragColor=accent_color*(1.0-shade_color.a)+shade_color;\\n#ifdef LIGHTING_3D_MODE\\nglFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nglFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos));\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n}'),line:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform lowp float u_device_pixel_ratio;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec4 v_uv;\\n#ifdef RENDER_LINE_DASH\\nuniform sampler2D u_dash_image;in vec2 v_tex;\\n#endif\\n#ifdef RENDER_LINE_GRADIENT\\nuniform sampler2D u_gradient_image;\\n#endif\\nfloat luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;}uniform float u_emissive_strength;\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define lowp float floorwidth\\n#pragma mapbox: define lowp vec4 dash\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float border_width\\n#pragma mapbox: define lowp vec4 border_color\\nfloat linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize lowp float floorwidth\\n#pragma mapbox: initialize lowp vec4 dash\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float border_width\\n#pragma mapbox: initialize lowp vec4 border_color\\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);\\n#ifdef RENDER_LINE_DASH\\nfloat sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/dash.z;alpha*=linearstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);\\n#endif\\nhighp vec4 out_color;\\n#ifdef RENDER_LINE_GRADIENT\\nout_color=texture(u_gradient_image,v_uv.xy);\\n#else\\nout_color=color;\\n#endif\\nfloat trimmed=1.0;\\n#ifdef RENDER_LINE_TRIM_OFFSET\\nhighp float start=v_uv[2];highp float end=v_uv[3];highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=(start+(v_uv.x)*(end-start));if (trim_end > trim_start) {if (line_progress <=trim_end && line_progress >=trim_start) {out_color=vec4(0,0,0,0);trimmed=0.0;}}\\n#endif\\nif (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}}\\n#ifdef RENDER_LINE_BORDER\\nfloat edgeBlur=(border_width+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2.t-edgeBlur),v_width2.s-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) { \\nfloat Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color.rgb=mix(border_color.rgb*border_color.a*trimmed,out_color.rgb,smoothAlpha);}}\\n#endif\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\\n#endif\\n#ifdef FOG\\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\\n#endif\\nout_color*=(alpha*opacity);\\n#ifdef INDICATOR_CUTOUT\\nout_color=applyCutout(out_color);\\n#endif\\nglFragColor=out_color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#define EXTRUDE_SCALE 0.015873016\\nin vec2 a_pos_normal;in vec4 a_data;\\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\\nin highp vec4 a_packed;\\n#endif\\n#ifdef RENDER_LINE_DASH\\nin float a_linesofar;\\n#endif\\nuniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec4 v_uv;\\n#ifdef RENDER_LINE_DASH\\nuniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex;\\n#endif\\n#ifdef RENDER_LINE_GRADIENT\\nuniform float u_image_height;\\n#endif\\n#pragma mapbox: define highp vec4 color\\n#pragma mapbox: define lowp float floorwidth\\n#pragma mapbox: define lowp vec4 dash\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define mediump float gapwidth\\n#pragma mapbox: define lowp float offset\\n#pragma mapbox: define mediump float width\\n#pragma mapbox: define lowp float border_width\\n#pragma mapbox: define lowp vec4 border_color\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 color\\n#pragma mapbox: initialize lowp float floorwidth\\n#pragma mapbox: initialize lowp vec4 dash\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize mediump float gapwidth\\n#pragma mapbox: initialize lowp float offset\\n#pragma mapbox: initialize mediump float width\\n#pragma mapbox: initialize lowp float border_width\\n#pragma mapbox: initialize lowp vec4 border_color\\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist*u_pixels_to_tile_units,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude;\\n#ifndef RENDER_TO_TEXTURE\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#else\\nv_gamma_scale=1.0;\\n#endif\\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\\nfloat a_uv_x=a_packed[0];float a_split_index=a_packed[1];highp float a_clip_start=a_packed[2];highp float a_clip_end=a_packed[3];\\n#ifdef RENDER_LINE_GRADIENT\\nhighp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec4(a_uv_x,a_split_index*texel_height-half_texel_height,a_clip_start,a_clip_end);\\n#else\\nv_uv=vec4(a_uv_x,0.0,a_clip_start,a_clip_end);\\n#endif\\n#endif\\n#ifdef RENDER_LINE_DASH\\nfloat scale=dash.z==0.0 ? 0.0 : u_tile_units_to_pixels/dash.z;float height=dash.y;v_tex=vec2(a_linesofar*scale/floorwidth,(-normal.y*height+dash.x+0.5)/u_texsize.y);\\n#endif\\nv_width2=vec2(outset,inset);\\n#ifdef FOG\\nv_fog_pos=fog_position(pos);\\n#endif\\n}'),linePattern:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\\n#pragma mapbox: define lowp vec4 pattern\\n#pragma mapbox: define lowp float pixel_ratio\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\nvoid main() {\\n#pragma mapbox: initialize mediump vec4 pattern\\n#pragma mapbox: initialize lowp float pixel_ratio\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;vec2 pattern_size=vec2(display_size.x/u_tile_units_to_pixels,display_size.y);float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float pattern_x=v_linesofar/pattern_size.x*aspect;float x=mod(pattern_x,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos);\\n#ifdef LIGHTING_3D_MODE\\ncolor=apply_lighting_ground(color);\\n#endif\\n#ifdef FOG\\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\\n#endif\\ncolor*=(alpha*opacity);\\n#ifdef INDICATOR_CUTOUT\\ncolor=applyCutout(color);\\n#endif\\nglFragColor=color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#define scale 0.015873016\\nin vec2 a_pos_normal;in vec4 a_data;in float a_linesofar;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\\n#pragma mapbox: define lowp float blur\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float offset\\n#pragma mapbox: define mediump float gapwidth\\n#pragma mapbox: define mediump float width\\n#pragma mapbox: define lowp float floorwidth\\n#pragma mapbox: define lowp vec4 pattern\\n#pragma mapbox: define lowp float pixel_ratio\\nvoid main() {\\n#pragma mapbox: initialize lowp float blur\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float offset\\n#pragma mapbox: initialize mediump float gapwidth\\n#pragma mapbox: initialize mediump float width\\n#pragma mapbox: initialize lowp float floorwidth\\n#pragma mapbox: initialize mediump vec4 pattern\\n#pragma mapbox: initialize lowp float pixel_ratio\\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist*u_pixels_to_tile_units,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude;\\n#ifndef RENDER_TO_TEXTURE\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#else\\nv_gamma_scale=1.0;\\n#endif\\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;\\n#ifdef FOG\\nv_fog_pos=fog_position(pos);\\n#endif\\n}'),raster:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\n#include \"_prelude_raster_array.glsl\"\\nuniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;in float v_depth;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength;\\n#ifndef RASTER_ARRAY\\nuniform sampler2D u_image0;uniform sampler2D u_image1;\\n#endif\\n#ifdef RASTER_COLOR\\nuniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res;\\n#endif\\nvoid main() {vec4 color0,color1,color;vec2 value;\\n#ifdef RASTER_COLOR\\n#ifdef RASTER_ARRAY\\n#ifdef RASTER_ARRAY_LINEAR\\nvalue=mix(\\nraTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\\n);\\n#else\\nvalue=mix(\\nraTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\\n);\\n#endif\\nif (value.y > 0.0) value.x/=value.y;\\n#else\\ncolor=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a);\\n#endif\\ncolor=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y;\\n#else\\ncolor0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);\\n#endif\\ncolor.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(\\ndot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb;\\n#endif\\n#ifdef FOG\\nhighp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit));\\n#endif\\nglFragColor=vec4(out_color*color.a,color.a);\\n#ifdef RENDER_CUTOFF\\nglFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth);\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\nuniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center;\\n#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8;\\n#ifdef GLOBE_POLES\\nin vec3 a_globe_pos;in vec2 a_uv;\\n#else\\nin vec2 a_pos;in vec2 a_texture_pos;\\n#endif\\nout vec2 v_pos0;out vec2 v_pos1;out float v_depth;void main() {vec2 uv;\\n#ifdef GLOBE_POLES\\nvec3 globe_pos=a_globe_pos;globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos ,1.0);uv=a_uv;\\n#ifdef FOG\\nv_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz);\\n#endif\\n#else\\nfloat w=1.0+dot(a_texture_pos,u_perspective_transform);uv=a_texture_pos/8192.0;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos;\\n#ifdef FOG\\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\\n#endif\\n#else\\ngl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w);\\n#ifdef FOG\\nv_fog_pos=fog_position(a_pos);\\n#endif\\n#endif\\n#endif\\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1;\\n#ifdef RENDER_CUTOFF\\nv_depth=gl_Position.z;\\n#endif\\n}'),symbolIcon:gi('#include \"_prelude_lighting.glsl\"\\nuniform sampler2D u_texture;\\n#ifdef ICON_TRANSITION\\nuniform float u_icon_transition;\\n#endif\\nin float v_fade_opacity;in vec2 v_tex_a;\\n#ifdef ICON_TRANSITION\\nin vec2 v_tex_b;\\n#endif\\nuniform mediump float u_icon_saturation;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float emissive_strength\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float emissive_strength\\nlowp float alpha=opacity*v_fade_opacity;vec4 out_color;\\n#ifdef ICON_TRANSITION\\nvec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b)*alpha;\\n#else\\nout_color=texture(u_texture,v_tex_a)*alpha;\\n#endif\\n#ifdef SATURATION\\nvec3 luma=vec3(dot(out_color.rgb,vec3(0.2126,0.7152,0.0722)));out_color.rgb=mix(luma,out_color.rgb,u_icon_saturation);\\n#endif\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\\n#endif\\nglFragColor=out_color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_terrain.vertex.glsl\"\\nin vec4 a_pos_offset;in vec4 a_tex_size;in vec4 a_pixeloffset;in vec4 a_projected_pos;in float a_fade_opacity;\\n#ifdef Z_OFFSET\\nin float a_z_offset;\\n#endif\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_globe_anchor;in vec3 a_globe_normal;\\n#endif\\n#ifdef ICON_TRANSITION\\nin vec2 a_texb;\\n#endif\\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform vec3 u_up_vector;\\n#ifdef PROJECTION_GLOBE_VIEW\\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\\n#endif\\nout vec2 v_tex_a;\\n#ifdef ICON_TRANSITION\\nout vec2 v_tex_b;\\n#endif\\nout float v_fade_opacity;\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float emissive_strength\\nvoid main() {\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float emissive_strength\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_min_font_scale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=elevation(tile_anchor);\\n#ifdef Z_OFFSET\\ne+=a_z_offset;\\n#endif\\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos=mix_globe_mercator(a_globe_anchor+h,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\\n#else\\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\\n#endif\\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ?\\ncamera_to_anchor_distance/u_camera_to_center_distance :\\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(\\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjected_point;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetProjected_point=u_matrix*vec4(a_globe_anchor+displacement,1);\\n#else\\noffsetProjected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);\\n#endif\\nvec2 a=projected_point.xy/projected_point.w;vec2 b=offsetProjected_point.xy/offsetProjected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz+h,mercator_pos,u_zoom_transition);projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\\n#else\\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\\n#endif\\nhighp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0);\\n#ifdef TERRAIN\\n#ifdef PITCH_WITH_MAP_TERRAIN\\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\\n#endif\\n#endif\\nfloat occlusion_fade=occlusionFade(projected_point)*globe_occlusion_fade;float projection_transition_fade=1.0;\\n#if defined(PROJECTED_POS_ON_VIEWPORT) && defined(PROJECTION_GLOBE_VIEW)\\nprojection_transition_fade=1.0-step(EPSILON,u_zoom_transition);\\n#endif\\nvec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change))*projection_transition_fade;float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\\n#else\\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\\n#endif\\nv_tex_a=a_tex/u_texsize;\\n#ifdef ICON_TRANSITION\\nv_tex_b=a_texb/u_texsize;\\n#endif\\nv_fade_opacity=out_fade_opacity;}'),symbolSDF:gi('#include \"_prelude_lighting.glsl\"\\n#define SDF_PX 8.0\\nuniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;in float v_draw_halo;in vec2 v_data0;in vec3 v_data1;\\n#pragma mapbox: define highp vec4 fill_color\\n#pragma mapbox: define highp vec4 halo_color\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float halo_width\\n#pragma mapbox: define lowp float halo_blur\\n#pragma mapbox: define lowp float emissive_strength\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 fill_color\\n#pragma mapbox: initialize highp vec4 halo_color\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float halo_width\\n#pragma mapbox: initialize lowp float halo_blur\\n#pragma mapbox: initialize lowp float emissive_strength\\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);vec4 out_color=color*(alpha*opacity*fade_opacity);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\\n#endif\\nglFragColor=out_color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_terrain.vertex.glsl\"\\nin vec4 a_pos_offset;in vec4 a_tex_size;in vec4 a_pixeloffset;in vec4 a_projected_pos;in float a_fade_opacity;\\n#ifdef Z_OFFSET\\nin float a_z_offset;\\n#endif\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_globe_anchor;in vec3 a_globe_normal;\\n#endif\\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform bool u_is_halo;\\n#ifdef PROJECTION_GLOBE_VIEW\\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\\n#endif\\nout float v_draw_halo;out vec2 v_data0;out vec3 v_data1;\\n#pragma mapbox: define highp vec4 fill_color\\n#pragma mapbox: define highp vec4 halo_color\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float halo_width\\n#pragma mapbox: define lowp float halo_blur\\n#pragma mapbox: define lowp float emissive_strength\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 fill_color\\n#pragma mapbox: initialize highp vec4 halo_color\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float halo_width\\n#pragma mapbox: initialize lowp float halo_blur\\n#pragma mapbox: initialize lowp float emissive_strength\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[3];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=elevation(tile_anchor);\\n#ifdef Z_OFFSET\\ne+=a_z_offset;\\n#endif\\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos=mix_globe_mercator(a_globe_anchor+h,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\\n#else\\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\\n#endif\\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ?\\ncamera_to_anchor_distance/u_camera_to_center_distance :\\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(\\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(a_globe_anchor+displacement,1);\\n#else\\noffsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);\\n#endif\\nvec2 a=projected_point.xy/projected_point.w;vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz+h,mercator_pos,u_zoom_transition);projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\\n#else\\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\\n#endif\\nhighp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset);\\n#ifdef TERRAIN\\n#ifdef PITCH_WITH_MAP_TERRAIN\\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\\n#endif\\n#endif\\nfloat occlusion_fade=occlusionFade(projected_point)*globe_occlusion_fade;float projection_transition_fade=1.0;\\n#if defined(PROJECTED_POS_ON_VIEWPORT) && defined(PROJECTION_GLOBE_VIEW)\\nprojection_transition_fade=1.0-step(EPSILON,u_zoom_transition);\\n#endif\\nvec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));float out_fade_opacity=interpolated_fade_opacity*projection_transition_fade;float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\\n#else\\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\\n#endif\\nfloat gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,out_fade_opacity);}'),symbolTextAndIcon:gi('#include \"_prelude_lighting.glsl\"\\n#define SDF_PX 8.0\\n#define SDF 1.0\\n#define ICON 0.0\\nuniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_halo;in float v_draw_halo;in vec4 v_data0;in vec4 v_data1;\\n#pragma mapbox: define highp vec4 fill_color\\n#pragma mapbox: define highp vec4 halo_color\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float halo_width\\n#pragma mapbox: define lowp float halo_blur\\n#pragma mapbox: define lowp float emissive_strength\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 fill_color\\n#pragma mapbox: initialize highp vec4 halo_color\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float halo_width\\n#pragma mapbox: initialize lowp float halo_blur\\n#pragma mapbox: initialize lowp float emissive_strength\\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;glFragColor=texture(u_texture_icon,tex_icon)*alpha;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);vec4 out_color=color*(alpha*opacity*fade_opacity);\\n#ifdef LIGHTING_3D_MODE\\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\\n#endif\\nglFragColor=out_color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_terrain.vertex.glsl\"\\nin vec4 a_pos_offset;in vec4 a_tex_size;in vec4 a_projected_pos;in float a_fade_opacity;\\n#ifdef Z_OFFSET\\nin float a_z_offset;\\n#endif\\n#ifdef PROJECTION_GLOBE_VIEW\\nin vec3 a_globe_anchor;in vec3 a_globe_normal;\\n#endif\\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo;\\n#ifdef PROJECTION_GLOBE_VIEW\\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\\n#endif\\nout float v_draw_halo;out vec4 v_data0;out vec4 v_data1;\\n#pragma mapbox: define highp vec4 fill_color\\n#pragma mapbox: define highp vec4 halo_color\\n#pragma mapbox: define lowp float opacity\\n#pragma mapbox: define lowp float halo_width\\n#pragma mapbox: define lowp float halo_blur\\n#pragma mapbox: define lowp float emissive_strength\\nvoid main() {\\n#pragma mapbox: initialize highp vec4 fill_color\\n#pragma mapbox: initialize highp vec4 halo_color\\n#pragma mapbox: initialize lowp float opacity\\n#pragma mapbox: initialize lowp float halo_width\\n#pragma mapbox: initialize lowp float halo_blur\\n#pragma mapbox: initialize lowp float emissive_strength\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[3];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=elevation(tile_anchor);\\n#ifdef Z_OFFSET\\ne+=a_z_offset;\\n#endif\\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos=mix_globe_mercator(a_globe_anchor+h,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\\n#else\\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\\n#endif\\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ?\\ncamera_to_anchor_distance/u_camera_to_center_distance :\\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(\\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offset_projected_point=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projected_point.xy/projected_point.w;vec2 b=offset_projected_point.xy/offset_projected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz+h,mercator_pos,u_zoom_transition);projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\\n#else\\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\\n#endif\\nhighp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*font_scale);\\n#ifdef TERRAIN\\n#ifdef PITCH_WITH_MAP_TERRAIN\\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\\n#endif\\n#endif\\nfloat occlusion_fade=occlusionFade(projected_point)*globe_occlusion_fade;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));float projection_transition_fade=1.0;\\n#if defined(PROJECTED_POS_ON_VIEWPORT) && defined(PROJECTION_GLOBE_VIEW)\\nprojection_transition_fade=1.0-step(EPSILON,u_zoom_transition);\\n#endif\\nfloat out_fade_opacity=interpolated_fade_opacity*projection_transition_fade;float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);\\n#ifdef PROJECTION_GLOBE_VIEW\\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);gl_Position=mix(u_coord_matrix*vec4(projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y,1.0),AWAY,hidden);\\n#else\\ngl_Position=mix(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+offset,z,1.0),AWAY,hidden);\\n#endif\\nfloat gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,out_fade_opacity,is_sdf);}'),terrainRaster:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_shadow.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform sampler2D u_image0;in vec2 v_pos0;\\n#ifdef FOG\\nin float v_fog_opacity;\\n#endif\\n#ifdef RENDER_SHADOWS\\nin vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;in float v_depth;\\n#endif\\nuniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color;\\n#ifdef LIGHTING_3D_MODE\\nconst vec3 normal=vec3(0.0,0.0,1.0);\\n#ifdef RENDER_SHADOWS\\nfloat cutoffOpacity=1.0;\\n#ifdef RENDER_CUTOFF\\ncutoffOpacity=cutoff_opacity(u_cutoff_params,v_depth);\\n#endif\\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\\nvec3 unlit_base=image_color.rgb*(1.0-image_color.a);vec3 emissive_base=image_color.rgb*image_color.a;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,v_depth,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0;\\n#else\\nfloat lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity));\\n#endif\\n#else\\nfloat lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor);\\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\\ncolor.rgb=mix(color.rgb,image_color.rgb,image_color.a);color.a=1.0;\\n#endif\\n#endif\\n#else\\ncolor=image_color;\\n#endif\\n#ifdef FOG\\n#ifdef ZERO_EXAGGERATION\\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\\n#else\\ncolor=fog_dither(fog_apply_from_vert(color,v_fog_opacity));\\n#endif\\n#endif\\nglFragColor=color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_terrain.vertex.glsl\"\\nuniform mat4 u_matrix;uniform float u_skirt_height;in vec2 a_pos;out vec2 v_pos0;\\n#ifdef FOG\\nout float v_fog_opacity;\\n#endif\\n#ifdef RENDER_SHADOWS\\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1;out float v_depth;\\n#endif\\nvoid main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0);\\n#ifdef FOG\\n#ifdef ZERO_EXAGGERATION\\nv_fog_pos=fog_position(decodedPos);\\n#else\\nv_fog_opacity=fog(fog_position(vec3(decodedPos,elevation)));\\n#endif\\n#endif\\n#ifdef RENDER_SHADOWS\\nvec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.);v_depth=gl_Position.w;\\n#endif\\n}'),terrainDepth:gi(\"precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}\",'#include \"_prelude_terrain.vertex.glsl\"\\nuniform mat4 u_matrix;in vec2 a_pos;out float v_depth;void main() {float elevation=elevation(a_pos);gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}'),skybox:gi('#include \"_prelude_fog.fragment.glsl\"\\nin lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep(\\ncos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=texture(u_cubemap,uv).rgb;\\n#ifdef FOG\\nsky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color);\\n#endif\\nsky_color.rgb=dither(sky_color.rgb,gl_FragCoord.xy+u_temporal_offset);sky_color+=0.1*sun_disk(v_uv,u_sun_direction);glFragColor=vec4(sky_color*u_opacity,u_opacity);\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\n}',oi),skyboxGradient:gi('#include \"_prelude_fog.fragment.glsl\"\\nin highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture(u_color_ramp,vec2(progress,0.5));\\n#ifdef FOG\\ncolor.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a;\\n#endif\\ncolor*=u_opacity;color.rgb=dither(color.rgb,gl_FragCoord.xy+u_temporal_offset);glFragColor=color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\n}',oi),skyboxCapture:gi(\"\\nin highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float;\\n#define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6)\\n#define BETA_M vec3(21e-6,21e-6,21e-6)\\n#define MIE_G 0.76\\n#define DENSITY_HEIGHT_SCALE_R 8000.0\\n#define DENSITY_HEIGHT_SCALE_M 1200.0\\n#define PLANET_RADIUS 6360e3\\n#define ATMOSPHERE_RADIUS 6420e3\\n#define SAMPLE_STEPS 10\\n#define DENSITY_STEPS 4\\nfloat ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}\",\"in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=pos.xyz;v_position.y*=-1.0;v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}\"),globeRaster:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform sampler2D u_image0;in vec2 v_pos0;\\n#ifndef FOG\\nuniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport;\\n#endif\\nvoid main() {vec4 color;\\n#ifdef CUSTOM_ANTIALIASING\\nvec2 uv=gl_FragCoord.xy/u_viewport;highp vec3 ray_dir=mix(\\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);vec3 dir=normalize(ray_dir);vec3 closest_point=dot(u_globe_pos,dir)*dir;float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0);\\n#ifdef LIGHTING_3D_MODE\\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\\nraster=apply_lighting_with_emission_ground(raster,raster.a);color=vec4(raster.rgb*antialias,antialias);\\n#else\\nraster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias);\\n#endif\\n#else\\ncolor=vec4(raster.rgb*antialias,raster.a*antialias);\\n#endif\\n#else\\ncolor=texture(u_image0,v_pos0);\\n#ifdef LIGHTING_3D_MODE\\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\\ncolor=apply_lighting_with_emission_ground(color,color.a);color.a=1.0;\\n#else\\ncolor=apply_lighting_ground(color);\\n#endif\\n#endif\\n#endif\\n#ifdef FOG\\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\\n#endif\\nglFragColor=color;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_terrain.vertex.glsl\"\\nuniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height;\\n#ifdef GLOBE_POLES\\nin vec3 a_globe_pos;in vec2 a_uv;\\n#else\\nin vec2 a_pos;\\n#endif\\nout vec2 v_pos0;void main() {\\n#ifdef GLOBE_POLES\\nvec3 globe_pos=a_globe_pos;vec2 uv=a_uv;\\n#else\\nfloat tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY);\\n#endif\\nv_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale;\\n#ifdef GLOBE_POLES\\nvec3 up_vector=globe_derived_up_vector;\\n#else\\nvec3 up_vector=elevationVector(tile_pos);\\n#endif\\nfloat height=elevation(tile_pos);globe_pos+=up_vector*height;\\n#ifndef GLOBE_POLES\\nglobe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z;\\n#endif\\n#ifdef GLOBE_POLES\\nvec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0);\\n#else\\nvec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0);\\n#endif\\ngl_Position=u_proj_matrix*interpolated_pos;\\n#ifdef FOG\\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\\n#endif\\n}'),globeAtmosphere:gi('#include \"_prelude_fog.fragment.glsl\"\\nuniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir;\\n#ifdef PROJECTION_GLOBE_VIEW\\nglobe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) {\\n#ifdef ALPHA_PASS\\nglFragColor=vec4(0,0,0,0);return;\\n#else\\n#ifdef NATIVE\\nglFragColor=vec4(1,1,1,1);\\n#else\\nglFragColor=vec4(0,0,0,1);\\n#endif\\nreturn;\\n#endif\\n}\\n#endif\\nhighp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ?\\n0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle;\\n#ifdef PROJECTION_GLOBE_VIEW\\nhighp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ?\\nPI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t);\\n#else\\nhorizon_angle=horizon_angle_mercator;\\n#endif\\nhorizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb;\\n#ifdef ALPHA_PASS\\nfloat a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a);\\n#else\\nvec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;\\n#ifndef NATIVE\\nc=dither(c,gl_FragCoord.xy+u_temporal_offset);\\n#endif\\nglFragColor=vec4(c*t,t);\\n#endif\\n}',\"in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix(\\nmix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix(\\nmix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}\"),model:gi('#include \"_prelude_fog.fragment.glsl\"\\n#include \"_prelude_shadow.fragment.glsl\"\\n#include \"_prelude_lighting.glsl\"\\nuniform float u_opacity;uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix;\\n#ifdef RENDER_SHADOWS\\nin vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;in float v_depth_shadows;\\n#endif\\n#ifdef OCCLUSION_TEXTURE_TRANSFORM\\nuniform vec4 u_occlusionTextureTransform;\\n#endif\\n#pragma mapbox: define-attribute highp vec3 normal_3f\\n#pragma mapbox: define-attribute highp vec3 color_3f\\n#pragma mapbox: define-attribute highp vec4 color_4f\\n#pragma mapbox: define-attribute highp vec2 uv_2f\\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\\n#pragma mapbox: initialize-attribute highp vec3 color_3f\\n#pragma mapbox: initialize-attribute highp vec4 color_4f\\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\\n#ifdef HAS_ATTRIBUTE_a_pbr\\nin lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params;\\n#endif\\n#ifdef HAS_TEXTURE_u_baseColorTexture\\nuniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff;\\n#endif\\n#ifdef HAS_TEXTURE_u_metallicRoughnessTexture\\nuniform sampler2D u_metallicRoughnessTexture;\\n#endif\\n#ifdef HAS_TEXTURE_u_occlusionTexture\\nuniform sampler2D u_occlusionTexture;uniform float u_aoIntensity;\\n#endif\\n#ifdef HAS_TEXTURE_u_normalTexture\\nuniform sampler2D u_normalTexture;\\n#endif\\n#ifdef HAS_TEXTURE_u_emissionTexture\\nuniform sampler2D u_emissionTexture;\\n#endif\\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\\nin highp float v_depth;uniform sampler2D u_depthTexture;uniform vec2 u_inv_depth_size;bool isOccluded() {vec2 coord=gl_FragCoord.xy*u_inv_depth_size;highp float depth=unpack_depth(texture(u_depthTexture,coord));return v_depth > depth+0.0005;}\\n#endif\\n#define saturate(_x) clamp(_x,0.,1.)\\nvec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor)\\n{\\n#ifdef LIGHTING_3D_MODE\\nvec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor;\\n#ifdef RENDER_SHADOWS\\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\\n#else\\nlighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir));\\n#endif\\nreturn apply_lighting(albedo,transformed_normal,lighting_factor);\\n#else\\nvec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3;\\n#endif\\n}vec4 getBaseColor() {vec4 albedo=u_baseColorFactor;\\n#ifdef HAS_ATTRIBUTE_a_color_3f\\nalbedo*=vec4(color_3f,1.0);\\n#endif\\n#ifdef HAS_ATTRIBUTE_a_pbr\\n#else\\n#ifdef HAS_ATTRIBUTE_a_color_4f\\nalbedo*=color_4f;\\n#endif\\n#endif\\n#if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f)\\nvec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}}\\n#ifdef UNPREMULT_TEXTURE_IN_SHADER\\nif(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0;\\n#endif\\nif(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;}\\n#endif\\nreturn vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a);}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) {\\n#ifdef HAS_TEXTURE_u_normalTexture\\nhighp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res;\\n#else\\nreturn mat3(1.0);\\n#endif\\n}highp vec3 getNormal(){highp vec3 n;\\n#ifdef HAS_ATTRIBUTE_a_normal_3f\\nn=normalize(normal_3f);\\n#else\\nhighp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z));n=normalize(cross(fdx,fdy))*-1.0;\\n#endif\\n#if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\\nvec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap);\\n#endif\\nreturn n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor;\\n#ifdef HAS_ATTRIBUTE_a_pbr\\nmat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w;\\n#endif\\n#if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) \\nvec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b;\\n#endif\\nconst float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness)\\n{float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH)\\n{return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH)\\n{float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness)\\n{highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV)\\n{float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat)\\n{\\n#ifdef LIGHTING_3D_MODE\\nreturn mat.diffuseColor;\\n#else\\nreturn mat.diffuseColor/PI;\\n#endif\\n}vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV)\\n{vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal)\\n{vec3 env_light=vec3(0.65,0.65,0.65);\\n#ifdef LIGHTING_3D_MODE\\nfloat ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor;\\n#endif\\nvec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor)\\n{highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor;\\n#ifdef RENDER_SHADOWS\\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\\n#else\\nlighting_factor=NdotL;\\n#endif\\nvec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0;\\n#if !defined(LIGHTING_3D_MODE)\\nconst vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL);\\n#endif\\ncolor*=intensityFactor;return color;}void main() {\\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\\nif (isOccluded()) {discard;}\\n#endif\\nvec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor;\\n#ifdef LIGHTING_3D_MODE\\nlightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color;\\n#endif\\nvec4 finalColor;\\n#ifdef DIFFUSE_SHADED\\nvec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor);\\n#ifdef HAS_TEXTURE_u_occlusionTexture\\nfloat ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao;\\n#endif\\nfinalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity;\\n#else\\nMaterial mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0;\\n#if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\\n#ifdef OCCLUSION_TEXTURE_TRANSFORM\\nvec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy;\\n#else\\nvec2 uv=uv_2f;\\n#endif\\nao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao;\\n#endif\\nvec4 emissive=u_emissiveFactor;\\n#if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\\nemissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb);\\n#endif\\ncolor+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity;\\n#ifdef HAS_ATTRIBUTE_a_pbr\\nfloat resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);color=mix(color,v_color_mix.rgb,min(1.0,resEmission));\\n#ifdef HAS_ATTRIBUTE_a_color_4f\\nfloat distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance);\\n#endif\\n#endif\\nvec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity);\\n#endif\\n#ifdef FOG\\nfinalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w));\\n#endif\\n#ifdef RENDER_CUTOFF\\nfinalColor*=v_cutoff_opacity;\\n#endif\\n#ifdef INDICATOR_CUTOUT\\nfinalColor=applyCutout(finalColor);\\n#endif\\nglFragColor=finalColor;\\n#ifdef OVERDRAW_INSPECTOR\\nglFragColor=vec4(1.0);\\n#endif\\nHANDLE_WIREFRAME_DEBUG;}','#include \"_prelude_fog.vertex.glsl\"\\n#include \"_prelude_shadow.vertex.glsl\"\\nin vec3 a_pos_3f;\\n#pragma mapbox: define-attribute highp vec3 normal_3f\\n#pragma mapbox: define-attribute highp vec2 uv_2f\\n#pragma mapbox: define-attribute highp vec3 color_3f\\n#pragma mapbox: define-attribute highp vec4 color_4f\\n#pragma mapbox: define-attribute-vertex-shader-only highp vec4 pbr\\n#pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength\\nuniform mat4 u_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix;\\n#ifdef INSTANCED_ARRAYS\\nin vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3;\\n#else\\nuniform highp mat4 u_normal_matrix;\\n#endif\\n#ifdef RENDER_SHADOWS\\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1;out float v_depth_shadows;\\n#endif\\nout vec4 v_position_height;out lowp vec4 v_color_mix;\\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\\nout highp float v_depth;\\n#endif\\n#ifdef HAS_ATTRIBUTE_a_pbr\\nout lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params;\\n#endif\\nvec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() {\\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\\n#pragma mapbox: initialize-attribute highp vec3 color_3f\\n#pragma mapbox: initialize-attribute highp vec4 color_4f\\n#pragma mapbox: initialize-attribute-custom highp vec4 pbr\\n#pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength\\nhighp mat4 normal_matrix;\\n#ifdef INSTANCED_ARRAYS\\nnormal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\\n#else\\nnormal_matrix=u_normal_matrix;\\n#endif\\nvec3 local_pos;mat3 rs;\\n#ifdef MODEL_POSITION_ON_GPU\\nvec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=u_matrix*pos;pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos;\\n#else\\nlocal_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a);\\n#endif\\nv_position_height.w=a_pos_3f.z;\\n#ifdef HAS_ATTRIBUTE_a_pbr\\nvec4 albedo_c=decode_color(pbr.xy);vec2 e_r_m=unpack_float(pbr.z);vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(pbr.w)/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x;\\n#endif\\n#ifdef FOG\\nv_fog_pos=fog_position(local_pos);\\n#endif\\n#ifdef RENDER_CUTOFF\\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\\n#endif\\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n#ifdef HAS_ATTRIBUTE_a_normal_3f\\n#ifdef MODEL_POSITION_ON_GPU\\nfloat x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f);\\n#else\\nnormal_3f=vec3(normal_matrix*vec4(normal_3f,0));\\n#endif\\n#endif\\n#ifdef HAS_ATTRIBUTE_a_pbr\\n#ifdef HAS_ATTRIBUTE_a_color_4f\\nv_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0);\\n#endif\\n#endif\\n#ifdef RENDER_SHADOWS\\nvec3 shadow_pos=local_pos;\\n#ifdef NORMAL_OFFSET\\n#ifdef HAS_ATTRIBUTE_a_normal_3f\\n#ifdef MODEL_POSITION_ON_GPU\\nvec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos+=offset*shadow_normal_offset_multiplier0();\\n#else\\nvec3 offset=shadow_normal_offset_model(normalize(normal_3f));shadow_pos+=offset*shadow_normal_offset_multiplier0();\\n#endif\\n#endif\\n#endif\\nv_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1);v_depth_shadows=gl_Position.w;\\n#endif\\n}'),modelDepth:gi(\"in highp float v_depth;void main() {\\n#ifndef DEPTH_TEXTURE\\nglFragColor=pack_depth(v_depth);\\n#endif\\n}\",\"in vec3 a_pos_3f;uniform mat4 u_matrix;out highp float v_depth;\\n#ifdef MODEL_POSITION_ON_GPU\\n#ifdef INSTANCED_ARRAYS\\nin vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3;\\n#else\\nuniform highp mat4 u_instance;\\n#endif\\nuniform highp mat4 u_node_matrix;\\n#endif\\nvoid main() {\\n#ifdef MODEL_POSITION_ON_GPU\\nhighp mat4 instance;\\n#ifdef INSTANCED_ARRAYS\\ninstance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\\n#else\\ninstance=u_instance;\\n#endif\\nvec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=u_matrix*pos;\\n#else\\ngl_Position=u_matrix*vec4(a_pos_3f,1);\\n#endif\\nv_depth=gl_Position.z/gl_Position.w;}\"),stars:gi(\"in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv)\\n{float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}\",\"\\nin vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_fade_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_fade_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}\")};function fi(e,t){const i=e.replace(/\\s*\\/\\/[^\\n]*\\n/g,\"\\n\").split(\"\\n\");for(let e of i)if(e=e.trim(),\"#\"===e[0]&&e.includes(\"if\")&&!e.includes(\"endif\")){e=e.replace(\"#\",\"\").replace(/ifdef|ifndef|elif|if/g,\"\").replace(/!|defined|\\(|\\)|\\|\\||&&/g,\"\").replace(/\\s+/g,\" \").trim();const i=e.split(\" \");for(const e of i)t.includes(e)||t.push(e);}}function gi(e,t){const i=/#include\\s+\"([^\"]+)\"/g,o=/#pragma mapbox: ([\\w\\-]+) ([\\w]+) ([\\w]+) ([\\w]+)/g;let r=t.match(/(attribute(\\S*)|(^\\s*|;)in) (highp |mediump |lowp )?([\\w]+) ([\\w]+)/gm);r&&(r=r.map((e=>{const t=e.split(\" \");return t[t.length-1]})),r=[...new Set(r)]);const s={},n=[],a=[];if(e=e.replace(i,((e,t)=>(a.push(t),\"\"))),(t=t.replace(i,((e,t)=>(n.push(t),\"\")))).includes(\"flat out\"))return void console.error('The usage of \"flat\" qualifier is disallowed, see: https://bugs.webkit.org/show_bug.cgi?id=268071');let l=[...hi];fi(e,l),fi(t,l);for(const e of [...n,...a])_i[e]||console.error(`Undefined include: ${e}`),di[e]||(di[e]=[],fi(_i[e],di[e])),l=[...l,...di[e]];return {fragmentSource:e=e.replace(o,((e,t,i,o,r)=>(s[r]=!0,\"define\"===t?`\\n#ifndef HAS_UNIFORM_u_${r}\\nin ${i} ${o} ${r};\\n#else\\nuniform ${i} ${o} u_${r};\\n#endif\\n`:\"initialize\"===t?`\\n#ifdef HAS_UNIFORM_u_${r}\\n ${i} ${o} ${r} = u_${r};\\n#endif\\n`:\"define-attribute\"===t?`\\n#ifdef HAS_ATTRIBUTE_a_${r}\\n in ${i} ${o} ${r};\\n#endif\\n`:\"initialize-attribute\"===t?\"\":void 0))),vertexSource:t=t.replace(o,((e,t,i,o,r)=>{const n=\"float\"===o?\"vec2\":o,a=r.match(/color/)?\"color\":n;return \"define-attribute-vertex-shader-only\"===t?`\\n#ifdef HAS_ATTRIBUTE_a_${r}\\nin ${i} ${o} a_${r};\\n#endif\\n`:s[r]?\"define\"===t?`\\n#ifndef HAS_UNIFORM_u_${r}\\nuniform lowp float u_${r}_t;\\nin ${i} ${n} a_${r};\\nout ${i} ${o} ${r};\\n#else\\nuniform ${i} ${o} u_${r};\\n#endif\\n`:\"initialize\"===t?\"vec4\"===a?`\\n#ifndef HAS_UNIFORM_u_${r}\\n ${r} = a_${r};\\n#else\\n ${i} ${o} ${r} = u_${r};\\n#endif\\n`:`\\n#ifndef HAS_UNIFORM_u_${r}\\n ${r} = unpack_mix_${a}(a_${r}, u_${r}_t);\\n#else\\n ${i} ${o} ${r} = u_${r};\\n#endif\\n`:\"define-attribute\"===t?`\\n#ifdef HAS_ATTRIBUTE_a_${r}\\n in ${i} ${o} a_${r};\\n out ${i} ${o} ${r};\\n#endif\\n`:\"initialize-attribute\"===t?`\\n#ifdef HAS_ATTRIBUTE_a_${r}\\n ${r} = a_${r};\\n#endif\\n`:void 0:\"define\"===t?`\\n#ifndef HAS_UNIFORM_u_${r}\\nuniform lowp float u_${r}_t;\\nin ${i} ${n} a_${r};\\n#else\\nuniform ${i} ${o} u_${r};\\n#endif\\n`:\"define-instanced\"===t?\"mat4\"===a?`\\n#ifdef INSTANCED_ARRAYS\\nin vec4 a_${r}0;\\nin vec4 a_${r}1;\\nin vec4 a_${r}2;\\nin vec4 a_${r}3;\\n#else\\nuniform ${i} ${o} u_${r};\\n#endif\\n`:`\\n#ifdef INSTANCED_ARRAYS\\nin ${i} ${n} a_${r};\\n#else\\nuniform ${i} ${o} u_${r};\\n#endif\\n`:\"initialize-attribute-custom\"===t?`\\n#ifdef HAS_ATTRIBUTE_a_${r}\\n ${i} ${o} ${r} = a_${r};\\n#endif\\n`:\"vec4\"===a?`\\n#ifndef HAS_UNIFORM_u_${r}\\n ${i} ${o} ${r} = a_${r};\\n#else\\n ${i} ${o} ${r} = u_${r};\\n#endif\\n`:`\\n#ifndef HAS_UNIFORM_u_${r}\\n ${i} ${o} ${r} = unpack_mix_${a}(a_${r}, u_${r}_t);\\n#else\\n ${i} ${o} ${r} = u_${r};\\n#endif\\n`})),staticAttributes:r,usedDefines:l,vertexIncludes:n,fragmentIncludes:a}}class vi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null;}bind(e,t,i,o,r,s,n,a){this.context=e;let l=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!l&&e{const s=o.paint.get(\"hillshade-shadow-color\"),n=o.paint.get(\"hillshade-highlight-color\"),a=o.paint.get(\"hillshade-accent-color\"),l=o.paint.get(\"hillshade-emissive-strength\");let c=e.d(o.paint.get(\"hillshade-illumination-direction\"));if(\"viewport\"===o.paint.get(\"hillshade-illumination-anchor\"))c-=t.transform.angle;else if(t.style&&t.style.enable3dLights()&&t.style.directionalLight){const i=t.style.directionalLight.properties.get(\"direction\"),o=e.b3(i.x,i.y,i.z);c=e.d(o[1]);}const h=!t.options.moving;return {u_matrix:r||t.transform.calculateProjMatrix(i.tileID.toUnwrapped(),h),u_image:0,u_latrange:xi(0,i.tileID),u_light:[o.paint.get(\"hillshade-exaggeration\"),c],u_shadow:s,u_highlight:n,u_emissive_strength:l,u_accent:a}})(t,o,r,t.terrain?i.projMatrix:null);t.uploadCommonUniforms(l,d,i.toUnwrapped());const{tileBoundsBuffer:p,tileBoundsIndexBuffer:m,tileBoundsSegments:f}=t.getTileBoundsBuffers(o);d.draw(t,c.TRIANGLES,s,n,a,e.b5.disabled,u,r.id,p,m,f);}function bi(t,i,o){if(!i.needsDEMTextureUpload)return;const r=t.context,s=r.gl;r.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||t.getTileTexture(o.stride);const n=o.getPixels();i.demTexture?i.demTexture.update(n,{premultiply:!1}):i.demTexture=new e.a9(r,n,s.R32F,{premultiply:!1}),i.needsDEMTextureUpload=!1;}function wi(t,i,o){const r=t.context,s=r.gl;if(!i.dem)return;const n=i.dem;if(r.activeTexture.set(s.TEXTURE1),bi(t,i,n),!i.demTexture)return;i.demTexture.bind(s.NEAREST,s.CLAMP_TO_EDGE);const a=n.dim;r.activeTexture.set(s.TEXTURE0);let l=i.hillshadeFBO;if(!l){const t=new e.a9(r,{width:a,height:a,data:null},s.RGBA);t.bind(s.LINEAR,s.CLAMP_TO_EDGE),l=i.hillshadeFBO=r.createFramebuffer(a,a,!0,\"renderbuffer\"),l.colorAttachment.set(t.texture);}r.bindFramebuffer.set(l.framebuffer),r.viewport.set([0,0,a,a]);const{tileBoundsBuffer:c,tileBoundsIndexBuffer:h,tileBoundsSegments:_}=t.getMercatorTileBoundsBuffers(),d=[];t.linearFloatFilteringSupported()&&d.push(\"TERRAIN_DEM_FLOAT_FORMAT\"),t.getOrCreateProgram(\"hillshadePrepare\",{defines:d}).draw(t,s.TRIANGLES,e.b4.disabled,e.b6.disabled,e.a.unblended,e.b5.disabled,((t,i)=>{const o=i.stride,r=e.m.create();return e.m.ortho(r,0,e.J,-e.J,0,0,1),e.m.translate(r,r,[0,-e.J,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:t.overscaledZ}})(i.tileID,n),o.id,c,h,_),i.needsHillshadePrepare=!1;}const Ti=t=>({u_matrix:new e.a_(t),u_image0:new e.a$(t),u_skirt_height:new e.b2(t),u_ground_shadow_factor:new e.b7(t)}),Ei=(e,t,i)=>({u_matrix:e,u_image0:0,u_skirt_height:t,u_ground_shadow_factor:i}),Ci=(e,t,i,o,r,s,n,a,l,c,h,_,d,u,p)=>({u_proj_matrix:Float32Array.from(e),u_globe_matrix:t,u_normalize_matrix:Float32Array.from(o),u_merc_matrix:i,u_zoom_transition:r,u_merc_center:s,u_image0:0,u_frustum_tl:n,u_frustum_tr:a,u_frustum_br:l,u_frustum_bl:c,u_globe_pos:h,u_globe_radius:_,u_viewport:d,u_grid_matrix:p?Float32Array.from(p):new Float32Array(9),u_skirt_height:u}),Ii=(t,i)=>{if(i>0&&t.terrain&&e.X(\"Cutoff is currently disabled on terrain\"),i<=0||t.terrain)return {shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const o=t.transform,r=Math.max(Math.abs(o._zoom-(t.minCutoffZoom-1)),1),s=o.isLODDisabled(!1)?e.an(60,45,o.pitch):e.an(30,15,o.pitch),n=o._farZ-o._nearZ,a=i*o.height,l=((1-(c=s))*o.cameraToCenterDistance+c*(o._farZ+a))*r;var c;return {shouldRenderCutoff:s<1,uniformValues:{u_cutoff_params:[o._nearZ,o._farZ,(l-o._nearZ)/n,(l-a-o._nearZ)/n]}}};function Si(e,t){return null!=e&&null!=t&&!(!e.hasData()||!t.hasData())&&null!=e.demTexture&&null!=t.demTexture&&e.tileID.key!==t.tileID.key}const Mi=new class{constructor(){this.operations={};}newMorphing(e,t,i,o,r){if(e in this.operations){const t=this.operations[e];t.to.tileID.key!==i.tileID.key&&(t.queued=i);}else this.operations[e]={startTime:o,phase:0,duration:r,from:t,to:i,queued:null};}getMorphValuesForProxy(e){if(!(e in this.operations))return null;const t=this.operations[e];return {from:t.from,to:t.to,phase:t.phase}}update(e){for(const t in this.operations){const i=this.operations[t];for(i.phase=(e-i.startTime)/i.duration;i.phase>=1||!this._validOp(i);)if(!this._nextOp(i,e)){delete this.operations[t];break}}}_nextOp(e,t){return !!e.queued&&(e.from=e.to,e.to=e.queued,e.queued=null,e.phase=0,e.startTime=t,!0)}_validOp(e){return e.from.hasData()&&e.to.hasData()}},Li={0:null,1:\"TERRAIN_VERTEX_MORPHING\"};function Pi(e,t,i){if(0===t)return 0;const o=t<1&&514===i?.25/t:1;return 6*Math.pow(1.5,22-e)*Math.max(t,1)*o}function Di(e,t){const i=1<({u_matrix:e});function Ri(t,i,o,r,s){if(s>0){const n=e.a4.now(),a=(n-t.timeAdded)/s,l=i?(n-i.timeAdded)/s:-1,c=o.getSource(),h=r.coveringZoomLevel({tileSize:c.tileSize,roundZoom:c.roundZoom}),_=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(t.tileID.overscaledZ-h),d=_&&t.refreshedUponExpiration?1:e.c(_?a:1-l,0,1);return t.refreshedUponExpiration&&a>=1&&(t.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}class zi extends e.bq{constructor(t){const i={type:\"raster-dem\",maxzoom:t.transform.maxZoom},o=new e.br(e.bs(),null),r=st(\"mock-dem\",i,o,t.style);super(\"mock-dem\",r,!1),r.setEventedParent(this),this._sourceLoaded=!0;}_loadTile(e,t){e.state=\"loaded\",t(null);}}class Oi extends e.bq{constructor(t){const i=st(\"proxy\",{type:\"geojson\",maxzoom:t.transform.maxZoom},new e.br(e.bs(),null),t.style);super(\"proxy\",i,!1),i.setEventedParent(this),this.map=this.getSource().map=t,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={};}update(t,i,o){if(t.freezeTileCoverage)return;this.transform=t;const r=t.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce(((i,o)=>{if(i[o.key]=\"\",!this._tiles[o.key]){const i=new e.bt(o,this._source.tileSize*o.overscaleFactor(),t.tileZoom);i.state=\"loaded\",this._tiles[o.key]=i;}return i}),{});for(const e in this._tiles)e in r||(this.freeFBO(e),this._tiles[e].unloadVectorData(),delete this._tiles[e]);}freeFBO(e){const t=this.proxyCachedFBO[e];if(void 0!==t){const i=Object.values(t);this.renderCachePool.push(...i),delete this.proxyCachedFBO[e];}}deallocRenderCache(){this.renderCache.forEach((e=>e.fb.destroy())),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={};}}class Fi extends e.O{constructor(e,t,i){super(e.overscaledZ,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y),this.proxyTileKey=t,this.projMatrix=i;}}class Bi extends e.bk{constructor(t,i){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},t.tp.registerParameter(this._debugParams,[\"Terrain\"],\"sortTilesHiZFirst\",{},(()=>{this._style.map.triggerRepaint();})),t.tp.registerParameter(this._debugParams,[\"Terrain\"],\"disableRenderCache\",{},(()=>{this._style.map.triggerRepaint();})),t.tp.registerButton([\"Terrain\"],\"Invalidate Render Cache\",(()=>{this.invalidateRenderCache=!0,this._style.map.triggerRepaint();})),this.painter=t,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[o,r,s]=function(t){const i=new e.bo,o=new e.bp,r=131;i.reserve(17161),o.reserve(33800);const s=e.J/128,n=e.J+s/2,a=n+s;for(let t=-s;tn||t<0||t>n?24575:0,s=e.c(Math.round(o),0,e.J),a=e.c(Math.round(t),0,e.J);i.emplaceBack(s+r,a);}const l=(e,t)=>{const i=t*r+e;o.emplaceBack(i+1,i,i+r),o.emplaceBack(i+r,i+r+1,i+1);};for(let e=1;e<129;e++)for(let t=1;t<129;t++)l(t,e);return [0,129].forEach((e=>{for(let t=0;t<130;t++)l(t,e),l(e,t);})),[i,o,32768]}(),n=t.context;this.gridBuffer=n.createVertexBuffer(o,e.bl.members),this.gridIndexBuffer=n.createIndexBuffer(r),this.gridSegments=e.bm.simpleSegment(0,0,o.length,r.length),this.gridNoSkirtSegments=e.bm.simpleSegment(0,0,o.length,s),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new Oi(i.map),this.orthoMatrix=e.m.create(),e.m.ortho(this.orthoMatrix,\"globe\"===this.painter.transform.projection.name?.015:0,e.J,0,e.J,0,1);const a=n.gl;this._overlapStencilMode=new e.b6({func:a.GEQUAL,mask:255},0,255,a.KEEP,a.KEEP,a.REPLACE),this._previousZoom=t.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=i,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new zi(i.map),this._pendingGroundEffectLayers=[];}set style(e){e.on(\"data\",this._onStyleDataEvent.bind(this)),this._style=e,this._style.map.on(\"moveend\",(()=>{this._clearLineLayersFromRenderCache();}));}update(t,i,o){if(t&&t.terrain){this._style!==t&&(this.style=t,this._evaluationZoom=void 0);const r=t.terrain.properties,s=0===t.terrain.drapeRenderMode,n=t.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=e.a4.now();const a=t.terrain&&t.terrain.scope,l=r.get(\"source\"),c=s?this._mockSourceCache:t.getSourceCache(l,a);if(!c)return void e.X(`Couldn't find terrain source \"${l}\".`);if(this.sourceCache=c,this._exaggeration=n?this.calculateExaggeration(i):r.get(\"exaggeration\"),!i.projection.requiresDraping&&n&&0===this._exaggeration)return void this._disable();this.enabled=!0;const h=()=>{this.sourceCache.used&&e.X(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source.\\nThis leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.`);const t=this.getScaledDemTileSize();this.sourceCache.update(i,t,!0),this.resetTileLookupCache(this.sourceCache.id);};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,h(),this._initializing=!0),h(),i.updateElevation(!0,o),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(i),this._emptyDEMTextureDirty=!0,this._previousZoom=i.zoom;}else this._disable();}calculateExaggeration(t){const i=this._previousCameraAltitude,o=t.getFreeCameraOptions().position.z/t.pixelsPerMeter*t.worldSize;this._previousCameraAltitude=o;const r=null!=i?o-i:Number.MAX_VALUE;if(Math.abs(r)<2)return this._exaggeration;const s=t.zoom,n=this._style.terrain;if(!this._previousUpdateTimestamp)return n.getExaggeration(s);let a=s-this._previousZoom;const l=this._previousUpdateTimestamp;let c=s;null!=this._evaluationZoom&&(c=this._evaluationZoom,Math.abs(s-c)>.5&&(a=.5*(s-c+a)),a*r<0&&(c+=a)),this._evaluationZoom=c;const h=n.getExaggeration(c),_=h===n.getExaggeration(Math.max(0,c-.1));if(_&&Math.abs(h-this._exaggeration)<.01)return h;let d=Math.min(.1,.00375*(this._updateTimestamp-l));return (_||h<.1||Math.abs(a)<1e-4)&&(d=Math.min(.2,4*d)),e.n(this._exaggeration,h,d)}resetTileLookupCache(e){this._findCoveringTileCache[e]={};}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(e){e.coord&&\"source\"===e.dataType?this._clearRenderCacheForTile(e.sourceCacheId,e.coord):\"style\"===e.dataType&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0);}_disable(){if(this.enabled&&(this.enabled=!1,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const e in this._style._mergedSourceCaches)this._style._mergedSourceCaches[e].usedForTerrain=!1;}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this._emptyDepthBufferTexture&&this._emptyDepthBufferTexture.destroy(),this.pool.forEach((e=>e.fb.destroy())),this.pool=[],this._depthFBO&&(this._depthFBO.destroy(),this._depthFBO=void 0,this._depthTexture=void 0),this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy();}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this._exaggeration}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const e=2*this.proxySourceCache.getSource().tileSize;return [e,e]}set useVertexMorphing(e){this._useVertexMorphing=e;}updateTileBinding(t){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const i=this.proxySourceCache,o=this.painter.transform;this._initializing&&(this._initializing=0===o._centerAltitude&&-1===this.getAtPointOrZero(e.M.fromLngLat(o.center),-1),this._emptyDEMTextureDirty=!this._initializing);const r=this.proxyCoords=i.getIds().map((e=>{const t=i.getTileByID(e).tileID;return t.projMatrix=o.calculateProjMatrix(t.toUnwrapped()),t}));!function(t,i){const o=i.transform.pointCoordinate(i.transform.getCameraPoint()),r=new e.P(o.x,o.y);t.sort(((t,i)=>{if(i.overscaledZ-t.overscaledZ)return i.overscaledZ-t.overscaledZ;const o=new e.P(t.canonical.x+(1<{this.proxyToSource[e.key]={};})),this.terrainTileForTile={};const n=this._style._mergedSourceCaches;for(const e in n){const i=n[e];if(!i.used)continue;if(i!==this.sourceCache&&this.resetTileLookupCache(i.id),this._setupProxiedCoordsForOrtho(i,t[e],s),i.usedForTerrain)continue;const o=t[e];i.getSource().reparseOverscaled&&this._assignTerrainTiles(o);}this.proxiedCoords[i.id]=r.map((e=>new Fi(e,e.key,this.orthoMatrix))),this._assignTerrainTiles(r),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(s),this.renderingToTexture=!1;const a={};this._visibleDemTiles=[];for(const e of this.proxyCoords){const t=this.terrainTileForTile[e.key];if(!t)continue;const i=t.tileID.key;i in a||(this._visibleDemTiles.push(t),a[i]=i);}}_assignTerrainTiles(e){this._initializing||e.forEach((e=>{if(this.terrainTileForTile[e.key])return;const t=this._findTileCoveringTileID(e,this.sourceCache);t&&(this.terrainTileForTile[e.key]=t);}));}_prepareDEMTextures(){const e=this.painter.context,t=e.gl;for(const i in this.terrainTileForTile){const o=this.terrainTileForTile[i],r=o.dem;!r||o.demTexture&&!o.needsDEMTextureUpload||(e.activeTexture.set(t.TEXTURE1),bi(this.painter,o,r));}}_prepareDemTileUniforms(e,t,i,o){if(!t||null==t.demTexture)return !1;const r=e.tileID.canonical,s=Math.pow(2,t.tileID.canonical.z-r.z),n=o||\"\";return i[`u_dem_tl${n}`]=[r.x*s%1,r.y*s%1],i[`u_dem_scale${n}`]=s,!0}get emptyDEMTexture(){return !this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}get emptyDepthBufferTexture(){const t=this.painter.context,i=t.gl;if(!this._emptyDepthBufferTexture){const o=new e.a5({width:1,height:1},Uint8Array.of(255,255,255,255));this._emptyDepthBufferTexture=new e.a9(t,o,i.RGBA,{premultiply:!1});}return this._emptyDepthBufferTexture}_getLoadedAreaMinimum(){let e=0;const t=this._visibleDemTiles.reduce(((t,i)=>{if(!i.dem)return t;const o=i.dem.tree.minimums[0];return o>0&&e++,t+o}),0);return e?t/e:0}_updateEmptyDEMTexture(){const t=this.painter.context,i=t.gl;t.activeTexture.set(i.TEXTURE2);const o=this._getLoadedAreaMinimum(),[r,s]=(()=>{const t=new e.bu({width:1,height:1},new Float32Array([o]));return [i.R32F,t]})();this._emptyDEMTextureDirty=!1;let n=this._emptyDEMTexture;return n?n.update(s,{premultiply:!1}):n=this._emptyDEMTexture=new e.a9(t,s,r,{premultiply:!1}),n}setupElevationDraw(t,i,o){const r=this.painter.context,s=r.gl,n={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_exaggeration:0};n.u_exaggeration=this.exaggeration();let a=null,l=null,c=1;if(o&&o.morphing&&this._useVertexMorphing){const e=o.morphing.srcDemTile,i=o.morphing.dstDemTile;c=o.morphing.phase,e&&i&&(this._prepareDemTileUniforms(t,e,n,\"_prev\")&&(l=e),this._prepareDemTileUniforms(t,i,n)&&(a=i));}const h=e=>e&&e.demTexture&&this.painter.linearFloatFilteringSupported()?s.LINEAR:s.NEAREST,_=e=>{n.u_dem_size=1===e.size[0]?1:e.size[0]-2;};if(l&&a)r.activeTexture.set(s.TEXTURE2),a.demTexture.bind(h(a),s.CLAMP_TO_EDGE),r.activeTexture.set(s.TEXTURE4),l.demTexture.bind(h(l),s.CLAMP_TO_EDGE),a.demTexture&&_(a.demTexture),n.u_dem_lerp=c;else {a=this.terrainTileForTile[t.tileID.key],r.activeTexture.set(s.TEXTURE2);const e=this._prepareDemTileUniforms(t,a,n)?a.demTexture:this.emptyDEMTexture;e.bind(h(a),s.CLAMP_TO_EDGE),_(e);}if(r.activeTexture.set(s.TEXTURE3),o&&o.useDepthForOcclusion?(this._depthTexture&&this._depthTexture.bind(s.NEAREST,s.CLAMP_TO_EDGE),this._depthFBO&&(n.u_depth_size_inv=[1/this._depthFBO.width,1/this._depthFBO.height])):(this.emptyDepthBufferTexture.bind(s.NEAREST,s.CLAMP_TO_EDGE),n.u_depth_size_inv=[1,1]),o&&o.useMeterToDem&&a){const t=(1<{if(c===i)return;const o=[Li[i],\"PROJECTION_GLOBE_VIEW\"];_&&o.push(\"CUSTOM_ANTIALIASING\");const r=t.isTileAffectedByFog(e);l=t.getOrCreateProgram(\"globeRaster\",{defines:o,overrideFog:r}),c=i;},u=t.colorModeForRenderPass(),p=new e.b4(a.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D);Mi.update(s);const m=e.bc(h),f=[e.E(h.center.lng),e.H(h.center.lat)],g=t.globeSharedBuffers,v=[h.width*e.a4.devicePixelRatio,h.height*e.a4.devicePixelRatio],x=Float32Array.from(h.globeMatrix),y={useDenormalizedUpVectorScale:!0};{const h=t.transform,_=Pi(h.zoom,i.exaggeration(),i.sourceCache._source.tileSize);c=-1;const b=a.TRIANGLES;for(const c of r){const r=o.getTile(c),w=e.b6.disabled,T=i.prevTerrainTileForTile[c.key],E=i.terrainTileForTile[c.key];Si(T,E)&&Mi.newMorphing(c.key,T,E,s,250),n.activeTexture.set(a.TEXTURE0),r.texture&&r.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE);const C=Mi.getMorphValuesForProxy(c.key),I=C?1:0;C&&e.bd(y,{morphing:{srcDemTile:C.from,dstDemTile:C.to,phase:e.ba(C.phase)}});const S=e.be(c.canonical),M=e.bf(S.getCenter().lat),L=e.bg(c.canonical,S,M,h.worldSize/h._pixelsPerMercatorPixel),P=e.bh(e.bi(c.canonical)),D=Ci(h.expandedFarZProjMatrix,x,m,P,e.ao(h.zoom),f,h.frustumCorners.TL,h.frustumCorners.TR,h.frustumCorners.BR,h.frustumCorners.BL,h.globeCenterInViewSpace,h.globeRadius,v,_,L);if(d(c,I),l&&(i.setupElevationDraw(r,l,y),t.uploadCommonUniforms(n,l,c.toUnwrapped()),g)){const[i,o,r]=g.getGridBuffers(M,0!==_);l.draw(t,b,p,w,u,e.b5.backCCW,D,\"globe_raster\",i,o,r);}}}if(g&&(t.renderDefaultNorthPole||t.renderDefaultSouthPole)){const s=[\"GLOBE_POLES\",\"PROJECTION_GLOBE_VIEW\"];_&&s.push(\"CUSTOM_ANTIALIASING\"),l=t.getOrCreateProgram(\"globeRaster\",{defines:s});for(const s of r){const{x:r,y:c,z:_}=s.canonical,d=0===c,m=c===(1<<_)-1,[x,b,w,T]=g.getPoleBuffers(_,!1);if(T&&(d||m)){const c=o.getTile(s);n.activeTexture.set(a.TEXTURE0),c.texture&&c.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE);let g=e.bj(_,r,h);const E=e.bh(e.bi(s.canonical)),C=(i,o)=>i.draw(t,a.TRIANGLES,p,e.b6.disabled,u,e.b5.disabled,Ci(h.expandedFarZProjMatrix,g,g,E,0,f,h.frustumCorners.TL,h.frustumCorners.TR,h.frustumCorners.BR,h.frustumCorners.BL,h.globeCenterInViewSpace,h.globeRadius,v,0),\"globe_pole_raster\",o,w,T);i.setupElevationDraw(c,l,y),t.uploadCommonUniforms(n,l,s.toUnwrapped()),d&&t.renderDefaultNorthPole&&C(l,x),m&&t.renderDefaultSouthPole&&(g=e.m.scale(e.m.create(),g,[1,-1,1]),C(l,b));}}}}(t,i,o,r,s);else {const n=t.context,a=n.gl;let l,c;const h=t.shadowRenderer,_=Ii(t,t.longestCutoffRange),d=e=>{if(c===e)return;const i=[];i.push(Li[e]),_.shouldRenderCutoff&&i.push(\"RENDER_CUTOFF\"),l=t.getOrCreateProgram(\"terrainRaster\",{defines:i}),c=e;},u=t.colorModeForRenderPass(),p=new e.b4(a.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D);Mi.update(s);const m=t.transform,f=Pi(m.zoom,i.exaggeration(),i.sourceCache._source.tileSize);let g=[0,0,0];if(h){const e=t.style.directionalLight,i=t.style.ambientLight;e&&i&&(g=wr(e,i));}{c=-1;const v=a.TRIANGLES,[x,y]=[i.gridIndexBuffer,i.gridSegments];for(const c of r){const r=o.getTile(c),b=e.b6.disabled,w=i.prevTerrainTileForTile[c.key],T=i.terrainTileForTile[c.key];Si(w,T)&&Mi.newMorphing(c.key,w,T,s,250),n.activeTexture.set(a.TEXTURE0),r.texture&&r.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE);const E=Mi.getMorphValuesForProxy(c.key),C=E?1:0;let I;E&&(I={morphing:{srcDemTile:E.from,dstDemTile:E.to,phase:e.ba(E.phase)}});const S=Ei(c.projMatrix,Di(c.canonical,m.renderWorldCopies)?f/10:f,g);if(d(C),!l)continue;i.setupElevationDraw(r,l,I);const M=c.toUnwrapped();h&&h.setupShadows(M,l),t.uploadCommonUniforms(n,l,M,null,_),l.draw(t,v,p,b,u,e.b5.backCCW,S,\"terrain_raster\",i.gridBuffer,x,y);}}}}(i,this,this.proxySourceCache,t,this._updateTimestamp),this.renderingToTexture=!0,i.gpuTimingDeferredRenderEnd(),t.splice(0,t.length));}renderBatch(t){if(0===this._drapedRenderBatches.length)return t+1;this.renderingToTexture=!0;const i=this.painter,o=this.painter.context,r=this.proxySourceCache,s=this.proxiedCoords[r.id],n=this._drapedRenderBatches.shift(),a=i.style.order,l=[];let c=0;for(const h of s){const s=r.getTileByID(h.proxyTileKey),_=r.proxyCachedFBO[h.key]?r.proxyCachedFBO[h.key][t]:void 0,d=void 0!==_?r.renderCache[_]:this.pool[c++],u=void 0!==_;if(s.texture=d.tex,u&&!d.dirty){l.push(s.tileID);continue}let p;o.bindFramebuffer.set(d.fb.framebuffer),this.renderedToTile=!1,d.dirty&&(o.clear({color:e.C.transparent,stencil:0}),d.dirty=!1);for(let e=n.start;e<=n.end;++e){const t=i.style._mergedLayers[a[e]];if(t.isHidden(i.transform.zoom))continue;const r=i.style.getLayerSourceCache(t),s=r?this.proxyToSource[h.key][r.id]:[h];if(!s)continue;const n=s;o.viewport.set([0,0,d.fb.width,d.fb.height]),p!==(r?r.id:null)&&(this._setupStencil(d,s,t,r),p=r?r.id:null),i.renderLayer(i,r,t,n);}if(0===this._drapedRenderBatches.length)for(const e of this._pendingGroundEffectLayers){const t=i.style._mergedLayers[a[e]];if(t.isHidden(i.transform.zoom))continue;const r=i.style.getLayerSourceCache(t),s=r?this.proxyToSource[h.key][r.id]:[h];if(!s)continue;const n=s;o.viewport.set([0,0,d.fb.width,d.fb.height]),p!==(r?r.id:null)&&(this._setupStencil(d,s,t,r),p=r?r.id:null),i.renderLayer(i,r,t,n);}this.renderedToTile?(d.dirty=!0,l.push(s.tileID)):u||--c,5===c&&(c=0,this.renderToBackBuffer(l));}return this.renderToBackBuffer(l),this.renderingToTexture=!1,o.bindFramebuffer.set(null),o.viewport.set([0,0,i.width,i.height]),n.end+1}postRender(){}isLayerOrderingCorrect(e){const t=e.order.length;let i=-1,o=t;for(let r=0;ri}getMinElevationBelowMSL(){let e=0;return this._visibleDemTiles.filter((e=>e.dem)).forEach((t=>{e=Math.min(e,t.dem.tree.minimums[0]);})),0===e?e:(e-30)*this._exaggeration}raycast(e,t,i){if(!this._visibleDemTiles)return null;const o=this._visibleDemTiles.filter((e=>e.dem)).map((o=>{const r=o.tileID,s=1<(null!==e.t?e.t:Number.MAX_VALUE)-(null!==t.t?t.t:Number.MAX_VALUE)));for(const r of o){if(null==r.t)return null;const o=r.tile.dem.tree.raycast(r.minx,r.miny,r.maxx,r.maxy,e,t,i);if(null!=o)return o}return null}_createFBO(){const t=this.painter.context,i=t.gl,o=this.drapeBufferSize;t.activeTexture.set(i.TEXTURE0);const r=new e.a9(t,{width:o[0],height:o[1],data:null},i.RGBA);r.bind(i.LINEAR,i.CLAMP_TO_EDGE);const s=t.createFramebuffer(o[0],o[1],!0,null);return s.colorAttachment.set(r.texture),s.depthAttachment=new oe(t,s.framebuffer),void 0===this._sharedDepthStencil?(this._sharedDepthStencil=t.createRenderbuffer(t.gl.DEPTH_STENCIL,o[0],o[1]),this._stencilRef=0,s.depthAttachment.set(this._sharedDepthStencil),t.clear({stencil:0})):s.depthAttachment.set(this._sharedDepthStencil),t.extTextureFilterAnisotropic&&i.texParameterf(i.TEXTURE_2D,t.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,t.extTextureFilterAnisotropicMax),{fb:s,tex:r,dirty:!1}}_initFBOPool(){for(;this.pool.length{const t=this._style._mergedLayers[e],i=t.isHidden(this.painter.transform.zoom);return \"custom\"===t.type?!i&&t.shouldRedrape():!i&&t.hasTransition()}))}_clearLineLayersFromRenderCache(){let t=!1;for(const e of this._style.getSources())if(e instanceof it){t=!0;break}if(!t)return;const i={};for(let t=0;te>t.end))||e.X(\"fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.\");}this._drapedRenderBatches=o;}_setupRenderCache(e){const t=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,t.renderCache.length>t.renderCachePool.length){const e=Object.values(t.proxyCachedFBO);t.proxyCachedFBO={};for(let i=0;i=0;r--){const s=i[r];if(t.getTileByID(s.key),void 0!==t.proxyCachedFBO[s.key]){const i=e[s.key],r=this.proxyToSource[s.key];let n=0;for(const e in r){const t=r[e],s=i[e];if(!s||s.length!==t.length||t.some(((t,i)=>t!==s[i]||o[e]&&o[e].hasOwnProperty(t.key)))){n=-1;break}++n;}for(const e in t.proxyCachedFBO[s.key])t.renderCache[t.proxyCachedFBO[s.key][e]].dirty=n<0||n!==Object.values(i).length;}}const r=[...this._drapedRenderBatches];r.sort(((e,t)=>t.end-t.start-(e.end-e.start)));for(const e of r)for(const o of i){if(t.proxyCachedFBO[o.key])continue;let i=t.renderCachePool.pop();void 0===i&&t.renderCache.length<50&&(i=t.renderCache.length,t.renderCache.push(this._createFBO())),void 0!==i&&(t.proxyCachedFBO[o.key]={},t.proxyCachedFBO[o.key][e.start]=i,t.renderCache[i].dirty=!0);}this._tilesDirty={};}_setupStencil(e,t,i,o){if(!o||!this._sourceTilesOverlap[o.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const r=this.painter.context,s=r.gl;if(t.length<=1)return void(this._overlapStencilType=!1);let n;if(i.isTileClipped())n=t.length,this._overlapStencilMode.test={func:s.EQUAL,mask:255},this._overlapStencilType=\"Clip\";else {if(!(t[0].overscaledZ>t[t.length-1].overscaledZ))return void(this._overlapStencilType=!1);n=1,this._overlapStencilMode.test={func:s.GREATER,mask:255},this._overlapStencilType=\"Mask\";}this._stencilRef+n>255&&(r.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=n,this._overlapStencilMode.ref=this._stencilRef,i.isTileClipped()&&this._renderTileClippingMasks(t,this._overlapStencilMode.ref);}clipOrMaskOverlapStencilType(){return \"Clip\"===this._overlapStencilType||\"Mask\"===this._overlapStencilType}stencilModeForRTTOverlap(t){return this.renderingToTexture&&this._overlapStencilType?(\"Clip\"===this._overlapStencilType&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[t.key]),this._overlapStencilMode):e.b6.disabled}_renderTileClippingMasks(t,i){const o=this.painter,r=this.painter.context,s=r.gl;o._tileClippingMaskIDs={},r.setColorMode(e.a.disabled),r.setDepthMode(e.b4.disabled);const n=o.getOrCreateProgram(\"clippingMask\");for(const r of t){const t=o._tileClippingMaskIDs[r.key]=--i;n.draw(o,s.TRIANGLES,e.b4.disabled,new e.b6({func:s.ALWAYS,mask:0},t,255,s.KEEP,s.KEEP,s.REPLACE),e.a.disabled,e.b5.disabled,Ai(r.projMatrix),\"$clipping\",o.tileExtentBuffer,o.quadTriangleIndexBuffer,o.tileExtentSegments);}}pointCoordinate(t){const i=this.painter.transform;if(t.x<0||t.x>i.width||t.y<0||t.y>i.height)return null;const o=[t.x,t.y,1,1];e.e.transformMat4(o,o,i.pixelMatrixInverse),e.e.scale(o,o,1/o[3]),o[0]/=i.worldSize,o[1]/=i.worldSize;const r=i._camera.position,s=e.b(1,i.center.lat),n=[r[0],r[1],r[2]/s,0],a=e.v.subtract([],o.slice(0,3),n);e.v.normalize(a,a);const l=this.raycast(n,a,this._exaggeration);return null!==l&&l?(e.v.scaleAndAdd(n,n,a,l),n[3]=n[2],n[2]*=s,n):null}drawDepth(){const t=this.painter,i=t.context,o=this.proxySourceCache,r=Math.ceil(t.width),s=Math.ceil(t.height);if(!this._depthFBO||this._depthFBO.width===r&&this._depthFBO.height===s||(this._depthFBO.destroy(),this._depthFBO=void 0,this._depthTexture=void 0),!this._depthFBO){const t=i.gl,o=i.createFramebuffer(r,s,!0,\"renderbuffer\");i.activeTexture.set(t.TEXTURE0);const n=new e.a9(i,{width:r,height:s,data:null},t.RGBA);n.bind(t.NEAREST,t.CLAMP_TO_EDGE),o.colorAttachment.set(n.texture);const a=i.createRenderbuffer(i.gl.DEPTH_COMPONENT16,r,s);o.depthAttachment.set(a),this._depthFBO=o,this._depthTexture=n;}i.bindFramebuffer.set(this._depthFBO.framebuffer),i.viewport.set([0,0,r,s]),function(t,i,o,r){if(\"globe\"===t.transform.projection.name)return;const s=t.context,n=s.gl;s.clear({depth:1});const a=t.getOrCreateProgram(\"terrainDepth\"),l=new e.b4(n.LESS,e.b4.ReadWrite,t.depthRangeFor3D);for(const s of r){const r=o.getTile(s),c=Ei(s.projMatrix,0,[0,0,0]);i.setupElevationDraw(r,a),a.draw(t,n.TRIANGLES,l,e.b6.disabled,e.a.unblended,e.b5.backCCW,c,\"terrain_depth\",i.gridBuffer,i.gridIndexBuffer,i.gridNoSkirtSegments);}}(t,this,o,this.proxyCoords);}_setupProxiedCoordsForOrtho(t,i,o){if(t.getSource()instanceof e.aK)return this._setupProxiedCoordsForImageSource(t,i,o);this._findCoveringTileCache[t.id]=this._findCoveringTileCache[t.id]||{};const r=this.proxiedCoords[t.id]=[],s=this.proxyCoords;for(let e=0;et.overscaledZ-e.overscaledZ));}_setupProxiedCoordsForImageSource(t,i,o){if(!t.getSource().loaded())return;const r=this.proxiedCoords[t.id]=[],s=this.proxyCoords,n=t.getSource(),a=n.tileID;if(!a)return;const l=new e.P(a.x,a.y)._div(1<(e.min.x=Math.min(e.min.x,t.x-l.x),e.min.y=Math.min(e.min.y,t.y-l.y),e.max.x=Math.max(e.max.x,t.x-l.x),e.max.y=Math.max(e.max.y,t.y-l.y),e)),{min:new e.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new e.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),h=(t,i)=>{const o=t.wrap+t.canonical.x/(1<n+c.max.x||r+sa+c.max.y};for(let e=0;ee.key===i.tileID.key));if(e)return e}if(i.tileID.key!==t.key){const o=t.canonical.z-i.tileID.canonical.z;let s,n,a;r=e.m.create();const l=i.tileID.wrap-t.wrap<0?(s=e.J>>o,n=s*((i.tileID.canonical.x<=r){const o=t.canonical.z-r;i.getSource().reparseOverscaled?(a=Math.max(t.canonical.z+2,i.transform.tileZoom),n=new e.O(a,t.wrap,r,t.canonical.x>>o,t.canonical.y>>o)):0!==o&&(a=r,n=new e.O(a,t.wrap,r,t.canonical.x>>o,t.canonical.y>>o));}n.key!==t.key&&(c.push(n.key),o=i.getTile(n));}const h=e=>{c.forEach((t=>{r[t]=e;})),c.length=0;};for(a-=1;a>=l&&(!o||!o.hasData());a--){o&&h(o.tileID.key);const e=n.calculateScaledKey(a);if(o=i.getTileByID(e),o&&o.hasData())break;const t=r[e];if(null===t)break;void 0===t?c.push(e):o=i.getTileByID(t);}return h(o?o.tileID.key:null),o&&o.hasData()?o:null}findDEMTileFor(e){return this.enabled?this._findTileCoveringTileID(e,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0;}_clearRenderCacheForTile(e,t){let i=this._tilesDirty[e];i||(i=this._tilesDirty[e]={}),i[t.key]=!0;}}function ki(t,i,o){const r=function(t,i,o){const r=e.v.dot(i,t),s=e.v.dot(o,[.2126,.7152,.0722]),n=(e,t,i)=>(1-i)*e+i*t,a=n(1-.3*Math.min(s,1),1,Math.min(r+1,1));return n(.92,1,Math.asin(e.c(i[2],-1,1))/Math.PI+.5)*a}(t,[0,0,1],i),s=[0,0,0];e.v.scale(s,o.slice(0,3),r);const n=[0,0,0];e.v.scale(n,i.slice(0,3),t[2]);const a=[0,0,0];return e.v.add(a,s,n),e.bw(a)}const Ni=[\"fill\",\"fillOutline\",\"fillPattern\",\"line\",\"linePattern\",\"background\",\"backgroundPattern\",\"hillshade\",\"raster\"],Ui=[\"stars\",\"fillExtrusion\",\"fillExtrusionGroundEffect\",\"model\",\"symbolSDF\",\"symbolIcon\",\"symbolTextAndIcon\"];class Gi{static cacheKey(e,t,i,o){let r=`${t}${o?o.cacheKey:\"\"}`;for(const t of i)e.usedDefines.includes(t)&&(r+=`/${t}`);return r}constructor(t,i,o,r,s,n){const a=t.gl;this.program=a.createProgram(),this.configuration=r,this.name=i,this.fixedDefines=[...n];const l=r?r.getBinderAttributes():[],c=(o.staticAttributes||[]).concat(l);let h=r?r.defines():[];h=h.concat(n.map((e=>`#define ${e}`)));const _=\"#version 300 es\\n\";let d=_+h.concat(\"precision mediump float;\",pi,ui.fragmentSource).join(\"\\n\");for(const e of o.fragmentIncludes)d+=`\\n${_i[e]}`;d+=`\\n${o.fragmentSource}`;let u=_+h.concat(\"precision highp float;\",pi,ui.vertexSource).join(\"\\n\");for(const e of o.vertexIncludes)u+=`\\n${_i[e]}`;u+=`\\n${o.vertexSource}`;const p=a.createShader(a.FRAGMENT_SHADER);if(a.isContextLost())return void(this.failedToCreate=!0);a.shaderSource(p,d),a.compileShader(p),a.attachShader(this.program,p);const m=a.createShader(a.VERTEX_SHADER);if(a.isContextLost())this.failedToCreate=!0;else {a.shaderSource(m,u),a.compileShader(m),a.attachShader(this.program,m),this.attributes={},this.numAttributes=c.length;for(let e=0;e({u_dem:new e.a$(t),u_dem_prev:new e.a$(t),u_dem_tl:new e.b0(t),u_dem_scale:new e.b2(t),u_dem_tl_prev:new e.b0(t),u_dem_scale_prev:new e.b2(t),u_dem_size:new e.b2(t),u_dem_lerp:new e.b2(t),u_exaggeration:new e.b2(t),u_depth:new e.a$(t),u_depth_size_inv:new e.b0(t),u_meter_to_dem:new e.b2(t),u_label_plane_matrix_inv:new e.a_(t)}))(t)),n.includes(\"GLOBE\")&&(this.globeUniforms=(t=>({u_tile_tl_up:new e.b7(t),u_tile_tr_up:new e.b7(t),u_tile_br_up:new e.b7(t),u_tile_bl_up:new e.b7(t),u_tile_up_scale:new e.b2(t)}))(t)),n.includes(\"FOG\")&&(this.fogUniforms=(t=>({u_fog_matrix:new e.a_(t),u_fog_range:new e.b0(t),u_fog_color:new e.b9(t),u_fog_horizon_blend:new e.b2(t),u_fog_vertical_limit:new e.b0(t),u_fog_temporal_offset:new e.b2(t),u_frustum_tl:new e.b7(t),u_frustum_tr:new e.b7(t),u_frustum_br:new e.b7(t),u_frustum_bl:new e.b7(t),u_globe_pos:new e.b7(t),u_globe_radius:new e.b2(t),u_globe_transition:new e.b2(t),u_is_globe:new e.a$(t),u_viewport:new e.b0(t)}))(t)),n.includes(\"RENDER_CUTOFF\")&&(this.cutoffUniforms=(t=>({u_cutoff_params:new e.b9(t)}))(t)),n.includes(\"LIGHTING_3D_MODE\")&&(this.lightsUniforms=(t=>({u_lighting_ambient_color:new e.b7(t),u_lighting_directional_dir:new e.b7(t),u_lighting_directional_color:new e.b7(t),u_ground_radiance:new e.b7(t)}))(t)),n.includes(\"RENDER_SHADOWS\")&&(this.shadowUniforms=(t=>({u_light_matrix_0:new e.a_(t),u_light_matrix_1:new e.a_(t),u_fade_range:new e.b0(t),u_shadow_normal_offset:new e.b7(t),u_shadow_intensity:new e.b2(t),u_shadow_texel_size:new e.b2(t),u_shadow_map_resolution:new e.b2(t),u_shadow_direction:new e.b7(t),u_shadow_bias:new e.b7(t),u_shadowmap_0:new e.a$(t),u_shadowmap_1:new e.a$(t)}))(t));}}setTerrainUniformValues(e,t){if(!this.terrainUniforms)return;const i=this.terrainUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e]&&i[e].set(this.program,e,t[e]);}}setGlobeUniformValues(e,t){if(!this.globeUniforms)return;const i=this.globeUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e]&&i[e].set(this.program,e,t[e]);}}setFogUniformValues(e,t){if(!this.fogUniforms)return;const i=this.fogUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e]);}}setCutoffUniformValues(e,t){if(!this.cutoffUniforms)return;const i=this.cutoffUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e]);}}setLightsUniformValues(e,t){if(!this.lightsUniforms)return;const i=this.lightsUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e]);}}setShadowUniformValues(e,t){if(this.failedToCreate||!this.shadowUniforms)return;const i=this.shadowUniforms;e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e]);}_drawDebugWireframe(t,i,o,r,s,n,a,l,c,h){const _=t.options.wireframe;if(!1===_.terrain&&!1===_.layers2D&&!1===_.layers3D)return;const d=t.context;if(!(()=>!(!_.terrain||\"terrainRaster\"!==this.name&&\"globeRaster\"!==this.name)||!(!_.layers2D||t._terrain&&t._terrain.renderingToTexture||!Ni.includes(this.name))||!(!_.layers3D||!Ui.includes(this.name)))())return;const u=d.gl,p=t.wireframeDebugCache.getLinesFromTrianglesBuffer(t.frameCounter,s,d);if(!p)return;const m=[...this.fixedDefines];m.push(\"DEBUG_WIREFRAME\");const f=t.getOrCreateProgram(this.name,{config:this.configuration,defines:m});d.program.set(f.program);const g=(e,t,i)=>{if(t[e]&&i[e])for(const o in t[e])i[e][o]&&i[e][o].set(i.program,o,t[e][o].current);};c&&c.setUniforms(f.program,d,f.binderUniforms,a,{zoom:l}),g(\"fixedUniforms\",this,f),g(\"terrainUniforms\",this,f),g(\"globeUniforms\",this,f),g(\"fogUniforms\",this,f),g(\"lightsUniforms\",this,f),g(\"shadowUniforms\",this,f),p.bind(),d.setColorMode(new e.a([u.ONE,u.ONE_MINUS_SRC_ALPHA,u.ZERO,u.ONE],e.C.transparent,[!0,!0,!0,!1])),d.setDepthMode(new e.b4(i.func===u.LESS?u.LEQUAL:i.func,e.b4.ReadOnly,i.range)),d.setStencilMode(e.b6.disabled);const v=3*n.primitiveLength*2,x=3*n.primitiveOffset*2*2;h&&h>1?u.drawElementsInstanced(u.LINES,v,u.UNSIGNED_SHORT,x,h):u.drawElements(u.LINES,v,u.UNSIGNED_SHORT,x),s.bind(),d.program.set(this.program),d.setDepthMode(i),d.setStencilMode(o),d.setColorMode(r);}draw(e,t,i,o,r,s,n,a,l,c,h,_,d,u,p,m){const f=e.context,g=f.gl;if(this.failedToCreate)return;f.program.set(this.program),f.setDepthMode(i),f.setStencilMode(o),f.setColorMode(r),f.setCullFace(s);for(const e of Object.keys(this.fixedUniforms))this.fixedUniforms[e].set(this.program,e,n[e]);u&&u.setUniforms(this.program,f,this.binderUniforms,_,{zoom:d});const v={[g.LINES]:2,[g.TRIANGLES]:3,[g.LINE_STRIP]:1}[t],x=m&&m>0?1:void 0;for(const s of h.get()){const n=s.vaos||(s.vaos={});(n[a]||(n[a]=new vi)).bind(f,this,l,u?u.getPaintVertexBuffers():[],c,s.vertexOffset,p||[],x),m&&m>1?g.drawElementsInstanced(t,s.primitiveLength*v,g.UNSIGNED_SHORT,s.primitiveOffset*v*2,m):g.drawElements(t,s.primitiveLength*v,g.UNSIGNED_SHORT,s.primitiveOffset*v*2),t===g.TRIANGLES&&this._drawDebugWireframe(e,i,o,r,c,s,_,d,u,m);}}}function ji(t,i){const o=Math.pow(2,i.tileID.overscaledZ),r=i.tileSize*Math.pow(2,t.transform.tileZoom)/o,s=r*(i.tileID.canonical.x+i.tileID.wrap*o),n=r*i.tileID.canonical.y;return {u_image:0,u_texsize:i.imageAtlasTexture?i.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/e.ay(i,1,t.transform.tileZoom),u_pixel_coord_upper:[s>>16,n>>16],u_pixel_coord_lower:[65535&s,65535&n]}}const Vi=e.m.create(),Zi=(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f)=>{const g=i.style.light,v=g.properties.get(\"position\"),x=[v.x,v.y,v.z],y=e.bx.create();\"viewport\"===g.properties.get(\"anchor\")&&(e.bx.fromRotation(y,-i.transform.angle),e.v.transformMat3(x,x,y));const b=g.properties.get(\"color\"),w=i.transform,T={u_matrix:t,u_lightpos:x,u_lightintensity:g.properties.get(\"intensity\"),u_lightcolor:[b.r,b.g,b.b],u_vertical_gradient:+o,u_opacity:r,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Vi,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_ao:s,u_edge_radius:n,u_flood_light_color:d,u_vertical_scale:u,u_flood_light_intensity:p,u_ground_shadow_factor:m,u_emissive_strength:f};return \"globe\"===w.projection.name&&(T.u_tile_id=[a.canonical.x,a.canonical.y,1<({u_matrix:e,u_edge_radius:t,u_vertical_scale:i}),Hi=(t,i,o,r,s,n,a,l,c,h,_,d,u,p)=>{const m=Zi(t,i,o,r,s,n,a,c,h,_,d,u,p,1,[0,0,0],0),f={u_height_factor:-Math.pow(2,a.overscaledZ)/l.tileSize/8};return e.ak(m,ji(i,l),f)},qi=(e,t)=>({u_matrix:e,u_emissive_strength:t}),$i=(t,i,o,r)=>e.ak(qi(t,i),ji(o,r)),Xi=(e,t,i)=>({u_matrix:e,u_world:i,u_emissive_strength:t}),Ji=(t,i,o,r,s)=>e.ak($i(t,i,o,r),{u_world:s}),Yi=(t,i,o,r)=>{const s=e.J/o.tileSize;return {u_matrix:t,u_camera_to_center_distance:i.getCameraToCenterDistance(r),u_extrude_scale:[i.pixelsToGLUnits[0]/s,i.pixelsToGLUnits[1]/s]}},Ki=(e,t,i=1)=>({u_matrix:e,u_color:t,u_overlay:0,u_overlay_scale:i}),Qi=e.m.create(),eo=(t,i,o,r,s,n,a)=>{const l=t.transform,c=\"globe\"===l.projection.name,h=c?e.by(l.zoom,i.canonical)*l._pixelsPerMercatorPixel:e.ay(o,1,n),_={u_matrix:i.projMatrix,u_extrude_scale:h,u_intensity:a,u_inv_rot_matrix:Qi,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(c){_.u_inv_rot_matrix=r,_.u_merc_center=s,_.u_tile_id=[i.canonical.x,i.canonical.y,1<{return {u_matrix:e,u_normalize_matrix:t,u_globe_matrix:i,u_merc_matrix:o,u_grid_matrix:r,u_tl_parent:s,u_scale_parent:c,u_fade_t:h.mix,u_opacity:h.opacity*_.paint.get(\"raster-opacity\"),u_image0:0,u_image1:1,u_brightness_low:_.paint.get(\"raster-brightness-min\"),u_brightness_high:_.paint.get(\"raster-brightness-max\"),u_saturation_factor:(w=_.paint.get(\"raster-saturation\"),w>0?1-1/(1.001-w):-w),u_contrast_factor:(b=_.paint.get(\"raster-contrast\"),b>0?1/(1-b):1+b),u_spin_weights:io(_.paint.get(\"raster-hue-rotate\")),u_perspective_transform:d,u_raster_elevation:u,u_zoom_transition:n,u_merc_center:a,u_cutoff_params:l,u_colorization_mix:oo(m,g),u_colorization_offset:ro(f,g),u_color_ramp:p,u_texture_offset:[x/(v+2*x),v/(v+2*x)],u_texture_res:[v+2*x,v+2*x],u_emissive_strength:y};var b,w;};function io(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}function oo([t,i,o,r],[s,n]){if(s===n)return [0,0,0,0];const a=(e.bz+3)/(e.bz+1)/(n-s);return [t*a,i*a,o*a,r*a]}function ro(t,[i,o]){return i===o?0:((t-i)/(o-i)*(e.bz+3)-1)/(e.bz+1)}const so=e.m.create(),no=(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f,g,v)=>{const x=s.transform,y={u_is_size_zoom_constant:+(\"constant\"===t||\"source\"===t),u_is_size_feature_constant:+(\"constant\"===t||\"camera\"===t),u_size_t:i?i.uSizeT:0,u_size:i?i.uSize:0,u_camera_to_center_distance:x.getCameraToCenterDistance(f),u_rotate_symbol:+o,u_aspect_ratio:x.width/x.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_matrix:n,u_label_plane_matrix:a,u_coord_matrix:l,u_is_text:+c,u_pitch_with_map:+r,u_texsize:h,u_texture:0,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:so,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:so,u_up_vector:[0,-1,0],u_icon_transition:v||0,u_icon_saturation:g};return \"globe\"===f.name&&(y.u_tile_id=[_.canonical.x,_.canonical.y,1<<_.canonical.z],y.u_zoom_transition=d,y.u_inv_rot_matrix=p,y.u_merc_center=u,y.u_camera_forward=x._camera.forward(),y.u_ecef_origin=e.bA(x.globeMatrix,_.toUnwrapped()),y.u_tile_matrix=Float32Array.from(x.globeMatrix),y.u_up_vector=m),y},ao=(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f,g)=>e.ak(no(t,i,o,r,s,n,a,l,c,h,d,u,p,m,f,g,1),{u_gamma_scale:r?s.transform.getCameraToCenterDistance(g)*Math.cos(s.terrain?0:s.transform._pitch):1,u_device_pixel_ratio:e.a4.devicePixelRatio,u_is_halo:+_,undefined:void 0}),lo=(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f)=>e.ak(ao(t,i,o,r,s,n,a,l,!0,c,!0,_,d,u,p,m,f),{u_texsize_icon:h,u_texture_icon:1}),co=(e,t,i,o)=>({u_matrix:e,u_emissive_strength:t,u_opacity:i,u_color:o}),ho=(t,i,o,r,s,n,a)=>e.ak(function(t,i,o,r){const s=o.imageManager.getPattern(t.toString(),i),{width:n,height:a}=o.imageManager.getPixelSize(i),l=Math.pow(2,r.tileID.overscaledZ),c=r.tileSize*Math.pow(2,o.transform.tileZoom)/l,h=c*(r.tileID.canonical.x+r.tileID.wrap*l),_=c*r.tileID.canonical.y;return {u_image:0,u_pattern_tl:s.tl,u_pattern_br:s.br,u_texsize:[n,a],u_pattern_size:s.displaySize,u_tile_units_to_pixels:1/e.ay(r,1,o.transform.tileZoom),u_pixel_coord_upper:[h>>16,_>>16],u_pixel_coord_lower:[65535&h,65535&_]}}(s,n,r,a),{u_matrix:t,u_emissive_strength:i,u_opacity:o}),_o={BaseColor:5,MetallicRoughness:6,Normal:7,Occlusion:8,Emission:9,ShadowMap0:10},uo=(t,i,o,r,s,n,a,l,c,h,_,d,u=[0,0,0])=>{const p=r.style.light,m=p.properties.get(\"position\"),f=[-m.x,-m.y,m.z],g=e.bx.create();\"viewport\"===p.properties.get(\"anchor\")&&(e.bx.fromRotation(g,-r.transform.angle),e.v.transformMat3(f,f,g));const v=\"MASK\"===h.alphaMode,x=p.properties.get(\"color\"),y=d.paint.get(\"model-ambient-occlusion-intensity\"),b=d.paint.get(\"model-color\").constantOr(e.C.white),w=d.paint.get(\"model-color-mix-intensity\").constantOr(0);return {u_matrix:t,u_lighting_matrix:i,u_normal_matrix:o,u_lightpos:f,u_lightintensity:p.properties.get(\"intensity\"),u_lightcolor:[x.r,x.g,x.b],u_camera_pos:u,u_opacity:s,u_baseTextureIsAlpha:0,u_alphaMask:+v,u_alphaCutoff:h.alphaCutoff,u_baseColorFactor:[n.r,n.g,n.b,n.a],u_emissiveFactor:[a[0],a[1],a[2],1],u_metallicFactor:l,u_roughnessFactor:c,u_baseColorTexture:_o.BaseColor,u_metallicRoughnessTexture:_o.MetallicRoughness,u_normalTexture:_o.Normal,u_occlusionTexture:_o.Occlusion,u_emissionTexture:_o.Emission,u_color_mix:[b.r,b.g,b.b,w],u_aoIntensity:y,u_emissive_strength:_}},po=new Float32Array(16),mo=(e,t=po,i=po)=>({u_matrix:e,u_instance:t,u_node_matrix:i}),fo={fillExtrusion:t=>({u_matrix:new e.a_(t),u_lightpos:new e.b7(t),u_lightintensity:new e.b2(t),u_lightcolor:new e.b7(t),u_vertical_gradient:new e.b2(t),u_opacity:new e.b2(t),u_edge_radius:new e.b2(t),u_ao:new e.b0(t),u_tile_id:new e.b7(t),u_zoom_transition:new e.b2(t),u_inv_rot_matrix:new e.a_(t),u_merc_center:new e.b0(t),u_up_dir:new e.b7(t),u_height_lift:new e.b2(t),u_flood_light_color:new e.b7(t),u_vertical_scale:new e.b2(t),u_flood_light_intensity:new e.b2(t),u_ground_shadow_factor:new e.b7(t),u_emissive_strength:new e.b2(t)}),fillExtrusionDepth:t=>({u_matrix:new e.a_(t),u_edge_radius:new e.b2(t),u_vertical_scale:new e.b2(t)}),fillExtrusionPattern:t=>({u_matrix:new e.a_(t),u_lightpos:new e.b7(t),u_lightintensity:new e.b2(t),u_lightcolor:new e.b7(t),u_vertical_gradient:new e.b2(t),u_height_factor:new e.b2(t),u_edge_radius:new e.b2(t),u_ao:new e.b0(t),u_tile_id:new e.b7(t),u_zoom_transition:new e.b2(t),u_inv_rot_matrix:new e.a_(t),u_merc_center:new e.b0(t),u_up_dir:new e.b7(t),u_height_lift:new e.b2(t),u_image:new e.a$(t),u_texsize:new e.b0(t),u_pixel_coord_upper:new e.b0(t),u_pixel_coord_lower:new e.b0(t),u_tile_units_to_pixels:new e.b2(t),u_opacity:new e.b2(t)}),fillExtrusionGroundEffect:t=>({u_matrix:new e.a_(t),u_opacity:new e.b2(t),u_ao_pass:new e.b2(t),u_meter_to_tile:new e.b2(t),u_ao:new e.b0(t),u_flood_light_intensity:new e.b2(t),u_flood_light_color:new e.b7(t),u_attenuation:new e.b2(t),u_edge_radius:new e.b2(t),u_fb:new e.a$(t),u_fb_size:new e.b2(t)}),fill:t=>({u_matrix:new e.a_(t),u_emissive_strength:new e.b2(t)}),fillPattern:t=>({u_matrix:new e.a_(t),u_emissive_strength:new e.b2(t),u_image:new e.a$(t),u_texsize:new e.b0(t),u_pixel_coord_upper:new e.b0(t),u_pixel_coord_lower:new e.b0(t),u_tile_units_to_pixels:new e.b2(t)}),fillOutline:t=>({u_matrix:new e.a_(t),u_emissive_strength:new e.b2(t),u_world:new e.b0(t)}),fillOutlinePattern:t=>({u_matrix:new e.a_(t),u_emissive_strength:new e.b2(t),u_world:new e.b0(t),u_image:new e.a$(t),u_texsize:new e.b0(t),u_pixel_coord_upper:new e.b0(t),u_pixel_coord_lower:new e.b0(t),u_tile_units_to_pixels:new e.b2(t)}),circle:e.bB,collisionBox:t=>({u_matrix:new e.a_(t),u_camera_to_center_distance:new e.b2(t),u_extrude_scale:new e.b0(t)}),collisionCircle:t=>({u_matrix:new e.a_(t),u_inv_matrix:new e.a_(t),u_camera_to_center_distance:new e.b2(t),u_viewport_size:new e.b0(t)}),debug:t=>({u_color:new e.b1(t),u_matrix:new e.a_(t),u_overlay:new e.a$(t),u_overlay_scale:new e.b2(t)}),clippingMask:t=>({u_matrix:new e.a_(t)}),heatmap:t=>({u_extrude_scale:new e.b2(t),u_intensity:new e.b2(t),u_matrix:new e.a_(t),u_inv_rot_matrix:new e.a_(t),u_merc_center:new e.b0(t),u_tile_id:new e.b7(t),u_zoom_transition:new e.b2(t),u_up_dir:new e.b7(t)}),heatmapTexture:t=>({u_image:new e.a$(t),u_color_ramp:new e.a$(t),u_opacity:new e.b2(t)}),hillshade:t=>({u_matrix:new e.a_(t),u_image:new e.a$(t),u_latrange:new e.b0(t),u_light:new e.b0(t),u_shadow:new e.b1(t),u_highlight:new e.b1(t),u_emissive_strength:new e.b2(t),u_accent:new e.b1(t)}),hillshadePrepare:t=>({u_matrix:new e.a_(t),u_image:new e.a$(t),u_dimension:new e.b0(t),u_zoom:new e.b2(t)}),line:e.bC,linePattern:e.bD,raster:t=>({u_matrix:new e.a_(t),u_normalize_matrix:new e.a_(t),u_globe_matrix:new e.a_(t),u_merc_matrix:new e.a_(t),u_grid_matrix:new e.b8(t),u_tl_parent:new e.b0(t),u_scale_parent:new e.b2(t),u_fade_t:new e.b2(t),u_opacity:new e.b2(t),u_image0:new e.a$(t),u_image1:new e.a$(t),u_brightness_low:new e.b2(t),u_brightness_high:new e.b2(t),u_saturation_factor:new e.b2(t),u_contrast_factor:new e.b2(t),u_spin_weights:new e.b7(t),u_perspective_transform:new e.b0(t),u_raster_elevation:new e.b2(t),u_zoom_transition:new e.b2(t),u_merc_center:new e.b0(t),u_cutoff_params:new e.b9(t),u_colorization_mix:new e.b9(t),u_colorization_offset:new e.b2(t),u_color_ramp:new e.a$(t),u_texture_offset:new e.b0(t),u_texture_res:new e.b0(t),u_emissive_strength:new e.b2(t)}),symbolIcon:t=>({u_is_size_zoom_constant:new e.a$(t),u_is_size_feature_constant:new e.a$(t),u_size_t:new e.b2(t),u_size:new e.b2(t),u_camera_to_center_distance:new e.b2(t),u_rotate_symbol:new e.a$(t),u_aspect_ratio:new e.b2(t),u_fade_change:new e.b2(t),u_matrix:new e.a_(t),u_label_plane_matrix:new e.a_(t),u_coord_matrix:new e.a_(t),u_is_text:new e.a$(t),u_pitch_with_map:new e.a$(t),u_texsize:new e.b0(t),u_tile_id:new e.b7(t),u_zoom_transition:new e.b2(t),u_inv_rot_matrix:new e.a_(t),u_merc_center:new e.b0(t),u_camera_forward:new e.b7(t),u_tile_matrix:new e.a_(t),u_up_vector:new e.b7(t),u_ecef_origin:new e.b7(t),u_texture:new e.a$(t),u_icon_transition:new e.b2(t),u_icon_saturation:new e.b2(t)}),symbolSDF:t=>({u_is_size_zoom_constant:new e.a$(t),u_is_size_feature_constant:new e.a$(t),u_size_t:new e.b2(t),u_size:new e.b2(t),u_camera_to_center_distance:new e.b2(t),u_rotate_symbol:new e.a$(t),u_aspect_ratio:new e.b2(t),u_fade_change:new e.b2(t),u_matrix:new e.a_(t),u_label_plane_matrix:new e.a_(t),u_coord_matrix:new e.a_(t),u_is_text:new e.a$(t),u_pitch_with_map:new e.a$(t),u_texsize:new e.b0(t),u_texture:new e.a$(t),u_gamma_scale:new e.b2(t),u_device_pixel_ratio:new e.b2(t),u_tile_id:new e.b7(t),u_zoom_transition:new e.b2(t),u_inv_rot_matrix:new e.a_(t),u_merc_center:new e.b0(t),u_camera_forward:new e.b7(t),u_tile_matrix:new e.a_(t),u_up_vector:new e.b7(t),u_ecef_origin:new e.b7(t),u_is_halo:new e.a$(t)}),symbolTextAndIcon:t=>({u_is_size_zoom_constant:new e.a$(t),u_is_size_feature_constant:new e.a$(t),u_size_t:new e.b2(t),u_size:new e.b2(t),u_camera_to_center_distance:new e.b2(t),u_rotate_symbol:new e.a$(t),u_aspect_ratio:new e.b2(t),u_fade_change:new e.b2(t),u_matrix:new e.a_(t),u_label_plane_matrix:new e.a_(t),u_coord_matrix:new e.a_(t),u_is_text:new e.a$(t),u_pitch_with_map:new e.a$(t),u_texsize:new e.b0(t),u_texsize_icon:new e.b0(t),u_texture:new e.a$(t),u_texture_icon:new e.a$(t),u_gamma_scale:new e.b2(t),u_device_pixel_ratio:new e.b2(t),u_is_halo:new e.a$(t)}),background:t=>({u_matrix:new e.a_(t),u_emissive_strength:new e.b2(t),u_opacity:new e.b2(t),u_color:new e.b1(t)}),backgroundPattern:t=>({u_matrix:new e.a_(t),u_emissive_strength:new e.b2(t),u_opacity:new e.b2(t),u_image:new e.a$(t),u_pattern_tl:new e.b0(t),u_pattern_br:new e.b0(t),u_texsize:new e.b0(t),u_pattern_size:new e.b0(t),u_pixel_coord_upper:new e.b0(t),u_pixel_coord_lower:new e.b0(t),u_tile_units_to_pixels:new e.b2(t)}),terrainRaster:Ti,terrainDepth:Ti,skybox:t=>({u_matrix:new e.a_(t),u_sun_direction:new e.b7(t),u_cubemap:new e.a$(t),u_opacity:new e.b2(t),u_temporal_offset:new e.b2(t)}),skyboxGradient:t=>({u_matrix:new e.a_(t),u_color_ramp:new e.a$(t),u_center_direction:new e.b7(t),u_radius:new e.b2(t),u_opacity:new e.b2(t),u_temporal_offset:new e.b2(t)}),skyboxCapture:t=>({u_matrix_3f:new e.b8(t),u_sun_direction:new e.b7(t),u_sun_intensity:new e.b2(t),u_color_tint_r:new e.b9(t),u_color_tint_m:new e.b9(t),u_luminance:new e.b2(t)}),globeRaster:t=>({u_proj_matrix:new e.a_(t),u_globe_matrix:new e.a_(t),u_normalize_matrix:new e.a_(t),u_merc_matrix:new e.a_(t),u_zoom_transition:new e.b2(t),u_merc_center:new e.b0(t),u_image0:new e.a$(t),u_grid_matrix:new e.b8(t),u_skirt_height:new e.b2(t),u_frustum_tl:new e.b7(t),u_frustum_tr:new e.b7(t),u_frustum_br:new e.b7(t),u_frustum_bl:new e.b7(t),u_globe_pos:new e.b7(t),u_globe_radius:new e.b2(t),u_viewport:new e.b0(t)}),globeAtmosphere:t=>({u_frustum_tl:new e.b7(t),u_frustum_tr:new e.b7(t),u_frustum_br:new e.b7(t),u_frustum_bl:new e.b7(t),u_horizon:new e.b2(t),u_transition:new e.b2(t),u_fadeout_range:new e.b2(t),u_color:new e.b9(t),u_high_color:new e.b9(t),u_space_color:new e.b9(t),u_temporal_offset:new e.b2(t),u_horizon_angle:new e.b2(t)}),model:t=>({u_matrix:new e.a_(t),u_lighting_matrix:new e.a_(t),u_normal_matrix:new e.a_(t),u_lightpos:new e.b7(t),u_lightintensity:new e.b2(t),u_lightcolor:new e.b7(t),u_camera_pos:new e.b7(t),u_opacity:new e.b2(t),u_baseColorFactor:new e.b9(t),u_emissiveFactor:new e.b9(t),u_metallicFactor:new e.b2(t),u_roughnessFactor:new e.b2(t),u_baseTextureIsAlpha:new e.a$(t),u_alphaMask:new e.a$(t),u_alphaCutoff:new e.b2(t),u_baseColorTexture:new e.a$(t),u_metallicRoughnessTexture:new e.a$(t),u_normalTexture:new e.a$(t),u_occlusionTexture:new e.a$(t),u_emissionTexture:new e.a$(t),u_color_mix:new e.b9(t),u_aoIntensity:new e.b2(t),u_emissive_strength:new e.b2(t)}),modelDepth:t=>({u_matrix:new e.a_(t),u_instance:new e.a_(t),u_node_matrix:new e.a_(t)}),groundShadow:t=>({u_matrix:new e.a_(t),u_ground_shadow_factor:new e.b7(t)}),stars:t=>({u_matrix:new e.a_(t),u_up:new e.b7(t),u_right:new e.b7(t),u_intensity_multiplier:new e.b2(t)})};let go;function vo(t,i,o,r,s,n,a){const l=t.context,c=l.gl,h=t.transform,_=t.getOrCreateProgram(\"collisionBox\"),d=[];let u=0,p=0;for(let l=0;l0){const t=e.m.create(),i=x;e.m.mul(t,g.placementInvProjMatrix,h.glCoordMatrix),e.m.mul(t,t,g.placementViewportMatrix),d.push({circleArray:b,circleOffset:p,transform:i,invTransform:t,projection:g.getProjection()}),u+=b.length/4,p=u;}y&&(t.terrain&&t.terrain.setupElevationDraw(f,_),_.draw(t,c.LINES,e.b4.disabled,e.b6.disabled,t.colorModeForRenderPass(),e.b5.disabled,Yi(x,h,f,g.getProjection()),o.id,y.layoutVertexBuffer,y.indexBuffer,y.segments,null,h.zoom,null,[y.collisionVertexBuffer,y.collisionVertexBufferExt]));}if(!a||!d.length)return;const m=t.getOrCreateProgram(\"collisionCircle\"),f=new e.bE;f.resize(4*u),f._trim();let g=0;for(const e of d)for(let t=0;t=0&&(m[y.associatedIconIndex]={x:C,y:I,z:S,angle:A});}else Se(T,u);}if(_){p.clear();const i=t.icon.placedSymbolArray;for(let t=0;t0&&ee.push(\"ICON_TRANSITION\"),d.zOffsetVertexBuffer&&ee.push(\"Z_OFFSET\");const te=p&&0!==o.paint.get(s?\"text-halo-width\":\"icon-halo-width\").constantOr(1);let ie;p?ie=c.iconsInText?lo(T.kind,D,y,v,t,X,J,Y,A,F,l,U,E,K,N,c.getProjection()):ao(T.kind,D,y,v,t,X,J,Y,s,A,!0,l,U,E,K,N,c.getProjection()):(_<1&&ee.push(\"SATURATION\"),ie=no(T.kind,D,y,v,t,X,J,Y,s,A,l,U,E,K,N,c.getProjection(),_,Q));const oe={program:t.getOrCreateProgram(wo(p,s,c),{config:u,defines:ee}),buffers:d,uniformValues:ie,atlasTexture:R,atlasTextureIcon:B,atlasInterpolation:z,atlasInterpolationIcon:O,isSDF:p,hasHalo:te,tile:r,labelPlaneMatrixInv:Z};if(b&&c.canOverlap){w=!0;const t=d.segments.get();for(const i of t)S.push({segments:new e.bm([i]),sortKey:i.sortKey,state:oe});}else S.push({segments:d.segments,sortKey:0,state:oe});}w&&S.sort(((e,t)=>e.sortKey-t.sortKey));for(const e of S){const i=e.state;if(t.terrain&&t.terrain.setupElevationDraw(i.tile,i.program,{useDepthForOcclusion:f.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:i.labelPlaneMatrixInv}),p.activeTexture.set(m.TEXTURE0),i.atlasTexture&&i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE,!0),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE,!0)),t.uploadCommonLightUniforms(t.context,i.program),i.hasHalo){const r=i.uniformValues;r.u_is_halo=1,Eo(i.buffers,e.segments,o,t,i.program,T,d,u,r,2),r.u_is_halo=0;}else {if(i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,Eo(i.buffers,e.segments,o,t,i.program,T,d,u,r,1)),r.u_is_halo=0;}Eo(i.buffers,e.segments,o,t,i.program,T,d,u,i.uniformValues,1);}}}function Eo(t,i,o,r,s,n,a,l,c,h){const _=[t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer,t.iconTransitioningVertexBuffer,t.globeExtVertexBuffer,t.zOffsetVertexBuffer];s.draw(r,r.context.gl.TRIANGLES,n,a,l,e.b5.disabled,c,o.id,t.layoutVertexBuffer,t.indexBuffer,i,o.paint,r.transform.zoom,t.programConfigurations.get(o.id),_,h);}function Co(t,i,o,r,s,n,a){const l=t.context.gl,c=o.paint.get(\"fill-pattern\"),h=c&&c.constantOr(1);let _,d,u,p,m;a?(d=h&&!o.getPaintProperty(\"fill-outline-color\")?\"fillOutlinePattern\":\"fillOutline\",_=l.LINES):(d=h?\"fillPattern\":\"fill\",_=l.TRIANGLES);for(const f of r){const r=i.getTile(f);if(h&&!r.patternsLoaded())continue;const g=r.getBucket(o);if(!g)continue;t.prepareDrawTile();const v=g.programConfigurations.get(o.id),x=t.isTileAffectedByFog(f),y=t.getOrCreateProgram(d,{config:v,overrideFog:x});h&&(t.context.activeTexture.set(l.TEXTURE0),r.imageAtlasTexture&&r.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),v.updatePaintBuffers());const b=c.constantOr(null);if(b&&r.imageAtlas){const e=r.imageAtlas.patternPositions[b.toString()];e&&v.setConstantPatternPositions(e);}const w=t.translatePosMatrix(f.projMatrix,r,o.paint.get(\"fill-translate\"),o.paint.get(\"fill-translate-anchor\")),T=o.paint.get(\"fill-emissive-strength\");if(a){p=g.indexBuffer2,m=g.segments2;const e=t.terrain&&t.terrain.renderingToTexture?t.terrain.drapeBufferSize:[l.drawingBufferWidth,l.drawingBufferHeight];u=\"fillOutlinePattern\"===d&&h?Ji(w,T,t,r,e):Xi(w,T,e);}else p=g.indexBuffer,m=g.segments,u=h?$i(w,T,t,r):qi(w,T);t.uploadCommonUniforms(t.context,y,f.toUnwrapped()),y.draw(t,_,s,t.stencilModeForClipping(f),n,e.b5.disabled,u,o.id,g.layoutVertexBuffer,p,m,o.paint,t.transform.zoom,v,void 0);}}function Io(t,i,o,r,s,n,a,l){o.resetLayerRenderingStats();const c=t.context,h=c.gl,_=t.transform,d=o.paint.get(\"fill-extrusion-pattern\"),u=d.constantOr(1),p=o.paint.get(\"fill-extrusion-opacity\"),m=t.style.enable3dLights(),f=o.paint.get(m&&!u?\"fill-extrusion-ambient-occlusion-wall-radius\":\"fill-extrusion-ambient-occlusion-radius\"),g=[o.paint.get(\"fill-extrusion-ambient-occlusion-intensity\"),f],v=o.layout.get(\"fill-extrusion-edge-radius\"),x=v>0&&!o.paint.get(\"fill-extrusion-rounded-roof\"),y=x?0:v,b=\"globe\"===_.projection.name?e.bO():0,w=\"globe\"===_.projection.name,T=w?e.ao(_.zoom):0,E=[e.E(_.center.lng),e.H(_.center.lat)],C=o.paint.get(\"fill-extrusion-flood-light-color\").toArray01().slice(0,3),I=o.paint.get(\"fill-extrusion-flood-light-intensity\"),S=o.paint.get(\"fill-extrusion-vertical-scale\"),M=Ii(t,o.paint.get(\"fill-extrusion-cutoff-fade-range\")),L=o.paint.get(\"fill-extrusion-emissive-strength\"),P=[];let D;w&&P.push(\"PROJECTION_GLOBE_VIEW\"),g[0]>0&&P.push(\"FAUX_AO\"),x&&P.push(\"ZERO_ROOF_RADIUS\"),l&&P.push(\"HAS_CENTROID\"),I>0&&P.push(\"FLOOD_LIGHT\"),M.shouldRenderCutoff&&P.push(\"RENDER_CUTOFF\");const A=\"shadow\"===t.renderPass,R=t.shadowRenderer,z=A&&!!R;t.shadowRenderer&&(t.shadowRenderer.useNormalOffset=!0);let O=[0,0,0];if(R){const e=t.style.directionalLight,i=t.style.ambientLight;e&&i&&(O=wr(e,i)),D=P.concat([\"SHADOWS_SINGLE_CASCADE\"]);}const F=z?\"fillExtrusionDepth\":u?\"fillExtrusionPattern\":\"fillExtrusion\",B=o.getLayerRenderingStats();for(const m of r){const r=i.getTile(m),f=r.getBucket(o);if(!f||f.projection.name!==_.projection.name)continue;let v=!1;R&&(v=0===R.getMaxCascadeForTile(m.toUnwrapped()));const x=t.isTileAffectedByFog(m),z=f.programConfigurations.get(o.id),k=t.getOrCreateProgram(F,{config:z,defines:v?D:P,overrideFog:x});if(t.terrain&&t.terrain.setupElevationDraw(r,k,{useMeterToDem:!0}),!f.centroidVertexBuffer){const e=k.attributes.a_centroid_pos;void 0!==e&&h.vertexAttrib2f(e,0,0);}!A&&R&&R.setupShadows(r.tileID.toUnwrapped(),k,\"vector-tile\",r.tileID.overscaledZ),u&&(t.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture&&r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),z.updatePaintBuffers());const N=d.constantOr(null);if(N&&r.imageAtlas){const e=r.imageAtlas.patternPositions[N.toString()];e&&z.setConstantPatternPositions(e);}const U=o.paint.get(\"fill-extrusion-vertical-gradient\");let G;if(A&&R){if(Ao(r.tileID,f,t))continue;const e=R.calculateShadowPassMatrixFromTile(r.tileID.toUnwrapped());G=Wi(e,y,S);}else {const e=t.translatePosMatrix(m.expandedProjMatrix,r,o.paint.get(\"fill-extrusion-translate\"),o.paint.get(\"fill-extrusion-translate-anchor\")),i=_.projection.createInversionMatrix(_,m.canonical);G=u?Hi(e,t,U,p,g,y,m,r,b,T,E,i,C,S):Zi(e,t,U,p,g,y,m,b,T,E,i,C,S,I,O,L);}t.uploadCommonUniforms(c,k,m.toUnwrapped(),null,M);let j=f.segments;if(\"mercator\"===_.projection.name&&!A&&(j=f.getVisibleSegments(r.tileID,t.terrain,t.transform.getFrustum(0)),!j.get().length))continue;if(B)if(A)for(const e of j.get())B.numRenderedVerticesInShadowPass+=e.primitiveLength;else for(const e of j.get())B.numRenderedVerticesInTransparentPass+=e.primitiveLength;const V=[];(t.terrain||l)&&V.push(f.centroidVertexBuffer),w&&V.push(f.layoutVertexExtBuffer),k.draw(t,c.gl.TRIANGLES,s,n,a,e.b5.backCCW,G,o.id,f.layoutVertexBuffer,f.indexBuffer,j,o.paint,t.transform.zoom,z,V);}t.shadowRenderer&&(t.shadowRenderer.useNormalOffset=!1);}function So(t,i,o,r,s,n,a,l,c,h,_,d,u,p,m,f,g,v,x){const y=t.context,b=y.gl,w=t.transform,T=t.transform.zoom,E=[],C=Ii(t,o.paint.get(\"fill-extrusion-cutoff-fade-range\"));\"clear\"===h?(E.push(\"CLEAR_SUBPASS\"),x&&(E.push(\"CLEAR_FROM_TEXTURE\"),y.activeTexture.set(b.TEXTURE0),x.bind(b.LINEAR,b.CLAMP_TO_EDGE))):\"sdf\"===h&&E.push(\"SDF_SUBPASS\"),g&&E.push(\"HAS_CENTROID\"),C.shouldRenderCutoff&&E.push(\"RENDER_CUTOFF\");const I=o.layout.get(\"fill-extrusion-edge-radius\"),S=(e,i,r,h,v)=>{const b=i.programConfigurations.get(o.id),w=t.isTileAffectedByFog(e),S=t.getOrCreateProgram(\"fillExtrusionGroundEffect\",{config:b,defines:E,overrideFog:w}),M=((e,t,i,o,r,s,n,a,l,c,h)=>({u_matrix:t,u_opacity:i,u_ao_pass:o?1:0,u_meter_to_tile:r,u_ao:s,u_flood_light_intensity:n,u_flood_light_color:a,u_attenuation:l,u_edge_radius:c,u_fb:0,u_fb_size:h}))(0,h,_,c,v,[d,u*v],p,m,f,T>=17?0:I*v,x?x.size[0]:0),L=[];g&&L.push(i.hiddenByLandmarkVertexBuffer),t.uploadCommonUniforms(y,S,e.toUnwrapped(),null,C),S.draw(t,y.gl.TRIANGLES,s,n,a,l,M,o.id,i.vertexBuffer,i.indexBuffer,r,o.paint,T,b,L);};for(const s of r){const r=i.getTile(s),n=r.getBucket(o);if(!n||n.projection.name!==w.projection.name||!n.groundEffect||n.groundEffect&&!n.groundEffect.hasData())continue;const a=n.groundEffect,l=1/n.tileToMeter;{const e=t.translatePosMatrix(s.projMatrix,r,o.paint.get(\"fill-extrusion-translate\"),o.paint.get(\"fill-extrusion-translate-anchor\")),i=a.getDefaultSegment();S(s,a,i,e,l);}if(v)for(let n=0;n<4;n++){const a=e.bP[n](s),c=i.getTile(a);if(!c)continue;const h=c.getBucket(o);if(!h||h.projection.name!==w.projection.name||!h.groundEffect||h.groundEffect&&!h.groundEffect.hasData())continue;const _=h.groundEffect;let d,u;0===n?(d=[-e.J,0,0],u=1):1===n?(d=[e.J,0,0],u=0):2===n?(d=[0,-e.J,0],u=3):(d=[0,e.J,0],u=2);const p=_.regionSegments[u];if(!p)continue;const m=new Float32Array(16);e.m.translate(m,s.projMatrix,d),S(s,_,p,t.translatePosMatrix(m,r,o.paint.get(\"fill-extrusion-translate\"),o.paint.get(\"fill-extrusion-translate-anchor\")),l);}}}function Mo(t,i,o,r,s,n,a){0===r.centroidVertexArray.length&&r.createCentroidsBuffer();const l=n?n.findDEMTileFor(o):null;if(!(l&&l.dem||a))return;const c=t=>new e.P(Math.ceil((t+e.bS)*e.bT),0),h=e=>{const t=i.getSource().minzoom,o=e=>{const t=i.getTileByID(e);if(t&&t.hasData())return t.getBucket(s)},r=[0,-1,1];for(const i of r){if(e.overscaledZ+i(_[0]=Math.min(t.min.y,i.min.y),_[1]=Math.max(t.max.y,i.max.y),_[2]=e.J-i.min.x>t.max.x?i.min.x-e.J:t.max.x,_),u=(t,i)=>(_[0]=Math.min(t.min.x,i.min.x),_[1]=Math.max(t.max.x,i.max.x),_[2]=e.J-i.min.y>t.max.y?i.min.y-e.J:t.max.y,_),p=[(e,t)=>d(e,t),(e,t)=>d(t,e),(e,t)=>u(e,t),(e,t)=>u(t,e)],m=(t,i,r,s,a,c,h)=>{if(!n)return 0;const _=[[c?r:t,c?t:r,0],[c?r:i,c?i:r,0]],d=h<0?e.J+h:h,u=[c?d:(t+i)/2,c?(t+i)/2:d,0];return 0===r&&h<0||0!==r&&h>0?n.getForTilePoints(a,[u],!0,s):_.push(u),n.getForTilePoints(o,_,!0,l),Math.max(_[0][2],_[1][2],u[2])/n.exaggeration()};for(let t=0;t<4;t++){const i=r.borderFeatureIndices[t];if(0===i.length)continue;const s=e.bP[t](o),l=h(s);if(!(l&&l instanceof e.bQ))continue;if(r.borderDoneWithNeighborZ[t]===l.canonical.z)continue;0===l.centroidVertexArray.length&&l.createCentroidsBuffer();const _=n?n.findDEMTileFor(s):null;if(!(_&&_.dem||a))continue;const d=(t<2?1:5)-t,u=l.borderDoneWithNeighborZ[d]!==r.canonical.z,v=l.borderFeatureIndices[d];let x=0;if(r.canonical.z!==l.canonical.z){for(const e of i)r.showCentroid(r.featuresOnBorder[e]);if(u)for(const e of v)l.showCentroid(l.featuresOnBorder[e]);r.borderDoneWithNeighborZ[t]=l.canonical.z,l.borderDoneWithNeighborZ[d]=r.canonical.z;}for(const o of i){const i=r.featuresOnBorder[o],n=r.centroidData[i.centroidDataIndex],h=i.borders[t];let u;for(;xh[0]+3||e[0]>h[0]-3)break;l.showCentroid(u),x++;}if(u&&xh[1]-3)&&(y++,++x!==v.length);)u=l.featuresOnBorder[v[x]];if(u=l.featuresOnBorder[v[o]],y>1){const e=u.borders[d];Math.abs(h[0]-e[0])<3&&Math.abs(h[1]-e[1])<3&&(y=1,x=o+1);}else if(0===y){r.showCentroid(i);continue}const b=l.centroidData[u.centroidDataIndex];a&&1===y&&(((f=n).flags|(g=b).flags)&e.bR?(f.flags|=e.bR,g.flags|=e.bR):(f.flags&=~e.bR,g.flags&=~e.bR));const w=i.intersectsCount()>1||u.intersectsCount()>1;if(y>1)x=o,n.centroidXY=b.centroidXY=new e.P(0,0);else if(_&&_.dem&&!w){const i=p[t](n,b),o=t%2?e.J-1:0,r=m(i[0],Math.min(e.J-1,i[1]),o,_,s,t<2,i[2]);n.centroidXY=b.centroidXY=c(r);}else w?n.centroidXY=b.centroidXY=new e.P(0,0):(n.centroidXY=r.encodeBorderCentroid(i),b.centroidXY=l.encodeBorderCentroid(u));r.writeCentroidToBuffer(n),l.writeCentroidToBuffer(b);}else r.showCentroid(i);}r.borderDoneWithNeighborZ[t]=l.canonical.z,l.borderDoneWithNeighborZ[d]=r.canonical.z;}var f,g;(r.needsCentroidUpdate||!r.centroidVertexBuffer&&0!==r.centroidVertexArray.length)&&r.uploadCentroid(t);}const Lo=[1,0,0],Po=[0,1,0],Do=[0,0,1];function Ao(t,i,o){const r=o.transform,s=o.shadowRenderer;if(!s)return !0;const n=t.toUnwrapped(),a=r.tileSize*s._cascades[o.currentShadowCascade].scale;let l=i.maxHeight;if(r.elevation){const e=r.elevation.getMinMaxForTile(t);e&&(l+=e.max);}const c=[...s.shadowDirection];c[2]=-c[2];const h=s.computeSimplifiedTileShadowVolume(n,l,a,c);if(!h)return !1;const _=[Lo,Po,Do,c,[c[0],0,c[2]],[0,c[1],c[2]]],d=\"globe\"===r.projection.name,u=r.scaleZoom(a),p=e.F.fromInvProjectionMatrix(r.invProjMatrix,r.worldSize,u,!d),m=s.getCurrentCascadeFrustum();return 0===p.intersectsPrecise(h.vertices,h.planes,_)||0===m.intersectsPrecise(h.vertices,h.planes,_)}function Ro(e){const t=e._nearZ,i=e.projection.farthestPixelDistance(e),o=i-t,r=.2*e.height,s=t+r;return [t,i,(s-r-t)/o,(s-t)/o]}const zo=new e.C(1,0,0,1),Oo=new e.C(0,1,0,1),Fo=new e.C(0,0,1,1),Bo=new e.C(1,0,1,1),ko=new e.C(0,1,1,1);function No(t,i,o,r,s,n){const a=t.context,l=t.transform,c=a.gl,h=\"globe\"===l.projection.name,_=h?[\"PROJECTION_GLOBE_VIEW\"]:[];let d=e.m.clone(o.projMatrix);if(h&&e.ao(l.zoom)>0){const t=e.bU(o.canonical,l),i=e.bV(t);d=e.m.multiply(new Float32Array(16),l.globeMatrix,i),e.m.multiply(d,l.projMatrix,d);}const u=e.m.create();u[12]+=2*s/(e.a4.devicePixelRatio*l.width),u[13]+=2*n/(e.a4.devicePixelRatio*l.height),e.m.multiply(d,u,d);const p=t.getOrCreateProgram(\"debug\",{defines:_}),m=i.getTileByID(o.key);t.terrain&&t.terrain.setupElevationDraw(m,p);const f=e.b4.disabled,g=e.b6.disabled,v=t.colorModeForRenderPass(),x=\"$debug\";a.activeTexture.set(c.TEXTURE0),t.emptyTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),h?m._makeGlobeTileDebugBuffers(t.context,l):m._makeDebugTileBoundsBuffers(t.context,l.projection);const y=m._tileDebugBuffer||t.debugBuffer,b=m._tileDebugIndexBuffer||t.debugIndexBuffer,w=m._tileDebugSegments||t.debugSegments;p.draw(t,c.LINE_STRIP,f,g,v,e.b5.disabled,Ki(d,r),x,y,b,w,null,null,null,[m._globeTileDebugBorderBuffer]);const T=m.latestRawTileData,E=Math.floor((T&&T.byteLength||0)/1024),C=i.getTile(o).tileSize,I=512/Math.min(C,512)*(o.overscaledZ/l.zoom)*.5;let S=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(S+=` => ${o.overscaledZ}`),S+=` ${E}kb`,function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext(\"2d\");r.clearRect(0,0,i.width,i.height),r.shadowColor=\"white\",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle=\"white\",r.textBaseline=\"top\",r.font=\"bold 36px Open Sans, sans-serif\",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(t,S);const M=m._tileDebugTextBuffer||t.debugBuffer,L=m._tileDebugTextIndexBuffer||t.quadTriangleIndexBuffer,P=m._tileDebugTextSegments||t.debugSegments;p.draw(t,c.TRIANGLES,f,g,e.a.alphaBlended,e.b5.disabled,Ki(d,e.C.transparent,I),x,M,L,P,null,null,null,[m._globeTileDebugTextBuffer]);}function Uo(e,t,i,o){jo(e,0,t+i/2,e.transform.width,i,o);}function Go(e,t,i,o){jo(e,t-i/2,0,i,e.transform.height,o);}function jo(t,i,o,r,s,n){const a=t.context,l=a.gl;l.enable(l.SCISSOR_TEST),l.scissor(i*e.a4.devicePixelRatio,o*e.a4.devicePixelRatio,r*e.a4.devicePixelRatio,s*e.a4.devicePixelRatio),a.clear({color:n}),l.disable(l.SCISSOR_TEST);}const Vo=e.bW([{name:\"a_pos_3f\",components:3,type:\"Float32\"}]),{members:Zo}=Vo;function Wo(e,t,i,o){e.emplaceBack(t,i,o);}class Ho{constructor(t){this.vertexArray=new e.bX,this.indices=new e.bp,Wo(this.vertexArray,-1,-1,1),Wo(this.vertexArray,1,-1,1),Wo(this.vertexArray,-1,1,1),Wo(this.vertexArray,1,1,1),Wo(this.vertexArray,-1,-1,-1),Wo(this.vertexArray,1,-1,-1),Wo(this.vertexArray,-1,1,-1),Wo(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=t.createVertexBuffer(this.vertexArray,Zo),this.indexBuffer=t.createIndexBuffer(this.indices),this.segment=e.bm.simpleSegment(0,0,36,12);}}function qo(t,i,o,r,s,n){const a=t.context.gl,l=i.paint.get(\"sky-atmosphere-color\"),c=i.paint.get(\"sky-atmosphere-halo-color\"),h=i.paint.get(\"sky-atmosphere-sun-intensity\"),_=((e,t,i,o,r)=>({u_matrix_3f:e,u_sun_direction:t,u_sun_intensity:i,u_color_tint_r:[o.r,o.g,o.b,o.a],u_color_tint_m:[r.r,r.g,r.b,r.a],u_luminance:5e-5}))(e.bx.fromMat4(e.bx.create(),r),s,h,l,c);a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+n,i.skyboxTexture,0),o.draw(t,a.TRIANGLES,e.b4.disabled,e.b6.disabled,e.a.unblended,e.b5.frontCW,_,\"skyboxCapture\",i.skyboxGeometry.vertexBuffer,i.skyboxGeometry.indexBuffer,i.skyboxGeometry.segment);}const $o=e.bW([{type:\"Float32\",name:\"a_pos\",components:3},{type:\"Float32\",name:\"a_uv\",components:2}]);class Xo{constructor(t){const i=new e.bY;i.emplaceBack(-1,1,1,0,0),i.emplaceBack(1,1,1,1,0),i.emplaceBack(1,-1,1,1,1),i.emplaceBack(-1,-1,1,0,1);const o=new e.bp;o.emplaceBack(0,1,2),o.emplaceBack(2,3,0),this.vertexBuffer=t.createVertexBuffer(i,$o.members),this.indexBuffer=t.createIndexBuffer(o),this.segments=e.bm.simpleSegment(0,0,4,2);}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy();}}const Jo=e.bW([{type:\"Float32\",name:\"a_pos_3f\",components:3},{type:\"Float32\",name:\"a_uv\",components:2},{type:\"Float32\",name:\"a_size_scale\",components:1},{type:\"Float32\",name:\"a_fade_opacity\",components:1}]);class Yo{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15;}}class Ko{constructor(t){this.colorModeAlphaBlendedWriteRGB=new e.a([e.bZ,e.b_,e.bZ,e.b_],e.C.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new e.a([e.bZ,e.b$,e.bZ,e.b$],e.C.transparent,[!1,!1,!1,!0]),this.params=new Yo,this.allocatedStarsCount=0,t.tp.registerParameter(this.params,[\"Stars\"],\"starsCount\",{min:100,max:16e3,step:1}),t.tp.registerParameter(this.params,[\"Stars\"],\"sizeMultiplier\",{min:.01,max:2,step:.01});}update(t){const i=t.context;if(!this.atmosphereBuffer||this.allocatedStarsCount!==this.params.starsCount){this.atmosphereBuffer=new Xo(i),this.allocatedStarsCount=this.params.starsCount;const t=100,o=200,r=function(t){const i=e.c2(30),o=[];for(let r=0;r{const _=\"globe\"===s.projection.name?[\"PROJECTION_GLOBE_VIEW\",\"FOG\"]:[\"FOG\"];i&&_.push(\"ALPHA_PASS\");const u=t.getOrCreateProgram(\"globeAtmosphere\",{defines:_}),m=((e,t,i,o,r,s,n,a,l,c,h,_)=>({u_frustum_tl:e,u_frustum_tr:t,u_frustum_br:i,u_frustum_bl:o,u_horizon:r,u_transition:s,u_fadeout_range:n,u_color:a,u_high_color:l,u_space_color:c,u_temporal_offset:h,u_horizon_angle:_}))(s.frustumCorners.TL,s.frustumCorners.TR,s.frustumCorners.BR,s.frustumCorners.BL,s.frustumCorners.horizon,a,d,l,c,h,p,g);t.uploadCommonUniforms(o,u);const f=this.atmosphereBuffer;f&&u.draw(t,r.TRIANGLES,n,e.b6.disabled,i?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,e.b5.backCW,m,i?\"atmosphere_glow_alpha\":\"atmosphere_glow\",f.vertexBuffer,f.indexBuffer,f.segments);};v(!1),v(!0);}drawStars(t,i){const o=e.c(i.properties.get(\"star-intensity\"),0,1);if(0===o)return;const r=t.context,s=r.gl,n=t.transform,a=t.getOrCreateProgram(\"stars\"),l=e.q.identity([]);e.q.rotateX(l,l,-n._pitch),e.q.rotateZ(l,l,-n.angle),e.q.rotateX(l,l,e.d(n._center.lat)),e.q.rotateY(l,l,-e.d(n._center.lng));const c=e.m.fromQuat(new Float32Array(16),l),h=e.m.multiply([],n.starsProjMatrix,c),_=e.bx.fromMat4([],c),d=e.bx.invert([],_),u=[0,1,0];e.v.transformMat3(u,u,d),e.v.scale(u,u,this.params.sizeMultiplier);const p=[1,0,0];e.v.transformMat3(p,p,d),e.v.scale(p,p,this.params.sizeMultiplier);const m=(f=u,g=p,v=o,{u_matrix:Float32Array.from(h),u_up:f,u_right:g,u_intensity_multiplier:v});var f,g,v;t.uploadCommonUniforms(r,a),this.starsVx&&this.starsIdx&&a.draw(t,s.TRIANGLES,e.b4.disabled,e.b6.disabled,this.colorModeAlphaBlendedWriteRGB,e.b5.disabled,m,\"atmosphere_stars\",this.starsVx,this.starsIdx,this.starsSegments);}}function Qo(t,i){const o=[...t],r=i.cameraWorldSizeForFog/i.worldSize,s=e.m.identity([]);return e.m.scale(s,s,[r,r,1]),e.m.multiply(o,s,o),e.m.multiply(o,i.worldToFogMatrix,o),o}function er(e,t,i,o){const r=i.material,s=o.context,{baseColorTexture:n,metallicRoughnessTexture:a}=r.pbrMetallicRoughness,{normalTexture:l,occlusionTexture:c,emissionTexture:h}=r;function _(t,i,o){if(t&&(e.push(i),s.activeTexture.set(s.gl.TEXTURE0+o),t.gfxTexture)){const{minFilter:e,magFilter:i,wrapS:o,wrapT:r}=t.sampler;t.gfxTexture.bindExtraParam(e,i,o,r);}}_(n,\"HAS_TEXTURE_u_baseColorTexture\",_o.BaseColor),_(a,\"HAS_TEXTURE_u_metallicRoughnessTexture\",_o.MetallicRoughness),_(l,\"HAS_TEXTURE_u_normalTexture\",_o.Normal),_(c,\"HAS_TEXTURE_u_occlusionTexture\",_o.Occlusion),_(h,\"HAS_TEXTURE_u_emissionTexture\",_o.Emission),i.texcoordBuffer&&(e.push(\"HAS_ATTRIBUTE_a_uv_2f\"),t.push(i.texcoordBuffer)),i.colorBuffer&&(e.push(12===i.colorBuffer.itemSize?\"HAS_ATTRIBUTE_a_color_3f\":\"HAS_ATTRIBUTE_a_color_4f\"),t.push(i.colorBuffer)),i.normalBuffer&&(e.push(\"HAS_ATTRIBUTE_a_normal_3f\"),t.push(i.normalBuffer)),i.pbrBuffer&&(e.push(\"HAS_ATTRIBUTE_a_pbr\"),e.push(\"HAS_ATTRIBUTE_a_heightBasedEmissiveStrength\"),t.push(i.pbrBuffer)),\"OPAQUE\"!==r.alphaMode&&\"MASK\"!==r.alphaMode||e.push(\"UNPREMULT_TEXTURE_IN_SHADER\"),r.defined||e.push(\"DIFFUSE_SHADED\"),e.push(\"USE_STANDARD_DERIVATIVES\");}function tr(t,i,o,r,s,n){const a=o.paint.get(\"model-opacity\"),l=i.context,c=new e.b4(i.context.gl.LEQUAL,e.b4.ReadWrite,i.depthRangeFor3D),h=i.transform,_=t.mesh,d=_.material,u=d.pbrMetallicRoughness,p=i.style.fog;let m;m=\"pixels\"===i.transform.projection.zAxisUnit?[...t.nodeModelMatrix]:e.m.multiply([],r.zScaleMatrix,t.nodeModelMatrix),e.m.multiply(m,r.negCameraPosMatrix,m);const f=e.m.invert([],m);e.m.transpose(f,f);const g=o.paint.get(\"model-emissive-strength\").constantOr(0),v=uo(new Float32Array(t.worldViewProjection),new Float32Array(m),new Float32Array(f),i,a,u.baseColorFactor,d.emissiveFactor,u.metallicFactor,u.roughnessFactor,d,g,o),x={defines:[]},y=[];er(x.defines,y,_,i);const b=i.shadowRenderer;b&&(b.useNormalOffset=!1);let w=null;if(p){const e=Qo(t.nodeModelMatrix,i.transform);if(w=new Float32Array(e),\"globe\"!==h.projection.name){const t=_.aabb.min,i=_.aabb.max,[o,r]=p.getOpacityForBounds(e,t[0],t[1],i[0],i[1]);x.overrideFog=o>=Ue||r>=Ue;}}const T=Ii(i,o.paint.get(\"model-cutoff-fade-range\"));T.shouldRenderCutoff&&x.defines.push(\"RENDER_CUTOFF\");const E=i.getOrCreateProgram(\"model\",x);i.uploadCommonUniforms(l,E,null,w,T),\"shadow\"!==i.renderPass&&b&&b.setupShadowsFromMatrix(t.nodeModelMatrix,E),E.draw(i,l.gl.TRIANGLES,c,s,n,_.material.doubleSided?e.b5.disabled:e.b5.backCCW,v,o.id,_.vertexBuffer,_.indexBuffer,_.segments,o.paint,i.transform.zoom,void 0,y);}function ir(t,i,o,r,s,n,a){let l;l=\"globe\"===t.projection.name?e.c5(o,t):[...o],e.m.multiply(l,l,i.matrix);const c=e.m.multiply([],r,l);if(i.meshes)for(const t of i.meshes){if(\"BLEND\"!==t.material.alphaMode){a.push({mesh:t,depth:0,modelIndex:s,worldViewProjection:c,nodeModelMatrix:l});continue}const i=e.v.transformMat4([],t.centroid,c);i[2]>0&&n.push({mesh:t,depth:i[2],modelIndex:s,worldViewProjection:c,nodeModelMatrix:l});}if(i.children)for(const e of i.children)ir(t,e,o,r,s,n,a);}function or(t,i,o,r){const s=o.shadowRenderer;if(!s)return;const n=s.getShadowPassDepthMode(),a=s.getShadowPassColorMode(),l=s.calculateShadowPassMatrixFromMatrix(i),c=mo(l);o.getOrCreateProgram(\"modelDepth\",{defines:[\"DEPTH_TEXTURE\"]}).draw(o,o.context.gl.TRIANGLES,n,e.b6.disabled,a,e.b5.backCCW,c,r.id,t.vertexBuffer,t.indexBuffer,t.segments,r.paint,o.transform.zoom,void 0,void 0);}function rr(t,i,o){const r=i.updateZoomBasedPaintProperties(),s=function(t,i,o){let r,s,n,a=t.terrain?t.terrain.exaggeration():0;if(t.terrain&&a>0){const i=t.terrain,s=i.findDEMTileFor(o);s&&s.dem?r=e.c7.create(i,o,s):a=0;}if(0===a&&(i.terrainElevationMin=0,i.terrainElevationMax=0),a===i.validForExaggeration&&(0===a||r&&r._demTile&&r._demTile.tileID===i.validForDEMTile.id&&r._dem._timestamp===i.validForDEMTile.timestamp))return !1;for(const e in i.instancesPerModel){const t=i.instancesPerModel[e];for(let e=0;eh&&(h=e.max);}const _=e.c(r.x,n,a)-r.x,d=e.c(r.y,l,c)-r.y,u=e.b(h,i.center.lat)-r.z;return i._zoomFromMercatorZ(Math.sqrt(_*_+d*d+u*u))}function ar(t,i,o,r,s,n,a){const l=t.context,c=\"shadow\"===t.renderPass,h=t.shadowRenderer,_=c&&h?h.getShadowPassDepthMode():new e.b4(l.gl.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D),d=t.isTileAffectedByFog(n);if(o.meshes)for(const u of o.meshes){const p=[\"MODEL_POSITION_ON_GPU\"],m=[];let f,g,v;r.instancedDataArray.length>20&&p.push(\"INSTANCED_ARRAYS\");const x=Ii(t,i.paint.get(\"model-cutoff-fade-range\"));if(x.shouldRenderCutoff&&p.push(\"RENDER_CUTOFF\"),c&&h)f=t.getOrCreateProgram(\"modelDepth\",{defines:p}),g=mo(a.shadowTileMatrix,a.shadowTileMatrix,Float32Array.from(o.matrix)),v=h.getShadowPassColorMode();else {er(p,m,u,t),f=t.getOrCreateProgram(\"model\",{defines:p,overrideFog:d});const r=u.material,c=r.pbrMetallicRoughness,_=i.paint.get(\"model-opacity\"),y=i.paint.get(\"model-emissive-strength\").constantOr(0);g=uo(n.expandedProjMatrix,Float32Array.from(o.matrix),new Float32Array(16),t,_,c.baseColorFactor,r.emissiveFactor,c.metallicFactor,c.roughnessFactor,r,y,i,s),h&&(a.shadowUniformsInitialized?f.setShadowUniformValues(l,h.getShadowUniformValues()):(h.setupShadows(n.toUnwrapped(),f,\"model-tile\",n.overscaledZ),a.shadowUniformsInitialized=!0)),v=x.shouldRenderCutoff||_<1||\"OPAQUE\"!==r.alphaMode?e.a.alphaBlended:e.a.unblended;}t.uploadCommonUniforms(l,f,n.toUnwrapped(),null,x);const y=u.material.doubleSided?e.b5.disabled:e.b5.backCCW;if(r.instancedDataArray.length>20)m.push(r.instancedDataBuffer),f.draw(t,l.gl.TRIANGLES,_,e.b6.disabled,v,y,g,i.id,u.vertexBuffer,u.indexBuffer,u.segments,i.paint,t.transform.zoom,void 0,m,r.instancedDataArray.length);else {const o=c?\"u_instance\":\"u_normal_matrix\";for(let s=0;s30&&(i.buf.destroy(),this._storage.delete(t));}destroy(){for(const[e,t]of this._storage)t.buf.destroy(),this._storage.delete(e);}}class dr{registerParameter(e,t,i,o,r){}registerButton(e,t,i){}}const ur={symbol:function(t,i,o,r,s){if(\"translucent\"!==t.renderPass)return;const n=e.b6.disabled,a=t.colorModeForRenderPass();o.layout.get(\"text-variable-anchor\")&&function(t,i,o,r,s,n,a){const l=i.transform,c=\"map\"===s,h=\"map\"===n;for(const i of t){const t=r.getTile(i),s=t.getBucket(o);if(!s||!s.text||!s.text.segments.get().length)continue;const n=e.i(s.textSizeData,l.zoom),_=St(i,s.getProjection(),l),d=l.calculatePixelsToTileUnitsMatrix(t),u=pe(_,t.tileID.canonical,h,c,l,s.getProjection(),d),p=s.hasIconTextFit()&&s.hasIconData();if(n){const o=Math.pow(2,l.zoom-t.tileID.overscaledZ);bo(s,c,h,a,e.bG,l,u,i,o,n,p);}}}(r,t,o,i,o.layout.get(\"text-rotation-alignment\"),o.layout.get(\"text-pitch-alignment\"),s),0!==o.paint.get(\"icon-opacity\").constantOr(1)&&To(t,i,o,r,!1,o.paint.get(\"icon-translate\"),o.paint.get(\"icon-translate-anchor\"),o.layout.get(\"icon-rotation-alignment\"),o.layout.get(\"icon-pitch-alignment\"),o.layout.get(\"icon-keep-upright\"),o.paint.get(\"icon-color-saturation\"),n,a),0!==o.paint.get(\"text-opacity\").constantOr(1)&&To(t,i,o,r,!0,o.paint.get(\"text-translate\"),o.paint.get(\"text-translate-anchor\"),o.layout.get(\"text-rotation-alignment\"),o.layout.get(\"text-pitch-alignment\"),o.layout.get(\"text-keep-upright\"),o.paint.get(\"icon-color-saturation\"),n,a),i.map.showCollisionBoxes&&(vo(t,i,o,r,o.paint.get(\"text-translate\"),o.paint.get(\"text-translate-anchor\"),!0),vo(t,i,o,r,o.paint.get(\"icon-translate\"),o.paint.get(\"icon-translate-anchor\"),!1));},circle:function(t,i,o,r){if(\"translucent\"!==t.renderPass)return;const s=o.paint.get(\"circle-opacity\"),n=o.paint.get(\"circle-stroke-width\"),a=o.paint.get(\"circle-stroke-opacity\"),l=void 0!==o.layout.get(\"circle-sort-key\").constantOr(1),c=o.paint.get(\"circle-emissive-strength\");if(0===s.constantOr(1)&&(0===n.constantOr(1)||0===a.constantOr(1)))return;const h=t.context,_=h.gl,d=t.transform,u=t.depthModeForSublayer(0,e.b4.ReadOnly),p=e.b6.disabled,m=t.colorModeForDrapableLayerRenderPass(c),f=\"globe\"===d.projection.name,g=[e.E(d.center.lng),e.H(d.center.lat)],v=[];for(let s=0;se.sortKey-t.sortKey));const x={useDepthForOcclusion:d.depthOcclusionForSymbolsAndCircles};for(const i of v){const{programConfiguration:r,program:s,layoutVertexBuffer:n,globeExtVertexBuffer:a,indexBuffer:l,uniformValues:c,tile:f}=i.state,g=i.segments;t.terrain&&t.terrain.setupElevationDraw(f,s,x),t.uploadCommonUniforms(h,s,f.tileID.toUnwrapped()),s.draw(t,_.TRIANGLES,u,p,m,e.b5.disabled,c,o.id,n,l,g,o.paint,d.zoom,r,[a]);}},heatmap:function(t,i,o,r){if(0!==o.paint.get(\"heatmap-opacity\"))if(\"offscreen\"===t.renderPass){const s=t.context,n=s.gl,a=e.b6.disabled,l=new e.a([n.ONE,n.ONE,n.ONE,n.ONE],e.C.transparent,[!0,!0,!0,!0]);!function(e,t,i,o){const r=e.gl,s=t.width*o,n=t.height*o;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,s,n]);let a=i.heatmapFbo;if(!a||a&&(a.width!==s||a.height!==n)){a&&a.destroy();const t=r.createTexture();r.bindTexture(r.TEXTURE_2D,t),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),a=i.heatmapFbo=e.createFramebuffer(s,n,!0,null),function(e,t,i,o,r,s){const n=e.gl;n.texImage2D(n.TEXTURE_2D,0,e.extRenderToTextureHalfFloat?n.RGBA16F:n.RGBA,r,s,0,n.RGBA,e.extRenderToTextureHalfFloat?n.HALF_FLOAT:n.UNSIGNED_BYTE,null),o.colorAttachment.set(i);}(e,0,t,a,s,n);}else r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer);}(s,t,o,\"globe\"===t.transform.projection.name?.5:.25),s.clear({color:e.C.transparent});const c=t.transform,h=\"globe\"===c.projection.name,_=h?[\"PROJECTION_GLOBE_VIEW\"]:[],d=h?e.b5.frontCCW:e.b5.disabled,u=[e.E(c.center.lng),e.H(c.center.lat)];for(let p=0;p({u_image:0,u_color_ramp:1,u_opacity:t.paint.get(\"heatmap-opacity\")}))(0,i),i.id,t.viewportBuffer,t.quadTriangleIndexBuffer,t.viewportSegments,i.paint,t.transform.zoom);}(t,o));},line:function(t,i,o,r){if(\"translucent\"!==t.renderPass)return;const s=o.paint.get(\"line-opacity\"),n=o.paint.get(\"line-width\");if(0===s.constantOr(1)||0===n.constantOr(1))return;const a=o.paint.get(\"line-emissive-strength\"),l=t.depthModeForSublayer(0,e.b4.ReadOnly),c=t.colorModeForDrapableLayerRenderPass(a),h=t.terrain&&t.terrain.renderingToTexture?1:e.a4.devicePixelRatio,_=o.paint.get(\"line-dasharray\"),d=_.constantOr(1),u=o.layout.get(\"line-cap\"),p=o.paint.get(\"line-pattern\"),m=p.constantOr(1),f=o.paint.get(\"line-pattern\").constantOr(1),g=1!==o.paint.get(\"line-opacity\").constantOr(1);let v=!f&&g;const x=o.paint.get(\"line-gradient\"),y=m?\"linePattern\":\"line\",b=t.context,w=b.gl,T=e.bJ(o);t.terrain&&t.terrain.clipOrMaskOverlapStencilType()&&(v=!1);for(const s of r){const r=i.getTile(s);if(m&&!r.patternsLoaded())continue;const n=r.getBucket(o);if(!n)continue;t.prepareDrawTile();const a=n.programConfigurations.get(o.id),f=t.isTileAffectedByFog(s),g=t.getOrCreateProgram(y,{config:a,defines:T,overrideFog:f}),E=p.constantOr(null);if(E&&r.imageAtlas){const e=r.imageAtlas.patternPositions[E.toString()];e&&a.setConstantPatternPositions(e);}const C=_.constantOr(null),I=u.constantOr(null);if(!m&&C&&I&&r.lineAtlas){const e=r.lineAtlas.getDash(C,I);e&&a.setConstantPatternPositions(e);}let[S,M]=o.paint.get(\"line-trim-offset\");if(\"round\"===I||\"square\"===I){const e=1;S!==M&&(0===S&&(S-=e),1===M&&(M+=e));}const L=t.terrain?s.projMatrix:null,P=m?e.bK(t,r,o,L,h):e.bL(t,r,o,L,n.lineClipsArray.length,h,[S,M]);if(x){const r=n.gradients[o.id];let a=r.texture;if(o.gradientVersion!==r.version){let l=256;if(o.stepInterpolant){const o=i.getSource().maxzoom,r=s.canonical.z===o?Math.ceil(1<{g.draw(t,w.TRIANGLES,l,i,c,e.b5.disabled,P,o.id,n.layoutVertexBuffer,n.indexBuffer,n.segments,o.paint,t.transform.zoom,a,[n.layoutVertexBuffer2]);};if(v){const i=t.stencilModeForClipping(s).ref;0===i&&t.terrain&&b.clear({stencil:0});const o={func:w.EQUAL,mask:255};P.u_alpha_discard_threshold=.8,D(new e.b6(o,i,255,w.KEEP,w.KEEP,w.INVERT)),P.u_alpha_discard_threshold=0,D(new e.b6(o,i,255,w.KEEP,w.KEEP,w.KEEP));}else D(t.stencilModeForClipping(s));}v&&(t.resetStencilClippingMasks(),t.terrain&&b.clear({stencil:0}));},fill:function(t,i,o,r){const s=o.paint.get(\"fill-color\"),n=o.paint.get(\"fill-opacity\");if(0===n.constantOr(1))return;const a=o.paint.get(\"fill-emissive-strength\"),l=t.colorModeForDrapableLayerRenderPass(a),c=o.paint.get(\"fill-pattern\"),h=t.opaquePassEnabledForLayer()&&!c.constantOr(1)&&1===s.constantOr(e.C.transparent).a&&1===n.constantOr(0)?\"opaque\":\"translucent\";if(t.renderPass===h){const s=t.depthModeForSublayer(1,\"opaque\"===t.renderPass?e.b4.ReadWrite:e.b4.ReadOnly);Co(t,i,o,r,s,l,!1);}if(\"translucent\"===t.renderPass&&o.paint.get(\"fill-antialias\")){const s=t.depthModeForSublayer(o.getPaintProperty(\"fill-outline-color\")?2:0,e.b4.ReadOnly);Co(t,i,o,r,s,l,!0);}},\"fill-extrusion\":function(t,i,o,r){const s=o.paint.get(\"fill-extrusion-opacity\"),n=t.context,a=n.gl,l=t.terrain,c=l&&l.renderingToTexture;if(0===s)return;const h=t.conflationActive&&t.layerUsedInConflation(o,i.getSource());if(h&&function(e,t,i,o){for(const r of o){const o=t.getTile(r).getBucket(i);o&&(o.updateReplacement(r,e.replacementSource),o.uploadCentroid(e.context));}}(t,i,o,r),l||h)for(const e of r){const r=i.getTile(e).getBucket(o);r&&Mo(t.context,i,e,r,o,l,h);}if(\"shadow\"===t.renderPass&&t.shadowRenderer){const n=t.shadowRenderer;if(l&&s<.65&&o._transitionablePaint._values[\"fill-extrusion-opacity\"].value.expression instanceof e.am)return;const a=n.getShadowPassDepthMode(),c=n.getShadowPassColorMode();Io(t,i,o,r,a,e.b6.disabled,c,h);}else if(\"translucent\"===t.renderPass){const _=!o.paint.get(\"fill-extrusion-pattern\").constantOr(1),d=o.paint.get(\"fill-extrusion-color\").constantOr(e.C.white);if(!c&&0!==d.a){const n=new e.b4(t.context.gl.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D);1===s&&_?Io(t,i,o,r,n,e.b6.disabled,e.a.unblended,h):(Io(t,i,o,r,n,e.b6.disabled,e.a.disabled,h),Io(t,i,o,r,n,t.stencilModeFor3D(),t.colorModeForRenderPass(),h),t.resetStencilClippingMasks());}if(t.style.enable3dLights()&&_&&(!l&&\"globe\"!==t.transform.projection.name||c)){const s=o.paint.get(\"fill-extrusion-opacity\"),_=o.paint.get(\"fill-extrusion-ambient-occlusion-intensity\"),d=o.paint.get(\"fill-extrusion-ambient-occlusion-ground-radius\"),u=o.paint.get(\"fill-extrusion-flood-light-intensity\"),p=o.paint.get(\"fill-extrusion-flood-light-color\").toArray01().slice(0,3),m=_>0&&d>0,f=u>0,g=(e,t,i)=>(1-i)*e+i*t,v=n=>{const l=t.depthModeForSublayer(1,e.b4.ReadOnly,a.LEQUAL,!0),c=o.paint.get(n?\"fill-extrusion-ambient-occlusion-ground-attenuation\":\"fill-extrusion-flood-light-ground-attenuation\"),m=g(.1,3,c),f=t._showOverdrawInspector;if(!f){const c=new e.b6({func:a.ALWAYS,mask:255},255,255,a.KEEP,a.KEEP,a.REPLACE),f=new e.a([a.ONE,a.ONE,a.ONE,a.ONE],e.C.transparent,[!1,!1,!1,!0],a.MIN);So(t,i,o,r,l,c,f,e.b5.disabled,n,\"sdf\",s,_,d,u,p,m,h,!1);}{const c=f?e.b6.disabled:new e.b6({func:a.EQUAL,mask:255},255,255,a.KEEP,a.DECR,a.DECR),g=f?t.colorModeForRenderPass():new e.a([a.ONE_MINUS_DST_ALPHA,a.DST_ALPHA,a.ONE,a.ONE],e.C.transparent,[!0,!0,!0,!0]);So(t,i,o,r,l,c,g,e.b5.disabled,n,\"color\",s,_,d,u,p,m,h,!1);}};if(c){const c=(n,l,c)=>{const m=t.depthModeForSublayer(1,e.b4.ReadOnly,a.LEQUAL,!1),f=o.paint.get(n?\"fill-extrusion-ambient-occlusion-ground-attenuation\":\"fill-extrusion-flood-light-ground-attenuation\"),v=g(.1,3,f);{const c=new e.a([a.ONE,a.ONE,a.ONE,a.ONE],e.C.transparent,[!1,!1,!1,!0]);So(t,i,o,r,m,e.b6.disabled,c,e.b5.disabled,n,\"clear\",s,_,d,u,p,v,h,l);}{const c=new e.b6({func:a.ALWAYS,mask:255},255,255,a.KEEP,a.KEEP,a.REPLACE),f=new e.a([a.ONE,a.ONE,a.ONE,a.ONE],e.C.transparent,[!1,!1,!1,!0],a.MIN);So(t,i,o,r,m,c,f,e.b5.disabled,n,\"sdf\",s,_,d,u,p,v,h,l);}{const c=n?a.ZERO:a.ONE_MINUS_DST_ALPHA,f=new e.b6({func:a.EQUAL,mask:255},255,255,a.KEEP,a.DECR,a.DECR),g=new e.a([c,a.DST_ALPHA,a.ONE_MINUS_DST_ALPHA,a.ZERO],e.C.transparent,[!0,!0,!0,!0]);So(t,i,o,r,m,f,g,e.b5.disabled,n,\"color\",s,_,d,u,p,v,h,l);}{const f=new e.a([a.ONE,a.ONE,a.ONE,n?a.ZERO:a.ONE],e.C.transparent,[!1,!1,!1,!0],n?a.FUNC_ADD:a.MAX);So(t,i,o,r,m,e.b6.disabled,f,e.b5.disabled,n,\"clear\",s,_,d,u,p,v,h,l,c);}};if(m||f){let i;if(t.prepareDrawTile(),l){const t=l.drapeBufferSize[0],o=l.drapeBufferSize[1];i=l.framebufferCopyTexture,i&&(!i||i.size[0]===t&&i.size[1]===o)||(i&&i.destroy(),i=l.framebufferCopyTexture=new e.a9(n,new e.a5({width:t,height:o}),a.RGBA)),i.bind(a.LINEAR,a.CLAMP_TO_EDGE),a.copyTexImage2D(a.TEXTURE_2D,0,a.RGBA,0,0,t,o,0);}m&&c(!0,!1,i),f&&c(!1,!0,i);}}else m&&v(!0),f&&v(!1);}}},hillshade:function(t,i,o,r){if(\"offscreen\"!==t.renderPass&&\"translucent\"!==t.renderPass)return;if(t.style.disableElevatedTerrain)return;const s=t.context,n=t.terrain&&t.terrain.renderingToTexture,[a,l]=\"translucent\"!==t.renderPass||n?[{},r]:t.stencilConfigForOverlap(r);for(const r of l){const s=i.getTile(r);if(s.needsHillshadePrepare&&\"offscreen\"===t.renderPass)wi(t,s,o);else if(\"translucent\"===t.renderPass){const i=t.depthModeForSublayer(0,e.b4.ReadOnly),l=o.paint.get(\"hillshade-emissive-strength\"),c=t.colorModeForDrapableLayerRenderPass(l),h=n&&t.terrain?t.terrain.stencilModeForRTTOverlap(r):a[r.overscaledZ];yi(t,r,s,o,i,h,c);}}s.viewport.set([0,0,t.width,t.height]),t.resetStencilClippingMasks();},raster:function(t,i,o,r,s,n){if(\"translucent\"!==t.renderPass)return;if(0===o.paint.get(\"raster-opacity\"))return;const a=t.context,l=a.gl,c=i.getSource(),h=function(t,i,o){const r=t.paint.get(\"raster-color\"),s=[],n=t.paint.get(\"raster-resampling\"),a=t.paint.get(\"raster-color-mix\"),l=t.paint.get(\"raster-color-range\"),c=[a[0],a[1],a[2],0],h=a[3],_=\"nearest\"===n?o.NEAREST:o.LINEAR;if(r&&s.push(\"RASTER_COLOR\"),r){i.activeTexture.set(o.TEXTURE2);let r=t.colorRampTexture;r||(r=t.colorRampTexture=new e.a9(i,t.colorRamp,o.RGBA)),r.bind(o.LINEAR,o.CLAMP_TO_EDGE);}return {mix:c,range:l,offset:h,defines:s,resampling:_}}(o,a,l),_=h.defines,d=\"globe\"===t.transform.projection.name;let u=!1;if(c instanceof e.aK&&!r.length){if(!d)return;if(c.onNorthPole)u=!0,_.push(\"GLOBE_POLES\");else {if(!c.onSouthPole)return;u=!0,_.push(\"GLOBE_POLES\");}}const p=o.paint.get(\"raster-emissive-strength\"),m=t.colorModeForDrapableLayerRenderPass(p),f=t.terrain&&t.terrain.renderingToTexture,g=c instanceof e.aK&&0!==o.paint.get(\"raster-elevation\"),v=!t.options.moving,x=\"nearest\"===o.paint.get(\"raster-resampling\")?l.NEAREST:l.LINEAR;if(u){const r=i.getSource();if(!(r instanceof e.aK))return;const s=r.texture;if(!s)return;const n=t.globeSharedBuffers;if(!n)return;const c=new e.b4(l.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D),_=Float32Array.from(t.transform.expandedFarZProjMatrix);let d=e.bj(0,0,t.transform);const u=Float32Array.from(e.bh(e.bi(new e.t(0,0,0)))),f={opacity:1,mix:0};t.terrain&&t.terrain.prepareDrawTile(),a.activeTexture.set(l.TEXTURE0),s.bind(x,l.CLAMP_TO_EDGE),a.activeTexture.set(l.TEXTURE1),s.bind(x,l.CLAMP_TO_EDGE),s.useMipmap&&a.extTextureFilterAnisotropic&&t.transform.pitch>20&&l.texParameterf(l.TEXTURE_2D,a.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,a.extTextureFilterAnisotropicMax);const[g,v,y,b]=n.getPoleBuffers(0,!0);let w;r.onNorthPole?(w=g,t.renderDefaultNorthPole=!1):(d=e.m.scale(e.m.create(),d,[1,-1,1]),w=v,t.renderDefaultSouthPole=!1);const T=((e,t,i,o,r,s,n,a,l,c,h,_)=>to(e,t,i,new Float32Array(16),new Float32Array(9),[0,0],0,[0,0],[0,0,0,0],1,o,r,[0,0]||[0,0],n,2,l,c,h,1,0,_))(_,u,d,f,o,0,o.paint.get(\"raster-elevation\"),0,h.mix,h.offset,h.range,p),E=t.getOrCreateProgram(\"raster\",{defines:h.defines});return t.uploadCommonUniforms(a,E,null),void E.draw(t,l.TRIANGLES,c,e.b6.disabled,m,e.b5.disabled,T,o.id,w,y,b)}if(!r.length)return;const[y,b]=c instanceof e.aK||f?[{},r]:t.stencilConfigForOverlap(r),w=b[b.length-1].overscaledZ,T=g&&d;T&&h.defines.push(\"PROJECTION_GLOBE_VIEW\"),g&&h.defines.push(\"RENDER_CUTOFF\");for(const r of b){const s=r.toUnwrapped(),_=i.getTile(r);if(f&&(!_||!_.hasData()))continue;if(!_.texture)continue;let u,b;f?(u=e.b4.disabled,b=r.projMatrix):g?(u=new e.b4(l.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D),b=d?Float32Array.from(t.transform.expandedFarZProjMatrix):t.transform.calculateProjMatrix(s,v)):(u=t.depthModeForSublayer(r.overscaledZ-w,1===o.paint.get(\"raster-opacity\")?e.b4.ReadWrite:e.b4.ReadOnly,l.LESS),b=t.transform.calculateProjMatrix(s,v));const E=t.terrain&&f?t.terrain.stencilModeForRTTOverlap(r):y[r.overscaledZ],C=n?0:o.paint.get(\"raster-fade-duration\");_.registerFadeDuration(C);const I=i.findLoadedParent(r,0),S=Ri(_,I,i,t.transform,C);let M,L;t.terrain&&t.terrain.prepareDrawTile(),a.activeTexture.set(l.TEXTURE0),_.texture&&_.texture.bind(x,l.CLAMP_TO_EDGE),a.activeTexture.set(l.TEXTURE1),I?(I.texture&&I.texture.bind(x,l.CLAMP_TO_EDGE),M=Math.pow(2,I.tileID.overscaledZ-_.tileID.overscaledZ),L=[_.tileID.canonical.x*M%1,_.tileID.canonical.y*M%1]):_.texture&&_.texture.bind(x,l.CLAMP_TO_EDGE),_.texture&&_.texture.useMipmap&&a.extTextureFilterAnisotropic&&t.transform.pitch>20&&l.texParameterf(l.TEXTURE_2D,a.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,a.extTextureFilterAnisotropicMax);const P=t.transform;let D;const A=g?Ro(P):[0,0,0,0];let R,z,O,F,B;T&&c instanceof e.aK&&c.coordinates.length>3?(R=Float32Array.from(e.bh(e.bi(new e.t(0,0,0)))),z=Float32Array.from(P.globeMatrix),O=Float32Array.from(e.bc(P)),F=[e.E(P.center.lng),e.H(P.center.lat)],D=c.elevatedGlobePerspectiveTransform,B=c.elevatedGlobeGridMatrix||new Float32Array(9)):(D=c instanceof e.aK?c.perspectiveTransform:[0,0],R=new Float32Array(16),z=new Float32Array(9),O=new Float32Array(16),F=[0,0],B=new Float32Array(9));const k=to(b,R,z,O,B,L||[0,0],e.ao(t.transform.zoom),F,A,M||1,S,o,D,g?o.paint.get(\"raster-elevation\"):0,2,h.mix,h.offset,h.range,1,0,p),N=t.isTileAffectedByFog(r),U=t.getOrCreateProgram(\"raster\",{defines:h.defines,overrideFog:N});if(t.uploadCommonUniforms(a,U,s),c instanceof e.aK){const i=c.elevatedGlobeVertexBuffer,r=c.elevatedGlobeIndexBuffer;if(f||!d)c.boundsBuffer&&c.boundsSegments&&U.draw(t,l.TRIANGLES,u,e.b6.disabled,m,e.b5.disabled,k,o.id,c.boundsBuffer,t.quadTriangleIndexBuffer,c.boundsSegments);else if(i&&r){const s=P.zoom<=e.Z?c.elevatedGlobeSegments:c.getSegmentsForLongitude(P.center.lng);s&&(U.draw(t,l.TRIANGLES,u,e.b6.disabled,m,e.b5.backCW,k,o.id,i,r,s),U.draw(t,l.TRIANGLES,u,e.b6.disabled,m,e.b5.frontCW,k,o.id,i,r,s));}}else {const{tileBoundsBuffer:i,tileBoundsIndexBuffer:r,tileBoundsSegments:s}=t.getTileBoundsBuffers(_);U.draw(t,l.TRIANGLES,u,E,m,e.b5.disabled,k,o.id,i,r,s);}}t.resetStencilClippingMasks();},background:function(t,i,o,r){const s=o.paint.get(\"background-color\"),n=o.paint.get(\"background-opacity\"),a=o.paint.get(\"background-emissive-strength\");if(0===n)return;const l=t.context,c=l.gl,h=t.transform,_=h.tileSize,d=o.paint.get(\"background-pattern\");if(t.isPatternMissing(d,o.scope))return;const u=!d&&1===s.a&&1===n&&t.opaquePassEnabledForLayer()?\"opaque\":\"translucent\";if(t.renderPass!==u)return;const p=e.b6.disabled,m=t.depthModeForSublayer(0,\"opaque\"===u?e.b4.ReadWrite:e.b4.ReadOnly),f=t.colorModeForDrapableLayerRenderPass(a),g=d?\"backgroundPattern\":\"background\";let v,x=r;x||(v=t.getBackgroundTiles(),x=Object.values(v).map((e=>e.tileID))),d&&(l.activeTexture.set(c.TEXTURE0),t.imageManager.bind(t.context,o.scope));for(const u of x){const x=t.isTileAffectedByFog(u),y=t.getOrCreateProgram(g,{overrideFog:x}),b=u.toUnwrapped(),w=r?u.projMatrix:t.transform.calculateProjMatrix(b);t.prepareDrawTile();const T=i?i.getTile(u):v?v[u.key]:new e.bt(u,_,h.zoom,t),E=d?ho(w,a,n,t,d,o.scope,{tileID:u,tileSize:_}):co(w,a,n,s);t.uploadCommonUniforms(l,y,b);const{tileBoundsBuffer:C,tileBoundsIndexBuffer:I,tileBoundsSegments:S}=t.getTileBoundsBuffers(T);y.draw(t,c.TRIANGLES,m,p,f,e.b5.disabled,E,o.id,C,I,S);}},sky:function(t,i,o){const r=t._atmosphere?e.ao(t.transform.zoom):1,s=o.paint.get(\"sky-opacity\")*r;if(0===s)return;const n=t.context,a=o.paint.get(\"sky-type\"),l=new e.b4(n.gl.LEQUAL,e.b4.ReadOnly,[0,1]),c=t.frameCounter/1e3%1;\"atmosphere\"===a?\"offscreen\"===t.renderPass?o.needsSkyboxCapture(t)&&(function(t,i,o,r){const s=t.context,n=s.gl;let a=i.skyboxFbo;if(!a){a=i.skyboxFbo=s.createFramebuffer(32,32,!0,null),i.skyboxGeometry=new Ho(s),i.skyboxTexture=s.gl.createTexture(),n.bindTexture(n.TEXTURE_CUBE_MAP,i.skyboxTexture),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,n.LINEAR);for(let e=0;e<6;++e)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,n.RGBA,32,32,0,n.RGBA,n.UNSIGNED_BYTE,null);}s.bindFramebuffer.set(a.framebuffer),s.viewport.set([0,0,32,32]);const l=i.getCenter(t,!0),c=t.getOrCreateProgram(\"skyboxCapture\"),h=new Float64Array(16);e.m.identity(h),e.m.rotateY(h,h,.5*-Math.PI),qo(t,i,c,h,l,0),e.m.identity(h),e.m.rotateY(h,h,.5*Math.PI),qo(t,i,c,h,l,1),e.m.identity(h),e.m.rotateX(h,h,.5*-Math.PI),qo(t,i,c,h,l,2),e.m.identity(h),e.m.rotateX(h,h,.5*Math.PI),qo(t,i,c,h,l,3),e.m.identity(h),qo(t,i,c,h,l,4),e.m.identity(h),e.m.rotateY(h,h,Math.PI),qo(t,i,c,h,l,5),s.viewport.set([0,0,t.width,t.height]);}(t,o),o.markSkyboxValid(t)):\"sky\"===t.renderPass&&function(t,i,o,r,s){const n=t.context,a=n.gl,l=t.transform,c=t.getOrCreateProgram(\"skybox\");n.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_CUBE_MAP,i.skyboxTexture);const h=((e,t,i,o,r)=>({u_matrix:e,u_sun_direction:t,u_cubemap:0,u_opacity:o,u_temporal_offset:r}))(l.skyboxMatrix,i.getCenter(t,!1),0,r,s);t.uploadCommonUniforms(n,c),c.draw(t,a.TRIANGLES,o,e.b6.disabled,t.colorModeForRenderPass(),e.b5.backCW,h,\"skybox\",i.skyboxGeometry.vertexBuffer,i.skyboxGeometry.indexBuffer,i.skyboxGeometry.segment);}(t,o,l,s,c):\"gradient\"===a&&\"sky\"===t.renderPass&&function(t,i,o,r,s){const n=t.context,a=n.gl,l=t.transform,c=t.getOrCreateProgram(\"skyboxGradient\");i.skyboxGeometry||(i.skyboxGeometry=new Ho(n)),n.activeTexture.set(a.TEXTURE0);let h=i.colorRampTexture;h||(h=i.colorRampTexture=new e.a9(n,i.colorRamp,a.RGBA)),h.bind(a.LINEAR,a.CLAMP_TO_EDGE);const _=((t,i,o,r,s)=>({u_matrix:t,u_color_ramp:0,u_center_direction:i,u_radius:e.d(o),u_opacity:r,u_temporal_offset:s}))(l.skyboxMatrix,i.getCenter(t,!1),i.paint.get(\"sky-gradient-radius\"),r,s);t.uploadCommonUniforms(n,c),c.draw(t,a.TRIANGLES,o,e.b6.disabled,t.colorModeForRenderPass(),e.b5.backCW,_,\"skyboxGradient\",i.skyboxGeometry.vertexBuffer,i.skyboxGeometry.indexBuffer,i.skyboxGeometry.segment);}(t,o,l,s,c);},debug:function(t,i,o,r,s){for(let n=0;n{a&&(a.useNormalOffset=!0,l||(a.enabled=!0));},h=i.getSource();if(\"light-beam\"===t.renderPass&&\"batched-model\"!==h.type)return;if(\"vector\"===h.type||\"geojson\"===h.type)return function(t,i,o,r){const s=t.transform;if(\"mercator\"!==s.projection.name)return void e.X(`Drawing 3D models for ${s.projection.name} projection is not yet implemented`);const n=s.getFreeCameraOptions().position;if(!t.modelManager)return;const a=t.modelManager,l=t.shadowRenderer;if(!o._unevaluatedLayout._values.hasOwnProperty(\"model-id\"))return;const c=o._unevaluatedLayout._values[\"model-id\"],h={...o.layout.get(\"model-id\").parameters};for(const _ of r){const r=i.getTile(_).getBucket(o);if(!r||r.projection.name!==s.projection.name)continue;const d=nr(_,s);h.zoom=d;const u=c.possiblyEvaluate(h);if(rr(t,r,_),sr.shadowUniformsInitialized=!1,sr.useSingleShadowCascade=!!l&&0===l.getMaxCascadeForTile(_.toUnwrapped()),\"shadow\"===t.renderPass&&l){if(1===t.currentShadowCascade&&r.isInsideFirstShadowMapFrustum)continue;const i=s.calculatePosMatrix(_.toUnwrapped(),s.worldSize);if(sr.tileMatrix.set(i),sr.shadowTileMatrix=Float32Array.from(l.calculateShadowPassMatrixFromMatrix(i)),sr.aabb.min.fill(0),sr.aabb.max[0]=sr.aabb.max[1]=e.J,sr.aabb.max[2]=0,cr(r,sr,t,o.scope))continue}const p=1<<_.canonical.z,m=[((n.x-_.wrap)*p-_.canonical.x)*e.J,(n.y*p-_.canonical.y)*e.J,n.z*p*e.J];for(let e in r.instancesPerModel){const i=r.instancesPerModel[e];i.features.length>0&&(e=u.evaluate(i.features[0].feature,{}));const s=a.getModel(e,o.scope);if(s&&s.uploaded)for(const e of s.nodes)ar(t,o,e,i,m,_,sr);}}}(t,i,o,r),void c();if(!h.loaded())return;if(\"batched-model\"===h.type)return function(t,i,o,r){const s=t.context,n=t.transform,a=t.style.fog,l=t.shadowRenderer;if(\"mercator\"!==n.projection.name)return void e.X(`Drawing 3D landmark models for ${n.projection.name} projection is not yet implemented`);const c=t.transform.getFreeCameraOptions().position,h=e.v.scale([],[c.x,c.y,c.z],t.transform.worldSize);e.v.negate(h,h);const _=e.m.identity([]),d=e.c4(n.center.lat,n.zoom),u=e.m.fromScaling([],[1,1,1/d]);e.m.translate(_,_,h);const p=o.paint.get(\"model-opacity\"),m=new e.b4(s.gl.LEQUAL,e.b4.ReadWrite,t.depthRangeFor3D),f=new e.b4(s.gl.LEQUAL,e.b4.ReadOnly,t.depthRangeFor3D),g=function(c,h){for(const d of r){const r=i.getTile(d).getBucket(o);if(!r||!r.uploaded)continue;let g=!1;l&&(g=0===l.getMaxCascadeForTile(d.toUnwrapped()));const v=n.calculatePosMatrix(d.toUnwrapped(),n.worldSize),x=r.modelTraits;for(const i of r.getNodesInfo()){if(i.hiddenByReplacement)continue;if(!i.node.meshes)continue;const r=i.node,y=\"light-beam\"===t.renderPass,b=[...v],w=i.evaluatedScale;let T=0;t.terrain&&r.elevation&&(T=r.elevation*t.terrain.exaggeration()),e.m.translate(b,b,[(r.anchor?r.anchor[0]:0)*(w[0]-1),(r.anchor?r.anchor[1]:0)*(w[1]-1),T]),w!==e.c6&&e.m.scale(b,b,w),e.m.multiply(b,b,r.matrix);const E=e.m.multiply([],u,b);e.m.multiply(E,_,E);const C=e.m.invert([],E);e.m.transpose(C,C),e.m.scale(C,C,lr);const I=e.m.multiply([],n.expandedFarZProjMatrix,b),S=x&e.c8.HasMapboxMeshFeatures,M=S?0:i.evaluatedRMEA[0][2];for(let _=0;_=Ue||r>=Ue;}}const P=t.getOrCreateProgram(\"model\",x);!T&&l&&(l.useNormalOffset=!!u.normalBuffer,l.setupShadowsFromMatrix(b,P,l.useNormalOffset)),t.uploadCommonUniforms(s,P,d.toUnwrapped(),L);const D=u.material,A=D.pbrMetallicRoughness;A.metallicFactor=.9,A.roughnessFactor=.5;const R=uo(new Float32Array(I),new Float32Array(E),new Float32Array(C),t,p,A.baseColorFactor,D.emissiveFactor,A.metallicFactor,A.roughnessFactor,D,M,o);P.draw(t,s.gl.TRIANGLES,h&&!v?m:f,e.b6.disabled,c?v||p<1||i.hasTranslucentParts?e.a.alphaBlended:e.a.unblended:e.a.disabled,e.b5.backCCW,R,o.id,u.vertexBuffer,u.indexBuffer,u.segments,o.paint,t.transform.zoom,void 0,w);}}}};((function(e,t,i,o){const r=e.terrain?e.terrain.exaggeration():0,s=e.transform.zoom;for(const n of o){const o=t.getTile(n).getBucket(i);o&&(e.conflationActive&&o.updateReplacement(n,e.replacementSource),o.evaluateScale(e,i),e.terrain&&r>0&&o.elevationUpdate(e.terrain,r,n,i.source),o.needsReEvaluation(e,s,i)&&o.evaluate(i));}}))(t,i,o,r),1===p?g(!0,!0):(g(!1,!0),g(!0,!1));}(t,i,o,r),void c();const _=h.getModels(),d=[],u=t.transform.getFreeCameraOptions().position,p=e.v.scale([],[u.x,u.y,u.z],t.transform.worldSize);e.v.negate(p,p);const m=[],f=[];let g=0;for(const i of _){const r=o.paint.get(\"model-rotation\").constantOr(null),s=o.paint.get(\"model-scale\").constantOr(null),n=o.paint.get(\"model-translation\").constantOr(null);i.computeModelMatrix(t,r,s,n,!0,!0,!1);const a=e.m.identity([]),l=e.c4(i.position.lat,t.transform.zoom),c=e.m.fromScaling([],[1,1,1/l]);e.m.translate(a,a,p),d.push({zScaleMatrix:c,negCameraPosMatrix:a});for(const e of i.nodes)ir(t.transform,e,i.matrix,t.transform.expandedFarZProjMatrix,g,m,f);g++;}if(m.sort(((e,t)=>t.depth-e.depth)),\"shadow\"!==t.renderPass){if(1===s)for(const i of f)tr(i,t,o,d[i.modelIndex],e.b6.disabled,t.colorModeForRenderPass());else {for(const i of f)tr(i,t,o,d[i.modelIndex],e.b6.disabled,e.a.disabled);for(const e of f)tr(e,t,o,d[e.modelIndex],t.stencilModeFor3D(),t.colorModeForRenderPass());t.resetStencilClippingMasks();}for(const i of m)tr(i,t,o,d[i.modelIndex],e.b6.disabled,t.colorModeForRenderPass());c();}else {for(const e of f)or(e.mesh,e.nodeModelMatrix,t,o);for(const e of m)or(e.mesh,e.nodeModelMatrix,t,o);c();}}},pr={modelUpload:function(e,t,i){const o=t.getSource();if(!o.loaded())return;if(\"vector\"===o.type||\"geojson\"===o.type)return void(e.modelManager&&e.modelManager.upload(e,i));if(\"batched-model\"===o.type)return;const r=o.getModels();for(const t of r)t.upload(e.context);}};class mr{constructor(t,i,o,r){this.context=new se(t,i),this.transform=o,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this.tp=r,this._debugParams={showTerrainProxyTiles:!1},r.registerParameter(this._debugParams,[\"Terrain\"],\"showTerrainProxyTiles\",{},(()=>{this.style.map.triggerRepaint();})),this.setup(),this.numSublayers=e.bq.maxUnderzooming+e.bq.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new e.ca,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new xr(this),this._wireframeDebugCache=new _r,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0;}updateTerrain(e,t){const i=!!e&&!!e.terrain&&this.transform.projection.supportsTerrain;if(!(i||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Bi(this,e));const o=this._terrain;this.transform.elevation=i?o:null,o.update(e,this.transform,t),this.transform.elevation&&!o.enabled&&(this.transform.elevation=null);}_updateFog(e){const t=e.fog;if(!t||\"globe\"===this.transform.projection.name||t.getOpacity(this.transform.pitch)<1||t.properties.get(\"horizon-blend\")<.03)return void(this.transform.fogCullDistSq=null);const[i,o]=t.getFovAdjustedRange(this.transform._fov);if(i>o)return void(this.transform.fogCullDistSq=null);const r=i+.78*(o-i);this.transform.fogCullDistSq=r*r;}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled?this._terrain:null}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(t,i){if(this.width=t*e.a4.devicePixelRatio,this.height=i*e.a4.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style.order)this.style._mergedLayers[e].resize();}setup(){const t=this.context,i=new e.bo;i.emplaceBack(0,0),i.emplaceBack(e.J,0),i.emplaceBack(0,e.J),i.emplaceBack(e.J,e.J),this.tileExtentBuffer=t.createVertexBuffer(i,e.bl.members),this.tileExtentSegments=e.bm.simpleSegment(0,0,4,2);const o=new e.bo;o.emplaceBack(0,0),o.emplaceBack(e.J,0),o.emplaceBack(0,e.J),o.emplaceBack(e.J,e.J),this.debugBuffer=t.createVertexBuffer(o,e.bl.members),this.debugSegments=e.bm.simpleSegment(0,0,4,5);const r=new e.bo;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(-1,1),r.emplaceBack(1,1),this.viewportBuffer=t.createVertexBuffer(r,e.bl.members),this.viewportSegments=e.bm.simpleSegment(0,0,4,2);const s=new e.cb;s.emplaceBack(0,0,0,0),s.emplaceBack(e.J,0,e.J,0),s.emplaceBack(0,e.J,0,e.J),s.emplaceBack(e.J,e.J,e.J,e.J),this.mercatorBoundsBuffer=t.createVertexBuffer(s,e.cc.members),this.mercatorBoundsSegments=e.bm.simpleSegment(0,0,4,2);const n=new e.bp;n.emplaceBack(0,1,2),n.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=t.createIndexBuffer(n);const a=new e.cd;for(const e of [0,1,3,2,0])a.emplaceBack(e);this.debugIndexBuffer=t.createIndexBuffer(a),this.emptyTexture=new e.a9(t,new e.a5({width:1,height:1},Uint8Array.of(0,0,0,0)),t.gl.RGBA),this.identityMat=e.m.create();const l=this.context.gl;this.stencilClearMode=new e.b6({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO),this.loadTimeStamps.push(performance.now());}getMercatorTileBoundsBuffers(){return {tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(e){return e._makeTileBoundsBuffers(this.context,this.transform.projection),e._tileBoundsBuffer?{tileBoundsBuffer:e._tileBoundsBuffer,tileBoundsIndexBuffer:e._tileBoundsIndexBuffer,tileBoundsSegments:e._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const t=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram(\"clippingMask\").draw(this,t.TRIANGLES,e.b4.disabled,this.stencilClearMode,e.a.disabled,e.b5.disabled,Ai(this.identityMat),\"$clipping\",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={});}_renderTileClippingMasks(t,i,o){if(!i||this.currentStencilSource===i.id||!t.isTileClipped()||!o||0===o.length)return;if(this._tileClippingMaskIDs&&!this.terrain){let e=!1;for(const t of o)if(void 0===this._tileClippingMaskIDs[t.key]){e=!0;break}if(!e)return}this.currentStencilSource=i.id;const r=this.context,s=r.gl;this.nextStencilID+o.length>256&&this.clearStencil(),r.setColorMode(e.a.disabled),r.setDepthMode(e.b4.disabled);const n=this.getOrCreateProgram(\"clippingMask\");this._tileClippingMaskIDs={};for(const t of o){const o=i.getTile(t),r=this._tileClippingMaskIDs[t.key]=this.nextStencilID++,{tileBoundsBuffer:a,tileBoundsIndexBuffer:l,tileBoundsSegments:c}=this.getTileBoundsBuffers(o);n.draw(this,s.TRIANGLES,e.b4.disabled,new e.b6({func:s.ALWAYS,mask:0},r,255,s.KEEP,s.KEEP,s.REPLACE),e.a.disabled,e.b5.disabled,Ai(t.projMatrix),\"$clipping\",a,l,c);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const t=this.nextStencilID++,i=this.context.gl;return new e.b6({func:i.NOTEQUAL,mask:255},t,255,i.KEEP,i.KEEP,i.REPLACE)}stencilModeForClipping(t){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(t);const i=this.context.gl;return new e.b6({func:i.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,i.KEEP,i.KEEP,i.REPLACE)}stencilConfigForOverlap(t){const i=this.context.gl,o=t.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=o[o.length-1].overscaledZ,s=o[0].overscaledZ-r+1;if(s>1){this.currentStencilSource=void 0,this.nextStencilID+s>256&&this.clearStencil();const t={};for(let o=0;othis.style&&this.style.enable3dLights()&&this.terrain&&this.terrain.renderingToTexture)()&&\"translucent\"===this.renderPass?new e.a([i.ONE,i.ONE_MINUS_SRC_ALPHA,i.CONSTANT_ALPHA,i.ONE_MINUS_SRC_ALPHA],new e.C(0,0,0,void 0===t?0:t),[!0,!0,!0,!0]):this.colorModeForRenderPass()}depthModeForSublayer(t,i,o,r=!1){if(!this.opaquePassEnabledForLayer()&&!r)return e.b4.disabled;const s=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon;return new e.b4(o||this.context.gl.LEQUAL,i,[s,s])}opaquePassEnabledForLayer(){return this.currentLayero[e])),n=this.style._mergedSourceCaches;this.imageManager=t.imageManager,this.modelManager=t.modelManager,this.symbolFadeChange=t.placement.symbolFadeChange(e.a4.now()),this.imageManager.beginFrame();let a=0,l=!1;for(const e in n){const t=n[e];t.used&&(t.prepare(this.context),t.getSource().usedInConflation&&++a);}const c={},h={},_={},d={},u={};for(const e in n){const t=n[e];c[e]=t.getVisibleCoordinates(),h[e]=c[e].slice().reverse(),_[e]=t.getVisibleCoordinates(!0).reverse(),d[e]=t.getShadowCasterCoordinates(),u[e]=t.sortCoordinatesByDistance(c[e]);}const p=e=>{const t=this.style.getLayerSourceCache(e);return t&&t.used?t.getSource():null};if(a){const e=[];for(const t of s)this.layerUsedInConflation(t,p(t))&&e.push(t);if(e&&e.length>1){const t=[];for(const i of e){const e=this.style.getLayerSourceCache(i);e&&e.used&&e.getSource().usedInConflation&&t.push({layer:i.fqid,cache:e});}this.replacementSource.setSources(t),l=!0;}}l||this.replacementSource.clear(),this.conflationActive=l,this.minCutoffZoom=0,this.longestCutoffRange=0;for(const e of s){const t=e.cutoffRange();if(this.longestCutoffRange=Math.max(t,this.longestCutoffRange),t>0){const t=p(e);t&&(this.minCutoffZoom=Math.max(t.minzoom,this.minCutoffZoom)),e.minzoom&&(this.minCutoffZoom=Math.max(e.minzoom,this.minCutoffZoom));}}this.opaquePassCutoff=1/0;for(let e=0;e{if(i.showOverdrawInspector)return e.C.black;if(this.style.fog&&this.transform.projection.supportsFog&&!v){const t=this.style.fog.properties.get(\"color\").toArray01();return new e.C(...t)}if(this.style.fog&&this.transform.projection.supportsFog&&v){const t=this.style.fog.properties.get(\"space-color\").toArray01();return new e.C(...t)}return e.C.transparent})();if(this.context.clear({color:x,depth:1}),this.clearStencil(),this._showOverdrawInspector=i.showOverdrawInspector,this.renderPass=\"opaque\",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&v&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){const e=s[this.currentLayer],i=t.getLayerSourceCache(e);if(e.isSky())continue;const o=i?(e.is3D()?u:h)[i.id]:void 0;this._renderTileClippingMasks(e,i,o),this.renderLayer(this,i,e,o);}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&v&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass=\"sky\",(!this._atmosphere||e.ao(this.transform.zoom)>0)&&(\"globe\"===this.transform.projection.name||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer0&&e.hasShadowPass()&&0==--y&&(f.drawGroundShadows(),this.firstLightBeamLayer<=this.currentLayer)){const e=this.currentLayer;for(this.renderPass=\"light-beam\",this.currentLayer=this.firstLightBeamLayer;this.currentLayer<=e;this.currentLayer++){const e=s[this.currentLayer];if(!e.hasLightBeamPass())continue;const i=t.getLayerSourceCache(e);this.renderLayer(this,i,e,i?h[i.id]:void 0);}this.currentLayer=e,this.renderPass=\"translucent\";}++this.currentLayer;}if(this.terrain&&this.terrain.postRender(),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let i=null;s.forEach((e=>{const o=t.getLayerSourceCache(e);o&&!e.isHidden(this.transform.zoom)&&o.getVisibleCoordinates().length&&(!i||i.getSource().maxzoom0?t.pop():null}isPatternMissing(e,t){return null===e||void 0!==e&&!this.imageManager.getPattern(e.toString(),t)}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture}linearFloatFilteringSupported(){return null!=this.context.extTextureFloatLinear}currentGlobalDefines(e,t,i){const o=void 0===i?this.terrain&&this.terrain.renderingToTexture:i,r=this.terrain&&0===this.terrain.exaggeration(),s=[];return this.style&&this.style.enable3dLights()&&(\"globeRaster\"===e||\"terrainRaster\"===e?(s.push(\"LIGHTING_3D_MODE\"),s.push(\"LIGHTING_3D_ALPHA_EMISSIVENESS\")):o||s.push(\"LIGHTING_3D_MODE\")),\"shadow\"===this.renderPass?this._shadowMapDebug||s.push(\"DEPTH_TEXTURE\"):this.shadowRenderer&&(this.shadowRenderer.useNormalOffset?s.push(\"RENDER_SHADOWS\",\"DEPTH_TEXTURE\",\"NORMAL_OFFSET\"):s.push(\"RENDER_SHADOWS\",\"DEPTH_TEXTURE\")),this.terrainRenderModeElevated()&&(s.push(\"TERRAIN\"),this.linearFloatFilteringSupported()&&s.push(\"TERRAIN_DEM_FLOAT_FORMAT\"),r&&s.push(\"ZERO_EXAGGERATION\")),\"globe\"===this.transform.projection.name&&s.push(\"GLOBE\"),!this._fogVisible||o||void 0!==t&&!t||s.push(\"FOG\",\"FOG_DITHERING\"),o&&s.push(\"RENDER_TO_TEXTURE\"),this._showOverdrawInspector&&s.push(\"OVERDRAW_INSPECTOR\"),s}getOrCreateProgram(e,t){this.cache=this.cache||{};const i=t&&t.defines||[],o=t&&t.config,r=this.currentGlobalDefines(e,t&&t.overrideFog,t&&t.overrideRtt).concat(i),s=Gi.cacheKey(mi[e],e,r,o);return this.cache[s]||(this.cache[s]=new Gi(this.context,e,mi[e],o,fo[e],r)),this.cache[s]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement(\"canvas\"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new e.a9(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy();}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile();}uploadCommonLightUniforms(t,i){if(this.style.enable3dLights()){const o=this.style.directionalLight,r=this.style.ambientLight;if(o&&r){const s=((t,i)=>{const o=t.properties.get(\"direction\"),r=t.properties.get(\"color\").toArray01(),s=t.properties.get(\"intensity\"),n=i.properties.get(\"color\").toArray01(),a=i.properties.get(\"intensity\"),l=[o.x,o.y,o.z],c=e.bv(n,a),h=e.bv(r,s);return {u_lighting_ambient_color:c,u_lighting_directional_dir:l,u_lighting_directional_color:h,u_ground_radiance:ki(l,h,c)}})(o,r);i.setLightsUniformValues(t,s);}}}uploadCommonUniforms(t,i,o,r,s){if(this.uploadCommonLightUniforms(t,i),this.terrain&&this.terrain.renderingToTexture)return;const n=this.style.fog;if(n){const s=n.getOpacity(this.transform.pitch),a=((t,i,o,r,s,n,a,l,c,h,_,d)=>{const u=t.transform,p=i.properties.get(\"color\").toArray01();p[3]=r;const m=t.frameCounter/1e3%1,[f,g]=i.properties.get(\"vertical-range\");return {u_fog_matrix:o?u.calculateFogTileMatrix(o):d||t.identityMat,u_fog_range:i.getFovAdjustedRange(u._fov),u_fog_color:p,u_fog_horizon_blend:i.properties.get(\"horizon-blend\"),u_fog_vertical_limit:[Math.min(f,g),g],u_fog_temporal_offset:m,u_frustum_tl:s,u_frustum_tr:n,u_frustum_br:a,u_frustum_bl:l,u_globe_pos:c,u_globe_radius:h,u_viewport:_,u_globe_transition:e.ao(u.zoom),u_is_globe:+(\"globe\"===u.projection.name)}})(this,n,o,s,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*e.a4.devicePixelRatio,this.transform.height*e.a4.devicePixelRatio],r);i.setFogUniformValues(t,a);}s&&i.setCutoffUniformValues(t,s.uniformValues);}setTileLoadedFlag(e){this.tileLoaded=e;}saveCanvasCopy(){const e=this.canvasCopy();e&&(this.frameCopies.push(e),this.tileLoaded=!1);}canvasCopy(){const e=this.context.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,e.drawingBufferWidth,e.drawingBufferHeight,0),t}getCanvasCopiesAndTimestamps(){return {canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return !1;const e=this.style&&this.style.fog;return !!e&&0!==e.getOpacity(this.transform.pitch)}getBackgroundTiles(){const t=this._backgroundTiles,i=this._backgroundTiles={},o=this.transform.coveringTiles({tileSize:512});for(const r of o)i[r.key]=t[r.key]||new e.bt(r,512,this.transform.tileZoom,this);return i}clearBackgroundTiles(){this._backgroundTiles={};}layerUsedInConflation(e,t){return !(!e.is3D()||e.minzoom&&e.minzoom>this.transform.zoom||\"building\"!==e.sourceLayer&&(!t||\"batched-model\"!==t.type))}isTileAffectedByFog(e){if(!this.style||!this.style.fog)return !1;if(\"globe\"===this.transform.projection.name)return !0;let t=this._cachedTileFogOpacities[e.key];return t||(this._cachedTileFogOpacities[e.key]=t=this.style.fog.getOpacityForTile(e)),t[0]>=Ue||t[1]>=Ue}}const fr={cascadeCount:2,shadowMapResolution:2048};class gr{constructor(e,t){this.aabb=e,this.lastCascade=t;}}class vr{add(e,t){const i=this.receivers[e.key];void 0!==i?(i.aabb.min[0]=Math.min(i.aabb.min[0],t.min[0]),i.aabb.min[1]=Math.min(i.aabb.min[1],t.min[1]),i.aabb.min[2]=Math.min(i.aabb.min[2],t.min[2]),i.aabb.max[0]=Math.max(i.aabb.max[0],t.max[0]),i.aabb.max[1]=Math.max(i.aabb.max[1],t.max[1]),i.aabb.max[2]=Math.max(i.aabb.max[2],t.max[2])):this.receivers[e.key]=new gr(t,null);}clear(){this.receivers={};}get(e){return this.receivers[e.key]}computeRequiredCascades(t,i,o){const r=e.c3.fromPoints(t.points);let s=0;for(const t in this.receivers){const n=this.receivers[t];if(!n)continue;if(!r.intersectsAabb(n.aabb))continue;n.aabb.min=r.closestPoint(n.aabb.min),n.aabb.max=r.closestPoint(n.aabb.max);const a=n.aabb.getCorners();for(let t=0;t1||n[1]<-1||n[1]>1){r=!1;break}}if(n.lastCascade=t,s=Math.max(s,t),r)break}}return s+1}}class xr{constructor(t){this.painter=t,this._enabled=!1,this._shadowLayerCount=0,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new vr,this._depthMode=new e.b4(t.context.gl.LEQUAL,e.b4.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this.useNormalOffset=!1,t.tp.registerParameter(fr,[\"Shadows\"],\"cascadeCount\",{min:1,max:2,step:1}),t.tp.registerParameter(fr,[\"Shadows\"],\"shadowMapResolution\",{min:32,max:2048,step:32});}destroy(){for(const e of this._cascades)e.texture.destroy(),e.framebuffer.destroy();this._cascades=[];}updateShadowParameters(t,i){const o=this.painter;if(this._enabled=!1,this._shadowLayerCount=0,this._receivers.clear(),!i||!i.properties)return;const r=i.properties.get(\"shadow-intensity\");if(!i.shadowsEnabled()||r<=0)return;if(this._shadowLayerCount=o.style.order.reduce(((e,i)=>{const r=o.style._mergedLayers[i];return e+(r.hasShadowPass()&&!r.isHidden(t.zoom)?1:0)}),0),this._enabled=this._shadowLayerCount>0,!this._enabled)return;const s=o.context,n=fr.shadowMapResolution,a=fr.shadowMapResolution;if(0===this._cascades.length||fr.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let t=0;te.dem)).forEach((e=>{const t=e.dem.tree;i[0]=Math.min(i[0],t.minimums[0]),i[1]=Math.max(i[1],t.maximums[0]);})),1e4!==i[0]&&(l=(i[1]-i[0])*e.exaggeration());}const c=1.5*t.cameraToCenterDistance,h=3*c,_=new Float64Array(16);for(let i=0;i=0)return {};const s=function(t,i,o){const r=o/(1<0&&(e.v.add(s[1],s[1],[r[0]*n,0,0]),e.v.add(s[2],s[2],[r[0]*n,0,0])),r[1]<0?(e.v.add(s[0],s[0],[0,r[1]*n,0]),e.v.add(s[1],s[1],[0,r[1]*n,0])):r[1]>0&&(e.v.add(s[2],s[2],[0,r[1]*n,0]),e.v.add(s[3],s[3],[0,r[1]*n,0]));const a={};return a.vertices=s,a.planes=[yr(s[1],s[0],s[4]),yr(s[2],s[1],s[5]),yr(s[3],s[2],s[6]),yr(s[0],s[3],s[7])],a}addShadowReceiver(t,i,o){this._receivers.add(t,e.c3.fromTileIdAndHeight(t,i,o));}getMaxCascadeForTile(e){const t=this._receivers.get(e);return t&&t.lastCascade?t.lastCascade:0}}function yr(t,i,o){const r=e.v.sub([],o,i),s=e.v.sub([],t,i),n=e.v.cross([],r,s),a=e.v.length(n);return 0===a?[0,0,1,0]:(e.v.scale(n,n,1/a),[n[0],n[1],n[2],-e.v.dot(n,i)])}function br(t){const i=t.properties.get(\"direction\"),o=e.b3(i.x,i.y,i.z);o[2]=e.c(o[2],0,75);const r=e.ch([o[0],o[1],o[2]]);return e.v.fromValues(r.x,r.y,r.z)}function wr(t,i){const o=t.properties.get(\"color\"),r=t.properties.get(\"intensity\"),s=t.properties.get(\"direction\"),n=[s.x,s.y,s.z],a=i.properties.get(\"color\"),l=i.properties.get(\"intensity\"),c=Math.max(e.v.dot([0,0,1],n),0),h=[0,0,0];e.v.scale(h,a.toArray01Linear().slice(0,3),l);const _=[0,0,0];return e.v.scale(_,o.toArray01Linear().slice(0,3),c*r),e.bw([h[0]>0?h[0]/(h[0]+_[0]):0,h[1]>0?h[1]/(h[1]+_[1]):0,h[2]>0?h[2]/(h[2]+_[2]):0])}function Tr(t,i,o,r,s,n){const a=t.zoom,l=t.scale,c=t.worldSize,h=1/c,_=t.aspect,d=Math.sqrt(1+_*_)*Math.tan(.5*t.fovX),u=d*d,p=r-o,m=r+o;let f,g;u>p/m?(f=r,g=r*d):(f=.5*m*(1+u),g=.5*Math.sqrt(p*p+2*(r*r+o*o)*u+m*m*u*u));const v=t.projection.pixelsPerMeter(t.center.lat,c),x=t._camera.getCameraToWorldMercator(),y=[0,0,-f*h];e.v.transformMat4(y,y,x);let b=g*h;const w=t._edgeInsets;if(!(0===w.left&&0===w.top&&0===w.right&&0===w.bottom||w.left===w.right&&w.top===w.bottom)){const i=t._camera.getWorldToCamera(t.worldSize,\"meters\"===t.projection.zAxisUnit?v:1),s=t._camera.getCameraToClipPerspective(t._fov,t.width/t.height,o,r);s[8]=2*-t.centerOffset.x/t.width,s[9]=2*t.centerOffset.y/t.height;const n=new Float64Array(16);e.m.mul(n,s,i);const h=new Float64Array(16);e.m.invert(h,n);const _=e.F.fromInvProjectionMatrix(h,c,a,!0);for(const i of _.points){const o=((T=i)[0]/=l,T[1]/=l,T[2]=e.b(T[2],t._center.lat),T);b=Math.max(b,e.v.len(e.v.subtract([],y,o)));}}var T;b*=s/(s-1);const E=Math.acos(i[2]),C=Math.atan2(-i[0],-i[1]),I=new _e;I.position=y,I.setPitchBearing(E,C);const S=I.getWorldToCamera(c,v),M=b*c,L=Math.min(t._mercatorZfromZoom(17)*c*-2,-2*M),P=I.getCameraToClipOrthographic(-M,M,-M,M,L,(M+n*v)/i[2]),D=new Float64Array(16);e.m.multiply(D,P,S);const A=e.v.fromValues(Math.floor(1e6*y[0])/1e6*c,Math.floor(1e6*y[1])/1e6*c,0),R=.5*s,z=[0,0,0];e.v.transformMat4(z,A,D),e.v.scale(z,z,R);const O=[Math.floor(z[0]),Math.floor(z[1]),Math.floor(z[2])],F=[0,0,0];e.v.sub(F,z,O),e.v.scale(F,F,-1/R);const B=new Float64Array(16);return e.m.identity(B),e.m.translate(B,B,F),e.m.multiply(D,B,D),[D,M]}class Er extends e.a6{constructor(e){super(),this.requestManager=e,this.models={\"\":{}},this.numModelsLoading={};}loadModel(t,i){return e.aO(this.requestManager.transformRequest(i,e.a2.Model).url).then((i=>{if(!i)return;const o=e.aP(i),r=new e.aQ(t,void 0,void 0,o);return r.computeBoundsAndApplyParent(),r})).catch((o=>{this.fire(new e.a7(new Error(`Could not load model ${t} from ${i}: ${o.message}`)));}))}load(t,i){this.models[i]||(this.models[i]={});const o=Object.keys(t);this.numModelsLoading[i]=(this.numModelsLoading[i]||0)+o.length;const r=[];for(const e of o)r.push(this.loadModel(e,t[e]));Promise.allSettled(r).then((t=>{for(let e=0;e{this.fire(new e.a7(new Error(`Could not load models: ${t.message}`)));}));}isLoaded(){for(const e in this.numModelsLoading)if(this.numModelsLoading[e]>0)return !1;return !0}hasModel(e,t){return !!this.getModel(e,t)}getModel(e,t){return this.models[t]||(this.models[t]={}),this.models[t][e]}addModel(e,t,i){this.models[i]||(this.models[i]={}),this.hasModel(e,i)&&this.removeModel(e,i),this.load({[e]:this.requestManager.normalizeModelURL(t)},i);}addModels(e,t){const i={};for(const t in e)i[t]=this.requestManager.normalizeModelURL(e[t]);this.load(i,t);}removeModel(e,t){this.models[t]||(this.models[t]={});const i=this.models[t][e];delete this.models[t][e],i.destroy();}listModels(e){return this.models[e]||(this.models[e]={}),Object.keys(this.models[e])}upload(e,t){this.models[t]||(this.models[t]={});for(const i in this.models[t])this.models[t][i].upload(e.context);}}const Cr=(t,i)=>e.ai(t,i&&i.filter((e=>\"source.canvas\"!==e.identifier))),Ir=e.p(ut,[\"addLayer\",\"removeLayer\",\"setLights\",\"setPaintProperty\",\"setLayoutProperty\",\"setSlot\",\"setFilter\",\"addSource\",\"removeSource\",\"setLayerZoomRange\",\"setLight\",\"setTransition\",\"setGeoJSONSourceData\",\"setTerrain\",\"setFog\",\"setProjection\",\"setCamera\",\"addImport\",\"removeImport\",\"setImportUrl\",\"setImportData\",\"setImportConfig\"]),Sr=e.p(ut,[\"setCenter\",\"setZoom\",\"setBearing\",\"setPitch\"]),Mr={version:8,layers:[],sources:{}},Lr={duration:300,delay:0},Pr=new Set([\"fill\",\"line\",\"background\",\"hillshade\",\"raster\"]);class Dr extends e.a6{constructor(t,i={}){super(),this.map=t,this.scope=i.scope||\"\",this.fragments=[],this.importDepth=i.importDepth||0,this.importsCache=i.importsCache||new Map,this.resolvedImports=i.resolvedImports||new Set,this.transition=e.ak({},Lr),this._buildingIndex=new ht(this),this.crossTileSymbolIndex=new Qt,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._changes=i.styleChanges||new v,this.dispatcher=i.dispatcher?i.dispatcher:new e.br(e.bs(),this),i.imageManager?this.imageManager=i.imageManager:(this.imageManager=new Re,this.imageManager.setEventedParent(this)),this.imageManager.createScope(this.scope),this.glyphManager=i.glyphManager?i.glyphManager:new e.cj(t._requestManager,i.localFontFamily?e.ck.all:i.localIdeographFontFamily?e.ck.ideographs:e.ck.none,i.localFontFamily||i.localIdeographFontFamily),i.modelManager?this.modelManager=i.modelManager:(this.modelManager=new Er(t._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._serializedLayers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._order=[],this._markersNeedUpdate=!1,this.options=i.configOptions?i.configOptions:new Map,this._configDependentLayers=i.configDependentLayers?i.configDependentLayers:new Set,this._config=i.config,this.dispatcher.broadcast(\"setReferrer\",e.cl());const o=this;this._rtlTextPluginCallback=Dr.registerForPluginStateChange((t=>{o.dispatcher.broadcast(\"syncRTLPluginState\",{pluginStatus:t.pluginStatus,pluginURL:t.pluginURL},((t,i)=>{if(e.cm(t),i&&i.every((e=>e)))for(const e in o._sourceCaches){const t=o._sourceCaches[e],i=t.getSource().type;\"vector\"!==i&&\"geojson\"!==i||t.reload();}}));})),this.on(\"data\",(e=>{if(\"source\"!==e.dataType||\"metadata\"!==e.sourceDataType)return;const t=this.getOwnSource(e.sourceId);if(t&&t.vectorLayerIds)for(const e in this._layers){const i=this._layers[e];i.source===t.id&&this._validateLayer(i);}}));}loadURL(t,i={}){this.fire(new e.a8(\"dataloading\",{dataType:\"style\"}));const o=\"boolean\"==typeof i.validate?i.validate:!e.cn(t);t=this.map._requestManager.normalizeStyleURL(t,i.accessToken),this.resolvedImports.add(t);const r=this.importsCache.get(t);if(r)return this._load(r,o);const s=this.map._requestManager.transformRequest(t,e.a2.Style);this._request=e.a1(s,((i,r)=>{if(this._request=null,i)this.fire(new e.a7(i));else if(r)return this.importsCache.set(t,r),this._load(r,o)}));}loadJSON(t,i={}){this.fire(new e.a8(\"dataloading\",{dataType:\"style\"})),this._request=e.a4.frame((()=>{this._request=null,this._load(t,!1!==i.validate);}));}loadEmpty(){this.fire(new e.a8(\"dataloading\",{dataType:\"style\"})),this._load(Mr,!1);}_loadImports(t,i){if(this.importDepth>=4)return e.X(\"Style doesn't support nesting deeper than 5\"),Promise.resolve();const o=[];for(const e of t){const t=this._createFragmentStyle(e),r=new Promise((e=>{t.once(\"style.import.load\",e),t.once(\"error\",e);})).then((()=>this.mergeAll()));if(o.push(r),this.resolvedImports.has(e.url)){t.loadEmpty();continue}const s=e.data||this.importsCache.get(e.url);s?t.loadJSON(s,{validate:i}):e.url?t.loadURL(e.url,{validate:i}):t.loadEmpty(),this.fragments.push({style:t,id:e.id,config:e.config});}return Promise.allSettled(o)}_createFragmentStyle(t){const i=this.scope?e.aE(t.id,this.scope):t.id,o=new Dr(this.map,{scope:i,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:t.config,configOptions:this.options,configDependentLayers:this._configDependentLayers});return o.setEventedParent(this.map,{style:o}),o}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast(\"setLayers\",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options});const t=this.isRootStyle();this._shouldPrecompile=t,this.fire(new e.a8(t?\"style.load\":\"style.import.load\"));}_load(t,i){const o=t.schema;if(this.isRootStyle()&&(t.fragment||o&&!1!==t.fragment)){const o=e.ak({},Mr,{imports:[{id:\"basemap\",data:t,url:\"\"}]});return void this._load(o,i)}if(this.setConfig(this._config,o),i&&Cr(this,e.aj(t)))return;this._loaded=!0,this.stylesheet=e.co(t);for(const e in t.sources)this.addSource(e,t.sources[e],{validate:!1,isInitialLoad:!0});t.sprite?this._loadSprite(t.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast(\"spriteLoaded\",{scope:this.scope,isLoaded:!0})),this.glyphManager.setURL(t.glyphs,this.scope);const r=dt(this.stylesheet.layers);if(this._order=r.map((e=>e.id)),this.stylesheet.light&&e.X(\"The `light` root property is deprecated, prefer using `lights` with `flat` light type instead.\"),this.stylesheet.lights)if(1===this.stylesheet.lights.length&&\"flat\"===this.stylesheet.lights[0].type){const e=this.stylesheet.lights[0];this.light=new Oe(e.properties,e.id);}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Oe(this.stylesheet.light)),this._layers={},this._serializedLayers={};for(const t of r){const i=e.cp(t,this.scope,this.options);i.isConfigDependent&&this._configDependentLayers.add(i.fqid),i.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=i,this._serializedLayers[i.id]=i.serialize();const o=this.getOwnLayerSourceCache(i),r=!!this.directionalLight&&this.directionalLight.shadowsEnabled();o&&i.canCastShadows()&&r&&(o.castsShadows=!0);}this.stylesheet.models&&this.modelManager.addModels(this.stylesheet.models,this.scope);const s=this.stylesheet.terrain;s&&(void 0===this.disableElevatedTerrain&&(this.disableElevatedTerrain=e.a4.hasCanvasFingerprintNoise()),this.disableElevatedTerrain?e.X(\"Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode).\"):this.terrainSetForDrapingOnly()||this._createTerrain(s,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new e.a8(\"data\",{dataType:\"style\"})),t.imports?this._loadImports(t.imports,i).then((()=>this._reloadImports())):this._reloadImports();}isRootStyle(){return 0===this.importDepth}mergeAll(){let t,i,o,r,s,n,a,l;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle((e=>{if(e.stylesheet){if(null!=e.light&&(t=e.light),e.stylesheet.lights)for(const t of e.stylesheet.lights)\"ambient\"===t.type&&null!=e.ambientLight&&(i=e.ambientLight),\"directional\"===t.type&&null!=e.directionalLight&&(o=e.directionalLight);r=this._prioritizeTerrain(r,e.terrain,e.stylesheet.terrain),e.stylesheet.fog&&null!=e.fog&&(s=e.fog),null!=e.stylesheet.camera&&(l=e.stylesheet.camera),null!=e.stylesheet.projection&&(n=e.stylesheet.projection),null!=e.stylesheet.transition&&(a=e.stylesheet.transition);}})),this.light=t,this.ambientLight=i,this.directionalLight=o,this.fog=s,null===r?delete this.terrain:this.terrain=r,this.camera=l||{\"camera-projection\":\"perspective\"},this.projection=n||{name:\"mercator\"},this.transition=e.ak({},Lr,a),this.mergeSources(),this.mergeLayers();}forEachFragmentStyle(e){const t=i=>{for(const e of i.fragments)t(e.style);e(i);};t(this);}_prioritizeTerrain(e,t,i){const o=e&&0===e.drapeRenderMode;return null===i?t&&0===t.drapeRenderMode?t:o?e:null:null!=t&&(!e||o||t&&1===t.drapeRenderMode)?t:e}mergeTerrain(){let e;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle((t=>{e=this._prioritizeTerrain(e,t.terrain,t.stylesheet.terrain);})),null===e?delete this.terrain:this.terrain=e;}mergeProjection(){let e;this.forEachFragmentStyle((t=>{null!=t.stylesheet.projection&&(e=t.stylesheet.projection);})),this.projection=e||{name:\"mercator\"};}mergeSources(){const t={},i={},o={};this.forEachFragmentStyle((r=>{for(const i in r._sourceCaches){const o=e.aE(i,r.scope);t[o]=r._sourceCaches[i];}for(const t in r._otherSourceCaches){const o=e.aE(t,r.scope);i[o]=r._otherSourceCaches[t];}for(const t in r._symbolSourceCaches){const i=e.aE(t,r.scope);o[i]=r._symbolSourceCaches[t];}})),this._mergedSourceCaches=t,this._mergedOtherSourceCaches=i,this._mergedSymbolSourceCaches=o;}mergeLayers(){const t={},i=[],o={};this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle((o=>{for(const r of o._order){const s=o._layers[r];if(\"slot\"===s.type){const i=e.cq(r);if(t[i])continue;t[i]=[];}s.slot&&t[s.slot]?t[s.slot].push(s):i.push(s);}})),this._mergedOrder=[];const r=(i=[])=>{for(const s of i)if(\"slot\"===s.type){const i=e.cq(s.id);t[i]&&r(t[i]);}else {const t=e.aE(s.id,s.scope);this._mergedOrder.push(t),o[t]=s,s.is3D()&&(this._has3DLayers=!0),\"circle\"===s.type&&(this._hasCircleLayers=!0),\"symbol\"===s.type&&(this._hasSymbolLayers=!0);}};r(i),this._mergedLayers=o,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged();}terrainSetForDrapingOnly(){return !!this.terrain&&0===this.terrain.drapeRenderMode}getCamera(){return this.stylesheet.camera}setCamera(t){return this.stylesheet.camera=e.ak({},this.stylesheet.camera,t),this.camera=this.stylesheet.camera,this}setProjection(e){e?this.stylesheet.projection=e:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection();}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast(\"setProjection\",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?this.getTerrain()||this.stylesheet.terrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null));}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection));}_loadSprite(t){this._spriteRequest=function(t,i,o){let r,s,n;const a=e.a4.devicePixelRatio>1?\"@2x\":\"\";let l=e.a1(i.transformRequest(i.normalizeSpriteURL(t,a,\".json\"),e.a2.SpriteJSON),((e,t)=>{l=null,n||(n=e,r=t,h());})),c=e.a3(i.transformRequest(i.normalizeSpriteURL(t,a,\".png\"),e.a2.SpriteImage),((e,t)=>{c=null,n||(n=e,s=t,h());}));function h(){if(n)o(n);else if(r&&s){const t=e.a4.getImageData(s),i={};for(const o in r){const{width:s,height:n,x:a,y:l,sdf:c,pixelRatio:h,stretchX:_,stretchY:d,content:u}=r[o],p=new e.a5({width:s,height:n});e.a5.copy(t,p,{x:a,y:l},{x:0,y:0},{width:s,height:n}),i[o]={data:p,pixelRatio:h,sdf:c,stretchX:_,stretchY:d,content:u};}o(null,i);}}return {cancel(){l&&(l.cancel(),l=null),c&&(c.cancel(),c=null);}}}(t,this.map._requestManager,((t,i)=>{if(this._spriteRequest=null,t)this.fire(new e.a7(t));else if(i)for(const e in i)this.imageManager.addImage(e,this.scope,i[e]);this.imageManager.setLoaded(!0,this.scope),this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast(\"setImages\",{scope:this.scope,images:this._availableImages}),this.dispatcher.broadcast(\"spriteLoaded\",{scope:this.scope,isLoaded:!0}),this.fire(new e.a8(\"data\",{dataType:\"style\"}));}));}_validateLayer(t){const i=this.getOwnSource(t.source);if(!i)return;const o=t.sourceLayer;o&&(\"geojson\"===i.type||i.vectorLayerIds&&-1===i.vectorLayerIds.indexOf(o))&&this.fire(new e.a7(new Error(`Source layer \"${o}\" does not exist on source \"${i.id}\" as specified by style layer \"${t.id}\"`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._changes.getUpdatedSourceCaches()).length)return !1;for(const e in this._sourceCaches)if(!this._sourceCaches[e].loaded())return !1;if(!this.imageManager.isLoaded())return !1;if(!this.modelManager.isLoaded())return !1;for(const{style:e}of this.fragments)if(!e.loaded())return !1;return !0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map(((e,t)=>{const i=this.fragments[t];return i&&i.style&&(e.data=i.style.serialize()),e}))}_serializeSources(){const e={};for(const t in this._sourceCaches){const i=this._sourceCaches[t].getSource();e[i.id]||(e[i.id]=i.serialize());}return e}_serializeLayers(e){const t=[];for(const i of e){const e=this._layers[i];e&&\"custom\"!==e.type&&t.push(e.serialize());}return t}hasLightTransitions(){return !(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return !!this.fog&&this.fog.hasTransition()}hasTransitions(){if(this.hasLightTransitions())return !0;if(this.hasFogTransition())return !0;for(const e in this._sourceCaches)if(this._sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}isLayerDraped(e){return !!this.terrain&&(\"function\"==typeof e.isLayerDraped?e.isLayerDraped(this.getLayerSourceCache(e)):Pr.has(e.type))}_checkLoaded(){if(!this._loaded)throw new Error(\"Style is not done loading\")}_checkLayer(t){const i=this.getOwnLayer(t);if(i)return i;this.fire(new e.a7(new Error(`The layer '${t}' does not exist in the map's style.`)));}_checkSource(t){const i=this.getOwnSource(t);if(i)return i;this.fire(new e.a7(new Error(`The source '${t}' does not exist in the map's style.`)));}update(t){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(t),this.directionalLight&&this.directionalLight.recalculate(t);const i=this.calculateLightsBrightness();t.brightness=i||0,i!==this._brightness&&(this._brightness=i,this.dispatcher.broadcast(\"setBrightness\",i));const o=this._changes.isDirty();if(this._changes.isDirty()){const e=this._changes.getLayerUpdatesByScope();for(const t in e){const{updatedIds:i,removedIds:o}=e[t];(i||o)&&this._updateWorkerLayers(t,i,o);}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(t),this.light&&this.light.updateTransitions(t),this.ambientLight&&this.ambientLight.updateTransitions(t),this.directionalLight&&this.directionalLight.updateTransitions(t),this.fog&&this.fog.updateTransitions(t),this._changes.reset();}const r={};for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e];r[e]=t.used,t.used=!1;}for(const e of this._mergedOrder){const i=this._mergedLayers[e];if(i.recalculate(t,this._availableImages),!i.isHidden(t.zoom)){const e=this.getLayerSourceCache(i);e&&(e.used=!0);}if(!this._precompileDone&&this._shouldPrecompile)for(let e=i.minzoom||0;e<(i.maxzoom||25.5);e++){const e=this.map.painter;if(e){const o=i.getProgramIds();if(!o)continue;for(const r of o){const o=i.getDefaultProgramParams(r,t.zoom);o&&(e.style=this,this.fog&&(e._fogVisible=!0,o.overrideFog=!0,e.getOrCreateProgram(r,o)),e._fogVisible=!1,o.overrideFog=!1,e.getOrCreateProgram(r,o),(this.stylesheet.terrain||this.stylesheet.projection&&\"globe\"===this.stylesheet.projection.name)&&(o.overrideRtt=!0,e.getOrCreateProgram(r,o)));}}}}this._shouldPrecompile&&(this._precompileDone=!0);for(const t in r){const i=this._mergedSourceCaches[t];r[t]!==i.used&&i.getSource().fire(new e.a8(\"data\",{sourceDataType:\"visibility\",dataType:\"source\",sourceId:i.getSource().id}));}this.light&&this.light.recalculate(t),this.terrain&&this.terrain.recalculate(t),this.fog&&this.fog.recalculate(t),this.z=t.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),o&&this.fire(new e.a8(\"data\",{dataType:\"style\"}));}_updateTilesForChangedImages(){const e=this._changes.getUpdatedImages();if(e.length){for(const t in this._sourceCaches)this._sourceCaches[t].reloadTilesForDependencies([\"icons\",\"patterns\"],e);this._changes.resetUpdatedImages();}}_updateWorkerLayers(e,t,i){const o=this.getFragmentStyle(e);o&&this.dispatcher.broadcast(\"updateLayers\",{layers:t?o._serializeLayers(t):[],scope:e,removedIds:i||[],options:o.options});}setState(i){if(this._checkLoaded(),Cr(this,e.aj(i)))return !1;(i=e.co(i)).layers=dt(i.layers);const o=function(e,i){if(!e)return [{command:ut.setStyle,args:[i]}];let o=[];try{if(!t(e.version,i.version))return [{command:ut.setStyle,args:[i]}];t(e.center,i.center)||o.push({command:ut.setCenter,args:[i.center]}),t(e.zoom,i.zoom)||o.push({command:ut.setZoom,args:[i.zoom]}),t(e.bearing,i.bearing)||o.push({command:ut.setBearing,args:[i.bearing]}),t(e.pitch,i.pitch)||o.push({command:ut.setPitch,args:[i.pitch]}),t(e.sprite,i.sprite)||o.push({command:ut.setSprite,args:[i.sprite]}),t(e.glyphs,i.glyphs)||o.push({command:ut.setGlyphs,args:[i.glyphs]}),t(e.imports,i.imports)||function(e=[],i=[],o){i=i||[];const r=(e=e||[]).map(xt),s=i.map(xt),n=e.reduce(yt,{}),a=i.reduce(yt,{}),l=r.slice();let c,h,_,d;for(c=0,h=0;c{e.source&&r[e.source]?o.push({command:ut.removeLayer,args:[e.id]}):n.push(e);}));let a=e.terrain;a&&r[a.source]&&(o.push({command:ut.setTerrain,args:[void 0]}),a=void 0),o=o.concat(s),t(a,i.terrain)||o.push({command:ut.setTerrain,args:[i.terrain]}),function(e,i,o){i=i||[];const r=(e=e||[]).map(xt),s=i.map(xt),n=e.reduce(yt,{}),a=i.reduce(yt,{}),l=r.slice(),c=Object.create(null);let h,_,d,u,p,m,f;for(h=0,_=0;h!(e.command in Sr)));if(0===o.length)return !1;const r=o.filter((e=>!(e.command in Ir)));if(r.length>0)throw new Error(`Unimplemented: ${r.map((e=>e.command)).join(\", \")}.`);return o.forEach((e=>{this[e.command].apply(this,e.args);})),this.stylesheet=i,this.mergeAll(),this.dispatcher.broadcast(\"setLayers\",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}addImage(t,i){return this.getImage(t)?this.fire(new e.a7(new Error(\"An image with this name already exists.\"))):(this.imageManager.addImage(t,this.scope,i),this._afterImageUpdated(t),this)}updateImage(e,t){this.imageManager.updateImage(e,this.scope,t);}getImage(e){return this.imageManager.getImage(e,this.scope)}removeImage(t){return this.getImage(t)?(this.imageManager.removeImage(t,this.scope),this._afterImageUpdated(t),this):this.fire(new e.a7(new Error(\"No image with this name exists.\")))}_afterImageUpdated(t){this._availableImages=this.imageManager.listImages(this.scope),this._changes.updateImage(t),this.dispatcher.broadcast(\"setImages\",{scope:this.scope,images:this._availableImages}),this.fire(new e.a8(\"data\",{dataType:\"style\"}));}listImages(){return this._checkLoaded(),this._availableImages.slice()}addModel(t,i,o={}){return this._checkLoaded(),this._validate(e.cr,`models.${t}`,i,null,o)||(this.modelManager.addModel(t,i,this.scope),this._changes.setDirty()),this}hasModel(e){return this.modelManager.hasModel(e,this.scope)}removeModel(t){return this.hasModel(t)?(this.modelManager.removeModel(t,this.scope),this):this.fire(new e.a7(new Error(\"No model with this ID exists.\")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.scope)}addSource(t,i,o={}){if(this._checkLoaded(),void 0!==this.getOwnSource(t))throw new Error(`There is already a source with ID \"${t}\".`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(\", \")}.`);if([\"vector\",\"raster\",\"geojson\",\"video\",\"image\"].indexOf(i.type)>=0&&this._validate(e.cs,`sources.${t}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=st(t,i,this.dispatcher,this);r.scope=this.scope,r.setEventedParent(this,(()=>({isSourceLoaded:this._isSourceCacheLoaded(r.id),source:r.serialize(),sourceId:r.id})));const s=t=>{const i=(t?\"symbol:\":\"other:\")+r.id,o=e.aE(i,this.scope),s=this._sourceCaches[i]=new e.bq(o,r,t);(t?this._symbolSourceCaches:this._otherSourceCaches)[r.id]=s,s.onAdd(this.map);};s(!1),\"vector\"!==i.type&&\"geojson\"!==i.type||s(!0),r.onAdd&&r.onAdd(this.map),o.isInitialLoad||(this.mergeSources(),this._changes.setDirty());}removeSource(t){this._checkLoaded();const i=this.getOwnSource(t);if(!i)throw new Error(\"There is no source with this ID\");for(const i in this._layers)if(this._layers[i].source===t)return this.fire(new e.a7(new Error(`Source \"${t}\" cannot be removed while layer \"${i}\" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===t)return this.fire(new e.a7(new Error(`Source \"${t}\" cannot be removed while terrain is using it.`)));const o=this.getOwnSourceCaches(t);for(const t of o){const i=e.cq(t.id);delete this._sourceCaches[i],this._changes.discardSourceCacheUpdate(t.id),t.fire(new e.a8(\"data\",{sourceDataType:\"metadata\",dataType:\"source\",sourceId:t.getSource().id})),t.setEventedParent(null),t.clearTiles();}return delete this._otherSourceCaches[t],delete this._symbolSourceCaches[t],this.mergeSources(),i.setEventedParent(null),i.onRemove&&i.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(e,t){this._checkLoaded(),this.getOwnSource(e).setData(t),this._changes.setDirty();}getOwnSource(e){const t=this.getOwnSourceCache(e);return t&&t.getSource()}getOwnSources(){const e=[];for(const t in this._otherSourceCaches){const i=this.getOwnSourceCache(t);i&&e.push(i.getSource());}return e}areTilesLoaded(){const e=this._mergedSourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if(\"loaded\"!==t.state&&\"errored\"!==t.state)return !1}}return !0}setLights(t){if(this._checkLoaded(),!t)return delete this.ambientLight,void delete this.directionalLight;const i=this._getTransitionParameters();for(const o of t){if(this._validate(e.ct,\"lights\",o))return;switch(o.type){case\"ambient\":if(this.ambientLight){const e=this.ambientLight;e.set(o),e.updateTransitions(i);}else this.ambientLight=new qe(o,$e,this.scope,this.options);break;case\"directional\":if(this.directionalLight){const e=this.directionalLight;e.set(o),e.updateTransitions(i);}else this.directionalLight=new qe(o,Xe,this.scope,this.options);}}const o=new e.al(this.z||0,i);this.ambientLight&&this.ambientLight.recalculate(o),this.directionalLight&&this.directionalLight.recalculate(o),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast(\"setBrightness\",this._brightness);}calculateLightsBrightness(){const t=this.directionalLight,i=this.ambientLight;if(!t||!i)return;const o=e=>.2126*(e[0]<=.03928?e[0]/12.92:Math.pow((e[0]+.055)/1.055,2.4))+.7152*(e[1]<=.03928?e[1]/12.92:Math.pow((e[1]+.055)/1.055,2.4))+.0722*(e[2]<=.03928?e[2]/12.92:Math.pow((e[2]+.055)/1.055,2.4)),r=t.properties.get(\"color\").toArray01(),s=t.properties.get(\"intensity\"),n=t.properties.get(\"direction\"),a=1-e.b3(n.x,n.y,n.z)[2]/90,l=o(r)*s*a,c=i.properties.get(\"color\").toArray01(),h=i.properties.get(\"intensity\");return (l+o(c)*h)/2}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const e=[];return this.directionalLight&&e.push(this.directionalLight.get()),this.ambientLight&&e.push(this.ambientLight.get()),e}enable3dLights(){return !!this.ambientLight&&!!this.directionalLight}getFragmentStyle(t){if(!t)return this;if(e.cu(t)){const i=e.cv(t),o=this.fragments.find((({id:e})=>e===i));if(!o)throw new Error(`Style import not found: ${t}`);const r=e.cq(t);return o.style.getFragmentStyle(r)}{const e=this.fragments.find((({id:e})=>e===t));if(!e)throw new Error(`Style import not found: ${t}`);return e.style}}getConfigProperty(t,i){const o=this.getFragmentStyle(t);if(!o)return null;const r=e.aE(i,o.scope),s=o.options.get(r),n=s?s.value||s.default:null;return n?n.serialize():null}setConfigProperty(t,i,o){const r=e.cw(o);if(\"success\"!==r.result)return void Cr(this,r.value);const s=r.value.expression,n=this.getFragmentStyle(t);if(!n)return;const a=e.aE(i,n.scope),l=n.options.get(a);l&&(this.options.set(a,{...l,value:s}),this.updateConfigDependencies());}setConfig(t,i){if(this._config=t,t||i)if(i)for(const o in i){let r,s;const n=e.cw(i[o].default);if(\"success\"===n.result&&(r=n.value.expression),t&&void 0!==t[o]){const i=e.cw(t[o]);\"success\"===i.result&&(s=i.value.expression);}const{minValue:a,maxValue:l,stepValue:c,type:h,values:_}=i[o];if(r){const t=e.aE(o,this.scope);this.options.set(t,{default:r,value:s,minValue:a,maxValue:l,stepValue:c,type:h,values:_});}else this.fire(new e.a7(new Error(`No schema defined for config option \"${o}\".`)));}else this.fire(new e.a7(new Error(\"Attempting to set config for a style without schema.\")));}updateConfigDependencies(){for(const e of this._configDependentLayers){const t=this.getLayer(e);t&&(t.possiblyEvaluateVisibility(),this._updateLayer(t));}this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this._changes.setDirty();}addLayer(t,i,o={}){this._checkLoaded();const r=t.id;if(this._layers[r])return void this.fire(new e.a7(new Error(`Layer with id \"${r}\" already exists on this map`)));let s;if(\"custom\"===t.type){if(Cr(this,e.cx(t)))return;s=e.cp(t,this.scope,this.options);}else {if(\"object\"==typeof t.source&&(this.addSource(r,t.source),t=e.co(t),t=e.ak(t,{source:r})),this._validate(e.cy,`layers.${r}`,t,{arrayIndex:-1},o))return;s=e.cp(t,this.scope,this.options),this._validateLayer(s),s.setEventedParent(this,{layer:{id:r}}),this._serializedLayers[s.id]=s.serialize();}s.isConfigDependent&&this._configDependentLayers.add(s.fqid);let n=this._order.length;if(i){const t=this._order.indexOf(i);if(-1===t)return void this.fire(new e.a7(new Error(`Layer with id \"${i}\" does not exist on this map.`)));s.slot===this._layers[i].slot?n=t:e.X(`Layer with id \"${i}\" has a different slot. Layers can only be rearranged within the same slot.`);}this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=s;const a=this.getOwnLayerSourceCache(s),l=!!this.directionalLight&&this.directionalLight.shadowsEnabled();a&&s.canCastShadows()&&l&&(a.castsShadows=!0);const c=this._changes.getRemovedLayer(s);if(c&&s.source&&a&&\"custom\"!==s.type){this._changes.discardLayerRemoval(s);const t=e.aE(s.source,s.scope);c.type!==s.type?this._changes.updateSourceCache(t,\"clear\"):(this._changes.updateSourceCache(t,\"reload\"),a.pause());}this._updateLayer(s),s.onAdd&&s.onAdd(this.map),s.scope=this.scope,this.mergeLayers();}moveLayer(t,i){this._checkLoaded();const o=this._checkLayer(t);if(!o)return;if(t===i)return;const r=this._order.indexOf(t);this._order.splice(r,1);let s=this._order.length;if(i){const t=this._order.indexOf(i);if(-1===t)return void this.fire(new e.a7(new Error(`Layer with id \"${i}\" does not exist on this map.`)));o.slot===this._layers[i].slot?s=t:e.X(`Layer with id \"${i}\" has a different slot. Layers can only be rearranged within the same slot.`);}this._order.splice(s,0,t),this._changes.setDirty(),this._layerOrderChanged=!0,this.mergeLayers();}removeLayer(e){this._checkLoaded();const t=this._checkLayer(e);if(!t)return;t.setEventedParent(null);const i=this._order.indexOf(e);this._order.splice(i,1),delete this._layers[e],delete this._serializedLayers[e],this._changes.setDirty(),this._layerOrderChanged=!0,this._configDependentLayers.delete(t.fqid),this._changes.removeLayer(t);const o=this.getOwnLayerSourceCache(t);if(o&&o.castsShadows){let e=!1;for(const i in this._layers)if(this._layers[i].source===t.source&&this._layers[i].canCastShadows()){e=!0;break}o.castsShadows=e;}t.onRemove&&t.onRemove(this.map),this.mergeLayers();}getOwnLayer(e){return this._layers[e]}hasLayer(e){return e in this._mergedLayers}hasLayerType(e){for(const t in this._layers)if(this._layers[t].type===e)return !0;return !1}setLayerZoomRange(e,t,i){this._checkLoaded();const o=this._checkLayer(e);o&&(o.minzoom===t&&o.maxzoom===i||(null!=t&&(o.minzoom=t),null!=i&&(o.maxzoom=i),this._updateLayer(o)));}setSlot(e,t){this._checkLoaded();const i=this._checkLayer(e);i&&i.slot!==t&&(i.slot=t,this._updateLayer(i));}setFilter(i,o,r={}){this._checkLoaded();const s=this._checkLayer(i);if(s&&!t(s.filter,o))return null==o?(s.filter=void 0,void this._updateLayer(s)):void(this._validate(e.cz,`layers.${s.id}.filter`,o,{layerType:s.type},r)||(s.filter=e.co(o),this._updateLayer(s)))}getFilter(t){const i=this._checkLayer(t);if(i)return e.co(i.filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const s=this._checkLayer(e);s&&(t(s.getLayoutProperty(i),o)||(s.setLayoutProperty(i,o,r),s.isConfigDependent&&this._configDependentLayers.add(s.fqid),this._updateLayer(s)));}getLayoutProperty(e,t){const i=this._checkLayer(e);if(i)return i.getLayoutProperty(t)}setPaintProperty(e,i,o,r={}){this._checkLoaded();const s=this._checkLayer(e);if(!s)return;if(t(s.getPaintProperty(i),o))return;const n=s.setPaintProperty(i,o,r);s.isConfigDependent&&this._configDependentLayers.add(s.fqid),n&&this._updateLayer(s),this._changes.updatePaintProperties(s);}getPaintProperty(e,t){const i=this._checkLayer(e);if(i)return i.getPaintProperty(t)}setFeatureState(t,i){this._checkLoaded();const o=t.source,r=t.sourceLayer,s=this._checkSource(o);if(!s)return;const n=s.type;if(\"geojson\"===n&&r)return void this.fire(new e.a7(new Error(\"GeoJSON sources cannot have a sourceLayer parameter.\")));if(\"vector\"===n&&!r)return void this.fire(new e.a7(new Error(\"The sourceLayer parameter must be provided for vector source types.\")));void 0===t.id&&this.fire(new e.a7(new Error(\"The feature id parameter must be provided.\")));const a=this.getOwnSourceCaches(o);for(const e of a)e.setFeatureState(r,t.id,i);}removeFeatureState(t,i){this._checkLoaded();const o=t.source,r=this._checkSource(o);if(!r)return;const s=r.type,n=\"vector\"===s?t.sourceLayer:void 0;if(\"vector\"===s&&!n)return void this.fire(new e.a7(new Error(\"The sourceLayer parameter must be provided for vector source types.\")));if(i&&\"string\"!=typeof t.id&&\"number\"!=typeof t.id)return void this.fire(new e.a7(new Error(\"A feature id is required to remove its specific state property.\")));const a=this.getOwnSourceCaches(o);for(const e of a)e.removeFeatureState(n,t.id,i);}getFeatureState(t){this._checkLoaded();const i=t.source,o=t.sourceLayer,r=this._checkSource(i);if(r){if(\"vector\"!==r.type||o)return void 0===t.id&&this.fire(new e.a7(new Error(\"The feature id parameter must be provided.\"))),this.getOwnSourceCaches(i)[0].getFeatureState(o,t.id);this.fire(new e.a7(new Error(\"The sourceLayer parameter must be provided for vector source types.\")));}}setTransition(t){return this.stylesheet.transition=e.ak({},this.stylesheet.transition,t),this.transition=this.stylesheet.transition,this}getTransition(){return e.ak({},this.stylesheet.transition)}serialize(){this._checkLoaded();const t=this.getTerrain(),i=t&&this.terrain&&this.terrain.scope===this.scope?t:this.stylesheet.terrain;return e.cA({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:i,fog:this.stylesheet.fog,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},(e=>void 0!==e))}_updateLayer(t){this._changes.updateLayer(t);const i=this.getLayerSourceCache(t),o=e.aE(t.source,t.scope),r=this._changes.getUpdatedSourceCaches();t.source&&!r[o]&&i&&\"raster\"!==i.getSource().type&&(this._changes.updateSourceCache(o,\"reload\"),i.pause()),t.invalidateCompiledFilter();}_flattenAndSortRenderedFeatures(e){const t=e=>\"fill-extrusion\"===this._mergedLayers[e].type,i=this.order,o={},r=[];for(let s=i.length-1;s>=0;s--){const n=i[s];if(t(n)){o[n]=s;for(const t of e){const e=t[n];if(e)for(const t of e)r.push(t);}}}r.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const s=[];for(let n=i.length-1;n>=0;n--){const a=i[n];if(t(a))for(let e=r.length-1;e>=0;e--){const t=r[e].feature;if(o[t.layer.id]{const t=this.getLayer(e);return t&&t.is3D()})):this.has3DLayers(),l=Je.createFromScreenPoints(t,o);for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e].getSource();if(!t||t.scope!==i.scope)continue;const c=this._mergedSourceCaches[e].getSource().id;i.layers&&!r[c]||s.push(at(this._mergedSourceCaches[e],this._mergedLayers,n,l,i,o,a,!!this.map._showQueryGeometry));}return this.placement&&s.push(function(e,t,i,o,r,s,n){const a={},l=s.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(n[e]);c.sort(ct);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,r.filter,r.layers,r.availableImages,e);for(const e in o){const t=a[e]=a[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}for(const t in a)a[t].forEach((o=>{const r=o.feature,s=i(e[t]);if(!s)return;const n=s.getFeatureState(r.layer[\"source-layer\"],r.id);r.source=r.layer.source,r.layer[\"source-layer\"]&&(r.sourceLayer=r.layer[\"source-layer\"]),r.state=n;}));return a}(this._mergedLayers,n,this.getLayerSourceCache.bind(this),l.screenGeometry,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(s)}querySourceFeatures(t,i){i&&i.filter&&this._validate(e.cz,\"querySourceFeatures.filter\",i.filter,null,i);const o=this.getOwnSourceCaches(t);let r=[];for(const e of o)r=r.concat(lt(e,i));return r}addSourceType(e,t,i){return Dr.getSourceType(e)?i(new Error(`A source type called \"${e}\" already exists.`)):(Dr.setSourceType(e,t),t.workerSourceURL?void this.dispatcher.broadcast(\"loadWorkerSource\",{name:e,url:t.workerSourceURL},i):i(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(e,i,o={}){this._checkLoaded();const r=this.light.getLight();let s=!1;for(const i in e)if(!t(e[i],r[i])){s=!0;break}if(!s)return;const n=this._getTransitionParameters();this.light.setLight(e,i,o),this.light.updateTransitions(n);}getTerrain(){return this.terrain&&1===this.terrain.drapeRenderMode?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:\"\",exaggeration:0},0);}setTerrain(i,o=1){if(this._checkLoaded(),!i)return delete this.terrain,null===i?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);let r=i;const s=null==i.source;if(1===o){if(\"object\"==typeof r.source){const t=\"terrain-dem-src\";this.addSource(t,r.source),r=e.co(r),r=e.ak(r,{source:t});}const t=e.ak({},r),i={};if(this.terrain&&s){t.source=this.terrain.get().source;const e=this.terrain?this.getFragmentStyle(this.terrain.scope):null;e&&(i.style=e.serialize());}if(this._validate(e.cB,\"terrain\",t,i))return}if(!this.terrain||this.terrain.scope!==this.scope&&!s||this.terrain&&o!==this.terrain.drapeRenderMode){if(!r)return;this._createTerrain(r,o),this.fire(new e.a8(\"data\",{dataType:\"style\"}));}else {const o=this.terrain,s=o.get();for(const t of Object.keys(e.ae.terrain))!r.hasOwnProperty(t)&&e.ae.terrain[t].default&&(r[t]=e.ae.terrain[t].default);for(const r in i)if(!t(i[r],s[r])){o.set(i,this.options),this.stylesheet.terrain=i;const t=this._getTransitionParameters({duration:0});o.updateTransitions(t),this.fire(new e.a8(\"data\",{dataType:\"style\"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0;}_createFog(e){const t=this.fog=new He(e,this.map.transform);this.stylesheet.fog=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i);}_updateMarkersOpacity(){0!==this.map._markers.length&&this.map._requestDomTask((()=>{for(const e of this.map._markers)e._evaluateOpacity();}));}getFog(){return this.fog?this.fog.get():null}setFog(e){if(this._checkLoaded(),!e)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const i=this.fog;if(!t(i.get(),e)){i.set(e),this.stylesheet.fog=i.get();const t=this._getTransitionParameters({duration:0});i.updateTransitions(t);}}else this._createFog(e);this._markersNeedUpdate=!0;}_getTransitionParameters(t){return {now:e.a4.now(),transition:e.ak(this.transition,t)}}updateDrapeFirstLayers(){if(!this.terrain)return;const e=[],t=[];for(const i in this._mergedLayers)this.isLayerDraped(this._mergedLayers[i])?e.push(i):t.push(i);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...e),this._drapedFirstOrder.push(...t);}_createTerrain(e,t){const i=this.terrain=new Be(e,t,this.scope,this.options);1===t&&(this.stylesheet.terrain=e),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const o=this._getTransitionParameters({duration:0});i.updateTransitions(o);}_force3DLayerUpdate(){for(const e in this._layers){const t=this._layers[e];\"fill-extrusion\"===t.type&&this._updateLayer(t);}}_forceSymbolLayerUpdate(){for(const e in this._layers){const t=this._layers[e];\"symbol\"===t.type&&this._updateLayer(t);}}_validate(t,i,o,r,s={}){if(s&&!1===s.validate)return !1;const n=e.ak({},this.serialize());return Cr(this,t.call(e.aj,e.ak({key:i,style:n,value:o,styleSpec:e.ae},r)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),e.cC.off(\"pluginStateChange\",this._rtlTextPluginCallback);for(const e in this._mergedLayers)this._mergedLayers[e].setEventedParent(null);for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].clearTiles(),this._mergedSourceCaches[e].setEventedParent(null);this.setEventedParent(null),delete this.fog,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.modelManager.setEventedParent(null),this.dispatcher.remove());}clearSource(e){const t=this.getSourceCaches(e);for(const e of t)e.clearTiles();}clearSources(){for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].clearTiles();}reloadSource(e){const t=this.getSourceCaches(e);for(const e of t)e.resume(),e.reload();}reloadSources(){for(const e of this.getSources())e.reload&&e.reload();}updateSources(e){let t;this.directionalLight&&(t=br(this.directionalLight));for(const i in this._mergedSourceCaches)this._mergedSourceCaches[i].update(e,void 0,void 0,t);}_generateCollisionBoxes(){for(const e in this._sourceCaches){const t=this._sourceCaches[e];t.resume(),t.reload();}}_updatePlacement(t,i,o,r,s=!1){let n=!1,a=!1;const l={},c={};for(const i of this._mergedOrder){const o=this._mergedLayers[i];if(\"symbol\"!==o.type)continue;const r=e.aE(o.source,o.scope);let s=l[r];if(!s){const e=this.getLayerSourceCache(o);if(!e)continue;const t=e.getRenderableIds(!0).map((t=>e.getTileByID(t)));c[r]=t.slice(),s=l[r]=t.sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const a=this.crossTileSymbolIndex.addLayer(o,s,t.center.lng,t.projection);n=n||a;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder),s=s||this._layerOrderChanged||0===o,this._layerOrderChanged&&this.fire(new e.a8(\"neworder\")),(s||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(e.a4.now(),t.zoom))&&(this.pauseablePlacement=new $t(t,this._mergedOrder,s,i,o,r,this.placement,this.fog&&t.projection.supportsFog?this.fog.state:null,this._buildingIndex),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,l,c),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(e.a4.now()),a=!0),n&&this.pauseablePlacement.placement.setStale()),a||n)for(const t of this._mergedOrder){const i=this._mergedLayers[t];\"symbol\"===i.type&&this.placement.updateLayerOpacities(i,l[e.aE(i.source,i.scope)]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(e.a4.now())}_releaseSymbolFadeTiles(){for(const e in this._sourceCaches)this._sourceCaches[e].releaseSymbolFadeTiles();}addImport(t){this._checkLoaded();const i=this.stylesheet.imports=this.stylesheet.imports||[];return -1!==i.findIndex((({id:e})=>e===t.id))?this.fire(new e.a7(new Error(`Import with id '${t.id}' already exists in the map's style.`))):(i.push(t),this._loadImports([t],!0),this)}setImportUrl(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],o=this.getImportIndex(e);if(-1===o)return this;i[o].url=t;const r=this.fragments[o];return r.style=this._createFragmentStyle(i[o]),r.style.on(\"style.import.load\",(()=>this.mergeAll())),r.style.loadURL(t),this}setImportData(e,t){this._checkLoaded();const i=this.getImportIndex(e),o=this.stylesheet.imports||[];return -1===i?this:t?(this.fragments[i].style.setState(t),this._reloadImports(),this):(delete o[i].data,this.setImportUrl(e,o[i].url))}setImportConfig(e,t){this._checkLoaded();const i=this.getImportIndex(e),o=this.stylesheet.imports||[];if(-1===i)return this;t?o[i].config=t:delete o[i].config;const r=this.fragments[i],s=r.style.stylesheet&&r.style.stylesheet.schema;return r.config=t,r.style.setConfig(t,s),this.updateConfigDependencies(),this}removeImport(e){this._checkLoaded();const t=this.stylesheet.imports||[],i=this.getImportIndex(e);return -1===i||(t.splice(i,1),this.fragments[i].style._remove(),this.fragments.splice(i,1),this._reloadImports()),this}getImportIndex(t){const i=(this.stylesheet.imports||[]).findIndex((e=>e.id===t));return -1===i&&this.fire(new e.a7(new Error(`Import '${t}' does not exist in the map's style and cannot be updated.`))),i}getLayer(e){return this._mergedLayers[e]}getSources(){const e=[];for(const t in this._mergedOtherSourceCaches){const i=this._mergedOtherSourceCaches[t];i&&e.push(i.getSource());}return e}getSource(e,t){const i=this.getSourceCache(e,t);return i&&i.getSource()}getLayerSource(e){const t=this.getLayerSourceCache(e);return t&&t.getSource()}getSourceCache(t,i){const o=e.aE(t,i);return this._mergedOtherSourceCaches[o]}getLayerSourceCache(t){const i=e.aE(t.source,t.scope);return \"symbol\"===t.type?this._mergedSymbolSourceCaches[i]:this._mergedOtherSourceCaches[i]}getSourceCaches(e){const t=[];return this._mergedOtherSourceCaches[e]&&t.push(this._mergedOtherSourceCaches[e]),this._mergedSymbolSourceCaches[e]&&t.push(this._mergedSymbolSourceCaches[e]),t}updateSourceCaches(){const e=this._changes.getUpdatedSourceCaches();for(const t in e){const i=e[t];\"reload\"===i?this.reloadSource(t):\"clear\"===i&&this.clearSource(t);}}updateLayers(e){const t=this._changes.getUpdatedPaintProperties();for(const i of t){const t=this.getLayer(i);t&&t.updateTransitions(e);}}getImages(e,t,i){this.imageManager.getImages(t.icons,t.scope,i),this._updateTilesForChangedImages();const o=e=>{e&&e.setDependencies(t.tileID.key,t.type,t.icons);};o(this._otherSourceCaches[t.source]),o(this._symbolSourceCaches[t.source]);}getGlyphs(e,t,i){this.glyphManager.getGlyphs(t.stacks,t.scope,i);}getResource(t,i,o){return e.cD(i,o)}getOwnSourceCache(e){return this._otherSourceCaches[e]}getOwnLayerSourceCache(e){return \"symbol\"===e.type?this._symbolSourceCaches[e.source]:this._otherSourceCaches[e.source]}getOwnSourceCaches(e){const t=[];return this._otherSourceCaches[e]&&t.push(this._otherSourceCaches[e]),this._symbolSourceCaches[e]&&t.push(this._symbolSourceCaches[e]),t}_isSourceCacheLoaded(t){const i=this.getOwnSourceCaches(t);return 0===i.length?(this.fire(new e.a7(new Error(`There is no source with ID '${t}'`))),!1):i.every((e=>e.loaded()))}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}_clearWorkerCaches(){this.dispatcher.broadcast(\"clearCaches\");}destroy(){this._clearWorkerCaches(),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain);}}function Ar(e,t){let i=!1,o=null;const r=()=>{o=null,i&&(e(),o=setTimeout(r,t),i=!1);};return ()=>(i=!0,o||r(),o)}Dr.getSourceType=function(e){return rt[e]},Dr.setSourceType=function(e,t){rt[e]=t;},Dr.registerForPluginStateChange=e.ci;class Rr{constructor(t){this._hashName=t&&encodeURIComponent(t),e.aR([\"_getCurrentHash\",\"_onHashChange\",\"_updateHash\"],this),this._updateHash=Ar(this._updateHashUnthrottled.bind(this),300);}addTo(e){return this._map=e,window.addEventListener(\"hashchange\",this._onHashChange,!1),e.on(\"moveend\",this._updateHash),this}remove(){return this._map?(this._map.off(\"moveend\",this._updateHash),window.removeEventListener(\"hashchange\",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const e=this._map;if(!e)return \"\";const t=zr(e);if(this._hashName){const e=this._hashName;let i=!1;const o=location.hash.slice(1).split(\"&\").map((o=>{const r=o.split(\"=\")[0];return r===e?(i=!0,`${r}=${t}`):o})).filter((e=>e));return i||o.push(`${e}=${t}`),`#${o.join(\"&\")}`}return `#${t}`}_getCurrentHash(){const e=location.hash.replace(\"#\",\"\");if(this._hashName){let t;return e.split(\"&\").map((e=>e.split(\"=\"))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||\"\").split(\"/\")}return e.split(\"/\")}_onHashChange(){const e=this._map;if(!e)return !1;const t=this._getCurrentHash();if(t.length>=3&&!t.some((e=>isNaN(e)))){const i=e.dragRotate.isEnabled()&&e.touchZoomRotate.isEnabled()?+(t[3]||0):e.getBearing();return e.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:i,pitch:+(t[4]||0)}),!0}return !1}_updateHashUnthrottled(){history.replaceState(history.state,\"\",location.href.replace(/(#.+)?$/,this.getHashString()));}}function zr(e,t){const i=e.getCenter(),o=Math.round(100*e.getZoom())/100,r=Math.ceil((o*Math.LN2+Math.log(512/360/.5))/Math.LN10),s=Math.pow(10,r),n=Math.round(i.lng*s)/s,a=Math.round(i.lat*s)/s,l=e.getBearing(),c=e.getPitch();let h=t?`/${n}/${a}/${o}`:`${o}/${a}/${n}`;return (l||c)&&(h+=\"/\"+Math.round(10*l)/10),c&&(h+=`/${Math.round(c)}`),h}const Or={linearity:.3,easing:e.cE(0,0,.3,1)},Fr=e.ak({deceleration:2500,maxSpeed:1400},Or),Br=e.ak({deceleration:20,maxSpeed:1400},Or),kr=e.ak({deceleration:1e3,maxSpeed:360},Or),Nr=e.ak({deceleration:1e3,maxSpeed:90},Or);class Ur{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(t){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:e.a4.now(),settings:t});}_drainInertiaBuffer(){const t=this._inertiaBuffer,i=e.a4.now();for(;t.length>0&&i-t[0].time>160;)t.shift();}_onMoveEnd(t){if(this._map._prefersReducedMotion())return;if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,pan:new e.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const s=jr(i.pan.mag(),o,e.ak({},Fr,t||{}));r.offset=i.pan.mult(s.amount/i.pan.mag()),r.center=this._map.transform.center,Gr(r,s);}if(i.zoom){const e=jr(i.zoom,o,Br);r.zoom=this._map.transform.zoom+e.amount,Gr(r,e);}if(i.bearing){const t=jr(i.bearing,o,kr);r.bearing=this._map.transform.bearing+e.c(t.amount,-179,179),Gr(r,t);}if(i.pitch){const e=jr(i.pitch,o,Nr);r.pitch=this._map.transform.pitch+e.amount,Gr(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),r.noMoveStart=!0,r}}function Gr(e,t){(!e.duration||e.durationi.unproject(e))),a=s.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new e.P(0,0));super(t,{points:s,point:a,lngLats:n,lngLat:i.unproject(a),originalEvent:o}),this._defaultPrevented=!1;}}class Wr extends e.a8{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Hr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){this._mousedownPos=void 0;}wheel(e){return this._firePreventable(new Wr(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new Vr(e.type,this._map,e))}mouseup(e){this._map.fire(new Vr(e.type,this._map,e));}preclick(t){const i=e.ak({},t);i.type=\"preclick\",this._map.fire(new Vr(i.type,this._map,i));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||(this.preclick(e),this._map.fire(new Vr(e.type,this._map,e)));}dblclick(e){return this._firePreventable(new Vr(e.type,this._map,e))}mouseover(e){this._map.fire(new Vr(e.type,this._map,e));}mouseout(e){this._map.fire(new Vr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Zr(e.type,this._map,e))}touchmove(e){this._map.fire(new Zr(e.type,this._map,e));}touchend(e){this._map.fire(new Zr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Zr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class qr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0;}mousemove(e){this._map.fire(new Vr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Vr(\"contextmenu\",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._map.fire(new Vr(e.type,this._map,e)),this._map.listens(\"contextmenu\")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class $r{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(h(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t,o=this._startPos,r=this._lastPos;if(!o||!r||r.equals(i)||!this._box&&i.dist(o){this._box&&(this._box.style.transform=`translate(${n}px,${l}px)`,this._box.style.width=a-n+\"px\",this._box.style.height=c-l+\"px\");}));}mouseupWindow(t,i){if(!this._active)return;const o=this._startPos,r=i;if(o&&0===t.button){if(this.reset(),u(),o.x!==r.x||o.y!==r.y)return this._map.fire(new e.a8(\"boxzoomend\",{originalEvent:t})),{cameraAnimation:e=>e.fitScreenCoordinates(o,r,this._map.getBearing(),{linear:!1})};this._fireEvent(\"boxzoomcancel\",t);}}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent(\"boxzoomcancel\",e));}blur(){this.reset();}reset(){this._active=!1,this._container.classList.remove(\"mapboxgl-crosshair\"),this._box&&(this._box.remove(),this._box=null),_(),delete this._startPos,delete this._lastPos;}_fireEvent(t,i){return this._map.fire(new e.a8(t,{originalEvent:i}))}}function Xr(e,t){const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(0===this.startTime&&(this.startTime=t.timeStamp),o.length===this.numTouches&&(this.centroid=function(t){const i=new e.P(0,0);for(const e of t)i._add(e);return i.div(t.length)}(i),this.touches=Xr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=Xr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Yr{constructor(e){this.singleTap=new Jr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Kr{constructor(){this._zoomIn=new Yr({numTouches:1,numTaps:2}),this._zoomOut=new Yr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i);return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:t.getZoom()+1,around:t.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:t.getZoom()-1,around:t.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}const Qr={0:1,2:2};class es{constructor(e){this.reset(),this._clickTolerance=e.clickTolerance||1;}blur(){this.reset();}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0;}_correctButton(e,t){return !1}_move(e,t){return {}}mousedown(e,t){if(this._lastPoint)return;const i=f(e);this._correctButton(e,i)&&(this._lastPoint=t,this._eventButton=i);}mousemoveWindow(e,t){const i=this._lastPoint;if(i)if(e.preventDefault(),null!=this._eventButton&&function(e,t){const i=Qr[t];return void 0===e.buttons||(e.buttons&i)!==i}(e,this._eventButton))this.reset();else if(this._moved||!(t.dist(i)0&&(this._active=!0);const r=Xr(o,i),s=new e.P(0,0),n=new e.P(0,0);let a=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(s._add(t),n._add(t.sub(i)),a++,r[e]=t);}if(this._touches=r,a{this._alertContainer.classList.remove(\"mapboxgl-touch-pan-blocker-show\"),this._alertContainer.removeAttribute(\"role\");}),500);}}class ss{constructor(){this.reset();}reset(){this._active=!1,this._firstTwoTouches=void 0;}_start(e){}_move(e,t,i){return {}}touchstart(e,t,i){this._firstTwoTouches||i.length<2||(this._firstTwoTouches=[i[0].identifier,i[1].identifier],this._start([t[0],t[1]]));}touchmove(e,t,i){const o=this._firstTwoTouches;if(!o)return;e.preventDefault();const[r,s]=o,n=ns(i,t,r),a=ns(i,t,s);if(!n||!a)return;const l=this._aroundCenter?null:n.add(a).div(2);return this._move([n,a],l,e)}touchend(e,t,i){if(!this._firstTwoTouches)return;const[o,r]=this._firstTwoTouches,s=ns(i,t,o),n=ns(i,t,r);s&&n||(this._active&&u(),this.reset());}touchcancel(){this.reset();}enable(e){this._enabled=!0,this._aroundCenter=!!e&&\"center\"===e.around;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}function ns(e,t,i){for(let o=0;oMath.abs(e.x)}class ds extends ss{constructor(e){super(),this._map=e;}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0;}_start(e){this._lastPoints=e,_s(e[0].sub(e[1]))&&(this._valid=!1);}_move(t,i,o){const r=this._lastPoints;if(!r)return;const s=t[0].sub(r[0]),n=t[1].sub(r[1]);return this._map._cooperativeGestures&&!e.cF()&&o.touches.length<3||(this._valid=this.gestureBeginsVertically(s,n,o.timeStamp),!this._valid)?void 0:(this._lastPoints=t,this._active=!0,{pitchDelta:(s.y+n.y)/2*-.5})}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return null==this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const s=e.y>0==t.y>0;return _s(e)&&_s(t)&&s}}const us={panStep:100,bearingStep:15,pitchStep:10};class ps{constructor(){const e=us;this._panStep=e.panStep,this._bearingStep=e.bearingStep,this._pitchStep=e.pitchStep,this._rotationDisabled=!1;}blur(){this.reset();}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,s=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),s=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),s=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:n=>{const a=n.getZoom();n.easeTo({duration:300,easeId:\"keyboardHandler\",easing:ms,zoom:t?Math.round(a)+t*(e.shiftKey?2:1):a,bearing:n.getBearing()+i*this._bearingStep,pitch:n.getPitch()+o*this._pitchStep,offset:[-r*this._panStep,-s*this._panStep],center:n.getCenter()},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ms(e){return e*(2-e)}const fs=4.000244140625;class gs{constructor(t,i){this._map=t,this._el=t.getCanvasContainer(),this._handler=i,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222,e.aR([\"_onTimeout\",\"_addScrollZoomBlocker\",\"_showBlockerAlert\"],this);}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&\"center\"===e.around,this._map._cooperativeGestures&&this._addScrollZoomBlocker());}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()));}wheel(t){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(t.ctrlKey||t.metaKey||this.isZooming()||e.cF()))return void this._showBlockerAlert();\"hidden\"!==this._alertContainer.style.visibility&&(this._alertContainer.style.visibility=\"hidden\",clearTimeout(this._alertTimer));}let i=t.deltaMode===WheelEvent.DOM_DELTA_LINE?40*t.deltaY:t.deltaY;const o=e.a4.now(),r=o-(this._lastWheelEventTime||0);this._lastWheelEventTime=o,0!==i&&i%fs==0?this._type=\"wheel\":0!==i&&Math.abs(i)<4?this._type=\"trackpad\":r>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(r*i)<200?\"trackpad\":\"wheel\",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),t.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=t,this._delta-=i,this._active||this._start(t)),t.preventDefault();}_onTimeout(e){this._type=\"wheel\",this._delta-=this._lastValue,this._active||this._start(e);}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const t=p(this._el,e);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:t,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const t=this._map.transform;\"wheel\"===this._type&&t.projection.wrap&&(t._center.lng>=180||t._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const i=()=>t._terrainEnabled()&&this._aroundCoord?t.computeZoomRelativeTo(this._aroundCoord):t.zoom;if(0!==this._delta){const e=\"wheel\"===this._type&&Math.abs(this._delta)>fs?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==o&&(o=1/o);const r=i(),s=Math.pow(2,r),n=\"number\"==typeof this._targetZoom?t.zoomScale(this._targetZoom):s;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(n*o))),\"wheel\"===this._type&&(this._startZoom=r,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0;}const o=\"number\"==typeof this._targetZoom?this._targetZoom:i(),r=this._startZoom,s=this._easing;let n,a=!1;if(\"wheel\"===this._type&&r&&s){const t=Math.min((e.a4.now()-this._lastWheelEventTime)/200,1),i=s(t);n=e.n(r,o,i),t<1?this._frameId||(this._frameId=!0):a=!0;}else n=o,a=!0;this._active=!0,a&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout;}),200));let l=n-i();return l*this._lastDelta<0&&(l=0),{noInertia:!0,needsRenderFrame:!a,zoomDelta:l,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(t){let i=e.cG;if(this._prevEase){const t=this._prevEase,o=(e.a4.now()-t.start)/t.duration,r=t.easing(o+.01)-t.easing(o),s=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-s*s);i=e.cE(s,n,.25,1);}return this._prevEase={start:e.a4.now(),duration:t,easing:i},i}blur(){this.reset();}reset(){this._active=!1;}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=s(\"div\",\"mapboxgl-scroll-zoom-blocker\",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.test(navigator.userAgent)?this._map._getUIString(\"ScrollZoomBlocker.CmdMessage\"):this._map._getUIString(\"ScrollZoomBlocker.CtrlMessage\"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`);}_showBlockerAlert(){this._alertContainer.style.visibility=\"visible\",this._alertContainer.classList.add(\"mapboxgl-scroll-zoom-blocker-show\"),this._alertContainer.setAttribute(\"role\",\"alert\"),clearTimeout(this._alertTimer),this._alertTimer=setTimeout((()=>{this._alertContainer.classList.remove(\"mapboxgl-scroll-zoom-blocker-show\"),this._alertContainer.removeAttribute(\"role\");}),200);}}class vs{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xs{constructor(){this.reset();}reset(){this._active=!1;}blur(){this.reset();}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:i.getZoom()+(e.shiftKey?-1:1),around:i.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ys{constructor(){this._tap=new Yr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset();}touchstart(e,t,i){this._swipePoint||(this._tapTime&&e.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=t[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(e,t,i));}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(e,t,i)&&(this._tapTime=e.timeStamp);}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class bs{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add(\"mapboxgl-touch-drag-pan\");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove(\"mapboxgl-touch-drag-pan\");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class ws{constructor(e,t,i){this._pitchWithRotate=e.pitchWithRotate,this._mouseRotate=t,this._mousePitch=i;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class Ts{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add(\"mapboxgl-touch-zoom-rotate\");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove(\"mapboxgl-touch-zoom-rotate\");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}const Es=e=>e.zoom||e.drag||e.pitch||e.rotate;class Cs extends e.a8{}class Is{constructor(){this.constants=[1,1,.01],this.radius=0;}setup(t,i){const o=e.v.sub([],i,t);this.radius=e.v.length(o[2]<0?e.v.div([],o,this.constants):[o[0],o[1],0]);}projectRay(t){e.v.div(t,t,this.constants),e.v.normalize(t,t),e.v.mul(t,t,this.constants);const i=e.v.scale([],t,this.radius);if(i[2]>0){const t=e.v.scale([],[0,0,1],e.v.dot(i,[0,0,1])),o=e.v.scale([],e.v.normalize([],[i[0],i[1],0]),this.radius),r=e.v.add([],i,e.v.scale([],e.v.sub([],e.v.add([],o,t),i),2));i[0]=r[0],i[1]=r[1];}return i}}function Ss(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta}class Ms{constructor(t,i){this._map=t,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ur(t),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Is,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(i),e.aR([\"handleEvent\",\"handleWindowEvent\"],this);const o=this._el;this._listeners=[[o,\"touchstart\",{passive:!0}],[o,\"touchmove\",{passive:!1}],[o,\"touchend\",void 0],[o,\"touchcancel\",void 0],[o,\"mousedown\",void 0],[o,\"mousemove\",void 0],[o,\"mouseup\",void 0],[document,\"mousemove\",{capture:!0}],[document,\"mouseup\",void 0],[o,\"mouseover\",void 0],[o,\"mouseout\",void 0],[o,\"dblclick\",void 0],[o,\"click\",void 0],[o,\"keydown\",{capture:!1}],[o,\"keyup\",void 0],[o,\"wheel\",{passive:!1}],[o,\"contextmenu\",void 0],[window,\"blur\",void 0]];for(const[e,t,i]of this._listeners){const o=e===document?this.handleWindowEvent:this.handleEvent;e.addEventListener(t,o,i);}}destroy(){for(const[e,t,i]of this._listeners){const o=e===document?this.handleWindowEvent:this.handleEvent;e.removeEventListener(t,o,i);}}_addDefaultHandlers(e){const t=this._map,i=t.getCanvasContainer();this._add(\"mapEvent\",new Hr(t,e));const o=t.boxZoom=new $r(t,e);this._add(\"boxZoom\",o);const r=new Kr,s=new xs;t.doubleClickZoom=new vs(s,r),this._add(\"tapZoom\",r),this._add(\"clickZoom\",s);const n=new ys;this._add(\"tapDragZoom\",n);const a=t.touchPitch=new ds(t);this._add(\"touchPitch\",a);const l=new is(e),c=new os(e);t.dragRotate=new ws(e,l,c),this._add(\"mouseRotate\",l,[\"mousePitch\"]),this._add(\"mousePitch\",c,[\"mouseRotate\"]);const h=new ts(e),_=new rs(t,e);t.dragPan=new bs(i,h,_),this._add(\"mousePan\",h),this._add(\"touchPan\",_,[\"touchZoom\",\"touchRotate\"]);const d=new hs,u=new ls;t.touchZoomRotate=new Ts(i,u,d,n),this._add(\"touchRotate\",d,[\"touchPan\",\"touchZoom\"]),this._add(\"touchZoom\",u,[\"touchPan\",\"touchRotate\"]),this._add(\"blockableMapEvent\",new qr(t));const p=t.scrollZoom=new gs(t,this);this._add(\"scrollZoom\",p,[\"mousePan\"]);const m=t.keyboard=new ps;this._add(\"keyboard\",m);for(const i of [\"boxZoom\",\"doubleClickZoom\",\"tapDragZoom\",\"touchPitch\",\"dragRotate\",\"dragPan\",\"touchZoomRotate\",\"scrollZoom\",\"keyboard\"])e.interactive&&e[i]&&t[i].enable(e[i]);}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[],this._originalZoom=void 0;}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return !!Es(this._eventsInProgress)||this.isZooming()}_isDragging(){return !!this._eventsInProgress.drag}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}handleWindowEvent(e){this.handleEvent(e,`${e.type}Window`);}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}handleEvent(e,t){this._updatingCamera=!0;const i=\"renderFrame\"===e.type,o=i?void 0:e,r={needsRenderFrame:!1},s={},n={},a=e.touches?this._getMapTouches(e.touches):void 0,l=a?m(this._el,a):i?void 0:p(this._el,e);for(const{handlerName:i,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let _;this._blockedByActive(n,h,i)?c.reset():c[t||e.type]&&(_=c[t||e.type](e,l,a),this.mergeHandlerResult(r,s,_,i,o),_&&_.needsRenderFrame&&this._triggerRenderFrame()),(_||c.isActive())&&(n[i]=c);}const c={};for(const e in this._previousActiveHandlers)n[e]||(c[e]=o);this._previousActiveHandlers=n,(Object.keys(c).length||Ss(r))&&(this._changes.push([r,s,c]),this._triggerRenderFrame()),(Object.keys(n).length||Ss(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:h}=r;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map));}mergeHandlerResult(t,i,o,r,s){if(!o)return;e.ak(t,o);const n={handlerName:r,originalEvent:o.originalEvent||s};void 0!==o.zoomDelta&&(i.zoom=n),void 0!==o.panDelta&&(i.drag=n),void 0!==o.pitchDelta&&(i.pitch=n),void 0!==o.bearingDelta&&(i.rotate=n);}_applyChanges(){const t={},i={},o={};for(const[r,s,n]of this._changes)r.panDelta&&(t.panDelta=(t.panDelta||new e.P(0,0))._add(r.panDelta)),r.zoomDelta&&(t.zoomDelta=(t.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(t.bearingDelta=(t.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(t.pitchDelta=(t.pitchDelta||0)+r.pitchDelta),void 0!==r.around&&(t.around=r.around),void 0!==r.aroundCoord&&(t.aroundCoord=r.aroundCoord),void 0!==r.pinchAround&&(t.pinchAround=r.pinchAround),r.noInertia&&(t.noInertia=r.noInertia),e.ak(i,s),e.ak(o,n);this._updateMapTransform(t,i,o),this._changes=[];}_updateMapTransform(t,i,o){const r=this._map,s=r.transform,n=e=>[e.x,e.y,e.z];if((e=>{const t=this._eventsInProgress.drag;return t&&!this._handlersById[t.handlerName].isActive()})()&&!Ss(t)){const e=s.zoom;s.cameraElevationReference=\"sea\",null!=this._originalZoom&&s._orthographicProjectionAtLowPitch&&\"globe\"!==s.projection.name&&0===s.pitch?(s.cameraElevationReference=\"ground\",s.zoom=this._originalZoom):(s.recenterOnTerrain(),s.cameraElevationReference=\"ground\"),e!==s.zoom&&this._map._update(!0);}if(s._isCameraConstrained&&r._stop(!0),!Ss(t))return void this._fireEvents(i,o,!0);let{panDelta:a,zoomDelta:l,bearingDelta:c,pitchDelta:h,around:_,aroundCoord:d,pinchAround:u}=t;s._isCameraConstrained&&(l>0&&(l=0),s._isCameraConstrained=!1),void 0!==u&&(_=u),(l||(e=>i[e]&&!this._eventsInProgress[e])(\"drag\"))&&_&&(this._dragOrigin=n(s.pointCoordinate3D(_)),this._originalZoom=s.zoom,this._trackingEllipsoid.setup(s._camera.position,this._dragOrigin)),s.cameraElevationReference=\"sea\",r._stop(!0),_=_||r.transform.centerPoint,c&&(s.bearing+=c),h&&(s.pitch+=h),s._updateCameraState();const p=[0,0,0];if(a)if(\"mercator\"===s.projection.name){const e=this._trackingEllipsoid.projectRay(s.screenPointToMercatorRay(_).dir),t=this._trackingEllipsoid.projectRay(s.screenPointToMercatorRay(_.sub(a)).dir);p[0]=t[0]-e[0],p[1]=t[1]-e[1];}else {const t=s.pointCoordinate(_);if(\"globe\"===s.projection.name){a=a.rotate(-s.angle);const i=s._pixelsPerMercatorPixel/s.worldSize;p[0]=-a.x*e.cH(e.l(t.y))*i,p[1]=-a.y*e.cH(s.center.lat)*i;}else {const e=s.pointCoordinate(_.sub(a));t&&e&&(p[0]=e.x-t.x,p[1]=e.y-t.y);}}const m=s.zoom,f=[0,0,0];if(l){const t=n(d||s.pointCoordinate3D(_)),i={dir:e.v.normalize([],e.v.sub([],t,s._camera.position))};if(i.dir[2]<0){const o=s.zoomDeltaToMovement(t,l);e.v.scale(f,i.dir,o);}}const g=e.v.add(p,p,f);s._translateCameraConstrained(g),l&&Math.abs(s.zoom-m)>1e-4&&s.recenterOnTerrain(),s.cameraElevationReference=\"ground\",this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(i,o,!0);}_fireEvents(t,i,o){const r=Es(this._eventsInProgress),s=Es(t),n={};for(const e in t){const{originalEvent:i}=t[e];this._eventsInProgress[e]||(n[`${e}start`]=i),this._eventsInProgress[e]=t[e];}!r&&s&&this._fireEvent(\"movestart\",s.originalEvent);for(const e in n)this._fireEvent(e,n[e]);s&&this._fireEvent(\"move\",s.originalEvent);for(const e in t){const{originalEvent:i}=t[e];this._fireEvent(e,i);}const a={};let l;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],l=i[t]||o,a[`${e}end`]=l);}for(const e in a)this._fireEvent(e,a[e]);const c=Es(this._eventsInProgress);if(o&&(r||s)&&!c){this._updatingCamera=!0;const t=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new Cs(\"renderFrame\",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}const Ls=\"map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.\";class Ps extends e.a6{constructor(t,i){super(),this._moving=!1,this._zooming=!1,this.transform=t,this._bearingSnap=i.bearingSnap,this._respectPrefersReducedMotion=!1!==i.respectPrefersReducedMotion,e.aR([\"_renderFrameCallback\"],this);}getCenter(){return new e.L(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}panBy(t,i,o){return t=e.P.convert(t).mult(-1),this.panTo(this.transform.center,e.ak({offset:t},i),o)}panTo(t,i,o){return this.easeTo(e.ak({center:t},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(t,i,o){return this.easeTo(e.ak({zoom:t},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(t,i,o){return this.easeTo(e.ak({bearing:t},i),o)}resetNorth(t,i){return this.rotateTo(0,e.ak({duration:1e3},t),i),this}resetNorthPitch(t,i){return this.easeTo(e.ak({bearing:0,pitch:0,duration:1e3},t),i),this}snapToNorth(e,t){return Math.abs(this.getBearing())e.aspect?i/(2*Math.tan(.5*e.fovX)*e.aspect):o/(2*Math.tan(.5*e.fovY)*e.aspect)}_cameraForBoundsOnGlobe(t,i,o,r,s,n){const a=t.clone(),l=this._extendCameraOptions(n);a.bearing=r,a.pitch=s;const c=e.L.convert(i),h=e.L.convert(o),_=.5*(c.lat+h.lat),d=.5*(c.lng+h.lng),u=e.cI(_,d),p=e.v.normalize([],u),m=e.v.normalize([],e.v.cross([],p,[0,1,0])),f=e.v.cross([],m,p),g=[m[0],m[1],m[2],0,f[0],f[1],f[2],0,p[0],p[1],p[2],0,0,0,0,1],v=[u,e.cI(c.lat,c.lng),e.cI(h.lat,c.lng),e.cI(h.lat,h.lng),e.cI(c.lat,h.lng),e.cI(_,c.lng),e.cI(_,h.lng),e.cI(c.lat,d),e.cI(h.lat,d)];let x=e.c3.fromPoints(v.map((t=>[e.v.dot(m,t),e.v.dot(f,t),e.v.dot(p,t)])));const y=e.v.transformMat4([],x.center,g);0===e.v.squaredLength(y)&&e.v.set(y,0,0,1),e.v.normalize(y,y),e.v.scale(y,y,e.aC),a.center=e.cJ(y);const b=a.getWorldToCameraMatrix(),w=e.m.invert(new Float64Array(16),b);x=e.c3.applyTransform(x,e.m.multiply([],b,g)),e.v.transformMat4(y,y,b);const T=.5*(x.max[2]-x.min[2]),E=this._minimumAABBFrustumDistance(a,x),C=e.v.scale([],[0,0,1],T),I=e.v.add(C,y,C),S=E+(0===a.pitch?0:e.v.distance(y,I)),M=a.globeCenterInViewSpace,L=e.v.sub([],y,[M[0],M[1],M[2]]);e.v.normalize(L,L),e.v.scale(L,L,S);const P=e.v.add([],y,L);e.v.transformMat4(P,P,w);const D=e.cL/e.aC,A=e.v.length(P),R=e.b(Math.max(A*D-e.cL,Number.EPSILON),0),z=Math.min(a.zoomFromMercatorZAdjusted(R),l.maxZoom);return z>.5*(e.Z+e.G)?(a.setProjection({name:\"mercator\"}),a.zoom=z,this._cameraForBounds(a,i,o,r,s,n)):{center:a.center,zoom:z,bearing:r,pitch:s}}queryTerrainElevation(t,i){const o=this.transform.elevation;return o?(i=e.ak({},{exaggerated:!0},i),o.getAtPoint(e.M.fromLngLat(t),null,i.exaggerated)):null}_cameraForBounds(t,i,o,r,s,n){if(\"globe\"===t.projection.name)return this._cameraForBoundsOnGlobe(t,i,o,r,s,n);const a=t.clone(),l=this._extendCameraOptions(n),c=a.padding;a.bearing=r,a.pitch=s;const h=e.L.convert(i),_=e.L.convert(o),d=new e.L(h.lng,_.lat),u=new e.L(_.lng,h.lat),p=a.project(h),m=a.project(_),f=this.queryTerrainElevation(h),g=this.queryTerrainElevation(_),v=this.queryTerrainElevation(d),x=this.queryTerrainElevation(u),y=[[p.x,p.y,Math.min(f||0,g||0,v||0,x||0)],[m.x,m.y,Math.max(f||0,g||0,v||0,x||0)]];let b=e.c3.fromPoints(y);const w=a.getWorldToCameraMatrix(),T=e.m.invert(new Float64Array(16),w);b=e.c3.applyTransform(b,w);const E=e.v.sub([],b.max,b.min),C=c.left||0,I=c.right||0,S=c.bottom||0,M=c.top||0,{left:L,right:P,top:D,bottom:A}=l.padding,R=.5*(C+I),z=.5*(M+S),O=Math.min(a.scaleZoom(a.scale*Math.min((a.width-(C+I+L+P))/E[0],(a.height-(S+M+A+D))/E[1])),l.maxZoom),F=a.scale/a.zoomScale(O);b=new e.c3([b.min[0]-(L+R)*F,b.min[1]-(A+z)*F,b.min[2]],[b.max[0]+(P+R)*F,b.max[1]+(D+z)*F,b.max[2]]);const B=.5*E[2],k=this._minimumAABBFrustumDistance(a,b),N=[0,0,1,0];e.e.transformMat4(N,N,w),e.e.normalize(N,N);const U=e.v.scale([],N,k+B),G=e.v.add([],b.center,U),j=(\"number\"==typeof l.offset.x&&\"number\"==typeof l.offset.y?new e.P(l.offset.x,l.offset.y):e.P.convert(l.offset)).rotate(-e.d(r));b.center[0]-=j.x*F,b.center[1]+=j.y*F,e.v.transformMat4(b.center,b.center,T),e.v.transformMat4(G,G,T);const V=[b.center[0],b.center[1],G[2]*a.pixelsPerMeter];e.v.scale(V,V,1/a.worldSize);const Z=e.cK(V[0]),W=e.l(V[1]),H=Math.min(a._zoomFromMercatorZ(V[2]),l.maxZoom),q=new e.L(Z,W);return a.mercatorFromTransition&&H<.5*(e.Z+e.G)?(a.setProjection({name:\"globe\"}),a.zoom=H,this._cameraForBounds(a,i,o,r,s,n)):{center:q,zoom:H,bearing:r,pitch:s}}fitBounds(e,t,i){const o=this.cameraForBounds(e,t);return this._fitInternal(o,t,i)}fitScreenCoordinates(t,i,o,r,s){const n=e.P.convert(t),a=e.P.convert(i),l=new e.P(Math.min(n.x,a.x),Math.min(n.y,a.y)),c=new e.P(Math.max(n.x,a.x),Math.max(n.y,a.y));if(\"mercator\"===this.transform.projection.name&&this.transform.anyCornerOffEdge(n,a))return this;const h=this.transform.pointLocation3D(l),_=this.transform.pointLocation3D(c),d=this.transform.pointLocation3D(new e.P(l.x,c.y)),u=this.transform.pointLocation3D(new e.P(c.x,l.y)),p=[Math.min(h.lng,_.lng,d.lng,u.lng),Math.min(h.lat,_.lat,d.lat,u.lat)],m=[Math.max(h.lng,_.lng,d.lng,u.lng),Math.max(h.lat,_.lat,d.lat,u.lat)],f=r&&r.pitch?r.pitch:this.getPitch(),g=this._cameraForBounds(this.transform,p,m,o,f,r);return this._fitInternal(g,r,s)}_fitInternal(t,i,o){return t?(delete(i=e.ak(t,i)).padding,i.linear?this.easeTo(i,o):this.flyTo(i,o)):this}jumpTo(t,i){this.stop();const o=t.preloadOnly?this.transform.clone():this.transform;let r=!1,s=!1,n=!1;return \"zoom\"in t&&o.zoom!==+t.zoom&&(r=!0,o.zoom=+t.zoom),void 0!==t.center&&(o.center=e.L.convert(t.center)),\"bearing\"in t&&o.bearing!==+t.bearing&&(s=!0,o.bearing=+t.bearing),\"pitch\"in t&&o.pitch!==+t.pitch&&(n=!0,o.pitch=+t.pitch),null==t.padding||o.isPaddingEqual(t.padding)||(o.padding=t.padding),t.preloadOnly?(this._preloadTiles(o),this):(this.fire(new e.a8(\"movestart\",i)).fire(new e.a8(\"move\",i)),r&&this.fire(new e.a8(\"zoomstart\",i)).fire(new e.a8(\"zoom\",i)).fire(new e.a8(\"zoomend\",i)),s&&this.fire(new e.a8(\"rotatestart\",i)).fire(new e.a8(\"rotate\",i)).fire(new e.a8(\"rotateend\",i)),n&&this.fire(new e.a8(\"pitchstart\",i)).fire(new e.a8(\"pitch\",i)).fire(new e.a8(\"pitchend\",i)),this.fire(new e.a8(\"moveend\",i)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||e.X(Ls),this.transform.getFreeCameraOptions()}setFreeCameraOptions(t,i){const o=this.transform;if(!o.projection.supportsFreeCamera)return e.X(Ls),this;this.stop();const r=o.zoom,s=o.pitch,n=o.bearing;o.setFreeCameraOptions(t);const a=r!==o.zoom,l=s!==o.pitch,c=n!==o.bearing;return this.fire(new e.a8(\"movestart\",i)).fire(new e.a8(\"move\",i)),a&&this.fire(new e.a8(\"zoomstart\",i)).fire(new e.a8(\"zoom\",i)).fire(new e.a8(\"zoomend\",i)),c&&this.fire(new e.a8(\"rotatestart\",i)).fire(new e.a8(\"rotate\",i)).fire(new e.a8(\"rotateend\",i)),l&&this.fire(new e.a8(\"pitchstart\",i)).fire(new e.a8(\"pitch\",i)).fire(new e.a8(\"pitchend\",i)),this.fire(new e.a8(\"moveend\",i)),this}easeTo(t,i){this._stop(!1,t.easeId),(!1===(t=e.ak({offset:[0,0],duration:500,easing:e.cG},t)).animate||this._prefersReducedMotion(t))&&(t.duration=0);const o=this.transform,r=this.getZoom(),s=this.getBearing(),n=this.getPitch(),a=this.getPadding(),l=\"zoom\"in t?+t.zoom:r,c=\"bearing\"in t?this._normalizeBearing(t.bearing,s):s,h=\"pitch\"in t?+t.pitch:n,_=\"padding\"in t?t.padding:o.padding,d=e.P.convert(t.offset);let u,p,m;if(\"globe\"===o.projection.name){const i=e.M.fromLngLat(o.center),r=d.rotate(-o.angle);i.x+=r.x/o.worldSize,i.y+=r.y/o.worldSize;const s=i.toLngLat(),n=e.L.convert(t.center||s);this._normalizeCenter(n),u=o.centerPoint.add(r),p=new e.P(i.x,i.y).mult(o.worldSize),m=new e.P(e.E(n.lng),e.H(n.lat)).mult(o.worldSize).sub(p);}else {u=o.centerPoint.add(d);const i=o.pointLocation(u),r=e.L.convert(t.center||i);this._normalizeCenter(r),p=o.project(i),m=o.project(r).sub(p);}const f=o.zoomScale(l-r);let g,v;t.around&&(g=e.L.convert(t.around),v=o.locationPoint(g));const x=this._zooming||l!==r,y=this._rotating||s!==c,b=this._pitching||h!==n,w=!o.isPaddingEqual(_),T=o=>T=>{if(x&&(o.zoom=e.n(r,l,T)),y&&(o.bearing=e.n(s,c,T)),b&&(o.pitch=e.n(n,h,T)),w&&(o.interpolatePadding(a,_,T),u=o.centerPoint.add(d)),g)o.setLocationAtPoint(g,v);else {const e=o.zoomScale(o.zoom-r),t=l>r?Math.min(2,f):Math.max(.5,f),i=Math.pow(t,1-T),s=o.unproject(p.add(m.mult(T*i)).mult(e));o.setLocationAtPoint(o.renderWorldCopies?s.wrap():s,u);}return t.preloadOnly||this._fireMoveEvents(i),o};if(t.preloadOnly){const e=this._emulate(T,t.duration,o);return this._preloadTiles(e),this}const E={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=x,this._rotating=y,this._pitching=b,this._easeId=t.easeId,this._prepareEase(i,t.noMoveStart,E),this._ease(T(o),(e=>{\"sea\"===o.cameraElevationReference&&o.recenterOnTerrain(),this._afterEase(i,e);}),t),this}_prepareEase(t,i,o={}){this._moving=!0,this.transform.cameraElevationReference=\"sea\",this.transform._orthographicProjectionAtLowPitch&&0===this.transform.pitch&&\"globe\"!==this.transform.projection.name&&(this.transform.cameraElevationReference=\"ground\"),i||o.moving||this.fire(new e.a8(\"movestart\",t)),this._zooming&&!o.zooming&&this.fire(new e.a8(\"zoomstart\",t)),this._rotating&&!o.rotating&&this.fire(new e.a8(\"rotatestart\",t)),this._pitching&&!o.pitching&&this.fire(new e.a8(\"pitchstart\",t));}_fireMoveEvents(t){this.fire(new e.a8(\"move\",t)),this._zooming&&this.fire(new e.a8(\"zoom\",t)),this._rotating&&this.fire(new e.a8(\"rotate\",t)),this._pitching&&this.fire(new e.a8(\"pitch\",t));}_afterEase(t,i){if(this._easeId&&i&&this._easeId===i)return;this._easeId=void 0,this.transform.cameraElevationReference=\"ground\";const o=this._zooming,r=this._rotating,s=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,o&&this.fire(new e.a8(\"zoomend\",t)),r&&this.fire(new e.a8(\"rotateend\",t)),s&&this.fire(new e.a8(\"pitchend\",t)),this.fire(new e.a8(\"moveend\",t));}flyTo(t,i){if(this._prefersReducedMotion(t)){const o=e.p(t,[\"center\",\"zoom\",\"bearing\",\"pitch\",\"around\"]);return this.jumpTo(o,i)}this.stop(),t=e.ak({offset:[0,0],speed:1.2,curve:1.42,easing:e.cG},t);const o=this.transform,r=this.getZoom(),s=this.getBearing(),n=this.getPitch(),a=\"zoom\"in t?e.c(+t.zoom,o.minZoom,o.maxZoom):r,l=\"bearing\"in t?this._normalizeBearing(t.bearing,s):s,c=\"pitch\"in t?+t.pitch:n,h=o.zoomScale(a-r),_=e.P.convert(t.offset),d=o.centerPoint.add(_),u=o.pointLocation(d);let p=t.center;if(p&&t.padding){const e=this._cameraForBounds(this.transform,p,p,l,c,t);e&&(p=e.center);}p=e.L.convert(p||u),this._normalizeCenter(p);const m=o.project(u),f=o.project(p).sub(m);let g=t.curve;const v=Math.max(o.width,o.height),x=v/h,y=f.mag();if(\"minZoom\"in t){const i=e.c(Math.min(t.minZoom,r,a),o.minZoom,o.maxZoom),s=v/o.zoomScale(i-r);g=Math.sqrt(s/y*2);}const b=g*g;function w(e){const t=(x*x-v*v+(e?-1:1)*b*b*y*y)/(2*(e?x:v)*b*y);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function E(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(0);let I=function(e){return E(C)/E(C+g*e)},S=function(e){return v*((E(C)*(T(t=C+g*e)/E(t))-T(C))/b)/y;var t;},M=(w(1)-C)/g;if(Math.abs(y)<1e-6||!isFinite(M)){if(Math.abs(v-x)<1e-6)return this.easeTo(t,i);const e=xt.maxDuration&&(t.duration=0);const L=s!==l,P=c!==n,D=o=>h=>{const _=h*M,u=1/I(_);o.zoom=1===h?a:r+o.scaleZoom(u),L&&(o.bearing=e.n(s,l,h)),P&&(o.pitch=e.n(n,c,h));const g=1===h?p:o.unproject(m.add(f.mult(S(_))).mult(u));return o.setLocationAtPoint(o.renderWorldCopies?g.wrap():g,d),o._updateCameraOnTerrain(),t.preloadOnly||this._fireMoveEvents(i),o};if(t.preloadOnly){const e=this._emulate(D,t.duration,o);return this._preloadTiles(e),this}return this._zooming=!0,this._rotating=L,this._pitching=P,this._prepareEase(i,!1),this._ease(D(o),(()=>this._afterEase(i)),t),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const e=this._onEaseEnd;this._onEaseEnd=void 0,e.call(this,t);}if(!e){const e=this.handlers;e&&e.stop(!1);}return this}_ease(t,i,o){!1===o.animate||0===o.duration?(t(1),i()):(this._easeStart=e.a4.now(),this._easeOptions=o,this._onEaseFrame=t,this._onEaseEnd=i,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_renderFrameCallback(){const t=Math.min((e.a4.now()-this._easeStart)/this._easeOptions.duration,1),i=this._onEaseFrame;i&&i(this._easeOptions.easing(t)),t<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();}_normalizeBearing(t,i){t=e.w(t,-180,180);const o=Math.abs(t-i);return Math.abs(t-360-i)180?-360:i<-180?360:0;}_prefersReducedMotion(t){return this._respectPrefersReducedMotion&&e.a4.prefersReducedMotion&&!(t&&t.essential)}_emulate(e,t,i){const o=Math.ceil(15*t/1e3),r=[],s=e(i.clone());for(let e=0;e<=o;e++){const t=s(e/o);r.push(t.clone());}return r}}class Ds{constructor(t={}){this.options=t,e.aR([\"_toggleAttribution\",\"_updateEditLink\",\"_updateData\",\"_updateCompact\"],this);}getDefaultPosition(){return \"bottom-right\"}onAdd(e){const t=this.options&&this.options.compact;return this._map=e,this._container=s(\"div\",\"mapboxgl-ctrl mapboxgl-ctrl-attrib\"),this._compactButton=s(\"button\",\"mapboxgl-ctrl-attrib-button\",this._container),s(\"span\",\"mapboxgl-ctrl-icon\",this._compactButton).setAttribute(\"aria-hidden\",\"true\"),this._compactButton.type=\"button\",this._compactButton.addEventListener(\"click\",this._toggleAttribution),this._setElementTitle(this._compactButton,\"ToggleAttribution\"),this._innerContainer=s(\"div\",\"mapboxgl-ctrl-attrib-inner\",this._container),t&&this._container.classList.add(\"mapboxgl-compact\"),this._updateAttributions(),this._updateEditLink(),this._map.on(\"styledata\",this._updateData),this._map.on(\"sourcedata\",this._updateData),this._map.on(\"moveend\",this._updateEditLink),void 0===t&&(this._map.on(\"resize\",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off(\"styledata\",this._updateData),this._map.off(\"sourcedata\",this._updateData),this._map.off(\"moveend\",this._updateEditLink),this._map.off(\"resize\",this._updateCompact),this._map=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.removeAttribute(\"title\"),e.firstElementChild&&e.firstElementChild.setAttribute(\"title\",i);}_toggleAttribution(){this._container.classList.contains(\"mapboxgl-compact-show\")?(this._container.classList.remove(\"mapboxgl-compact-show\"),this._compactButton.setAttribute(\"aria-expanded\",\"false\")):(this._container.classList.add(\"mapboxgl-compact-show\"),this._compactButton.setAttribute(\"aria-expanded\",\"true\"));}_updateEditLink(){let t=this._editLink;t||(t=this._editLink=this._container.querySelector(\".mapbox-improve-map\"));const i=[{key:\"owner\",value:this.styleOwner},{key:\"id\",value:this.styleId},{key:\"access_token\",value:this._map._requestManager._customAccessToken||e.cM.ACCESS_TOKEN}];if(t){const o=i.reduce(((e,t,o)=>(t.value&&(e+=`${t.key}=${t.value}${oe.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0})),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=[...this.options.customAttribution,...e]:e.unshift(this.options.customAttribution));const i=e.join(\" | \");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=i,this._container.classList.remove(\"mapboxgl-attrib-empty\")):this._container.classList.add(\"mapboxgl-attrib-empty\"),this._editLink=null);}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add(\"mapboxgl-compact\"):this._container.classList.remove(\"mapboxgl-compact\",\"mapboxgl-compact-show\");}}class As{constructor(){e.aR([\"_updateLogo\",\"_updateCompact\"],this);}onAdd(e){this._map=e,this._container=s(\"div\",\"mapboxgl-ctrl\");const t=s(\"a\",\"mapboxgl-ctrl-logo\");return t.target=\"_blank\",t.rel=\"noopener nofollow\",t.href=\"https://www.mapbox.com/\",t.setAttribute(\"aria-label\",this._map._getUIString(\"LogoControl.Title\")),t.setAttribute(\"rel\",\"noopener nofollow\"),this._container.appendChild(t),this._container.style.display=\"none\",this._map.on(\"sourcedata\",this._updateLogo),this._updateLogo(),this._map.on(\"resize\",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off(\"sourcedata\",this._updateLogo),this._map.off(\"resize\",this._updateCompact);}getDefaultPosition(){return \"bottom-left\"}_updateLogo(e){e&&\"metadata\"!==e.sourceDataType||(this._container.style.display=this._logoRequired()?\"block\":\"none\");}_logoRequired(){if(!this._map.style)return !0;const e=this._map.style._sourceCaches;if(0===Object.entries(e).length)return !0;for(const t in e){const i=e[t].getSource();if(i.hasOwnProperty(\"mapbox_logo\")&&!i.mapbox_logo)return !1}return !0}_updateCompact(){const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<250?t.classList.add(\"mapboxgl-compact\"):t.classList.remove(\"mapboxgl-compact\");}}}class Rs{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}function zs(t,i,o){if(t=new e.L(t.lng,t.lat),i){const r=new e.L(t.lng-360,t.lat),s=new e.L(t.lng+360,t.lat),n=360*Math.ceil(Math.abs(t.lng-o.center.lng)/360),a=o.locationPoint(t).distSqr(i),l=i.x<0||i.y<0||i.x>o.width||i.y>o.height;o.locationPoint(r).distSqr(i)180;){const e=o.locationPoint(t);if(e.x>=0&&e.y>=0&&e.x<=o.width&&e.y<=o.height)break;t.lng>o.center.lng?t.lng-=360:t.lng+=360;}return t}const Os={center:\"translate(-50%,-50%)\",top:\"translate(-50%,0)\",\"top-left\":\"translate(0,0)\",\"top-right\":\"translate(-100%,0)\",bottom:\"translate(-50%,-100%)\",\"bottom-left\":\"translate(0,-100%)\",\"bottom-right\":\"translate(-100%,-100%)\",left:\"translate(0,-50%)\",right:\"translate(-100%,-50%)\"};class Fs extends e.a6{constructor(t,i){if(super(),(t instanceof HTMLElement||i)&&(t=e.ak({element:t},i)),e.aR([\"_update\",\"_onMove\",\"_onUp\",\"_addDragHandler\",\"_onMapClick\",\"_onKeyPress\",\"_clearFadeTimer\"],this),this._anchor=t&&t.anchor||\"center\",this._color=t&&t.color||\"#3FB1CE\",this._scale=t&&t.scale||1,this._draggable=t&&t.draggable||!1,this._clickTolerance=t&&t.clickTolerance||0,this._isDragging=!1,this._state=\"inactive\",this._rotation=t&&t.rotation||0,this._rotationAlignment=t&&t.rotationAlignment||\"auto\",this._pitchAlignment=t&&t.pitchAlignment&&t.pitchAlignment||\"auto\",this._updateMoving=()=>this._update(!0),this._occludedOpacity=t&&t.occludedOpacity||.2,t&&t.element)this._element=t.element,this._offset=e.P.convert(t&&t.offset||[0,0]);else {this._defaultMarker=!0,this._element=s(\"div\");const i=41,o=27,r=n(\"svg\",{display:\"block\",height:i*this._scale+\"px\",width:o*this._scale+\"px\",viewBox:`0 0 ${o} ${i}`},this._element),a=n(\"radialGradient\",{id:\"shadowGradient\"},n(\"defs\",{},r));n(\"stop\",{offset:\"10%\",\"stop-opacity\":.4},a),n(\"stop\",{offset:\"100%\",\"stop-opacity\":.05},a),n(\"ellipse\",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:\"url(#shadowGradient)\"},r),n(\"path\",{fill:this._color,d:\"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z\"},r),n(\"path\",{opacity:.25,d:\"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z\"},r),n(\"circle\",{fill:\"white\",cx:13.5,cy:13.5,r:5.5},r),this._offset=e.P.convert(t&&t.offset||[0,-14]);}this._element.hasAttribute(\"aria-label\")||this._element.setAttribute(\"aria-label\",\"Map marker\"),this._element.hasAttribute(\"role\")||this._element.setAttribute(\"role\",\"img\"),this._element.classList.add(\"mapboxgl-marker\"),this._element.addEventListener(\"dragstart\",(e=>{e.preventDefault();})),this._element.addEventListener(\"mousedown\",(e=>{e.preventDefault();}));const o=this._element.classList;for(const e in Os)o.remove(`mapboxgl-marker-anchor-${e}`);o.add(`mapboxgl-marker-anchor-${this._anchor}`);const r=t&&t.className?t.className.trim().split(/\\s+/):[];o.add(...r),this._popup=null;}addTo(e){return e===this._map||(this.remove(),this._map=e,e.getCanvasContainer().appendChild(this._element),e.on(\"move\",this._updateMoving),e.on(\"moveend\",this._update),e.on(\"remove\",this._clearFadeTimer),e._addMarker(this),this.setDraggable(this._draggable),this._update(),e.on(\"click\",this._onMapClick)),this}remove(){const e=this._map;return e&&(e.off(\"click\",this._onMapClick),e.off(\"move\",this._updateMoving),e.off(\"moveend\",this._update),e.off(\"mousedown\",this._addDragHandler),e.off(\"touchstart\",this._addDragHandler),e.off(\"mouseup\",this._onUp),e.off(\"touchend\",this._onUp),e.off(\"mousemove\",this._onMove),e.off(\"touchmove\",this._onMove),e.off(\"remove\",this._clearFadeTimer),e._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=e.L.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute(\"role\"),this._element.removeEventListener(\"keypress\",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute(\"tabindex\")),e){if(!(\"offset\"in e.options)){const t=38.1,i=13.5,o=Math.sqrt(Math.pow(i,2)/2);e.options.offset=this._defaultMarker?{top:[0,0],\"top-left\":[0,0],\"top-right\":[0,0],bottom:[0,-t],\"bottom-left\":[o,-1*(t-i+o)],\"bottom-right\":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,e._marker=this,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute(\"role\",\"button\"),this._originalTabIndex=this._element.getAttribute(\"tabindex\"),this._originalTabIndex||this._element.setAttribute(\"tabindex\",\"0\"),this._element.addEventListener(\"keypress\",this._onKeyPress),this._element.setAttribute(\"aria-expanded\",\"false\");}return this}_onKeyPress(e){const t=e.code,i=e.charCode||e.keyCode;\"Space\"!==t&&\"Enter\"!==t&&32!==i&&13!==i||this.togglePopup();}_onMapClick(e){const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();}getPopup(){return this._popup}togglePopup(){const e=this._popup;return e?(e.isOpen()?(e.remove(),this._element.setAttribute(\"aria-expanded\",\"false\")):this._map&&(e.addTo(this._map),this._element.setAttribute(\"aria-expanded\",\"true\")),this):this}_behindTerrain(){const e=this._map,t=this._pos;if(!e||!t)return !1;const i=e.unproject(t),o=e.getFreeCameraOptions();if(!o.position)return !1;const r=o.position.toLngLat();return r.distanceTo(i)<.9*r.distanceTo(this._lngLat)}_evaluateOpacity(){const t=this._map;if(!t)return;const i=this._pos;if(!i||i.x<0||i.x>t.transform.width||i.y<0||i.y>t.transform.height)return void this._clearFadeTimer();const o=t.unproject(i);let r;t._showingGlobe()&&e.cN(t.transform,this._lngLat)?r=0:(r=1-t._queryFogOpacity(o),t.transform._terrainEnabled()&&t.getTerrain()&&this._behindTerrain()&&(r*=this._occludedOpacity)),this._element.style.opacity=`${r}`,this._element.style.pointerEvents=r>0?\"auto\":\"none\",this._popup&&this._popup._setOpacity(r),this._fadeTimer=null;}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null);}_updateDOM(){const e=this._pos;if(!e||!this._map)return;const t=this._offset.mult(this._scale);this._element.style.transform=`\\n translate(${e.x}px,${e.y}px)\\n ${Os[this._anchor]}\\n ${this._calculateXYTransform()} ${this._calculateZTransform()}\\n translate(${t.x}px,${t.y}px)\\n `;}_calculateXYTransform(){const t=this._pos,i=this._map,o=this.getPitchAlignment();if(!i||!t||\"map\"!==o)return \"\";if(!i._showingGlobe()){const e=i.getPitch();return e?`rotateX(${e}deg)`:\"\"}const r=e.Y(e.cO(i.transform,this._lngLat)),s=t.sub(e.cP(i.transform)),n=Math.abs(s.x)+Math.abs(s.y);if(0===n)return \"\";const a=r/n;return `rotateX(${-s.y*a}deg) rotateY(${s.x*a}deg)`}_calculateZTransform(){const t=this._pos,i=this._map;if(!i||!t)return \"\";let o=0;const r=this.getRotationAlignment();if(\"map\"===r)if(i._showingGlobe()){const t=i.project(new e.L(this._lngLat.lng,this._lngLat.lat+.001)),r=i.project(new e.L(this._lngLat.lng,this._lngLat.lat-.001)).sub(t);o=e.Y(Math.atan2(r.y,r.x))-90;}else o=-i.getBearing();else if(\"horizon\"===r){const r=e.an(4,6,i.getZoom()),s=e.cP(i.transform);s.y+=r*i.transform.height;const n=t.sub(s),a=e.Y(Math.atan2(n.y,n.x));o=(a>90?a-270:a+90)*(1-r);}return o+=this._rotation,o?`rotateZ(${o}deg)`:\"\"}_update(e){cancelAnimationFrame(this._updateFrameId);const t=this._map;t&&(t.transform.renderWorldCopies&&(this._lngLat=zs(this._lngLat,this._pos,t.transform)),this._pos=t.project(this._lngLat),!0===e?this._updateFrameId=requestAnimationFrame((()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM());})):this._pos=this._pos.round(),t._requestDomTask((()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(t._showingGlobe()||t.getTerrain()||t.getFog())&&!this._fadeTimer&&(this._fadeTimer=setTimeout(this._evaluateOpacity.bind(this),60)));})));}getOffset(){return this._offset}setOffset(t){return this._offset=e.P.convert(t),this._update(),this}addClassName(e){return this._element.classList.add(e),this}removeClassName(e){return this._element.classList.remove(e),this}toggleClassName(e){return this._element.classList.toggle(e)}_onMove(t){const i=this._map;if(!i)return;const o=this._pointerdownPos,r=this._positionDelta;if(o&&r){if(!this._isDragging){const e=this._clickTolerance||i._clickTolerance;if(t.point.dist(o)=this._endTime)return this._end;const i=e.ba((t-this._startTime)/(this._endTime-this._startTime));return this._start*(1-i)+this._end*i}isEasing(e){return e>=this._startTime&&e<=this._endTime}jumpTo(e){this._startTime=-1/0,this._endTime=-1/0,this._start=e,this._end=e;}easeTo(e,t,i){this._start=this.getValue(t),this._end=e,this._startTime=t,this._endTime=t+i;}}const Gs={\"AttributionControl.ToggleAttribution\":\"Toggle attribution\",\"AttributionControl.MapFeedback\":\"Map feedback\",\"FullscreenControl.Enter\":\"Enter fullscreen\",\"FullscreenControl.Exit\":\"Exit fullscreen\",\"GeolocateControl.FindMyLocation\":\"Find my location\",\"GeolocateControl.LocationNotAvailable\":\"Location not available\",\"LogoControl.Title\":\"Mapbox logo\",\"Map.Title\":\"Map\",\"NavigationControl.ResetBearing\":\"Reset bearing to north\",\"NavigationControl.ZoomIn\":\"Zoom in\",\"NavigationControl.ZoomOut\":\"Zoom out\",\"ScrollZoomBlocker.CtrlMessage\":\"Use ctrl + scroll to zoom the map\",\"ScrollZoomBlocker.CmdMessage\":\"Use ⌘ + scroll to zoom the map\",\"TouchPanBlocker.Message\":\"Use two fingers to move the map\"},js={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:\"sans-serif\",localFontFamily:null,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1};class Vs{constructor(){this.showOverdrawInspector=!1,this.showTileBoundaries=!1,this.continuousRedraw=!1,this.showTerrainWireframe=!1,this.showLayers2DWireframe=!1,this.showLayers3DWireframe=!1;}}const Zs={showCompass:!0,showZoom:!0,visualizePitch:!1};class Ws{constructor(t,i,o=!1){this._clickTolerance=10,this.element=i,this.mouseRotate=new is({clickTolerance:t.dragRotate._mouseRotate._clickTolerance}),this.map=t,o&&(this.mousePitch=new os({clickTolerance:t.dragRotate._mousePitch._clickTolerance})),e.aR([\"mousedown\",\"mousemove\",\"mouseup\",\"touchstart\",\"touchmove\",\"touchend\",\"reset\"],this),i.addEventListener(\"mousedown\",this.mousedown),i.addEventListener(\"touchstart\",this.touchstart,{passive:!1}),i.addEventListener(\"touchmove\",this.touchmove),i.addEventListener(\"touchend\",this.touchend),i.addEventListener(\"touchcancel\",this.reset);}down(e,t){this.mouseRotate.mousedown(e,t),this.mousePitch&&this.mousePitch.mousedown(e,t),h();}move(e,t){const i=this.map,o=this.mouseRotate.mousemoveWindow(e,t),r=o&&o.bearingDelta;if(r&&i.setBearing(i.getBearing()+r),this.mousePitch){const o=this.mousePitch.mousemoveWindow(e,t),r=o&&o.pitchDelta;r&&i.setPitch(i.getPitch()+r);}}off(){const e=this.element;e.removeEventListener(\"mousedown\",this.mousedown),e.removeEventListener(\"touchstart\",this.touchstart,{passive:!1}),e.removeEventListener(\"touchmove\",this.touchmove),e.removeEventListener(\"touchend\",this.touchend),e.removeEventListener(\"touchcancel\",this.reset),this.offTemp();}offTemp(){_(),window.removeEventListener(\"mousemove\",this.mousemove),window.removeEventListener(\"mouseup\",this.mouseup);}mousedown(t){this.down(e.ak({},t,{ctrlKey:!0,preventDefault:()=>t.preventDefault()}),p(this.element,t)),window.addEventListener(\"mousemove\",this.mousemove),window.addEventListener(\"mouseup\",this.mouseup);}mousemove(e){this.move(e,p(this.element,e));}mouseup(e){this.mouseRotate.mouseupWindow(e),this.mousePitch&&this.mousePitch.mouseupWindow(e),this.offTemp();}touchstart(e){1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=m(this.element,e.targetTouches)[0],this.down({type:\"mousedown\",button:0,ctrlKey:!0,preventDefault:()=>e.preventDefault()},this._startPos));}touchmove(e){1!==e.targetTouches.length?this.reset():(this._lastPos=m(this.element,e.targetTouches)[0],this.move({preventDefault:()=>e.preventDefault()},this._lastPos));}touchend(e){0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)t.maxZoom)throw new Error(\"maxZoom must be greater than or equal to minZoom\");if(null!=t.minPitch&&null!=t.maxPitch&&t.minPitch>t.maxPitch)throw new Error(\"maxPitch must be greater than or equal to minPitch\");if(null!=t.minPitch&&t.minPitch<0)throw new Error(\"minPitch must be greater than or equal to 0\");if(null!=t.maxPitch&&t.maxPitch>85)throw new Error(\"maxPitch must be less than or equal to 85\");if(t.antialias&&e.cQ(window)&&(t.antialias=!1,e.X(\"Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609\")),super(new De(t.minZoom,t.maxZoom,t.minPitch,t.maxPitch,t.renderWorldCopies),t),this._repaint=!1,this._interactive=t.interactive,this._minTileCacheSize=t.minTileCacheSize,this._maxTileCacheSize=t.maxTileCacheSize,this._failIfMajorPerformanceCaveat=t.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=t.preserveDrawingBuffer,this._antialias=t.antialias,this._trackResize=t.trackResize,this._bearingSnap=t.bearingSnap,this._refreshExpiredTiles=t.refreshExpiredTiles,this._fadeDuration=t.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=t.crossSourceCollisions,this._collectResourceTiming=t.collectResourceTiming,this._language=this._parseLanguage(t.language),this._worldview=t.worldview,this._renderTaskQueue=new Rs,this._domRenderTaskQueue=new Rs,this._controls=[],this._markers=[],this._popups=[],this._mapId=e.cR(),this._locale=e.ak({},Gs,t.locale),this._clickTolerance=t.clickTolerance,this._cooperativeGestures=t.cooperativeGestures,this._performanceMetricsCollection=t.performanceMetricsCollection,this._containerWidth=0,this._containerHeight=0,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Us(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._requestManager=new e.cS(t.transformRequest,t.accessToken,t.testMode),this._silenceAuthErrors=!!t.testMode,this._contextCreateOptions=t.contextCreateOptions?{...t.contextCreateOptions}:{},\"string\"==typeof t.container){const e=document.getElementById(t.container);if(!e)throw new Error(`Container '${t.container.toString()}' not found.`);this._container=e;}else {if(!(t.container instanceof HTMLElement))throw new Error(\"Invalid type: 'container' must be a String or HTMLElement.\");this._container=t.container;}if(this._container.childNodes.length>0&&e.X(\"The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead.\"),t.maxBounds&&this.setMaxBounds(t.maxBounds),e.aR([\"_onWindowOnline\",\"_onWindowResize\",\"_onVisibilityChange\",\"_onMapScroll\",\"_contextLost\",\"_contextRestored\"],this),this._setupContainer(),this._debugParams=new Vs,this._tp=t.devtools?new dr(this):new dr,this._tp.registerParameter(this._debugParams,[\"Debug\"],\"showOverdrawInspector\",void 0,(()=>{this._update();})),this._tp.registerParameter(this._debugParams,[\"Debug\"],\"showTileBoundaries\",void 0,(()=>{this._update();})),this._tp.registerParameter(this._debugParams,[\"Debug\"],\"continuousRedraw\",void 0,(e=>{this.repaint=e;})),this._tp.registerParameter(this._debugParams,[\"Debug\",\"Wireframe\"],\"showTerrainWireframe\",void 0,(()=>{this._update();})),this._tp.registerParameter(this._debugParams,[\"Debug\",\"Wireframe\"],\"showLayers2DWireframe\",void 0,(()=>{this._update();})),this._tp.registerParameter(this._debugParams,[\"Debug\",\"Wireframe\"],\"showLayers3DWireframe\",void 0,(()=>{this._update();})),this._setupPainter(),void 0===this.painter)throw new Error(\"Failed to initialize WebGL.\");if(this.on(\"move\",(()=>this._update(!1))),this.on(\"moveend\",(()=>this._update(!1))),this.on(\"zoom\",(()=>this._update(!0))),this._fullscreenchangeEvent=\"onfullscreenchange\"in document?\"fullscreenchange\":\"webkitfullscreenchange\",window.addEventListener(\"online\",this._onWindowOnline,!1),window.addEventListener(\"resize\",this._onWindowResize,!1),window.addEventListener(\"orientationchange\",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener(\"visibilitychange\",this._onVisibilityChange,!1),this.handlers=new Ms(this,t),this._localFontFamily=t.localFontFamily,this._localIdeographFontFamily=t.localIdeographFontFamily,(t.style||!t.testMode)&&this.setStyle(t.style||e.cM.DEFAULT_STYLE,{localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily}),t.projection&&this.setProjection(t.projection),t.hash&&(this._hash=new Rr(\"string\"==typeof t.hash&&t.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){null==i.center&&null==i.zoom||(this.transform._unmodified=!1),this.jumpTo({center:t.center,zoom:t.zoom,bearing:t.bearing,pitch:t.pitch});const o=t.bounds;o&&(this.resize(),this.fitBounds(o,e.ak({},t.fitBoundsOptions,{duration:0})));}this.resize(),t.attributionControl&&this.addControl(new Ds({customAttribution:t.customAttribution})),this._logoControl=new As,this.addControl(this._logoControl,t.logoPosition),this.on(\"style.load\",(()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet);})),this.on(\"data\",(t=>{this._update(\"style\"===t.dataType),this.fire(new e.a8(`${t.dataType}data`,t));})),this.on(\"dataloading\",(t=>{this.fire(new e.a8(`${t.dataType}dataloading`,t));}));}_getMapId(){return this._mapId}addControl(t,i){if(void 0===i&&(i=t.getDefaultPosition?t.getDefaultPosition():\"top-right\"),!t||!t.onAdd)return this.fire(new e.a7(new Error(\"Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.\")));const o=t.onAdd(this);this._controls.push(t);const r=this._controlPositions[i];return -1!==i.indexOf(\"bottom\")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(t){if(!t||!t.onRemove)return this.fire(new e.a7(new Error(\"Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.\")));const i=this._controls.indexOf(t);return i>-1&&this._controls.splice(i,1),t.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(t){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const i=!this._moving;return i&&this.fire(new e.a8(\"movestart\",t)).fire(new e.a8(\"move\",t)),this.fire(new e.a8(\"resize\",t)),i&&this.fire(new e.a8(\"moveend\",t)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(t){return this.transform.setMaxBounds(e.D.convert(t)),this._update()}setMinZoom(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t?this.setZoom(t):this.fire(new e.a8(\"zoomstart\")).fire(new e.a8(\"zoom\")).fire(new e.a8(\"zoomend\")),this;throw new Error(\"maxZoom must be greater than the current minZoom\")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(t){if((t=null==t?0:t)<0)throw new Error(\"minPitch must be greater than or equal to 0\");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()85)throw new Error(\"maxPitch must be less than or equal to 85\");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t?this.setPitch(t):this.fire(new e.a8(\"pitchstart\")).fire(new e.a8(\"pitch\")).fire(new e.a8(\"pitchend\")),this;throw new Error(\"maxPitch must be greater than or equal to minPitch\")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.renderWorldCopies=e,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(e){return \"auto\"===e?navigator.language:Array.isArray(e)?0===e.length?void 0:e.map((e=>\"auto\"===e?navigator.language:e)):e}setLanguage(e){const t=this._parseLanguage(e);if(!this.style||t===this._language)return this;this._language=t,this.style.reloadSources();for(const e of this._controls)e._setLanguage&&e._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(e){return this.style&&e!==this._worldview?(this._worldview=e,this.style.reloadSources(),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:\"globe\",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return \"globe\"===this.transform.projection.name}setProjection(e){return this._lazyInitEmptyStyle(),e?\"string\"==typeof e&&(e={name:e}):e=null,this._useExplicitProjection=!!e,this._prioritizeAndUpdateProjection(e,this.style.projection)}_updateProjectionTransition(){if(\"globe\"!==this.getProjection().name)return;const t=this.transform,i=t.projection.name;let o;\"globe\"===i&&t.zoom>=e.G?(t.setMercatorFromTransition(),o=!0):\"mercator\"===i&&t.zoom=e.G?this.transform.setMercatorFromTransition():this.transform.setProjection(t),this.style.applyProjectionUpdate(),i&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(t){return this.transform.locationPoint3D(e.L.convert(t))}unproject(t){return this.transform.pointLocation3D(e.P.convert(t))}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(e,t,i){if(\"mouseenter\"===e||\"mouseover\"===e){let o=!1;const r=r=>{const s=t.filter((e=>this.getLayer(e))),n=s.length?this.queryRenderedFeatures(r.point,{layers:s}):[];n.length?o||(o=!0,i.call(this,new Vr(e,this,r.originalEvent,{features:n}))):o=!1;},s=()=>{o=!1;};return {layers:new Set(t),listener:i,delegates:{mousemove:r,mouseout:s}}}if(\"mouseleave\"===e||\"mouseout\"===e){let o=!1;const r=r=>{const s=t.filter((e=>this.getLayer(e)));(s.length?this.queryRenderedFeatures(r.point,{layers:s}):[]).length?o=!0:o&&(o=!1,i.call(this,new Vr(e,this,r.originalEvent)));},s=t=>{o&&(o=!1,i.call(this,new Vr(e,this,t.originalEvent)));};return {layers:new Set(t),listener:i,delegates:{mousemove:r,mouseout:s}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:new Set(t),listener:i,delegates:{[e]:o}}}}on(e,t,i){if(void 0===i)return super.on(e,t);if(Array.isArray(t)||(t=[t]),t)for(const e of t)if(!this._isValidId(e))return this;const o=this._createDelegatedListener(e,t,i);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(o);for(const e in o.delegates)this.on(e,o.delegates[e]);return this}once(e,t,i){if(void 0===i)return super.once(e,t);if(Array.isArray(t)||(t=[t]),t)for(const e of t)if(!this._isValidId(e))return this;const o=this._createDelegatedListener(e,t,i);for(const e in o.delegates)this.once(e,o.delegates[e]);return this}off(e,t,i){if(void 0===i)return super.off(e,t);t=new Set(Array.isArray(t)?t:[t]);for(const e of t)if(!this._isValidId(e))return this;const o=(e,t)=>{if(e.size!==t.size)return !1;for(const i of e)if(!t.has(i))return !1;return !0},r=this._delegatedListeners?this._delegatedListeners[e]:void 0;return r&&(e=>{for(let r=0;r{t?this.fire(new e.a7(t)):o&&this._updateDiff(o,i);}));}else \"object\"==typeof t&&this._updateDiff(t,i);}_updateDiff(t,i){try{this.style.setState(t)&&this._update(!0);}catch(o){e.X(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(t,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(e.X(\"There is no style added to the map.\"),!1)}_isValidId(t){return null==t?(this.fire(new e.a7(new Error(\"IDs can't be empty.\"))),!1):!e.cu(t)||(this.fire(new e.a7(new Error(`IDs can't contain special symbols: \"${t}\".`))),!1)}addSource(e,t){return this._isValidId(e)?(this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)):this}isSourceLoaded(e){return !!this._isValidId(e)&&!!this.style&&this.style._isSourceCacheLoaded(e)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(e,t,i){this._lazyInitEmptyStyle(),this.style.addSourceType(e,t,i);}removeSource(e){return this._isValidId(e)?(this.style.removeSource(e),this._updateTerrain(),this._update(!0)):this}getSource(e){return this._isValidId(e)?this.style.getOwnSource(e):null}addImage(t,i,{pixelRatio:o=1,sdf:r=!1,stretchX:s,stretchY:n,content:a}={}){if(this._lazyInitEmptyStyle(),i instanceof HTMLImageElement||ImageBitmap&&i instanceof ImageBitmap){const{width:l,height:c,data:h}=e.a4.getImageData(i);this.style.addImage(t,{data:new e.a5({width:l,height:c},h),pixelRatio:o,stretchX:s,stretchY:n,content:a,sdf:r,version:0});}else if(void 0===i.width||void 0===i.height)this.fire(new e.a7(new Error(\"Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`\")));else {const{width:l,height:c}=i,h=i;this.style.addImage(t,{data:new e.a5({width:l,height:c},new Uint8Array(h.data)),pixelRatio:o,stretchX:s,stretchY:n,content:a,sdf:r,version:0,userImage:h}),h.onAdd&&h.onAdd(this,t);}}updateImage(t,i){this._lazyInitEmptyStyle();const o=this.style.getImage(t);if(!o)return void this.fire(new e.a7(new Error(\"The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.\")));const r=i instanceof HTMLImageElement||ImageBitmap&&i instanceof ImageBitmap?e.a4.getImageData(i):i,{width:s,height:n}=r,a=r.data;if(void 0===s||void 0===n)return void this.fire(new e.a7(new Error(\"Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`\")));if(s!==o.data.width||n!==o.data.height)return void this.fire(new e.a7(new Error(`The width and height of the updated image (${s}, ${n})\\n must be that same as the previous version of the image\\n (${o.data.width}, ${o.data.height})`)));const l=!(i instanceof HTMLImageElement||ImageBitmap&&i instanceof ImageBitmap);o.data.replace(a,l),this.style.updateImage(t,o);}hasImage(t){return t?!!this.style&&!!this.style.getImage(t):(this.fire(new e.a7(new Error(\"Missing required image id\"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(t,i){e.a3(this._requestManager.transformRequest(t,e.a2.Image),((t,o)=>{i(t,o instanceof HTMLImageElement?e.a4.getImageData(o):o);}));}listImages(){return this.style.listImages()}addModel(e,t){this._lazyInitEmptyStyle(),this.style.addModel(e,t);}hasModel(t){return t?this.style.hasModel(t):(this.fire(new e.a7(new Error(\"Missing required model id\"))),!1)}removeModel(e){this.style.removeModel(e);}listModels(){return this.style.listModels()}addLayer(e,t){return this._isValidId(e.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)):this}moveLayer(e,t){return this._isValidId(e)?(this.style.moveLayer(e,t),this._update(!0)):this}removeLayer(e){return this._isValidId(e)?(this.style.removeLayer(e),this._update(!0)):this}getLayer(e){return this._isValidId(e)?this.style.getOwnLayer(e):null}setLayerZoomRange(e,t,i){return this._isValidId(e)?(this.style.setLayerZoomRange(e,t,i),this._update(!0)):this}setFilter(e,t,i={}){return this._isValidId(e)?(this.style.setFilter(e,t,i),this._update(!0)):this}getFilter(e){return this._isValidId(e)?this.style.getFilter(e):null}setPaintProperty(e,t,i,o={}){return this._isValidId(e)?(this.style.setPaintProperty(e,t,i,o),this._update(!0)):this}getPaintProperty(e,t){return this._isValidId(e)?this.style.getPaintProperty(e,t):null}setLayoutProperty(e,t,i,o={}){return this._isValidId(e)?(this.style.setLayoutProperty(e,t,i,o),this._update(!0)):this}getLayoutProperty(e,t){return this._isValidId(e)?this.style.getLayoutProperty(e,t):null}getConfigProperty(e,t){return this.style.getConfigProperty(e,t)}setConfigProperty(e,t,i){return this.style.setConfigProperty(e,t,i),this._update(!0)}setLights(e){if(this._lazyInitEmptyStyle(),e&&1===e.length&&\"flat\"===e[0].type){const t=e[0];t.properties?this.style.setFlatLight(t.properties,t.id,{}):this.style.setFlatLight({},\"flat\");}else this.style.setLights(e),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const e=this.style.getLights()||[];return 0===e.length&&e.push({id:this.style.light.id,type:\"flat\",properties:this.style.getFlatLight()}),e}setLight(e,t={}){return console.log(\"The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead.\"),this.setLights([{id:\"flat\",type:\"flat\",properties:e}])}getLight(){return console.log(\"The `map.getLight` function is deprecated, prefer using `map.getLights` instead.\"),this.style.getFlatLight()}setTerrain(e){return this._lazyInitEmptyStyle(),!e&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(e),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(e){return this._lazyInitEmptyStyle(),this.style.setFog(e),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setCamera(e){return this.style.setCamera(e),this._triggerCameraUpdate(e)}_triggerCameraUpdate(e){return this._update(this.transform.setOrthographicProjectionAtLowPitch(\"orthographic\"===e[\"camera-projection\"]))}getCamera(){return this.style.camera}_queryFogOpacity(t){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(e.L.convert(t),this.transform):0}setFeatureState(e,t){return this._isValidId(e.source)?(this.style.setFeatureState(e,t),this._update()):this}removeFeatureState(e,t){return this._isValidId(e.source)?(this.style.removeFeatureState(e,t),this._update()):this}getFeatureState(e){return this._isValidId(e.source)?this.style.getFeatureState(e):null}_updateContainerDimensions(){if(!this._container)return;const e=this._container.getBoundingClientRect().width||400,t=this._container.getBoundingClientRect().height||300;let i,o,r,s=this._container;for(;s&&(!o||!r);){const e=window.getComputedStyle(s).transform;e&&\"none\"!==e&&(i=e.match(/matrix.*\\((.+)\\)/)[1].split(\", \"),i[0]&&\"0\"!==i[0]&&\"1\"!==i[0]&&(o=i[0]),i[3]&&\"0\"!==i[3]&&\"1\"!==i[3]&&(r=i[3])),s=s.parentElement;}this._containerWidth=o?Math.abs(e/o):e,this._containerHeight=r?Math.abs(t/r):t;}_detectMissingCSS(){\"rgb(250, 128, 114)\"!==window.getComputedStyle(this._missingCSSCanary).getPropertyValue(\"background-color\")&&e.X(\"This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.\");}_setupContainer(){const e=this._container;e.classList.add(\"mapboxgl-map\"),(this._missingCSSCanary=s(\"div\",\"mapboxgl-canary\",e)).style.visibility=\"hidden\",this._detectMissingCSS();const t=this._canvasContainer=s(\"div\",\"mapboxgl-canvas-container\",e);this._canvas=s(\"canvas\",\"mapboxgl-canvas\",t),this._interactive&&(t.classList.add(\"mapboxgl-interactive\"),this._canvas.setAttribute(\"tabindex\",\"0\")),this._canvas.addEventListener(\"webglcontextlost\",this._contextLost,!1),this._canvas.addEventListener(\"webglcontextrestored\",this._contextRestored,!1),this._canvas.setAttribute(\"aria-label\",this._getUIString(\"Map.Title\")),this._canvas.setAttribute(\"role\",\"region\"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const i=this._controlContainer=s(\"div\",\"mapboxgl-control-container\",e),o=this._controlPositions={};[\"top-left\",\"top-right\",\"bottom-left\",\"bottom-right\"].forEach((e=>{o[e]=s(\"div\",`mapboxgl-ctrl-${e}`,i);})),this._container.addEventListener(\"scroll\",this._onMapScroll,!1);}_resizeCanvas(t,i){const o=e.a4.devicePixelRatio||1;this._canvas.width=o*Math.ceil(t),this._canvas.height=o*Math.ceil(i),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${i}px`;}_addMarker(e){this._markers.push(e);}_removeMarker(e){const t=this._markers.indexOf(e);-1!==t&&this._markers.splice(t,1);}_addPopup(e){this._popups.push(e);}_removePopup(e){const t=this._popups.indexOf(e);-1!==t&&this._popups.splice(t,1);}_setupPainter(){const t=e.ak({},i.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),o=this._canvas.getContext(\"webgl2\",t);o?(e.cT(o,!0),this.painter=new mr(o,this._contextCreateOptions,this.transform,this._tp),this.on(\"data\",(e=>{\"source\"===e.dataType&&this.painter.setTileLoadedFlag(!0);})),e.cU.testSupport(o)):this.fire(new e.a7(new Error(\"Failed to initialize WebGL\")));}_contextLost(t){t.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new e.a8(\"webglcontextlost\",{originalEvent:t}));}_contextRestored(t){this._setupPainter(),this.resize(),this._update(),this.fire(new e.a8(\"webglcontextrestored\",{originalEvent:t}));}_onMapScroll(e){if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_requestDomTask(e){!this.loaded()||this.loaded()&&!this.isMoving()?e():this._domRenderTaskQueue.add(e);}_render(t){let i;this.fire(new e.a8(\"renderstart\"));const o=this.painter.context.extTimerQuery,r=e.a4.now(),s=this.painter.context.gl;if(this.listens(\"gpu-timing-frame\")&&(i=s.createQuery(),s.beginQuery(o.TIME_ELAPSED_EXT,i)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(t),this._domRenderTaskQueue.run(t),this._removed)return;this._updateProjectionTransition();const n=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const t=this.transform.zoom,i=this.transform.pitch,o=e.a4.now(),r=new e.al(t,{now:o,fadeDuration:n,pitch:i,transition:this.style.transition});this.style.update(r);}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let a=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),a=this._updateAverageElevation(r),this.style.updateSources(this.transform),this._forceMarkerAndPopupUpdate()):a=this._updateAverageElevation(r),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,n,this._crossSourceCollisions),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries||this._debugParams.showTileBoundaries,wireframe:{terrain:this.showTerrainWireframe||this._debugParams.showTerrainWireframe,layers2D:this.showLayers2DWireframe||this._debugParams.showLayers2DWireframe,layers3D:this.showLayers3DWireframe||this._debugParams.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector||this._debugParams.showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:n,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens(\"gpu-timing-layer\"),gpuTimingDeferredRender:!!this.listens(\"gpu-timing-deferred-render\"),speedIndexTiming:this.speedIndexTiming}),this.fire(new e.a8(\"render\")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new e.a8(\"load\"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),i){const t=e.a4.now()-r;s.endQuery(o.TIME_ELAPSED_EXT),setTimeout((()=>{const o=s.getQueryParameter(i,s.QUERY_RESULT)/1e6;s.deleteQuery(i),this.fire(new e.a8(\"gpu-timing-frame\",{cpuTime:t,gpuTime:o}));}),50);}if(this.listens(\"gpu-timing-layer\")){const t=this.painter.collectGpuTimers();setTimeout((()=>{const i=this.painter.queryGpuTimers(t);this.fire(new e.a8(\"gpu-timing-layer\",{layerTimes:i}));}),50);}if(this.listens(\"gpu-timing-deferred-render\")){const t=this.painter.collectDeferredRenderGpuQueries();setTimeout((()=>{const i=this.painter.queryGpuTimeDeferredRender(t);this.fire(new e.a8(\"gpu-timing-deferred-render\",{gpuTime:i}));}),50);}const l=this._sourcesDirty||this._styleDirty||this._placementDirty||a;if(l||this._repaint)this.triggerRepaint();else {const t=!this.isMoving()&&this.loaded();if(t&&(a=this._updateAverageElevation(r,!0)),a)this.triggerRepaint();else if(this._triggerFrame(!1),t&&(this.fire(new e.a8(\"idle\")),this._isInitialLoad=!1,this.speedIndexTiming)){const t=this._calculateSpeedIndex();this.fire(new e.a8(\"speedindexcompleted\",{speedIndex:t})),this.speedIndexTiming=!1;}}!this._loaded||this._fullyLoaded||l||(this._fullyLoaded=!0,this._performanceMetricsCollection&&e.cV(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate());}_forceMarkerAndPopupUpdate(e){for(const t of this._markers)e&&!this.getRenderWorldCopies()&&(t._lngLat=t._lngLat.wrap()),t._update();for(const t of this._popups)!e||this.getRenderWorldCopies()||t._trackPointer||(t._lngLat=t._lngLat.wrap()),t._update();}_updateAverageElevation(e,t=!1){const i=e=>(this.transform.averageElevation=e,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return 0!==this.transform.averageElevation&&i(0);const o=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(o||(t||e-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(e)){const t=this.transform.averageElevation;let r=this.transform.sampleAverageElevation();this.transform.elevation&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(r)?r=0:this._averageElevationLastSampledAt=e;const s=Math.abs(t-r);if(s>1){if(this._isInitialLoad||o)return this._averageElevation.jumpTo(r),i(r);this._averageElevation.easeTo(r,e,300);}else if(s>1e-4)return this._averageElevation.jumpTo(r),i(r)}return !!this._averageElevation.isEasing(e)&&i(this._averageElevation.getValue(e))}_authenticate(){e.cW(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,(t=>{if(t&&(t.message===e.cX||401===t.status)){const t=this.painter.context.gl;e.cT(t,!1),this._logoControl instanceof As&&this._logoControl._updateLogo(),t&&t.clear(t.DEPTH_BUFFER_BIT|t.COLOR_BUFFER_BIT|t.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new e.a7(new Error(\"A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/\")));}})),e.cY(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,(()=>{}));}_updateTerrain(){const e=this._isDragging();this.painter.updateTerrain(this.style,e);}_calculateSpeedIndex(){const e=this.painter.canvasCopy(),t=this.painter.getCanvasCopiesAndTimestamps();t.timeStamps.push(performance.now());const i=this.painter.context.gl,o=i.createFramebuffer();function r(e){i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0);const t=new Uint8Array(i.drawingBufferWidth*i.drawingBufferHeight*4);return i.readPixels(0,0,i.drawingBufferWidth,i.drawingBufferHeight,i.RGBA,i.UNSIGNED_BYTE,t),t}return i.bindFramebuffer(i.FRAMEBUFFER,o),this._canvasPixelComparison(r(e),t.canvasCopies.map(r),t.timeStamps)}_canvasPixelComparison(e,t,i){let o=i[1]-i[0];const r=e.length/4;for(let s=0;s{const t=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,t&&this._render(e);})));}_preloadTiles(t){const i=this.style?Object.values(this.style._sourceCaches):[];return e.c_(i,((e,i)=>e._preloadTiles(t,i)),(()=>{this.triggerRepaint();})),this}_onWindowOnline(){this._update();}_onWindowResize(e){this._trackResize&&this.resize({originalEvent:e})._update();}_onVisibilityChange(){\"hidden\"===document.visibilityState&&this._visibilityHidden++;}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showTerrainWireframe(){return !!this._showTerrainWireframe}set showTerrainWireframe(e){this._showTerrainWireframe!==e&&(this._showTerrainWireframe=e,this._update());}get showLayers2DWireframe(){return !!this._showLayers2DWireframe}set showLayers2DWireframe(e){this._showLayers2DWireframe!==e&&(this._showLayers2DWireframe=e,this._update());}get showLayers3DWireframe(){return !!this._showLayers3DWireframe}set showLayers3DWireframe(e){this._showLayers3DWireframe!==e&&(this._showLayers3DWireframe=e,this._update());}get speedIndexTiming(){return !!this._speedIndexTiming}set speedIndexTiming(e){this._speedIndexTiming!==e&&(this._speedIndexTiming=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get showTileAABBs(){return !!this._showTileAABBs}set showTileAABBs(e){this._showTileAABBs!==e&&(this._showTileAABBs=e,e&&this._update());}_setCacheLimits(t,i){e.d0(t,i);}get version(){return e.c$}},NavigationControl:class{constructor(t){this.options=e.ak({},Zs,t),this._container=s(\"div\",\"mapboxgl-ctrl mapboxgl-ctrl-group\"),this._container.addEventListener(\"contextmenu\",(e=>e.preventDefault())),this.options.showZoom&&(e.aR([\"_setButtonTitle\",\"_updateZoomButtons\"],this),this._zoomInButton=this._createButton(\"mapboxgl-ctrl-zoom-in\",(e=>{this._map&&this._map.zoomIn({},{originalEvent:e});})),s(\"span\",\"mapboxgl-ctrl-icon\",this._zoomInButton).setAttribute(\"aria-hidden\",\"true\"),this._zoomOutButton=this._createButton(\"mapboxgl-ctrl-zoom-out\",(e=>{this._map&&this._map.zoomOut({},{originalEvent:e});})),s(\"span\",\"mapboxgl-ctrl-icon\",this._zoomOutButton).setAttribute(\"aria-hidden\",\"true\")),this.options.showCompass&&(e.aR([\"_rotateCompassArrow\"],this),this._compass=this._createButton(\"mapboxgl-ctrl-compass\",(e=>{const t=this._map;t&&(this.options.visualizePitch?t.resetNorthPitch({},{originalEvent:e}):t.resetNorth({},{originalEvent:e}));})),this._compassIcon=s(\"span\",\"mapboxgl-ctrl-icon\",this._compass),this._compassIcon.setAttribute(\"aria-hidden\",\"true\"));}_updateZoomButtons(){const e=this._map;if(!e)return;const t=e.getZoom(),i=t===e.getMaxZoom(),o=t===e.getMinZoom();this._zoomInButton.disabled=i,this._zoomOutButton.disabled=o,this._zoomInButton.setAttribute(\"aria-disabled\",i.toString()),this._zoomOutButton.setAttribute(\"aria-disabled\",o.toString());}_rotateCompassArrow(){const e=this._map;if(!e)return;const t=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(e.transform.pitch*(Math.PI/180)),.5)}) rotateX(${e.transform.pitch}deg) rotateZ(${e.transform.angle*(180/Math.PI)}deg)`:`rotate(${e.transform.angle*(180/Math.PI)}deg)`;e._requestDomTask((()=>{this._compassIcon&&(this._compassIcon.style.transform=t);}));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,\"ZoomIn\"),this._setButtonTitle(this._zoomOutButton,\"ZoomOut\"),e.on(\"zoom\",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,\"ResetBearing\"),this.options.visualizePitch&&e.on(\"pitch\",this._rotateCompassArrow),e.on(\"rotate\",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Ws(e,this._compass,this.options.visualizePitch)),this._container}onRemove(){const e=this._map;e&&(this._container.remove(),this.options.showZoom&&e.off(\"zoom\",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&e.off(\"pitch\",this._rotateCompassArrow),e.off(\"rotate\",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0);}_createButton(e,t){const i=s(\"button\",e,this._container);return i.type=\"button\",i.addEventListener(\"click\",t),i}_setButtonTitle(e,t){if(!this._map)return;const i=this._map._getUIString(`NavigationControl.${t}`);e.setAttribute(\"aria-label\",i),e.firstElementChild&&e.firstElementChild.setAttribute(\"title\",i);}},GeolocateControl:class extends e.a6{constructor(t){super();const i=navigator.geolocation;this.options=e.ak({geolocation:i},Hs,t),e.aR([\"_onSuccess\",\"_onError\",\"_onZoom\",\"_finish\",\"_setupUI\",\"_updateCamera\",\"_updateMarker\",\"_updateMarkerRotation\",\"_onDeviceOrientation\"],this),this._updateMarkerRotationThrottled=Ar(this._updateMarkerRotation,20),this._numberOfWatches=0;}onAdd(e){return this._map=e,this._container=s(\"div\",\"mapboxgl-ctrl mapboxgl-ctrl-group\"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){void 0!==this._geolocationWatchID&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off(\"zoom\",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1;}_checkGeolocationSupport(e){const t=(t=!!this.options.geolocation)=>{this._supportsGeolocation=t,e(t);};void 0!==this._supportsGeolocation?e(this._supportsGeolocation):void 0!==navigator.permissions?navigator.permissions.query({name:\"geolocation\"}).then((e=>t(\"denied\"!==e.state))).catch((()=>t())):t();}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return !!t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case\"WAITING_ACTIVE\":this._watchState=\"ACTIVE_ERROR\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-active-error\");break;case\"ACTIVE_LOCK\":this._watchState=\"ACTIVE_ERROR\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-active-error\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-waiting\");break;case\"BACKGROUND\":this._watchState=\"BACKGROUND_ERROR\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-background-error\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-waiting\");}}_onSuccess(t){if(this._map){if(this._isOutOfMapMaxBounds(t))return this._setErrorState(),this.fire(new e.a8(\"outofmaxbounds\",t)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case\"WAITING_ACTIVE\":case\"ACTIVE_LOCK\":case\"ACTIVE_ERROR\":this._watchState=\"ACTIVE_LOCK\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active-error\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-active\");break;case\"BACKGROUND\":case\"BACKGROUND_ERROR\":this._watchState=\"BACKGROUND\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background-error\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-background\");}this.options.showUserLocation&&\"OFF\"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&\"ACTIVE_LOCK\"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName(\"mapboxgl-user-location-dot-stale\"),this.fire(new e.a8(\"geolocate\",t)),this._finish();}}_updateCamera(t){const i=new e.L(t.coords.longitude,t.coords.latitude),o=t.coords.accuracy,r=this._map.getBearing(),s=e.ak({bearing:r},this.options.fitBoundsOptions);this._map.fitBounds(i.toBounds(o),s,{geolocateSource:!0});}_updateMarker(t){if(t){const i=new e.L(t.coords.longitude,t.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=t.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();}_updateCircleRadius(){const t=this._map.transform,i=e.b(1,t._center.lat)*t.worldSize,o=Math.ceil(2*this._accuracy*i);this._circleElement.style.width=`${o}px`,this._circleElement.style.height=`${o}px`;}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}_updateMarkerRotation(){this._userLocationDotMarker&&\"number\"==typeof this._heading?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName(\"mapboxgl-user-location-show-heading\")):(this._userLocationDotMarker.removeClassName(\"mapboxgl-user-location-show-heading\"),this._userLocationDotMarker.setRotation(0));}_onError(t){if(this._map){if(this.options.trackUserLocation)if(1===t.code){this._watchState=\"OFF\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active-error\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background-error\"),this._geolocateButton.disabled=!0;const e=this._map._getUIString(\"GeolocateControl.LocationNotAvailable\");this._geolocateButton.setAttribute(\"aria-label\",e),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute(\"title\",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===t.code&&this._noTimeout)return;this._setErrorState();}\"OFF\"!==this._watchState&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName(\"mapboxgl-user-location-dot-stale\"),this.fire(new e.a8(\"error\",t)),this._finish();}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;}_setupUI(t){if(void 0!==this._map){if(this._container.addEventListener(\"contextmenu\",(e=>e.preventDefault())),this._geolocateButton=s(\"button\",\"mapboxgl-ctrl-geolocate\",this._container),s(\"span\",\"mapboxgl-ctrl-icon\",this._geolocateButton).setAttribute(\"aria-hidden\",\"true\"),this._geolocateButton.type=\"button\",!1===t){e.X(\"Geolocation support is not available so the GeolocateControl will be disabled.\");const t=this._map._getUIString(\"GeolocateControl.LocationNotAvailable\");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute(\"aria-label\",t),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute(\"title\",t);}else {const e=this._map._getUIString(\"GeolocateControl.FindMyLocation\");this._geolocateButton.setAttribute(\"aria-label\",e),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute(\"title\",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute(\"aria-pressed\",\"false\"),this._watchState=\"OFF\"),this.options.showUserLocation&&(this._dotElement=s(\"div\",\"mapboxgl-user-location\"),this._dotElement.appendChild(s(\"div\",\"mapboxgl-user-location-dot\")),this._dotElement.appendChild(s(\"div\",\"mapboxgl-user-location-heading\")),this._userLocationDotMarker=new Fs({element:this._dotElement,rotationAlignment:\"map\",pitchAlignment:\"map\"}),this._circleElement=s(\"div\",\"mapboxgl-user-location-accuracy-circle\"),this._accuracyCircleMarker=new Fs({element:this._circleElement,pitchAlignment:\"map\"}),this.options.trackUserLocation&&(this._watchState=\"OFF\"),this._map.on(\"zoom\",this._onZoom)),this._geolocateButton.addEventListener(\"click\",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on(\"movestart\",(t=>{t.geolocateSource||\"ACTIVE_LOCK\"!==this._watchState||t.originalEvent&&\"resize\"===t.originalEvent.type||(this._watchState=\"BACKGROUND\",this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-background\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active\"),this.fire(new e.a8(\"trackuserlocationend\")));}));}}_onDeviceOrientation(e){this._userLocationDotMarker&&(e.webkitCompassHeading?this._heading=e.webkitCompassHeading:!0===e.absolute&&(this._heading=-1*e.alpha),this._updateMarkerRotationThrottled());}trigger(){if(!this._setup)return e.X(\"Geolocate control triggered before added to a map\"),!1;if(this.options.trackUserLocation){switch(this._watchState){case\"OFF\":this._watchState=\"WAITING_ACTIVE\",this.fire(new e.a8(\"trackuserlocationstart\"));break;case\"WAITING_ACTIVE\":case\"ACTIVE_LOCK\":case\"ACTIVE_ERROR\":case\"BACKGROUND_ERROR\":this._numberOfWatches--,this._noTimeout=!1,this._watchState=\"OFF\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-active-error\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background\"),this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background-error\"),this.fire(new e.a8(\"trackuserlocationend\"));break;case\"BACKGROUND\":this._watchState=\"ACTIVE_LOCK\",this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-background\"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new e.a8(\"trackuserlocationstart\"));}switch(this._watchState){case\"WAITING_ACTIVE\":this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-active\");break;case\"ACTIVE_LOCK\":this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-active\");break;case\"ACTIVE_ERROR\":this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-active-error\");break;case\"BACKGROUND\":this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-background\");break;case\"BACKGROUND_ERROR\":this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-background-error\");}if(\"OFF\"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.setAttribute(\"aria-pressed\",\"true\"),this._numberOfWatches++,this._numberOfWatches>1?(e={maximumAge:6e5,timeout:0},this._noTimeout=!0):(e=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,e),this.options.showUserHeading&&this._addDeviceOrientationListener();}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_addDeviceOrientationListener(){const e=()=>{\"ondeviceorientationabsolute\"in window?window.addEventListener(\"deviceorientationabsolute\",this._onDeviceOrientation):window.addEventListener(\"deviceorientation\",this._onDeviceOrientation);};\"undefined\"!=typeof DeviceMotionEvent&&\"function\"==typeof DeviceMotionEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((t=>{\"granted\"===t&&e();})).catch(console.error):e();}_clearWatch(){this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener(\"deviceorientation\",this._onDeviceOrientation),window.removeEventListener(\"deviceorientationabsolute\",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(\"mapboxgl-ctrl-geolocate-waiting\"),this._geolocateButton.setAttribute(\"aria-pressed\",\"false\"),this.options.showUserLocation&&this._updateMarker(null);}},AttributionControl:Ds,ScaleControl:class{constructor(t){this.options=e.ak({},qs,t),this._isNumberFormatSupported=function(){try{return new Intl.NumberFormat(\"en\",{style:\"unit\",unitDisplay:\"short\",unit:\"meter\"}),!0}catch(e){return !1}}(),e.aR([\"_update\",\"_setScale\",\"setUnit\"],this);}getDefaultPosition(){return \"bottom-left\"}_update(){const e=this.options.maxWidth||100,t=this._map,i=t._containerHeight/2,o=t._containerWidth/2-e/2,r=t.unproject([o,i]),s=t.unproject([o+e,i]),n=r.distanceTo(s);if(\"imperial\"===this.options.unit){const t=3.2808*n;t>5280?this._setScale(e,t/5280,\"mile\"):this._setScale(e,t,\"foot\");}else \"nautical\"===this.options.unit?this._setScale(e,n/1852,\"nautical-mile\"):n>=1e3?this._setScale(e,n/1e3,\"kilometer\"):this._setScale(e,n,\"meter\");}_setScale(e,t,i){this._map._requestDomTask((()=>{const o=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(t),r=o/t;this._container.innerHTML=this._isNumberFormatSupported&&\"nautical-mile\"!==i?new Intl.NumberFormat(this._language,{style:\"unit\",unitDisplay:\"short\",unit:i}).format(o):`${o} ${$s[i]}`,this._container.style.width=e*r+\"px\";}));}onAdd(e){return this._map=e,this._language=e.getLanguage(),this._container=s(\"div\",\"mapboxgl-ctrl mapboxgl-ctrl-scale\",e.getContainer()),this._container.dir=\"auto\",this._map.on(\"move\",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off(\"move\",this._update),this._map=void 0;}_setLanguage(e){this._language=e,this._update();}setUnit(e){this.options.unit=e,this._update();}},FullscreenControl:class{constructor(t){this._fullscreen=!1,t&&t.container&&(t.container instanceof HTMLElement?this._container=t.container:e.X(\"Full screen control 'container' must be a DOM element.\")),e.aR([\"_onClickFullscreen\",\"_changeIcon\"],this),\"onfullscreenchange\"in document?this._fullscreenchange=\"fullscreenchange\":\"onwebkitfullscreenchange\"in document&&(this._fullscreenchange=\"webkitfullscreenchange\");}onAdd(t){return this._map=t,this._container||(this._container=this._map.getContainer()),this._controlContainer=s(\"div\",\"mapboxgl-ctrl mapboxgl-ctrl-group\"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display=\"none\",e.X(\"This device does not support fullscreen mode.\")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon);}_checkFullscreenSupport(){return !(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const e=this._fullscreenButton=s(\"button\",\"mapboxgl-ctrl-fullscreen\",this._controlContainer);s(\"span\",\"mapboxgl-ctrl-icon\",e).setAttribute(\"aria-hidden\",\"true\"),e.type=\"button\",this._updateTitle(),this._fullscreenButton.addEventListener(\"click\",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute(\"aria-label\",e),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute(\"title\",e);}_getTitle(){return this._map._getUIString(this._isFullscreen()?\"FullscreenControl.Exit\":\"FullscreenControl.Enter\")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(\"mapboxgl-ctrl-shrink\"),this._fullscreenButton.classList.toggle(\"mapboxgl-ctrl-fullscreen\"),this._updateTitle());}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen();}},Popup:class extends e.a6{constructor(t){super(),this.options=e.ak(Object.create(Bs),t),e.aR([\"_update\",\"_onClose\",\"remove\",\"_onMouseEvent\"],this),this._classList=new Set(t&&t.className?t.className.trim().split(/\\s+/):[]);}addTo(t){return this._map&&this.remove(),this._map=t,this.options.closeOnClick&&t.on(\"preclick\",this._onClose),this.options.closeOnMove&&t.on(\"move\",this._onClose),t.on(\"remove\",this.remove),this._update(),t._addPopup(this),this._focusFirstElement(),this._trackPointer?(t.on(\"mousemove\",this._onMouseEvent),t.on(\"mouseup\",this._onMouseEvent),t._canvasContainer.classList.add(\"mapboxgl-track-pointer\")):t.on(\"move\",this._update),this.fire(new e.a8(\"open\")),this}isOpen(){return !!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const t=this._map;return t&&(t.off(\"move\",this._update),t.off(\"move\",this._onClose),t.off(\"preclick\",this._onClose),t.off(\"click\",this._onClose),t.off(\"remove\",this.remove),t.off(\"mousemove\",this._onMouseEvent),t.off(\"mouseup\",this._onMouseEvent),t.off(\"drag\",this._onMouseEvent),t._canvasContainer&&t._canvasContainer.classList.remove(\"mapboxgl-track-pointer\"),t._removePopup(this),this._map=void 0),this.fire(new e.a8(\"close\")),this}getLngLat(){return this._lngLat}setLngLat(t){this._lngLat=e.L.convert(t),this._pos=null,this._trackPointer=!1,this._update();const i=this._map;return i&&(i.on(\"move\",this._update),i.off(\"mousemove\",this._onMouseEvent),i._canvasContainer.classList.remove(\"mapboxgl-track-pointer\")),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const e=this._map;return e&&(e.off(\"move\",this._update),e.on(\"mousemove\",this._onMouseEvent),e.on(\"drag\",this._onMouseEvent),e._canvasContainer.classList.add(\"mapboxgl-track-pointer\")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement(\"body\");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){let t=this._content;if(t)for(;t.hasChildNodes();)t.firstChild&&t.removeChild(t.firstChild);else t=this._content=s(\"div\",\"mapboxgl-popup-content\",this._container||void 0);if(t.appendChild(e),this.options.closeButton){const e=this._closeButton=s(\"button\",\"mapboxgl-popup-close-button\",t);e.type=\"button\",e.setAttribute(\"aria-label\",\"Close popup\"),e.setAttribute(\"aria-hidden\",\"true\"),e.innerHTML=\"×\",e.addEventListener(\"click\",this._onClose);}return this._update(),this._focusFirstElement(),this}addClassName(e){return this._classList.add(e),this._updateClassList(),this}removeClassName(e){return this._classList.delete(e),this._updateClassList(),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){let t;return this._classList.delete(e)?t=!1:(this._classList.add(e),t=!0),this._updateClassList(),t}_onMouseEvent(e){this._update(e.point);}_getAnchor(e){if(this.options.anchor)return this.options.anchor;const t=this._map,i=this._container,o=this._pos;if(!t||!i||!o)return \"bottom\";const r=i.offsetWidth,s=i.offsetHeight,n=o.xt.transform.width-r/2;if(o.y+et.transform.height-s){if(n)return \"bottom-left\";if(a)return \"bottom-right\"}return n?\"left\":a?\"right\":\"bottom\"}_updateClassList(){const e=this._container;if(!e)return;const t=[...this._classList];t.push(\"mapboxgl-popup\"),this._anchor&&t.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&t.push(\"mapboxgl-popup-track-pointer\"),e.className=t.join(\" \");}_update(t){const i=this._map,o=this._content;if(!i||!this._lngLat&&!this._trackPointer||!o)return;let r=this._container;if(r||(r=this._container=s(\"div\",\"mapboxgl-popup\",i.getContainer()),this._tip=s(\"div\",\"mapboxgl-popup-tip\",r),r.appendChild(o)),this.options.maxWidth&&r.style.maxWidth!==this.options.maxWidth&&(r.style.maxWidth=this.options.maxWidth),i.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=zs(this._lngLat,this._pos,i.transform)),!this._trackPointer||t){const e=this._pos=this._trackPointer&&t?t:i.project(this._lngLat),o=Ns(this.options.offset),r=this._anchor=this._getAnchor(o.y),s=Ns(this.options.offset,r),n=e.add(s).round();i._requestDomTask((()=>{this._container&&r&&(this._container.style.transform=`${Os[r]} translate(${n.x}px,${n.y}px)`);}));}if(!this._marker&&i._showingGlobe()){const t=e.cN(i.transform,this._lngLat)?0:1;this._setOpacity(t);}this._updateClassList();}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(ks);e&&e.focus();}_onClose(){this.remove();}_setOpacity(e){this._container&&(this._container.style.opacity=`${e}`),this._content&&(this._content.style.pointerEvents=e?\"auto\":\"none\");}},Marker:Fs,Style:Dr,LngLat:e.L,LngLatBounds:e.D,Point:e.P,MercatorCoordinate:e.M,FreeCameraOptions:he,Evented:e.a6,config:e.cM,prewarm:e.d3,clearPrewarmedResources:e.d4,get accessToken(){return e.cM.ACCESS_TOKEN},set accessToken(t){e.cM.ACCESS_TOKEN=t;},get baseApiUrl(){return e.cM.API_URL},set baseApiUrl(t){e.cM.API_URL=t;},get workerCount(){return e.d5.workerCount},set workerCount(t){e.d5.workerCount=t;},get maxParallelImageRequests(){return e.cM.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(t){e.cM.MAX_PARALLEL_IMAGE_REQUESTS=t;},clearStorage(t){e.d6(t);},get workerUrl(){return e.d7.workerUrl},set workerUrl(t){e.d7.workerUrl=t;},get workerClass(){return e.d7.workerClass},set workerClass(t){e.d7.workerClass=t;},get workerParams(){return e.d7.workerParams},set workerParams(t){e.d7.workerParams=t;},get dracoUrl(){return e.d8()},set dracoUrl(t){e.d9(t);},setNow:e.a4.setNow,restoreNow:e.a4.restoreNow};return Xs}));\n\n//\n// Our custom intro provides a specialized \"define()\" function, called by the\n// AMD modules below, that sets up the worker blob URL and then executes the\n// main module, storing its exported value as 'mapboxgl'\n\n\nvar mapboxgl$1 = mapboxgl;\n\nreturn mapboxgl$1;\n\n}));\n//# sourceMappingURL=mapbox-gl.js.map\n","/**\n * Based on Kendo UI Core expression code \n */\n'use strict'\n\nfunction Cache(maxSize) {\n this._maxSize = maxSize\n this.clear()\n}\nCache.prototype.clear = function () {\n this._size = 0\n this._values = Object.create(null)\n}\nCache.prototype.get = function (key) {\n return this._values[key]\n}\nCache.prototype.set = function (key, value) {\n this._size >= this._maxSize && this.clear()\n if (!(key in this._values)) this._size++\n\n return (this._values[key] = value)\n}\n\nvar SPLIT_REGEX = /[^.^\\]^[]+|(?=\\[\\]|\\.\\.)/g,\n DIGIT_REGEX = /^\\d+$/,\n LEAD_DIGIT_REGEX = /^\\d/,\n SPEC_CHAR_REGEX = /[~`!#$%\\^&*+=\\-\\[\\]\\\\';,/{}|\\\\\":<>\\?]/g,\n CLEAN_QUOTES_REGEX = /^\\s*(['\"]?)(.*?)(\\1)\\s*$/,\n MAX_CACHE_SIZE = 512\n\nvar pathCache = new Cache(MAX_CACHE_SIZE),\n setCache = new Cache(MAX_CACHE_SIZE),\n getCache = new Cache(MAX_CACHE_SIZE)\n\nvar config\n\nmodule.exports = {\n Cache: Cache,\n\n split: split,\n\n normalizePath: normalizePath,\n\n setter: function (path) {\n var parts = normalizePath(path)\n\n return (\n setCache.get(path) ||\n setCache.set(path, function setter(obj, value) {\n var index = 0\n var len = parts.length\n var data = obj\n\n while (index < len - 1) {\n var part = parts[index]\n if (\n part === '__proto__' ||\n part === 'constructor' ||\n part === 'prototype'\n ) {\n return obj\n }\n\n data = data[parts[index++]]\n }\n data[parts[index]] = value\n })\n )\n },\n\n getter: function (path, safe) {\n var parts = normalizePath(path)\n return (\n getCache.get(path) ||\n getCache.set(path, function getter(data) {\n var index = 0,\n len = parts.length\n while (index < len) {\n if (data != null || !safe) data = data[parts[index++]]\n else return\n }\n return data\n })\n )\n },\n\n join: function (segments) {\n return segments.reduce(function (path, part) {\n return (\n path +\n (isQuoted(part) || DIGIT_REGEX.test(part)\n ? '[' + part + ']'\n : (path ? '.' : '') + part)\n )\n }, '')\n },\n\n forEach: function (path, cb, thisArg) {\n forEach(Array.isArray(path) ? path : split(path), cb, thisArg)\n },\n}\n\nfunction normalizePath(path) {\n return (\n pathCache.get(path) ||\n pathCache.set(\n path,\n split(path).map(function (part) {\n return part.replace(CLEAN_QUOTES_REGEX, '$2')\n })\n )\n )\n}\n\nfunction split(path) {\n return path.match(SPLIT_REGEX) || ['']\n}\n\nfunction forEach(parts, iter, thisArg) {\n var len = parts.length,\n part,\n idx,\n isArray,\n isBracket\n\n for (idx = 0; idx < len; idx++) {\n part = parts[idx]\n\n if (part) {\n if (shouldBeQuoted(part)) {\n part = '\"' + part + '\"'\n }\n\n isBracket = isQuoted(part)\n isArray = !isBracket && /^\\d+$/.test(part)\n\n iter.call(thisArg, part, isBracket, isArray, idx, parts)\n }\n }\n}\n\nfunction isQuoted(str) {\n return (\n typeof str === 'string' && str && [\"'\", '\"'].indexOf(str.charAt(0)) !== -1\n )\n}\n\nfunction hasLeadingNumber(part) {\n return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)\n}\n\nfunction hasSpecialChars(part) {\n return SPEC_CHAR_REGEX.test(part)\n}\n\nfunction shouldBeQuoted(part) {\n return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))\n}\n","const reWords = /[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde]|$)|(?:[A-Z\\xc0-\\xd6\\xd8-\\xde]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde](?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])|$)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?(?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])|\\d+|(?:[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?(?:\\u200d(?:[^\\ud800-\\udfff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?)*/g\n\nconst words = (str) => str.match(reWords) || []\n\nconst upperFirst = (str) => str[0].toUpperCase() + str.slice(1)\n\nconst join = (str, d) => words(str).join(d).toLowerCase()\n\nconst camelCase = (str) =>\n words(str).reduce(\n (acc, next) =>\n `${acc}${\n !acc\n ? next.toLowerCase()\n : next[0].toUpperCase() + next.slice(1).toLowerCase()\n }`,\n '',\n )\n\nconst pascalCase = (str) => upperFirst(camelCase(str))\n\nconst snakeCase = (str) => join(str, '_')\n\nconst kebabCase = (str) => join(str, '-')\n\nconst sentenceCase = (str) => upperFirst(join(str, ' '))\n\nconst titleCase = (str) => words(str).map(upperFirst).join(' ')\n\nmodule.exports = {\n words,\n upperFirst,\n camelCase,\n pascalCase,\n snakeCase,\n kebabCase,\n sentenceCase,\n titleCase,\n}\n","\n/**\n * Topological sorting function\n *\n * @param {Array} edges\n * @returns {Array}\n */\n\nmodule.exports = function(edges) {\n return toposort(uniqueNodes(edges), edges)\n}\n\nmodule.exports.array = toposort\n\nfunction toposort(nodes, edges) {\n var cursor = nodes.length\n , sorted = new Array(cursor)\n , visited = {}\n , i = cursor\n // Better data structures make algorithm much faster.\n , outgoingEdges = makeOutgoingEdges(edges)\n , nodesHash = makeNodesHash(nodes)\n\n // check for unknown nodes\n edges.forEach(function(edge) {\n if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {\n throw new Error('Unknown node. There is an unknown node in the supplied edges.')\n }\n })\n\n while (i--) {\n if (!visited[i]) visit(nodes[i], i, new Set())\n }\n\n return sorted\n\n function visit(node, i, predecessors) {\n if(predecessors.has(node)) {\n var nodeRep\n try {\n nodeRep = \", node was:\" + JSON.stringify(node)\n } catch(e) {\n nodeRep = \"\"\n }\n throw new Error('Cyclic dependency' + nodeRep)\n }\n\n if (!nodesHash.has(node)) {\n throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node))\n }\n\n if (visited[i]) return;\n visited[i] = true\n\n var outgoing = outgoingEdges.get(node) || new Set()\n outgoing = Array.from(outgoing)\n\n if (i = outgoing.length) {\n predecessors.add(node)\n do {\n var child = outgoing[--i]\n visit(child, nodesHash.get(child), predecessors)\n } while (i)\n predecessors.delete(node)\n }\n\n sorted[--cursor] = node\n }\n}\n\nfunction uniqueNodes(arr){\n var res = new Set()\n for (var i = 0, len = arr.length; i < len; i++) {\n var edge = arr[i]\n res.add(edge[0])\n res.add(edge[1])\n }\n return Array.from(res)\n}\n\nfunction makeOutgoingEdges(arr){\n var edges = new Map()\n for (var i = 0, len = arr.length; i < len; i++) {\n var edge = arr[i]\n if (!edges.has(edge[0])) edges.set(edge[0], new Set())\n if (!edges.has(edge[1])) edges.set(edge[1], new Set())\n edges.get(edge[0]).add(edge[1])\n }\n return edges\n}\n\nfunction makeNodesHash(arr){\n var res = new Map()\n for (var i = 0, len = arr.length; i < len; i++) {\n res.set(arr[i], i)\n }\n return res\n}\n","import { getter, forEach, split, normalizePath, join } from 'property-expr';\nimport { camelCase, snakeCase } from 'tiny-case';\nimport toposort from 'toposort';\n\nconst toString = Object.prototype.toString;\nconst errorToString = Error.prototype.toString;\nconst regExpToString = RegExp.prototype.toString;\nconst symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';\nconst SYMBOL_REGEXP = /^Symbol\\((.*)\\)(.*)$/;\n\nfunction printNumber(val) {\n if (val != +val) return 'NaN';\n const isNegativeZero = val === 0 && 1 / val < 0;\n return isNegativeZero ? '-0' : '' + val;\n}\n\nfunction printSimpleValue(val, quoteStrings = false) {\n if (val == null || val === true || val === false) return '' + val;\n const typeOf = typeof val;\n if (typeOf === 'number') return printNumber(val);\n if (typeOf === 'string') return quoteStrings ? `\"${val}\"` : val;\n if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';\n if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');\n const tag = toString.call(val).slice(8, -1);\n if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);\n if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';\n if (tag === 'RegExp') return regExpToString.call(val);\n return null;\n}\n\nfunction printValue(value, quoteStrings) {\n let result = printSimpleValue(value, quoteStrings);\n if (result !== null) return result;\n return JSON.stringify(value, function (key, value) {\n let result = printSimpleValue(this[key], quoteStrings);\n if (result !== null) return result;\n return value;\n }, 2);\n}\n\nfunction toArray(value) {\n return value == null ? [] : [].concat(value);\n}\n\nlet strReg = /\\$\\{\\s*(\\w+)\\s*\\}/g;\nclass ValidationError extends Error {\n static formatError(message, params) {\n const path = params.label || params.path || 'this';\n if (path !== params.path) params = Object.assign({}, params, {\n path\n });\n if (typeof message === 'string') return message.replace(strReg, (_, key) => printValue(params[key]));\n if (typeof message === 'function') return message(params);\n return message;\n }\n\n static isError(err) {\n return err && err.name === 'ValidationError';\n }\n\n constructor(errorOrErrors, value, field, type) {\n super();\n this.value = void 0;\n this.path = void 0;\n this.type = void 0;\n this.errors = void 0;\n this.params = void 0;\n this.inner = void 0;\n this.name = 'ValidationError';\n this.value = value;\n this.path = field;\n this.type = type;\n this.errors = [];\n this.inner = [];\n toArray(errorOrErrors).forEach(err => {\n if (ValidationError.isError(err)) {\n this.errors.push(...err.errors);\n this.inner = this.inner.concat(err.inner.length ? err.inner : err);\n } else {\n this.errors.push(err);\n }\n });\n this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];\n if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);\n }\n\n}\n\nlet mixed = {\n default: '${path} is invalid',\n required: '${path} is a required field',\n defined: '${path} must be defined',\n notNull: '${path} cannot be null',\n oneOf: '${path} must be one of the following values: ${values}',\n notOneOf: '${path} must not be one of the following values: ${values}',\n notType: ({\n path,\n type,\n value,\n originalValue\n }) => {\n const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \\`${printValue(originalValue, true)}\\`).` : '.';\n return type !== 'mixed' ? `${path} must be a \\`${type}\\` type, ` + `but the final value was: \\`${printValue(value, true)}\\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \\`${printValue(value, true)}\\`` + castMsg;\n }\n};\nlet string = {\n length: '${path} must be exactly ${length} characters',\n min: '${path} must be at least ${min} characters',\n max: '${path} must be at most ${max} characters',\n matches: '${path} must match the following: \"${regex}\"',\n email: '${path} must be a valid email',\n url: '${path} must be a valid URL',\n uuid: '${path} must be a valid UUID',\n trim: '${path} must be a trimmed string',\n lowercase: '${path} must be a lowercase string',\n uppercase: '${path} must be a upper case string'\n};\nlet number = {\n min: '${path} must be greater than or equal to ${min}',\n max: '${path} must be less than or equal to ${max}',\n lessThan: '${path} must be less than ${less}',\n moreThan: '${path} must be greater than ${more}',\n positive: '${path} must be a positive number',\n negative: '${path} must be a negative number',\n integer: '${path} must be an integer'\n};\nlet date = {\n min: '${path} field must be later than ${min}',\n max: '${path} field must be at earlier than ${max}'\n};\nlet boolean = {\n isValue: '${path} field must be ${value}'\n};\nlet object = {\n noUnknown: '${path} field has unspecified keys: ${unknown}'\n};\nlet array = {\n min: '${path} field must have at least ${min} items',\n max: '${path} field must have less than or equal to ${max} items',\n length: '${path} must have ${length} items'\n};\nlet tuple = {\n notType: params => {\n const {\n path,\n value,\n spec\n } = params;\n const typeLen = spec.types.length;\n\n if (Array.isArray(value)) {\n if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \\`${printValue(value, true)}\\``;\n if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \\`${printValue(value, true)}\\``;\n }\n\n return ValidationError.formatError(mixed.notType, params);\n }\n};\nvar locale = Object.assign(Object.create(null), {\n mixed,\n string,\n number,\n date,\n object,\n array,\n boolean\n});\n\nconst isSchema = obj => obj && obj.__isYupSchema__;\n\nclass Condition {\n static fromOptions(refs, config) {\n if (!config.then && !config.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');\n let {\n is,\n then,\n otherwise\n } = config;\n let check = typeof is === 'function' ? is : (...values) => values.every(value => value === is);\n return new Condition(refs, (values, schema) => {\n var _branch;\n\n let branch = check(...values) ? then : otherwise;\n return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;\n });\n }\n\n constructor(refs, builder) {\n this.fn = void 0;\n this.refs = refs;\n this.refs = refs;\n this.fn = builder;\n }\n\n resolve(base, options) {\n let values = this.refs.map(ref => // TODO: ? operator here?\n ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));\n let schema = this.fn(values, base, options);\n\n if (schema === undefined || // @ts-ignore this can be base\n schema === base) {\n return base;\n }\n\n if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');\n return schema.resolve(options);\n }\n\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nconst prefixes = {\n context: '$',\n value: '.'\n};\nfunction create$9(key, options) {\n return new Reference(key, options);\n}\nclass Reference {\n constructor(key, options = {}) {\n this.key = void 0;\n this.isContext = void 0;\n this.isValue = void 0;\n this.isSibling = void 0;\n this.path = void 0;\n this.getter = void 0;\n this.map = void 0;\n if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);\n this.key = key.trim();\n if (key === '') throw new TypeError('ref must be a non-empty string');\n this.isContext = this.key[0] === prefixes.context;\n this.isValue = this.key[0] === prefixes.value;\n this.isSibling = !this.isContext && !this.isValue;\n let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';\n this.path = this.key.slice(prefix.length);\n this.getter = this.path && getter(this.path, true);\n this.map = options.map;\n }\n\n getValue(value, parent, context) {\n let result = this.isContext ? context : this.isValue ? value : parent;\n if (this.getter) result = this.getter(result || {});\n if (this.map) result = this.map(result);\n return result;\n }\n /**\n *\n * @param {*} value\n * @param {Object} options\n * @param {Object=} options.context\n * @param {Object=} options.parent\n */\n\n\n cast(value, options) {\n return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);\n }\n\n resolve() {\n return this;\n }\n\n describe() {\n return {\n type: 'ref',\n key: this.key\n };\n }\n\n toString() {\n return `Ref(${this.key})`;\n }\n\n static isRef(value) {\n return value && value.__isYupRef;\n }\n\n} // @ts-ignore\n\nReference.prototype.__isYupRef = true;\n\nconst isAbsent = value => value == null;\n\nconst _excluded = [\"value\", \"path\", \"label\", \"options\", \"originalValue\", \"spec\", \"sync\"];\nfunction createValidation(config) {\n function validate(_ref, panic, next) {\n let {\n value,\n path = '',\n label,\n options,\n originalValue,\n spec,\n sync\n } = _ref,\n rest = _objectWithoutPropertiesLoose(_ref, _excluded);\n\n const {\n name,\n test,\n params,\n message,\n skipAbsent\n } = config;\n let {\n parent,\n context,\n abortEarly = rest.schema.spec.abortEarly\n } = options;\n\n function resolve(item) {\n return Reference.isRef(item) ? item.getValue(value, parent, context) : item;\n }\n\n function createError(overrides = {}) {\n const nextParams = Object.assign({\n value,\n originalValue,\n label,\n path: overrides.path || path,\n spec\n }, params, overrides.params);\n\n for (const key of Object.keys(nextParams)) nextParams[key] = resolve(nextParams[key]);\n\n const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name);\n error.params = nextParams;\n return error;\n }\n\n const invalid = abortEarly ? panic : next;\n let ctx = Object.assign({\n path,\n parent,\n type: name,\n createError,\n resolve,\n options,\n originalValue\n }, rest);\n\n const handleResult = validOrError => {\n if (ValidationError.isError(validOrError)) invalid(validOrError);else if (!validOrError) invalid(createError());else next(null);\n };\n\n const handleError = err => {\n if (ValidationError.isError(err)) invalid(err);else panic(err);\n };\n\n const shouldSkip = skipAbsent && isAbsent(value);\n\n if (!sync) {\n try {\n Promise.resolve(!shouldSkip ? test.call(ctx, value, ctx) : true).then(handleResult, handleError);\n } catch (err) {\n handleError(err);\n }\n\n return;\n }\n\n let result;\n\n try {\n var _result;\n\n result = !shouldSkip ? test.call(ctx, value, ctx) : true;\n\n if (typeof ((_result = result) == null ? void 0 : _result.then) === 'function') {\n throw new Error(`Validation test of type: \"${ctx.type}\" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`);\n }\n } catch (err) {\n handleError(err);\n return;\n }\n\n handleResult(result);\n }\n\n validate.OPTIONS = config;\n return validate;\n}\n\nlet trim = part => part.substr(0, part.length - 1).substr(1);\n\nfunction getIn(schema, path, value, context = value) {\n let parent, lastPart, lastPartDebug; // root path: ''\n\n if (!path) return {\n parent,\n parentPath: path,\n schema\n };\n forEach(path, (_part, isBracket, isArray) => {\n let part = isBracket ? trim(_part) : _part;\n schema = schema.resolve({\n context,\n parent,\n value\n });\n let isTuple = schema.type === 'tuple';\n let idx = isArray ? parseInt(part, 10) : 0;\n\n if (schema.innerType || isTuple) {\n if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part \"${lastPartDebug}\" must contain an index to the tuple element, e.g. \"${lastPartDebug}[0]\"`);\n\n if (value && idx >= value.length) {\n throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `);\n }\n\n parent = value;\n value = value && value[idx];\n schema = isTuple ? schema.spec.types[idx] : schema.innerType;\n } // sometimes the array index part of a path doesn't exist: \"nested.arr.child\"\n // in these cases the current part is the next schema and should be processed\n // in this iteration. For cases where the index signature is included this\n // check will fail and we'll handle the `child` part on the next iteration like normal\n\n\n if (!isArray) {\n if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: \"${schema.type}\")`);\n parent = value;\n value = value && value[part];\n schema = schema.fields[part];\n }\n\n lastPart = part;\n lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;\n });\n return {\n schema,\n parent,\n parentPath: lastPart\n };\n}\n\nconst reach = (obj, path, value, context) => getIn(obj, path, value, context).schema;\n\nclass ReferenceSet {\n constructor() {\n this.list = void 0;\n this.refs = void 0;\n this.list = new Set();\n this.refs = new Map();\n }\n\n get size() {\n return this.list.size + this.refs.size;\n }\n\n describe() {\n const description = [];\n\n for (const item of this.list) description.push(item);\n\n for (const [, ref] of this.refs) description.push(ref.describe());\n\n return description;\n }\n\n toArray() {\n return Array.from(this.list).concat(Array.from(this.refs.values()));\n }\n\n resolveAll(resolve) {\n return this.toArray().reduce((acc, e) => acc.concat(Reference.isRef(e) ? resolve(e) : e), []);\n }\n\n add(value) {\n Reference.isRef(value) ? this.refs.set(value.key, value) : this.list.add(value);\n }\n\n delete(value) {\n Reference.isRef(value) ? this.refs.delete(value.key) : this.list.delete(value);\n }\n\n clone() {\n const next = new ReferenceSet();\n next.list = new Set(this.list);\n next.refs = new Map(this.refs);\n return next;\n }\n\n merge(newItems, removeItems) {\n const next = this.clone();\n newItems.list.forEach(value => next.add(value));\n newItems.refs.forEach(value => next.add(value));\n removeItems.list.forEach(value => next.delete(value));\n removeItems.refs.forEach(value => next.delete(value));\n return next;\n }\n\n}\n\n// tweaked from https://github.com/Kelin2025/nanoclone/blob/0abeb7635bda9b68ef2277093f76dbe3bf3948e1/src/index.js\n\nfunction clone(src, seen = new Map()) {\n if (isSchema(src) || !src || typeof src !== 'object') return src;\n if (seen.has(src)) return seen.get(src);\n let copy;\n\n if (src instanceof Date) {\n // Date\n copy = new Date(src.getTime());\n seen.set(src, copy);\n } else if (src instanceof RegExp) {\n // RegExp\n copy = new RegExp(src);\n seen.set(src, copy);\n } else if (Array.isArray(src)) {\n // Array\n copy = new Array(src.length);\n seen.set(src, copy);\n\n for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);\n } else if (src instanceof Map) {\n // Map\n copy = new Map();\n seen.set(src, copy);\n\n for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));\n } else if (src instanceof Set) {\n // Set\n copy = new Set();\n seen.set(src, copy);\n\n for (const v of src) copy.add(clone(v, seen));\n } else if (src instanceof Object) {\n // Object\n copy = {};\n seen.set(src, copy);\n\n for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);\n } else {\n throw Error(`Unable to clone ${src}`);\n }\n\n return copy;\n}\n\nclass Schema {\n constructor(options) {\n this.type = void 0;\n this.deps = [];\n this.tests = void 0;\n this.transforms = void 0;\n this.conditions = [];\n this._mutate = void 0;\n this.internalTests = {};\n this._whitelist = new ReferenceSet();\n this._blacklist = new ReferenceSet();\n this.exclusiveTests = Object.create(null);\n this._typeCheck = void 0;\n this.spec = void 0;\n this.tests = [];\n this.transforms = [];\n this.withMutation(() => {\n this.typeError(mixed.notType);\n });\n this.type = options.type;\n this._typeCheck = options.check;\n this.spec = Object.assign({\n strip: false,\n strict: false,\n abortEarly: true,\n recursive: true,\n nullable: false,\n optional: true,\n coarce: true\n }, options == null ? void 0 : options.spec);\n this.withMutation(s => {\n s.nonNullable();\n });\n } // TODO: remove\n\n\n get _type() {\n return this.type;\n }\n\n clone(spec) {\n if (this._mutate) {\n if (spec) Object.assign(this.spec, spec);\n return this;\n } // if the nested value is a schema we can skip cloning, since\n // they are already immutable\n\n\n const next = Object.create(Object.getPrototypeOf(this)); // @ts-expect-error this is readonly\n\n next.type = this.type;\n next._typeCheck = this._typeCheck;\n next._whitelist = this._whitelist.clone();\n next._blacklist = this._blacklist.clone();\n next.internalTests = Object.assign({}, this.internalTests);\n next.exclusiveTests = Object.assign({}, this.exclusiveTests); // @ts-expect-error this is readonly\n\n next.deps = [...this.deps];\n next.conditions = [...this.conditions];\n next.tests = [...this.tests];\n next.transforms = [...this.transforms];\n next.spec = clone(Object.assign({}, this.spec, spec));\n return next;\n }\n\n label(label) {\n let next = this.clone();\n next.spec.label = label;\n return next;\n }\n\n meta(...args) {\n if (args.length === 0) return this.spec.meta;\n let next = this.clone();\n next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);\n return next;\n }\n\n withMutation(fn) {\n let before = this._mutate;\n this._mutate = true;\n let result = fn(this);\n this._mutate = before;\n return result;\n }\n\n concat(schema) {\n if (!schema || schema === this) return this;\n if (schema.type !== this.type && this.type !== 'mixed') throw new TypeError(`You cannot \\`concat()\\` schema's of different types: ${this.type} and ${schema.type}`);\n let base = this;\n let combined = schema.clone();\n const mergedSpec = Object.assign({}, base.spec, combined.spec);\n combined.spec = mergedSpec;\n combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests); // manually merge the blacklist/whitelist (the other `schema` takes\n // precedence in case of conflicts)\n\n combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);\n combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist); // start with the current tests\n\n combined.tests = base.tests;\n combined.exclusiveTests = base.exclusiveTests; // manually add the new tests to ensure\n // the deduping logic is consistent\n\n combined.withMutation(next => {\n schema.tests.forEach(fn => {\n next.test(fn.OPTIONS);\n });\n });\n combined.transforms = [...base.transforms, ...combined.transforms];\n return combined;\n }\n\n isType(v) {\n if (v == null) {\n if (this.spec.nullable && v === null) return true;\n if (this.spec.optional && v === undefined) return true;\n return false;\n }\n\n return this._typeCheck(v);\n }\n\n resolve(options) {\n let schema = this;\n\n if (schema.conditions.length) {\n let conditions = schema.conditions;\n schema = schema.clone();\n schema.conditions = [];\n schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);\n schema = schema.resolve(options);\n }\n\n return schema;\n }\n\n resolveOptions(options) {\n var _options$strict, _options$abortEarly, _options$recursive;\n\n return Object.assign({}, options, {\n from: options.from || [],\n strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,\n abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,\n recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive\n });\n }\n /**\n * Run the configured transform pipeline over an input value.\n */\n\n\n cast(value, options = {}) {\n let resolvedSchema = this.resolve(Object.assign({\n value\n }, options));\n\n let result = resolvedSchema._cast(value, options);\n\n if (options.assert !== false && !resolvedSchema.isType(result)) {\n let formattedValue = printValue(value);\n let formattedResult = printValue(result);\n throw new TypeError(`The value of ${options.path || 'field'} could not be cast to a value ` + `that satisfies the schema type: \"${resolvedSchema.type}\". \\n\\n` + `attempted value: ${formattedValue} \\n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ''));\n }\n\n return result;\n }\n\n _cast(rawValue, _options) {\n let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this), rawValue);\n\n if (value === undefined) {\n value = this.getDefault();\n }\n\n return value;\n }\n\n _validate(_value, options = {}, panic, next) {\n let {\n sync,\n path,\n from = [],\n originalValue = _value,\n strict = this.spec.strict\n } = options;\n let value = _value;\n\n if (!strict) {\n value = this._cast(value, Object.assign({\n assert: false\n }, options));\n } // value is cast, we can check if it meets type requirements\n\n\n let args = {\n value,\n path,\n options,\n originalValue,\n schema: this,\n label: this.spec.label,\n spec: this.spec,\n sync,\n from\n };\n let initialTests = [];\n\n for (let test of Object.values(this.internalTests)) {\n if (test) initialTests.push(test);\n }\n\n this.runTests({\n args,\n value,\n tests: initialTests\n }, panic, initialErrors => {\n // even if we aren't ending early we can't proceed further if the types aren't correct\n if (initialErrors.length) {\n return next(initialErrors, value);\n }\n\n this.runTests({\n args,\n value,\n tests: this.tests\n }, panic, next);\n });\n }\n /**\n * Executes a set of validations, either schema, produced Tests or a nested\n * schema validate result. `args` is intended for schema validation tests, but\n * isn't required to allow the helper to awkwardly be used to run nested array/object\n * validations.\n */\n\n\n runTests(options, panic, next) {\n let fired = false;\n let {\n tests,\n args,\n value\n } = options;\n\n let panicOnce = arg => {\n if (fired) return;\n fired = true;\n panic(arg, value);\n };\n\n let nextOnce = arg => {\n if (fired) return;\n fired = true;\n next(arg, value);\n };\n\n let count = tests.length;\n let nestedErrors = [];\n if (!count) return nextOnce([]);\n\n for (let i = 0; i < tests.length; i++) {\n const test = tests[i];\n test(args, panicOnce, function finishTestRun(err) {\n if (err) {\n nestedErrors = nestedErrors.concat(err);\n }\n\n if (--count <= 0) {\n nextOnce(nestedErrors);\n }\n });\n }\n }\n\n asNestedTest({\n key,\n index,\n parent,\n parentPath,\n originalParent,\n options\n }) {\n const k = key != null ? key : index;\n\n if (k == null) {\n throw TypeError('Must include `key` or `index` for nested validations');\n }\n\n const isIndex = typeof k === 'number';\n let value = parent[k];\n const testOptions = Object.assign({}, options, {\n // Nested validations fields are always strict:\n // 1. parent isn't strict so the casting will also have cast inner values\n // 2. parent is strict in which case the nested values weren't cast either\n strict: true,\n parent,\n value,\n originalValue: originalParent[k],\n // FIXME: tests depend on `index` being passed around deeply,\n // we should not let the options.key/index bleed through\n key: undefined,\n // index: undefined,\n [isIndex ? 'index' : 'key']: k,\n path: isIndex || k.includes('.') ? `${parentPath || ''}[${value ? k : `\"${k}\"`}]` : (parentPath ? `${parentPath}.` : '') + key\n });\n return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);\n }\n\n validate(value, options) {\n let schema = this.resolve(Object.assign({}, options, {\n value\n }));\n return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {\n if (ValidationError.isError(error)) error.value = parsed;\n reject(error);\n }, (errors, validated) => {\n if (errors.length) reject(new ValidationError(errors, validated));else resolve(validated);\n }));\n }\n\n validateSync(value, options) {\n let schema = this.resolve(Object.assign({}, options, {\n value\n }));\n let result;\n\n schema._validate(value, Object.assign({}, options, {\n sync: true\n }), (error, parsed) => {\n if (ValidationError.isError(error)) error.value = parsed;\n throw error;\n }, (errors, validated) => {\n if (errors.length) throw new ValidationError(errors, value);\n result = validated;\n });\n\n return result;\n }\n\n isValid(value, options) {\n return this.validate(value, options).then(() => true, err => {\n if (ValidationError.isError(err)) return false;\n throw err;\n });\n }\n\n isValidSync(value, options) {\n try {\n this.validateSync(value, options);\n return true;\n } catch (err) {\n if (ValidationError.isError(err)) return false;\n throw err;\n }\n }\n\n _getDefault() {\n let defaultValue = this.spec.default;\n\n if (defaultValue == null) {\n return defaultValue;\n }\n\n return typeof defaultValue === 'function' ? defaultValue.call(this) : clone(defaultValue);\n }\n\n getDefault(options // If schema is defaulted we know it's at least not undefined\n ) {\n let schema = this.resolve(options || {});\n return schema._getDefault();\n }\n\n default(def) {\n if (arguments.length === 0) {\n return this._getDefault();\n }\n\n let next = this.clone({\n default: def\n });\n return next;\n }\n\n strict(isStrict = true) {\n return this.clone({\n strict: isStrict\n });\n }\n\n nullability(nullable, message) {\n const next = this.clone({\n nullable\n });\n next.internalTests.nullable = createValidation({\n message,\n name: 'nullable',\n\n test(value) {\n return value === null ? this.schema.spec.nullable : true;\n }\n\n });\n return next;\n }\n\n optionality(optional, message) {\n const next = this.clone({\n optional\n });\n next.internalTests.optionality = createValidation({\n message,\n name: 'optionality',\n\n test(value) {\n return value === undefined ? this.schema.spec.optional : true;\n }\n\n });\n return next;\n }\n\n optional() {\n return this.optionality(true);\n }\n\n defined(message = mixed.defined) {\n return this.optionality(false, message);\n }\n\n nullable() {\n return this.nullability(true);\n }\n\n nonNullable(message = mixed.notNull) {\n return this.nullability(false, message);\n }\n\n required(message = mixed.required) {\n return this.clone().withMutation(next => next.nonNullable(message).defined(message));\n }\n\n notRequired() {\n return this.clone().withMutation(next => next.nullable().optional());\n }\n\n transform(fn) {\n let next = this.clone();\n next.transforms.push(fn);\n return next;\n }\n /**\n * Adds a test function to the schema's queue of tests.\n * tests can be exclusive or non-exclusive.\n *\n * - exclusive tests, will replace any existing tests of the same name.\n * - non-exclusive: can be stacked\n *\n * If a non-exclusive test is added to a schema with an exclusive test of the same name\n * the exclusive test is removed and further tests of the same name will be stacked.\n *\n * If an exclusive test is added to a schema with non-exclusive tests of the same name\n * the previous tests are removed and further tests of the same name will replace each other.\n */\n\n\n test(...args) {\n let opts;\n\n if (args.length === 1) {\n if (typeof args[0] === 'function') {\n opts = {\n test: args[0]\n };\n } else {\n opts = args[0];\n }\n } else if (args.length === 2) {\n opts = {\n name: args[0],\n test: args[1]\n };\n } else {\n opts = {\n name: args[0],\n message: args[1],\n test: args[2]\n };\n }\n\n if (opts.message === undefined) opts.message = mixed.default;\n if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');\n let next = this.clone();\n let validate = createValidation(opts);\n let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;\n\n if (opts.exclusive) {\n if (!opts.name) throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');\n }\n\n if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;\n next.tests = next.tests.filter(fn => {\n if (fn.OPTIONS.name === opts.name) {\n if (isExclusive) return false;\n if (fn.OPTIONS.test === validate.OPTIONS.test) return false;\n }\n\n return true;\n });\n next.tests.push(validate);\n return next;\n }\n\n when(keys, options) {\n if (!Array.isArray(keys) && typeof keys !== 'string') {\n options = keys;\n keys = '.';\n }\n\n let next = this.clone();\n let deps = toArray(keys).map(key => new Reference(key));\n deps.forEach(dep => {\n // @ts-ignore readonly array\n if (dep.isSibling) next.deps.push(dep.key);\n });\n next.conditions.push(typeof options === 'function' ? new Condition(deps, options) : Condition.fromOptions(deps, options));\n return next;\n }\n\n typeError(message) {\n let next = this.clone();\n next.internalTests.typeError = createValidation({\n message,\n name: 'typeError',\n\n test(value) {\n if (!isAbsent(value) && !this.schema._typeCheck(value)) return this.createError({\n params: {\n type: this.schema.type\n }\n });\n return true;\n }\n\n });\n return next;\n }\n\n oneOf(enums, message = mixed.oneOf) {\n let next = this.clone();\n enums.forEach(val => {\n next._whitelist.add(val);\n\n next._blacklist.delete(val);\n });\n next.internalTests.whiteList = createValidation({\n message,\n name: 'oneOf',\n\n test(value) {\n if (value === undefined) return true;\n let valids = this.schema._whitelist;\n let resolved = valids.resolveAll(this.resolve);\n return resolved.includes(value) ? true : this.createError({\n params: {\n values: valids.toArray().join(', '),\n resolved\n }\n });\n }\n\n });\n return next;\n }\n\n notOneOf(enums, message = mixed.notOneOf) {\n let next = this.clone();\n enums.forEach(val => {\n next._blacklist.add(val);\n\n next._whitelist.delete(val);\n });\n next.internalTests.blacklist = createValidation({\n message,\n name: 'notOneOf',\n\n test(value) {\n let invalids = this.schema._blacklist;\n let resolved = invalids.resolveAll(this.resolve);\n if (resolved.includes(value)) return this.createError({\n params: {\n values: invalids.toArray().join(', '),\n resolved\n }\n });\n return true;\n }\n\n });\n return next;\n }\n\n strip(strip = true) {\n let next = this.clone();\n next.spec.strip = strip;\n return next;\n }\n /**\n * Return a serialized description of the schema including validations, flags, types etc.\n *\n * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).\n */\n\n\n describe(options) {\n const next = (options ? this.resolve(options) : this).clone();\n const {\n label,\n meta,\n optional,\n nullable\n } = next.spec;\n const description = {\n meta,\n label,\n optional,\n nullable,\n type: next.type,\n oneOf: next._whitelist.describe(),\n notOneOf: next._blacklist.describe(),\n tests: next.tests.map(fn => ({\n name: fn.OPTIONS.name,\n params: fn.OPTIONS.params\n })).filter((n, idx, list) => list.findIndex(c => c.name === n.name) === idx)\n };\n return description;\n }\n\n}\n// @ts-expect-error\nSchema.prototype.__isYupSchema__ = true;\n\nfor (const method of ['validate', 'validateSync']) Schema.prototype[`${method}At`] = function (path, value, options = {}) {\n const {\n parent,\n parentPath,\n schema\n } = getIn(this, path, value, options.context);\n return schema[method](parent && parent[parentPath], Object.assign({}, options, {\n parent,\n path\n }));\n};\n\nfor (const alias of ['equals', 'is']) Schema.prototype[alias] = Schema.prototype.oneOf;\n\nfor (const alias of ['not', 'nope']) Schema.prototype[alias] = Schema.prototype.notOneOf;\n\nconst returnsTrue = () => true;\n\nfunction create$8(spec) {\n return new MixedSchema(spec);\n}\nclass MixedSchema extends Schema {\n constructor(spec) {\n super(typeof spec === 'function' ? {\n type: 'mixed',\n check: spec\n } : Object.assign({\n type: 'mixed',\n check: returnsTrue\n }, spec));\n }\n\n}\ncreate$8.prototype = MixedSchema.prototype;\n\nfunction create$7() {\n return new BooleanSchema();\n}\nclass BooleanSchema extends Schema {\n constructor() {\n super({\n type: 'boolean',\n\n check(v) {\n if (v instanceof Boolean) v = v.valueOf();\n return typeof v === 'boolean';\n }\n\n });\n this.withMutation(() => {\n this.transform((value, _raw, ctx) => {\n if (ctx.spec.coarce && !ctx.isType(value)) {\n if (/^(true|1)$/i.test(String(value))) return true;\n if (/^(false|0)$/i.test(String(value))) return false;\n }\n\n return value;\n });\n });\n }\n\n isTrue(message = boolean.isValue) {\n return this.test({\n message,\n name: 'is-value',\n exclusive: true,\n params: {\n value: 'true'\n },\n\n test(value) {\n return isAbsent(value) || value === true;\n }\n\n });\n }\n\n isFalse(message = boolean.isValue) {\n return this.test({\n message,\n name: 'is-value',\n exclusive: true,\n params: {\n value: 'false'\n },\n\n test(value) {\n return isAbsent(value) || value === false;\n }\n\n });\n }\n\n default(def) {\n return super.default(def);\n } // concat>(schema: TOther): TOther;\n\n\n defined(msg) {\n return super.defined(msg);\n }\n\n optional() {\n return super.defined();\n }\n\n required(msg) {\n return super.required(msg);\n }\n\n notRequired() {\n return super.notRequired();\n }\n\n nullable() {\n return super.nullable();\n }\n\n nonNullable(msg) {\n return super.nonNullable(msg);\n }\n\n strip(v) {\n return super.strip(v);\n }\n\n}\ncreate$7.prototype = BooleanSchema.prototype;\n\nlet rEmail = // eslint-disable-next-line\n/^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\nlet rUrl = // eslint-disable-next-line\n/^((https?|ftp):)?\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)*)*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$/i; // eslint-disable-next-line\n\nlet rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\n\nlet isTrimmed = value => isAbsent(value) || value === value.trim();\n\nlet objStringTag = {}.toString();\n\nfunction create$6() {\n return new StringSchema();\n}\nclass StringSchema extends Schema {\n constructor() {\n super({\n type: 'string',\n\n check(value) {\n if (value instanceof String) value = value.valueOf();\n return typeof value === 'string';\n }\n\n });\n this.withMutation(() => {\n this.transform((value, _raw, ctx) => {\n if (!ctx.spec.coarce || ctx.isType(value)) return value; // don't ever convert arrays\n\n if (Array.isArray(value)) return value;\n const strValue = value != null && value.toString ? value.toString() : value; // no one wants plain objects converted to [Object object]\n\n if (strValue === objStringTag) return value;\n return strValue;\n });\n });\n }\n\n required(message) {\n return super.required(message).withMutation(schema => schema.test({\n message: message || mixed.required,\n name: 'required',\n skipAbsent: true,\n test: value => !!value.length\n }));\n }\n\n notRequired() {\n return super.notRequired().withMutation(schema => {\n schema.tests.filter(t => t.OPTIONS.name !== 'required');\n return schema;\n });\n }\n\n length(length, message = string.length) {\n return this.test({\n message,\n name: 'length',\n exclusive: true,\n params: {\n length\n },\n skipAbsent: true,\n\n test(value) {\n return value.length === this.resolve(length);\n }\n\n });\n }\n\n min(min, message = string.min) {\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n\n test(value) {\n return value.length >= this.resolve(min);\n }\n\n });\n }\n\n max(max, message = string.max) {\n return this.test({\n name: 'max',\n exclusive: true,\n message,\n params: {\n max\n },\n skipAbsent: true,\n\n test(value) {\n return value.length <= this.resolve(max);\n }\n\n });\n }\n\n matches(regex, options) {\n let excludeEmptyString = false;\n let message;\n let name;\n\n if (options) {\n if (typeof options === 'object') {\n ({\n excludeEmptyString = false,\n message,\n name\n } = options);\n } else {\n message = options;\n }\n }\n\n return this.test({\n name: name || 'matches',\n message: message || string.matches,\n params: {\n regex\n },\n skipAbsent: true,\n test: value => value === '' && excludeEmptyString || value.search(regex) !== -1\n });\n }\n\n email(message = string.email) {\n return this.matches(rEmail, {\n name: 'email',\n message,\n excludeEmptyString: true\n });\n }\n\n url(message = string.url) {\n return this.matches(rUrl, {\n name: 'url',\n message,\n excludeEmptyString: true\n });\n }\n\n uuid(message = string.uuid) {\n return this.matches(rUUID, {\n name: 'uuid',\n message,\n excludeEmptyString: false\n });\n } //-- transforms --\n\n\n ensure() {\n return this.default('').transform(val => val === null ? '' : val);\n }\n\n trim(message = string.trim) {\n return this.transform(val => val != null ? val.trim() : val).test({\n message,\n name: 'trim',\n test: isTrimmed\n });\n }\n\n lowercase(message = string.lowercase) {\n return this.transform(value => !isAbsent(value) ? value.toLowerCase() : value).test({\n message,\n name: 'string_case',\n exclusive: true,\n skipAbsent: true,\n test: value => isAbsent(value) || value === value.toLowerCase()\n });\n }\n\n uppercase(message = string.uppercase) {\n return this.transform(value => !isAbsent(value) ? value.toUpperCase() : value).test({\n message,\n name: 'string_case',\n exclusive: true,\n skipAbsent: true,\n test: value => isAbsent(value) || value === value.toUpperCase()\n });\n }\n\n}\ncreate$6.prototype = StringSchema.prototype; //\n// String Interfaces\n//\n\nlet isNaN$1 = value => value != +value;\n\nfunction create$5() {\n return new NumberSchema();\n}\nclass NumberSchema extends Schema {\n constructor() {\n super({\n type: 'number',\n\n check(value) {\n if (value instanceof Number) value = value.valueOf();\n return typeof value === 'number' && !isNaN$1(value);\n }\n\n });\n this.withMutation(() => {\n this.transform((value, _raw, ctx) => {\n if (!ctx.spec.coarce) return value;\n let parsed = value;\n\n if (typeof parsed === 'string') {\n parsed = parsed.replace(/\\s/g, '');\n if (parsed === '') return NaN; // don't use parseFloat to avoid positives on alpha-numeric strings\n\n parsed = +parsed;\n }\n\n if (ctx.isType(parsed)) return parsed;\n return parseFloat(parsed);\n });\n });\n }\n\n min(min, message = number.min) {\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n\n test(value) {\n return value >= this.resolve(min);\n }\n\n });\n }\n\n max(max, message = number.max) {\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n max\n },\n skipAbsent: true,\n\n test(value) {\n return value <= this.resolve(max);\n }\n\n });\n }\n\n lessThan(less, message = number.lessThan) {\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n less\n },\n skipAbsent: true,\n\n test(value) {\n return value < this.resolve(less);\n }\n\n });\n }\n\n moreThan(more, message = number.moreThan) {\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n more\n },\n skipAbsent: true,\n\n test(value) {\n return value > this.resolve(more);\n }\n\n });\n }\n\n positive(msg = number.positive) {\n return this.moreThan(0, msg);\n }\n\n negative(msg = number.negative) {\n return this.lessThan(0, msg);\n }\n\n integer(message = number.integer) {\n return this.test({\n name: 'integer',\n message,\n skipAbsent: true,\n test: val => Number.isInteger(val)\n });\n }\n\n truncate() {\n return this.transform(value => !isAbsent(value) ? value | 0 : value);\n }\n\n round(method) {\n var _method;\n\n let avail = ['ceil', 'floor', 'round', 'trunc'];\n method = ((_method = method) == null ? void 0 : _method.toLowerCase()) || 'round'; // this exists for symemtry with the new Math.trunc\n\n if (method === 'trunc') return this.truncate();\n if (avail.indexOf(method.toLowerCase()) === -1) throw new TypeError('Only valid options for round() are: ' + avail.join(', '));\n return this.transform(value => !isAbsent(value) ? Math[method](value) : value);\n }\n\n}\ncreate$5.prototype = NumberSchema.prototype; //\n// Number Interfaces\n//\n\n/* eslint-disable */\n\n/**\n *\n * Date.parse with progressive enhancement for ISO 8601 \n * NON-CONFORMANT EDITION.\n * © 2011 Colin Snover \n * Released under MIT license.\n */\n// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm\nvar isoReg = /^(\\d{4}|[+\\-]\\d{6})(?:-?(\\d{2})(?:-?(\\d{2}))?)?(?:[ T]?(\\d{2}):?(\\d{2})(?::?(\\d{2})(?:[,\\.](\\d{1,}))?)?(?:(Z)|([+\\-])(\\d{2})(?::?(\\d{2}))?)?)?$/;\nfunction parseIsoDate(date) {\n var numericKeys = [1, 4, 5, 6, 7, 10, 11],\n minutesOffset = 0,\n timestamp,\n struct;\n\n if (struct = isoReg.exec(date)) {\n // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC\n for (var i = 0, k; k = numericKeys[i]; ++i) struct[k] = +struct[k] || 0; // allow undefined days and months\n\n\n struct[2] = (+struct[2] || 1) - 1;\n struct[3] = +struct[3] || 1; // allow arbitrary sub-second precision beyond milliseconds\n\n struct[7] = struct[7] ? String(struct[7]).substr(0, 3) : 0; // timestamps without timezone identifiers should be considered local time\n\n if ((struct[8] === undefined || struct[8] === '') && (struct[9] === undefined || struct[9] === '')) timestamp = +new Date(struct[1], struct[2], struct[3], struct[4], struct[5], struct[6], struct[7]);else {\n if (struct[8] !== 'Z' && struct[9] !== undefined) {\n minutesOffset = struct[10] * 60 + struct[11];\n if (struct[9] === '+') minutesOffset = 0 - minutesOffset;\n }\n\n timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);\n }\n } else timestamp = Date.parse ? Date.parse(date) : NaN;\n\n return timestamp;\n}\n\n// @ts-ignore\nlet invalidDate = new Date('');\n\nlet isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';\n\nfunction create$4() {\n return new DateSchema();\n}\nclass DateSchema extends Schema {\n constructor() {\n super({\n type: 'date',\n\n check(v) {\n return isDate(v) && !isNaN(v.getTime());\n }\n\n });\n this.withMutation(() => {\n this.transform((value, _raw, ctx) => {\n if (!ctx.spec.coarce || ctx.isType(value)) return value;\n value = parseIsoDate(value); // 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.\n\n return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;\n });\n });\n }\n\n prepareParam(ref, name) {\n let param;\n\n if (!Reference.isRef(ref)) {\n let cast = this.cast(ref);\n if (!this._typeCheck(cast)) throw new TypeError(`\\`${name}\\` must be a Date or a value that can be \\`cast()\\` to a Date`);\n param = cast;\n } else {\n param = ref;\n }\n\n return param;\n }\n\n min(min, message = date.min) {\n let limit = this.prepareParam(min, 'min');\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n\n test(value) {\n return value >= this.resolve(limit);\n }\n\n });\n }\n\n max(max, message = date.max) {\n let limit = this.prepareParam(max, 'max');\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n max\n },\n skipAbsent: true,\n\n test(value) {\n return value <= this.resolve(limit);\n }\n\n });\n }\n\n}\nDateSchema.INVALID_DATE = invalidDate;\ncreate$4.prototype = DateSchema.prototype;\ncreate$4.INVALID_DATE = invalidDate;\n\n// @ts-expect-error\nfunction sortFields(fields, excludedEdges = []) {\n let edges = [];\n let nodes = new Set();\n let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));\n\n function addNode(depPath, key) {\n let node = split(depPath)[0];\n nodes.add(node);\n if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);\n }\n\n for (const key of Object.keys(fields)) {\n let value = fields[key];\n nodes.add(key);\n if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);else if (isSchema(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));\n }\n\n return toposort.array(Array.from(nodes), edges).reverse();\n}\n\nfunction findIndex(arr, err) {\n let idx = Infinity;\n arr.some((key, ii) => {\n var _err$path;\n\n if ((_err$path = err.path) != null && _err$path.includes(key)) {\n idx = ii;\n return true;\n }\n });\n return idx;\n}\n\nfunction sortByKeyOrder(keys) {\n return (a, b) => {\n return findIndex(keys, a) - findIndex(keys, b);\n };\n}\n\nconst parseJson = (value, _, ctx) => {\n if (typeof value !== 'string') {\n return value;\n }\n\n let parsed = value;\n\n try {\n parsed = JSON.parse(value);\n } catch (err) {\n /* */\n }\n\n return ctx.isType(parsed) ? parsed : value;\n};\n\n// @ts-ignore\n\nconst deepHas = (obj, p) => {\n const path = [...normalizePath(p)];\n if (path.length === 1) return path[0] in obj;\n let last = path.pop();\n let parent = getter(join(path), true)(obj);\n return !!(parent && last in parent);\n};\n\nlet isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';\n\nfunction unknown(ctx, value) {\n let known = Object.keys(ctx.fields);\n return Object.keys(value).filter(key => known.indexOf(key) === -1);\n}\n\nconst defaultSort = sortByKeyOrder([]);\nfunction create$3(spec) {\n return new ObjectSchema(spec);\n}\nclass ObjectSchema extends Schema {\n constructor(spec) {\n super({\n type: 'object',\n\n check(value) {\n return isObject(value) || typeof value === 'function';\n }\n\n });\n this.fields = Object.create(null);\n this._sortErrors = defaultSort;\n this._nodes = [];\n this._excludedEdges = [];\n this.withMutation(() => {\n if (spec) {\n this.shape(spec);\n }\n });\n }\n\n _cast(_value, options = {}) {\n var _options$stripUnknown;\n\n let value = super._cast(_value, options); //should ignore nulls here\n\n\n if (value === undefined) return this.getDefault();\n if (!this._typeCheck(value)) return value;\n let fields = this.fields;\n let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;\n let props = [].concat(this._nodes, Object.keys(value).filter(v => !this._nodes.includes(v)));\n let intermediateValue = {}; // is filled during the transform below\n\n let innerOptions = Object.assign({}, options, {\n parent: intermediateValue,\n __validating: options.__validating || false\n });\n let isChanged = false;\n\n for (const prop of props) {\n let field = fields[prop];\n let exists = (prop in value);\n\n if (field) {\n let fieldValue;\n let inputValue = value[prop]; // safe to mutate since this is fired in sequence\n\n innerOptions.path = (options.path ? `${options.path}.` : '') + prop; // innerOptions.value = value[prop];\n\n field = field.resolve({\n value: inputValue,\n context: options.context,\n parent: intermediateValue\n });\n let fieldSpec = field instanceof Schema ? field.spec : undefined;\n let strict = fieldSpec == null ? void 0 : fieldSpec.strict;\n\n if (fieldSpec != null && fieldSpec.strip) {\n isChanged = isChanged || prop in value;\n continue;\n }\n\n fieldValue = !options.__validating || !strict ? // TODO: use _cast, this is double resolving\n field.cast(value[prop], innerOptions) : value[prop];\n\n if (fieldValue !== undefined) {\n intermediateValue[prop] = fieldValue;\n }\n } else if (exists && !strip) {\n intermediateValue[prop] = value[prop];\n }\n\n if (intermediateValue[prop] !== value[prop]) {\n isChanged = true;\n }\n }\n\n return isChanged ? intermediateValue : value;\n }\n\n _validate(_value, options = {}, panic, next) {\n let {\n from = [],\n originalValue = _value,\n recursive = this.spec.recursive\n } = options;\n options.from = [{\n schema: this,\n value: originalValue\n }, ...from]; // this flag is needed for handling `strict` correctly in the context of\n // validation vs just casting. e.g strict() on a field is only used when validating\n\n options.__validating = true;\n options.originalValue = originalValue;\n\n super._validate(_value, options, panic, (objectErrors, value) => {\n if (!recursive || !isObject(value)) {\n next(objectErrors, value);\n return;\n }\n\n originalValue = originalValue || value;\n let tests = [];\n\n for (let key of this._nodes) {\n let field = this.fields[key];\n\n if (!field || Reference.isRef(field)) {\n continue;\n }\n\n tests.push(field.asNestedTest({\n options,\n key,\n parent: value,\n parentPath: options.path,\n originalParent: originalValue\n }));\n }\n\n this.runTests({\n tests,\n value\n }, panic, fieldErrors => {\n next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);\n });\n });\n }\n\n clone(spec) {\n const next = super.clone(spec);\n next.fields = Object.assign({}, this.fields);\n next._nodes = this._nodes;\n next._excludedEdges = this._excludedEdges;\n next._sortErrors = this._sortErrors;\n return next;\n }\n\n concat(schema) {\n let next = super.concat(schema);\n let nextFields = next.fields;\n\n for (let [field, schemaOrRef] of Object.entries(this.fields)) {\n const target = nextFields[field];\n nextFields[field] = target === undefined ? schemaOrRef : target;\n }\n\n return next.withMutation(s => s.setFields(nextFields, this._excludedEdges));\n }\n\n _getDefault() {\n if ('default' in this.spec) {\n return super._getDefault();\n } // if there is no default set invent one\n\n\n if (!this._nodes.length) {\n return undefined;\n }\n\n let dft = {};\n\n this._nodes.forEach(key => {\n const field = this.fields[key];\n dft[key] = 'getDefault' in field ? field.getDefault() : undefined;\n });\n\n return dft;\n }\n\n setFields(shape, excludedEdges) {\n let next = this.clone();\n next.fields = shape;\n next._nodes = sortFields(shape, excludedEdges);\n next._sortErrors = sortByKeyOrder(Object.keys(shape)); // XXX: this carries over edges which may not be what you want\n\n if (excludedEdges) next._excludedEdges = excludedEdges;\n return next;\n }\n\n shape(additions, excludes = []) {\n return this.clone().withMutation(next => {\n let edges = next._excludedEdges;\n\n if (excludes.length) {\n if (!Array.isArray(excludes[0])) excludes = [excludes];\n edges = [...next._excludedEdges, ...excludes];\n } // XXX: excludes here is wrong\n\n\n return next.setFields(Object.assign(next.fields, additions), edges);\n });\n }\n\n partial() {\n const partial = {};\n\n for (const [key, schema] of Object.entries(this.fields)) {\n partial[key] = schema instanceof Schema ? schema.optional() : schema;\n }\n\n return this.setFields(partial);\n }\n\n deepPartial() {\n const partial = {};\n\n for (const [key, schema] of Object.entries(this.fields)) {\n if (schema instanceof ObjectSchema) partial[key] = schema.deepPartial();else partial[key] = schema instanceof Schema ? schema.optional() : schema;\n }\n\n return this.setFields(partial);\n }\n\n pick(keys) {\n const picked = {};\n\n for (const key of keys) {\n if (this.fields[key]) picked[key] = this.fields[key];\n }\n\n return this.setFields(picked);\n }\n\n omit(keys) {\n const fields = Object.assign({}, this.fields);\n\n for (const key of keys) {\n delete fields[key];\n }\n\n return this.setFields(fields);\n }\n\n from(from, to, alias) {\n let fromGetter = getter(from, true);\n return this.transform(obj => {\n if (!obj) return obj;\n let newObj = obj;\n\n if (deepHas(obj, from)) {\n newObj = Object.assign({}, obj);\n if (!alias) delete newObj[from];\n newObj[to] = fromGetter(obj);\n }\n\n return newObj;\n });\n }\n /** Parse an input JSON string to an object */\n\n\n json() {\n return this.transform(parseJson);\n }\n\n noUnknown(noAllow = true, message = object.noUnknown) {\n if (typeof noAllow !== 'boolean') {\n message = noAllow;\n noAllow = true;\n }\n\n let next = this.test({\n name: 'noUnknown',\n exclusive: true,\n message: message,\n\n test(value) {\n if (value == null) return true;\n const unknownKeys = unknown(this.schema, value);\n return !noAllow || unknownKeys.length === 0 || this.createError({\n params: {\n unknown: unknownKeys.join(', ')\n }\n });\n }\n\n });\n next.spec.noUnknown = noAllow;\n return next;\n }\n\n unknown(allow = true, message = object.noUnknown) {\n return this.noUnknown(!allow, message);\n }\n\n transformKeys(fn) {\n return this.transform(obj => {\n if (!obj) return obj;\n const result = {};\n\n for (const key of Object.keys(obj)) result[fn(key)] = obj[key];\n\n return result;\n });\n }\n\n camelCase() {\n return this.transformKeys(camelCase);\n }\n\n snakeCase() {\n return this.transformKeys(snakeCase);\n }\n\n constantCase() {\n return this.transformKeys(key => snakeCase(key).toUpperCase());\n }\n\n describe(options) {\n let base = super.describe(options);\n base.fields = {};\n\n for (const [key, value] of Object.entries(this.fields)) {\n var _innerOptions;\n\n let innerOptions = options;\n\n if ((_innerOptions = innerOptions) != null && _innerOptions.value) {\n innerOptions = Object.assign({}, innerOptions, {\n parent: innerOptions.value,\n value: innerOptions.value[key]\n });\n }\n\n base.fields[key] = value.describe(innerOptions);\n }\n\n return base;\n }\n\n}\ncreate$3.prototype = ObjectSchema.prototype;\n\nfunction create$2(type) {\n return new ArraySchema(type);\n}\nclass ArraySchema extends Schema {\n constructor(type) {\n super({\n type: 'array',\n\n check(v) {\n return Array.isArray(v);\n }\n\n }); // `undefined` specifically means uninitialized, as opposed to \"no subtype\"\n\n this.innerType = void 0;\n this.innerType = type;\n }\n\n _cast(_value, _opts) {\n const value = super._cast(_value, _opts); // should ignore nulls here\n\n\n if (!this._typeCheck(value) || !this.innerType) {\n return value;\n }\n\n let isChanged = false;\n const castArray = value.map((v, idx) => {\n const castElement = this.innerType.cast(v, Object.assign({}, _opts, {\n path: `${_opts.path || ''}[${idx}]`\n }));\n\n if (castElement !== v) {\n isChanged = true;\n }\n\n return castElement;\n });\n return isChanged ? castArray : value;\n }\n\n _validate(_value, options = {}, panic, next) {\n var _options$recursive;\n\n // let sync = options.sync;\n // let path = options.path;\n let innerType = this.innerType; // let endEarly = options.abortEarly ?? this.spec.abortEarly;\n\n let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive;\n options.originalValue != null ? options.originalValue : _value;\n\n super._validate(_value, options, panic, (arrayErrors, value) => {\n if (!recursive || !innerType || !this._typeCheck(value)) {\n next(arrayErrors, value);\n return;\n }\n\n let tests = new Array(value.length);\n\n for (let index = 0; index < value.length; index++) {\n var _options$originalValu;\n\n tests[index] = innerType.asNestedTest({\n options,\n index,\n parent: value,\n parentPath: options.path,\n originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value\n });\n }\n\n this.runTests({\n value,\n tests\n }, panic, innerTypeErrors => next(innerTypeErrors.concat(arrayErrors), value));\n });\n }\n\n clone(spec) {\n const next = super.clone(spec); // @ts-expect-error readonly\n\n next.innerType = this.innerType;\n return next;\n }\n /** Parse an input JSON string to an object */\n\n\n json() {\n return this.transform(parseJson);\n }\n\n concat(schema) {\n let next = super.concat(schema); // @ts-expect-error readonly\n\n next.innerType = this.innerType;\n if (schema.innerType) // @ts-expect-error readonly\n next.innerType = next.innerType ? // @ts-expect-error Lazy doesn't have concat and will break\n next.innerType.concat(schema.innerType) : schema.innerType;\n return next;\n }\n\n of(schema) {\n // FIXME: this should return a new instance of array without the default to be\n let next = this.clone();\n if (!isSchema(schema)) throw new TypeError('`array.of()` sub-schema must be a valid yup schema not: ' + printValue(schema)); // @ts-expect-error readonly\n\n next.innerType = schema;\n return next;\n }\n\n length(length, message = array.length) {\n return this.test({\n message,\n name: 'length',\n exclusive: true,\n params: {\n length\n },\n skipAbsent: true,\n\n test(value) {\n return value.length === this.resolve(length);\n }\n\n });\n }\n\n min(min, message) {\n message = message || array.min;\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n\n // FIXME(ts): Array\n test(value) {\n return value.length >= this.resolve(min);\n }\n\n });\n }\n\n max(max, message) {\n message = message || array.max;\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n max\n },\n skipAbsent: true,\n\n test(value) {\n return value.length <= this.resolve(max);\n }\n\n });\n }\n\n ensure() {\n return this.default(() => []).transform((val, original) => {\n // We don't want to return `null` for nullable schema\n if (this._typeCheck(val)) return val;\n return original == null ? [] : [].concat(original);\n });\n }\n\n compact(rejector) {\n let reject = !rejector ? v => !!v : (v, i, a) => !rejector(v, i, a);\n return this.transform(values => values != null ? values.filter(reject) : values);\n }\n\n describe(options) {\n let base = super.describe();\n\n if (this.innerType) {\n var _innerOptions;\n\n let innerOptions = options;\n\n if ((_innerOptions = innerOptions) != null && _innerOptions.value) {\n innerOptions = Object.assign({}, innerOptions, {\n parent: innerOptions.value,\n value: innerOptions.value[0]\n });\n }\n\n base.innerType = this.innerType.describe(options);\n }\n\n return base;\n }\n\n}\ncreate$2.prototype = ArraySchema.prototype;\n\n// @ts-ignore\nfunction create$1(schemas) {\n return new TupleSchema(schemas);\n}\nclass TupleSchema extends Schema {\n constructor(schemas) {\n super({\n type: 'tuple',\n spec: {\n types: schemas\n },\n\n check(v) {\n const types = this.spec.types;\n return Array.isArray(v) && v.length === types.length;\n }\n\n });\n this.withMutation(() => {\n this.typeError(tuple.notType);\n });\n }\n\n _cast(inputValue, options) {\n const {\n types\n } = this.spec;\n\n const value = super._cast(inputValue, options);\n\n if (!this._typeCheck(value)) {\n return value;\n }\n\n let isChanged = false;\n const castArray = types.map((type, idx) => {\n const castElement = type.cast(value[idx], Object.assign({}, options, {\n path: `${options.path || ''}[${idx}]`\n }));\n if (castElement !== value[idx]) isChanged = true;\n return castElement;\n });\n return isChanged ? castArray : value;\n }\n\n _validate(_value, options = {}, panic, next) {\n let itemTypes = this.spec.types;\n\n super._validate(_value, options, panic, (tupleErrors, value) => {\n // intentionally not respecting recursive\n if (!this._typeCheck(value)) {\n next(tupleErrors, value);\n return;\n }\n\n let tests = [];\n\n for (let [index, itemSchema] of itemTypes.entries()) {\n var _options$originalValu;\n\n tests[index] = itemSchema.asNestedTest({\n options,\n index,\n parent: value,\n parentPath: options.path,\n originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value\n });\n }\n\n this.runTests({\n value,\n tests\n }, panic, innerTypeErrors => next(innerTypeErrors.concat(tupleErrors), value));\n });\n }\n\n}\ncreate$1.prototype = TupleSchema.prototype;\n\nfunction create(builder) {\n return new Lazy(builder);\n}\n\nclass Lazy {\n constructor(builder) {\n this.type = 'lazy';\n this.__isYupSchema__ = true;\n this.spec = void 0;\n\n this._resolve = (value, options = {}) => {\n let schema = this.builder(value, options);\n if (!isSchema(schema)) throw new TypeError('lazy() functions must return a valid schema');\n return schema.resolve(options);\n };\n\n this.builder = builder;\n this.spec = {\n meta: undefined\n };\n }\n\n clone() {\n const next = create(this.builder);\n next.spec = Object.assign({}, this.spec);\n return next;\n }\n\n resolve(options) {\n return this._resolve(options.value, options);\n }\n\n cast(value, options) {\n return this._resolve(value, options).cast(value, options);\n }\n\n asNestedTest(options) {\n var _options$index;\n\n let value = options.parent[(_options$index = options.index) != null ? _options$index : options.key];\n return this._resolve(value, options).asNestedTest(options);\n }\n\n validate(value, options) {\n return this._resolve(value, options).validate(value, options);\n }\n\n validateSync(value, options) {\n return this._resolve(value, options).validateSync(value, options);\n }\n\n validateAt(path, value, options) {\n return this._resolve(value, options).validateAt(path, value, options);\n }\n\n validateSyncAt(path, value, options) {\n return this._resolve(value, options).validateSyncAt(path, value, options);\n }\n\n isValid(value, options) {\n return this._resolve(value, options).isValid(value, options);\n }\n\n isValidSync(value, options) {\n return this._resolve(value, options).isValidSync(value, options);\n }\n\n describe(options) {\n return options ? this.resolve(options).describe(options) : {\n type: 'lazy',\n meta: this.spec.meta,\n label: undefined\n };\n }\n\n meta(...args) {\n if (args.length === 0) return this.spec.meta;\n let next = this.clone();\n next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);\n return next;\n }\n\n}\n\nfunction setLocale(custom) {\n Object.keys(custom).forEach(type => {\n // @ts-ignore\n Object.keys(custom[type]).forEach(method => {\n // @ts-ignore\n locale[type][method] = custom[type][method];\n });\n });\n}\n\nfunction addMethod(schemaType, name, fn) {\n if (!schemaType || !isSchema(schemaType.prototype)) throw new TypeError('You must provide a yup schema constructor function');\n if (typeof name !== 'string') throw new TypeError('A Method name must be provided');\n if (typeof fn !== 'function') throw new TypeError('Method function must be provided');\n schemaType.prototype[name] = fn;\n}\n\nexport { ArraySchema, BooleanSchema, DateSchema, MixedSchema, NumberSchema, ObjectSchema, Schema, StringSchema, TupleSchema, ValidationError, addMethod, create$2 as array, create$7 as bool, create$7 as boolean, create$4 as date, getIn, isSchema, create as lazy, create$8 as mixed, create$5 as number, create$3 as object, reach, create$9 as ref, setLocale, create$6 as string, create$1 as tuple };\n","import * as turf from '@turf/turf';\nimport { featureCollection, getType } from '@turf/turf';\nimport * as yup from 'yup';\nimport { geometryTypes } from '../constants/fields';\n\nexport const coordinatesSchema = yup.object().shape({\n lat: yup\n .number()\n .required('Required (eg. 42.14)')\n .min(-90, 'Minimum is -90')\n .max(90, 'Maximum is 90'),\n lng: yup\n .number()\n .required('Required (eg. -73.76)')\n .min(-180, 'Minimum is -180')\n .max(180, 'Maximum is 180'),\n});\n\n/**\n * Turns a coordinates object like { lng: -73.767363, lat: 42.149975 } into a\n * GeoJSON point feature.\n */\nexport const coordsObjToPoint = (coords) => {\n try {\n if (!coordinatesSchema.validateSync(coords)) {\n return null;\n }\n return turf.point([coords.lng, coords.lat]);\n } catch (e) {\n return null;\n }\n};\n\n/**\n * Returns a new LineString feature with reversed coordinates.\n */\nexport const reverseLineString = (feature) => {\n if (getType(feature) !== geometryTypes.LINE_STRING)\n throw new Error('Reverse LineString can only handle LineString features');\n const newFeature = turf.clone(feature);\n newFeature.geometry.coordinates = feature.geometry.coordinates\n .slice()\n .reverse();\n return newFeature;\n};\n\nexport const emptyFeature = () => ({\n type: 'FeatureCollection',\n features: [],\n});\n\nexport const emptyGeojson = (options = {}) => ({\n type: 'geojson',\n data: emptyFeature(),\n ...options,\n});\n\n/**\n * Converts a MultiPolygon feature to an array of Polygon features.\n */\nexport const multipolygonToPolygons = (\n feature,\n // By default, don't copy the properties of `feature` to each of the new features:\n { retainProperties = false } = {},\n) => {\n if (getType(feature) !== 'MultiPolygon') {\n throw new Error('Feature must be MultiPolygon.');\n }\n\n return feature.geometry.coordinates.map((coords) => ({\n type: 'Feature',\n properties: retainProperties ? feature.properties : {},\n geometry: { type: 'Polygon', coordinates: coords },\n }));\n};\n\n/**\n * Checks `feature` for self-intersecting polygons and attempts to fix them.\n * Accepts a Polygon or MultiPolygon feature and returns a Polygon or\n * Multipolygon feature.\n */\nexport const fixSelfIntersections = (\n feature,\n // By default, retain the properties and id of the original feature:\n { retainPropertiesAndId = true } = {},\n) => {\n try {\n if (!['Polygon', 'MultiPolygon'].includes(turf.getType(feature))) {\n throw new Error('Feature must be Polygon or MultiPolygon.');\n }\n\n const hasSelfIntersections = turf.kinks(feature).features.length > 0;\n\n // If no self intersections, return the original feature unchanged\n if (!hasSelfIntersections) return feature;\n\n // Otherwise, fix the self-intersections\n const fixedPolygons = turf.unkinkPolygon(feature).features;\n\n // Merge the fixed polygons into one MultiPolygon\n const merged = fixedPolygons.reduce((a, b) =>\n turf.union(featureCollection([a, b])),\n );\n\n // Copy over properties to new feature\n if (retainPropertiesAndId) {\n merged.properties = feature.properties;\n merged.id = feature.id;\n }\n\n return merged;\n } catch (err) {\n console.error(err);\n return feature;\n }\n};\n","import _ from 'lodash';\nimport { centerOfMass } from '@turf/turf';\nimport mapboxgl, { FullscreenControl } from 'mapbox-gl';\n\nimport { emptyGeojson } from './geojson';\nimport {\n mapLayers,\n STREET_LINES_LAYER_ID,\n STREETS_MARKERS,\n} from '../constants/map';\nimport { getSectionBounds, getSectionGroupBounds } from './sections';\nimport { waitForSuccess } from './utils';\n\n/**\n * Returns the source data for a given source ID.\n *\n * Sometimes `map.querySourceFeatures()` returns duplicates, so we filter them out.\n */\nexport const getSourceData = (map, sourceId) => {\n const queriedFeatures = map.querySourceFeatures(sourceId);\n return _.uniqBy(queriedFeatures, 'properties.id');\n};\n\n/**\n * Sets source data and waits for the data to actually load.\n */\nexport const setSourceData = async (map, sourceId, data) => {\n if (!map) throw new Error('map not defined');\n\n if (!data) throw new Error('Must provide data');\n if (!Array.isArray(data.features)) {\n throw new Error('Invalid data, must have features array');\n }\n\n const source = map.getSource(sourceId);\n if (!source) throw new Error('source not found');\n\n // Store some temp IDs so we can check to see when the data is updated\n const TEMP_ID = '_id';\n const tempIdMapping = {};\n data.features.forEach(({ properties }) => {\n const tempId = _.uniqueId('temp-id-');\n properties[TEMP_ID] = tempId; // eslint-disable-line no-param-reassign\n tempIdMapping[properties.id] = tempId;\n });\n\n // Set the data\n source.setData(data);\n\n // Wait for the data to actually be set\n return waitForSuccess(() => {\n const features = getSourceData(map, sourceId);\n\n return (\n features.length === data.features.length &&\n features.every(\n (feature) =>\n feature.properties[TEMP_ID] === tempIdMapping[feature.properties.id],\n )\n );\n });\n};\n\n/**\n * Adds empty reference layers to the map which are used for ordering\n * section specific layers.\n */\nexport const addReferenceLayers = (map) => {\n map.addSource('reference', emptyGeojson());\n Object.values(mapLayers).forEach((layerName) =>\n map.addLayer({\n id: layerName,\n type: 'circle',\n source: 'reference',\n }),\n );\n};\n\nexport const forceMapResize = () => window.dispatchEvent(new Event('resize'));\n\nexport const flyTo = (feature, mapRef, options = {}) => {\n if (feature && mapRef.current) {\n const [lng, lat] = centerOfMass(feature).geometry.coordinates;\n const center = { lng, lat };\n mapRef.current.flyTo({\n center,\n ...options,\n });\n }\n};\n\n// Percentage of the map to pad the bounds by when fitting the bounds.\n// Sections have more padding to give more surrounding context and\n// because they are generally smaller than section groups.\nconst SECTION_BOUNDS_PADDING = 0.2;\nconst SECTION_GROUP_BOUNDS_PADDING = 0.1;\n\nexport const fitSectionBounds = (section, mapRef) => {\n const {\n offsetWidth: width,\n offsetHeight: height,\n } = mapRef.current.getContainer();\n const bounds = getSectionBounds(section);\n if (!bounds) return;\n mapRef.current.fitBounds(bounds, {\n padding: {\n top: SECTION_BOUNDS_PADDING * height,\n bottom: SECTION_BOUNDS_PADDING * height,\n left: SECTION_BOUNDS_PADDING * width,\n right: SECTION_BOUNDS_PADDING * width,\n },\n maxZoom: mapRef.current.getZoom(),\n });\n};\n\nexport const fitSectionGroupBounds = (sectionGroup, sections, mapRef) => {\n const {\n offsetWidth: width,\n offsetHeight: height,\n } = mapRef.current.getContainer();\n mapRef.current.fitBounds(getSectionGroupBounds(sectionGroup, sections), {\n padding: {\n top: SECTION_GROUP_BOUNDS_PADDING * height,\n bottom: SECTION_GROUP_BOUNDS_PADDING * height,\n left: SECTION_GROUP_BOUNDS_PADDING * width,\n right: SECTION_GROUP_BOUNDS_PADDING * width,\n },\n });\n};\n\nexport const addLocation = (mapRef) => {\n mapRef.addControl(\n new mapboxgl.GeolocateControl({\n positionOptions: {\n enableHighAccuracy: true,\n },\n trackUserLocation: true,\n showUserHeading: true,\n }),\n );\n};\n\nexport const hideLayer = (map, layerId) => {\n map.setLayoutProperty(layerId, 'visibility', 'none');\n};\n\nexport const showLayer = (map, layerId) => {\n map.setLayoutProperty(layerId, 'visibility', 'visible');\n};\n\nexport const setLayerVisibility = (map, layerId, isVisible) =>\n isVisible ? showLayer(map, layerId) : hideLayer(map, layerId);\n\nexport const setMultiLayerVisibility = (map, visibilityMapList) => {\n visibilityMapList.forEach(({ layerId, isVisible }) =>\n setLayerVisibility(map, layerId, isVisible),\n );\n};\n\nconst isRoadsLayer = (layer) => {\n return STREETS_MARKERS.some((marker) => layer.id.includes(marker));\n};\n\nexport const setRoads = (map, roadsEnabled, showRoadLinesIfEnabled) => {\n map.getStyle().layers.forEach((layer) =>\n isRoadsLayer(layer)\n ? // street outline layer (used only on no-satellite view) is special case\n layer.id === STREET_LINES_LAYER_ID\n ? setLayerVisibility(\n map,\n layer.id,\n showRoadLinesIfEnabled && roadsEnabled,\n )\n : setLayerVisibility(map, layer.id, roadsEnabled)\n : null,\n );\n};\n\nexport const resetMapLayers = (map, layerNames) => {\n // eslint-disable-next-line no-underscore-dangle\n if (!map || map._removed) {\n return;\n }\n Object.values(layerNames).forEach((layer) => {\n const mapLayer = map.getLayer(layer);\n if (typeof mapLayer !== 'undefined') {\n map.removeLayer(layer);\n }\n });\n Object.values(layerNames).forEach((layer) => {\n const mapSource = map.getSource(layer);\n if (typeof mapSource !== 'undefined') {\n map.removeSource(layer);\n }\n });\n};\n\nexport const addImageToMap = (map, imageName, imagePath, options) => {\n // eslint-disable-next-line no-underscore-dangle\n if (!map || map._removed) return;\n\n if (!map.hasImage(imageName)) {\n map.loadImage(imagePath, (error, image) => {\n if (error) throw error;\n\n map.addImage(imageName, image, options);\n });\n }\n};\n\n/**\n * Toggle fullscreen state of `map`.\n *\n * This is a little hacky since it uses internal APIs. Note that this function\n * must be called as a part of a user interaction (e.g. a click event) or it\n * will be blocked by the browser.\n *\n * @param {mapboxgl.Map} map current map instance\n * @param {Event} evt user interaction event\n */\nexport const toggleFullscreen = (map, evt) => {\n if (!evt) return;\n\n // eslint-disable-next-line no-underscore-dangle\n const fullscreenControl = map?._controls?.find(\n (c) => c instanceof FullscreenControl,\n );\n\n if (fullscreenControl) {\n // eslint-disable-next-line no-underscore-dangle\n fullscreenControl._onClickFullscreen();\n }\n};\n\n/**\n * Resize the mapbox container element and update the map size. Returns a\n * cleanup function to restore the original size.\n */\nexport const resizeMapContainer = (map, { width, height }) => {\n const container = map.getContainer();\n container.setAttribute(\n 'style',\n `width:${width}px !important; height:${height}px !important`,\n );\n map.resize();\n\n const restoreMapContainer = () => {\n container.style.removeProperty('width');\n container.style.removeProperty('height');\n map.resize();\n };\n\n return { restoreMapContainer };\n};\n\n/**\n * Set the attribution control on the map.\n *\n * Removes the old attribution control, adds the new one, and updates the ref.\n */\nexport const setAttributionControl = (\n map,\n attributionControl,\n attributionControlRef,\n) => {\n if (!map || map._removed) return;\n const ref = attributionControlRef;\n if (ref?.current && map.hasControl(ref.current)) {\n map.removeControl(ref.current);\n }\n map.addControl(attributionControl, 'bottom-right');\n ref.current = attributionControl;\n};\n","/* @license twgl.js 5.5.4 Copyright (c) 2015, Gregg Tavares All Rights Reserved.\nAvailable via the MIT license.\nsee: http://github.com/greggman/twgl.js for details */\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n *\n * Vec3 math math functions.\n *\n * Almost all functions take an optional `dst` argument. If it is not passed in the\n * functions will create a new Vec3. In other words you can do this\n *\n * var v = v3.cross(v1, v2); // Creates a new Vec3 with the cross product of v1 x v2.\n *\n * or\n *\n * var v = v3.create();\n * v3.cross(v1, v2, v); // Puts the cross product of v1 x v2 in v\n *\n * The first style is often easier but depending on where it's used it generates garbage where\n * as there is almost never allocation with the second style.\n *\n * It is always save to pass any vector as the destination. So for example\n *\n * v3.cross(v1, v2, v1); // Puts the cross product of v1 x v2 in v1\n *\n * @module twgl/v3\n */\n\nlet VecType = Float32Array;\n\n/**\n * A JavaScript array with 3 values or a Float32Array with 3 values.\n * When created by the library will create the default type which is `Float32Array`\n * but can be set by calling {@link module:twgl/v3.setDefaultType}.\n * @typedef {(number[]|Float32Array)} Vec3\n * @memberOf module:twgl/v3\n */\n\n/**\n * Sets the type this library creates for a Vec3\n * @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`\n * @return {constructor} previous constructor for Vec3\n * @memberOf module:twgl/v3\n */\nfunction setDefaultType$1(ctor) {\n const oldType = VecType;\n VecType = ctor;\n return oldType;\n}\n\n/**\n * Creates a vec3; may be called with x, y, z to set initial values.\n * @param {number} [x] Initial x value.\n * @param {number} [y] Initial y value.\n * @param {number} [z] Initial z value.\n * @return {module:twgl/v3.Vec3} the created vector\n * @memberOf module:twgl/v3\n */\nfunction create$1(x, y, z) {\n const dst = new VecType(3);\n if (x) {\n dst[0] = x;\n }\n if (y) {\n dst[1] = y;\n }\n if (z) {\n dst[2] = z;\n }\n return dst;\n}\n\n/**\n * Adds two vectors; assumes a and b have the same dimension.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A vector tha tis the sum of a and b.\n * @memberOf module:twgl/v3\n */\nfunction add(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + b[0];\n dst[1] = a[1] + b[1];\n dst[2] = a[2] + b[2];\n\n return dst;\n}\n\n/**\n * Subtracts two vectors.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A vector that is the difference of a and b.\n * @memberOf module:twgl/v3\n */\nfunction subtract(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] - b[0];\n dst[1] = a[1] - b[1];\n dst[2] = a[2] - b[2];\n\n return dst;\n}\n\n/**\n * Performs linear interpolation on two vectors.\n * Given vectors a and b and interpolation coefficient t, returns\n * a + t * (b - a).\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {number} t Interpolation coefficient.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The linear interpolated result.\n * @memberOf module:twgl/v3\n */\nfunction lerp(a, b, t, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + t * (b[0] - a[0]);\n dst[1] = a[1] + t * (b[1] - a[1]);\n dst[2] = a[2] + t * (b[2] - a[2]);\n\n return dst;\n}\n\n/**\n * Performs linear interpolation on two vectors.\n * Given vectors a and b and interpolation coefficient vector t, returns\n * a + t * (b - a).\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} t Interpolation coefficients vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} the linear interpolated result.\n * @memberOf module:twgl/v3\n */\nfunction lerpV(a, b, t, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + t[0] * (b[0] - a[0]);\n dst[1] = a[1] + t[1] * (b[1] - a[1]);\n dst[2] = a[2] + t[2] * (b[2] - a[2]);\n\n return dst;\n}\n\n/**\n * Return max values of two vectors.\n * Given vectors a and b returns\n * [max(a[0], b[0]), max(a[1], b[1]), max(a[2], b[2])].\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The max components vector.\n * @memberOf module:twgl/v3\n */\nfunction max(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = Math.max(a[0], b[0]);\n dst[1] = Math.max(a[1], b[1]);\n dst[2] = Math.max(a[2], b[2]);\n\n return dst;\n}\n\n/**\n * Return min values of two vectors.\n * Given vectors a and b returns\n * [min(a[0], b[0]), min(a[1], b[1]), min(a[2], b[2])].\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The min components vector.\n * @memberOf module:twgl/v3\n */\nfunction min(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = Math.min(a[0], b[0]);\n dst[1] = Math.min(a[1], b[1]);\n dst[2] = Math.min(a[2], b[2]);\n\n return dst;\n}\n\n/**\n * Multiplies a vector by a scalar.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {number} k The scalar.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The scaled vector.\n * @memberOf module:twgl/v3\n */\nfunction mulScalar(v, k, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0] * k;\n dst[1] = v[1] * k;\n dst[2] = v[2] * k;\n\n return dst;\n}\n\n/**\n * Divides a vector by a scalar.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {number} k The scalar.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The scaled vector.\n * @memberOf module:twgl/v3\n */\nfunction divScalar(v, k, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0] / k;\n dst[1] = v[1] / k;\n dst[2] = v[2] / k;\n\n return dst;\n}\n\n/**\n * Computes the cross product of two vectors; assumes both vectors have\n * three entries.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of a cross b.\n * @memberOf module:twgl/v3\n */\nfunction cross(a, b, dst) {\n dst = dst || new VecType(3);\n\n const t1 = a[2] * b[0] - a[0] * b[2];\n const t2 = a[0] * b[1] - a[1] * b[0];\n dst[0] = a[1] * b[2] - a[2] * b[1];\n dst[1] = t1;\n dst[2] = t2;\n\n return dst;\n}\n\n/**\n * Computes the dot product of two vectors; assumes both vectors have\n * three entries.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @return {number} dot product\n * @memberOf module:twgl/v3\n */\nfunction dot(a, b) {\n return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);\n}\n\n/**\n * Computes the length of vector\n * @param {module:twgl/v3.Vec3} v vector.\n * @return {number} length of vector.\n * @memberOf module:twgl/v3\n */\nfunction length$1(v) {\n return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n}\n\n/**\n * Computes the square of the length of vector\n * @param {module:twgl/v3.Vec3} v vector.\n * @return {number} square of the length of vector.\n * @memberOf module:twgl/v3\n */\nfunction lengthSq(v) {\n return v[0] * v[0] + v[1] * v[1] + v[2] * v[2];\n}\n\n/**\n * Computes the distance between 2 points\n * @param {module:twgl/v3.Vec3} a vector.\n * @param {module:twgl/v3.Vec3} b vector.\n * @return {number} distance between a and b\n * @memberOf module:twgl/v3\n */\nfunction distance(a, b) {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n const dz = a[2] - b[2];\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n/**\n * Computes the square of the distance between 2 points\n * @param {module:twgl/v3.Vec3} a vector.\n * @param {module:twgl/v3.Vec3} b vector.\n * @return {number} square of the distance between a and b\n * @memberOf module:twgl/v3\n */\nfunction distanceSq(a, b) {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n const dz = a[2] - b[2];\n return dx * dx + dy * dy + dz * dz;\n}\n\n/**\n * Divides a vector by its Euclidean length and returns the quotient.\n * @param {module:twgl/v3.Vec3} a The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The normalized vector.\n * @memberOf module:twgl/v3\n */\nfunction normalize(a, dst) {\n dst = dst || new VecType(3);\n\n const lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];\n const len = Math.sqrt(lenSq);\n if (len > 0.00001) {\n dst[0] = a[0] / len;\n dst[1] = a[1] / len;\n dst[2] = a[2] / len;\n } else {\n dst[0] = 0;\n dst[1] = 0;\n dst[2] = 0;\n }\n\n return dst;\n}\n\n/**\n * Negates a vector.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} -v.\n * @memberOf module:twgl/v3\n */\nfunction negate$1(v, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = -v[0];\n dst[1] = -v[1];\n dst[2] = -v[2];\n\n return dst;\n}\n\n/**\n * Copies a vector.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A copy of v.\n * @memberOf module:twgl/v3\n */\nfunction copy$1(v, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0];\n dst[1] = v[1];\n dst[2] = v[2];\n\n return dst;\n}\n\n/**\n * Multiplies a vector by another vector (component-wise); assumes a and\n * b have the same length.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of products of entries of a and\n * b.\n * @memberOf module:twgl/v3\n */\nfunction multiply$1(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] * b[0];\n dst[1] = a[1] * b[1];\n dst[2] = a[2] * b[2];\n\n return dst;\n}\n\n/**\n * Divides a vector by another vector (component-wise); assumes a and\n * b have the same length.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of quotients of entries of a and\n * b.\n * @memberOf module:twgl/v3\n */\nfunction divide(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] / b[0];\n dst[1] = a[1] / b[1];\n dst[2] = a[2] / b[2];\n\n return dst;\n}\n\nvar v3 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n add: add,\n copy: copy$1,\n create: create$1,\n cross: cross,\n distance: distance,\n distanceSq: distanceSq,\n divide: divide,\n divScalar: divScalar,\n dot: dot,\n lerp: lerp,\n lerpV: lerpV,\n length: length$1,\n lengthSq: lengthSq,\n max: max,\n min: min,\n mulScalar: mulScalar,\n multiply: multiply$1,\n negate: negate$1,\n normalize: normalize,\n setDefaultType: setDefaultType$1,\n subtract: subtract\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * 4x4 Matrix math math functions.\n *\n * Almost all functions take an optional `dst` argument. If it is not passed in the\n * functions will create a new matrix. In other words you can do this\n *\n * const mat = m4.translation([1, 2, 3]); // Creates a new translation matrix\n *\n * or\n *\n * const mat = m4.create();\n * m4.translation([1, 2, 3], mat); // Puts translation matrix in mat.\n *\n * The first style is often easier but depending on where it's used it generates garbage where\n * as there is almost never allocation with the second style.\n *\n * It is always save to pass any matrix as the destination. So for example\n *\n * const mat = m4.identity();\n * const trans = m4.translation([1, 2, 3]);\n * m4.multiply(mat, trans, mat); // Multiplies mat * trans and puts result in mat.\n *\n * @module twgl/m4\n */\nlet MatType = Float32Array;\n\n/**\n * A JavaScript array with 16 values or a Float32Array with 16 values.\n * When created by the library will create the default type which is `Float32Array`\n * but can be set by calling {@link module:twgl/m4.setDefaultType}.\n * @typedef {(number[]|Float32Array)} Mat4\n * @memberOf module:twgl/m4\n */\n\n/**\n * Sets the type this library creates for a Mat4\n * @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`\n * @return {constructor} previous constructor for Mat4\n * @memberOf module:twgl/m4\n */\nfunction setDefaultType(ctor) {\n const oldType = MatType;\n MatType = ctor;\n return oldType;\n}\n\n/**\n * Negates a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} -m.\n * @memberOf module:twgl/m4\n */\nfunction negate(m, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = -m[ 0];\n dst[ 1] = -m[ 1];\n dst[ 2] = -m[ 2];\n dst[ 3] = -m[ 3];\n dst[ 4] = -m[ 4];\n dst[ 5] = -m[ 5];\n dst[ 6] = -m[ 6];\n dst[ 7] = -m[ 7];\n dst[ 8] = -m[ 8];\n dst[ 9] = -m[ 9];\n dst[10] = -m[10];\n dst[11] = -m[11];\n dst[12] = -m[12];\n dst[13] = -m[13];\n dst[14] = -m[14];\n dst[15] = -m[15];\n\n return dst;\n}\n\n/**\n * Creates a matrix.\n * @return {module:twgl/m4.Mat4} A new matrix.\n * @memberOf module:twgl/m4\n */\nfunction create() {\n return new MatType(16).fill(0);\n}\n\n/**\n * Copies a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] The matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} A copy of m.\n * @memberOf module:twgl/m4\n */\nfunction copy(m, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = m[ 0];\n dst[ 1] = m[ 1];\n dst[ 2] = m[ 2];\n dst[ 3] = m[ 3];\n dst[ 4] = m[ 4];\n dst[ 5] = m[ 5];\n dst[ 6] = m[ 6];\n dst[ 7] = m[ 7];\n dst[ 8] = m[ 8];\n dst[ 9] = m[ 9];\n dst[10] = m[10];\n dst[11] = m[11];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n\n return dst;\n}\n\n/**\n * Creates an n-by-n identity matrix.\n *\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} An n-by-n identity matrix.\n * @memberOf module:twgl/m4\n */\nfunction identity(dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Takes the transpose of a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The transpose of m.\n * @memberOf module:twgl/m4\n */\n function transpose(m, dst) {\n dst = dst || new MatType(16);\n if (dst === m) {\n let t;\n\n t = m[1];\n m[1] = m[4];\n m[4] = t;\n\n t = m[2];\n m[2] = m[8];\n m[8] = t;\n\n t = m[3];\n m[3] = m[12];\n m[12] = t;\n\n t = m[6];\n m[6] = m[9];\n m[9] = t;\n\n t = m[7];\n m[7] = m[13];\n m[13] = t;\n\n t = m[11];\n m[11] = m[14];\n m[14] = t;\n return dst;\n }\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n\n dst[ 0] = m00;\n dst[ 1] = m10;\n dst[ 2] = m20;\n dst[ 3] = m30;\n dst[ 4] = m01;\n dst[ 5] = m11;\n dst[ 6] = m21;\n dst[ 7] = m31;\n dst[ 8] = m02;\n dst[ 9] = m12;\n dst[10] = m22;\n dst[11] = m32;\n dst[12] = m03;\n dst[13] = m13;\n dst[14] = m23;\n dst[15] = m33;\n\n return dst;\n}\n\n/**\n * Computes the inverse of a 4-by-4 matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The inverse of m.\n * @memberOf module:twgl/m4\n */\nfunction inverse(m, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n const tmp_0 = m22 * m33;\n const tmp_1 = m32 * m23;\n const tmp_2 = m12 * m33;\n const tmp_3 = m32 * m13;\n const tmp_4 = m12 * m23;\n const tmp_5 = m22 * m13;\n const tmp_6 = m02 * m33;\n const tmp_7 = m32 * m03;\n const tmp_8 = m02 * m23;\n const tmp_9 = m22 * m03;\n const tmp_10 = m02 * m13;\n const tmp_11 = m12 * m03;\n const tmp_12 = m20 * m31;\n const tmp_13 = m30 * m21;\n const tmp_14 = m10 * m31;\n const tmp_15 = m30 * m11;\n const tmp_16 = m10 * m21;\n const tmp_17 = m20 * m11;\n const tmp_18 = m00 * m31;\n const tmp_19 = m30 * m01;\n const tmp_20 = m00 * m21;\n const tmp_21 = m20 * m01;\n const tmp_22 = m00 * m11;\n const tmp_23 = m10 * m01;\n\n const t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) -\n (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\n const t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) -\n (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\n const t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) -\n (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\n const t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) -\n (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\n\n const d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\n\n dst[ 0] = d * t0;\n dst[ 1] = d * t1;\n dst[ 2] = d * t2;\n dst[ 3] = d * t3;\n dst[ 4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) -\n (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));\n dst[ 5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) -\n (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));\n dst[ 6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) -\n (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));\n dst[ 7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) -\n (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));\n dst[ 8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) -\n (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));\n dst[ 9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) -\n (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));\n dst[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) -\n (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));\n dst[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) -\n (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));\n dst[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) -\n (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));\n dst[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) -\n (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));\n dst[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) -\n (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));\n dst[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) -\n (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));\n\n return dst;\n}\n\n/**\n * Multiplies two 4-by-4 matrices with a on the left and b on the right\n * @param {module:twgl/m4.Mat4} a The matrix on the left.\n * @param {module:twgl/m4.Mat4} b The matrix on the right.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix product of a and b.\n * @memberOf module:twgl/m4\n */\nfunction multiply(a, b, dst) {\n dst = dst || new MatType(16);\n\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[ 4 + 0];\n const a11 = a[ 4 + 1];\n const a12 = a[ 4 + 2];\n const a13 = a[ 4 + 3];\n const a20 = a[ 8 + 0];\n const a21 = a[ 8 + 1];\n const a22 = a[ 8 + 2];\n const a23 = a[ 8 + 3];\n const a30 = a[12 + 0];\n const a31 = a[12 + 1];\n const a32 = a[12 + 2];\n const a33 = a[12 + 3];\n const b00 = b[0];\n const b01 = b[1];\n const b02 = b[2];\n const b03 = b[3];\n const b10 = b[ 4 + 0];\n const b11 = b[ 4 + 1];\n const b12 = b[ 4 + 2];\n const b13 = b[ 4 + 3];\n const b20 = b[ 8 + 0];\n const b21 = b[ 8 + 1];\n const b22 = b[ 8 + 2];\n const b23 = b[ 8 + 3];\n const b30 = b[12 + 0];\n const b31 = b[12 + 1];\n const b32 = b[12 + 2];\n const b33 = b[12 + 3];\n\n dst[ 0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03;\n dst[ 1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03;\n dst[ 2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03;\n dst[ 3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03;\n dst[ 4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13;\n dst[ 5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13;\n dst[ 6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13;\n dst[ 7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13;\n dst[ 8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23;\n dst[ 9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23;\n dst[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23;\n dst[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23;\n dst[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33;\n dst[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33;\n dst[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33;\n dst[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33;\n\n return dst;\n}\n\n/**\n * Sets the translation component of a 4-by-4 matrix to the given\n * vector.\n * @param {module:twgl/m4.Mat4} a The matrix.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix with translation set.\n * @memberOf module:twgl/m4\n */\nfunction setTranslation(a, v, dst) {\n dst = dst || identity();\n if (a !== dst) {\n dst[ 0] = a[ 0];\n dst[ 1] = a[ 1];\n dst[ 2] = a[ 2];\n dst[ 3] = a[ 3];\n dst[ 4] = a[ 4];\n dst[ 5] = a[ 5];\n dst[ 6] = a[ 6];\n dst[ 7] = a[ 7];\n dst[ 8] = a[ 8];\n dst[ 9] = a[ 9];\n dst[10] = a[10];\n dst[11] = a[11];\n }\n dst[12] = v[0];\n dst[13] = v[1];\n dst[14] = v[2];\n dst[15] = 1;\n return dst;\n}\n\n/**\n * Returns the translation component of a 4-by-4 matrix as a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The translation component of m.\n * @memberOf module:twgl/m4\n */\nfunction getTranslation(m, dst) {\n dst = dst || create$1();\n dst[0] = m[12];\n dst[1] = m[13];\n dst[2] = m[14];\n return dst;\n}\n\n/**\n * Returns an axis of a 4x4 matrix as a vector with 3 entries\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} axis The axis 0 = x, 1 = y, 2 = z;\n * @return {module:twgl/v3.Vec3} [dst] vector.\n * @return {module:twgl/v3.Vec3} The axis component of m.\n * @memberOf module:twgl/m4\n */\nfunction getAxis(m, axis, dst) {\n dst = dst || create$1();\n const off = axis * 4;\n dst[0] = m[off + 0];\n dst[1] = m[off + 1];\n dst[2] = m[off + 2];\n return dst;\n}\n\n/**\n * Sets an axis of a 4x4 matrix as a vector with 3 entries\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v the axis vector\n * @param {number} axis The axis 0 = x, 1 = y, 2 = z;\n * @param {module:twgl/m4.Mat4} [dst] The matrix to set. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix with axis set.\n * @memberOf module:twgl/m4\n */\nfunction setAxis(a, v, axis, dst) {\n if (dst !== a) {\n dst = copy(a, dst);\n }\n const off = axis * 4;\n dst[off + 0] = v[0];\n dst[off + 1] = v[1];\n dst[off + 2] = v[2];\n return dst;\n}\n\n/**\n * Computes a 4-by-4 perspective transformation matrix given the angular height\n * of the frustum, the aspect ratio, and the near and far clipping planes. The\n * arguments define a frustum extending in the negative z direction. The given\n * angle is the vertical angle of the frustum, and the horizontal angle is\n * determined to produce the given aspect ratio. The arguments near and far are\n * the distances to the near and far clipping planes. Note that near and far\n * are not z coordinates, but rather they are distances along the negative\n * z-axis. The matrix generated sends the viewing frustum to the unit box.\n * We assume a unit box extending from -1 to 1 in the x and y dimensions and\n * from 0 to 1 in the z dimension.\n * @param {number} fieldOfViewYInRadians The camera angle from top to bottom (in radians).\n * @param {number} aspect The aspect ratio width / height.\n * @param {number} zNear The depth (negative z coordinate)\n * of the near clipping plane.\n * @param {number} zFar The depth (negative z coordinate)\n * of the far clipping plane.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective matrix.\n * @memberOf module:twgl/m4\n */\nfunction perspective(fieldOfViewYInRadians, aspect, zNear, zFar, dst) {\n dst = dst || new MatType(16);\n\n const f = Math.tan(Math.PI * 0.5 - 0.5 * fieldOfViewYInRadians);\n const rangeInv = 1.0 / (zNear - zFar);\n\n dst[0] = f / aspect;\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = f;\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = (zNear + zFar) * rangeInv;\n dst[11] = -1;\n\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = zNear * zFar * rangeInv * 2;\n dst[15] = 0;\n\n return dst;\n}\n\n/**\n * Computes a 4-by-4 orthogonal transformation matrix given the left, right,\n * bottom, and top dimensions of the near clipping plane as well as the\n * near and far clipping plane distances.\n * @param {number} left Left side of the near clipping plane viewport.\n * @param {number} right Right side of the near clipping plane viewport.\n * @param {number} bottom Bottom of the near clipping plane viewport.\n * @param {number} top Top of the near clipping plane viewport.\n * @param {number} near The depth (negative z coordinate)\n * of the near clipping plane.\n * @param {number} far The depth (negative z coordinate)\n * of the far clipping plane.\n * @param {module:twgl/m4.Mat4} [dst] Output matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective matrix.\n * @memberOf module:twgl/m4\n */\nfunction ortho(left, right, bottom, top, near, far, dst) {\n dst = dst || new MatType(16);\n\n dst[0] = 2 / (right - left);\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = 2 / (top - bottom);\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = 2 / (near - far);\n dst[11] = 0;\n\n dst[12] = (right + left) / (left - right);\n dst[13] = (top + bottom) / (bottom - top);\n dst[14] = (far + near) / (near - far);\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Computes a 4-by-4 perspective transformation matrix given the left, right,\n * top, bottom, near and far clipping planes. The arguments define a frustum\n * extending in the negative z direction. The arguments near and far are the\n * distances to the near and far clipping planes. Note that near and far are not\n * z coordinates, but rather they are distances along the negative z-axis. The\n * matrix generated sends the viewing frustum to the unit box. We assume a unit\n * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z\n * dimension.\n * @param {number} left The x coordinate of the left plane of the box.\n * @param {number} right The x coordinate of the right plane of the box.\n * @param {number} bottom The y coordinate of the bottom plane of the box.\n * @param {number} top The y coordinate of the right plane of the box.\n * @param {number} near The negative z coordinate of the near plane of the box.\n * @param {number} far The negative z coordinate of the far plane of the box.\n * @param {module:twgl/m4.Mat4} [dst] Output matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective projection matrix.\n * @memberOf module:twgl/m4\n */\nfunction frustum(left, right, bottom, top, near, far, dst) {\n dst = dst || new MatType(16);\n\n const dx = (right - left);\n const dy = (top - bottom);\n const dz = (near - far);\n\n dst[ 0] = 2 * near / dx;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 2 * near / dy;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = (left + right) / dx;\n dst[ 9] = (top + bottom) / dy;\n dst[10] = far / dz;\n dst[11] = -1;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = near * far / dz;\n dst[15] = 0;\n\n return dst;\n}\n\nlet xAxis;\nlet yAxis;\nlet zAxis;\n\n/**\n * Computes a 4-by-4 look-at transformation.\n *\n * This is a matrix which positions the camera itself. If you want\n * a view matrix (a matrix which moves things in front of the camera)\n * take the inverse of this.\n *\n * @param {module:twgl/v3.Vec3} eye The position of the eye.\n * @param {module:twgl/v3.Vec3} target The position meant to be viewed.\n * @param {module:twgl/v3.Vec3} up A vector pointing up.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The look-at matrix.\n * @memberOf module:twgl/m4\n */\nfunction lookAt(eye, target, up, dst) {\n dst = dst || new MatType(16);\n\n xAxis = xAxis || create$1();\n yAxis = yAxis || create$1();\n zAxis = zAxis || create$1();\n\n normalize(\n subtract(eye, target, zAxis), zAxis);\n normalize(cross(up, zAxis, xAxis), xAxis);\n normalize(cross(zAxis, xAxis, yAxis), yAxis);\n\n dst[ 0] = xAxis[0];\n dst[ 1] = xAxis[1];\n dst[ 2] = xAxis[2];\n dst[ 3] = 0;\n dst[ 4] = yAxis[0];\n dst[ 5] = yAxis[1];\n dst[ 6] = yAxis[2];\n dst[ 7] = 0;\n dst[ 8] = zAxis[0];\n dst[ 9] = zAxis[1];\n dst[10] = zAxis[2];\n dst[11] = 0;\n dst[12] = eye[0];\n dst[13] = eye[1];\n dst[14] = eye[2];\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which translates by the given vector v.\n * @param {module:twgl/v3.Vec3} v The vector by\n * which to translate.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The translation matrix.\n * @memberOf module:twgl/m4\n */\nfunction translation(v, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = v[0];\n dst[13] = v[1];\n dst[14] = v[2];\n dst[15] = 1;\n return dst;\n}\n\n/**\n * Translates the given 4-by-4 matrix by the given vector v.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The vector by\n * which to translate.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The translated matrix.\n * @memberOf module:twgl/m4\n */\nfunction translate(m, v, dst) {\n dst = dst || new MatType(16);\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n const m00 = m[0];\n const m01 = m[1];\n const m02 = m[2];\n const m03 = m[3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n\n if (m !== dst) {\n dst[ 0] = m00;\n dst[ 1] = m01;\n dst[ 2] = m02;\n dst[ 3] = m03;\n dst[ 4] = m10;\n dst[ 5] = m11;\n dst[ 6] = m12;\n dst[ 7] = m13;\n dst[ 8] = m20;\n dst[ 9] = m21;\n dst[10] = m22;\n dst[11] = m23;\n }\n\n dst[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30;\n dst[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31;\n dst[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32;\n dst[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33;\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationX(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = c;\n dst[ 6] = s;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = -s;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the x-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateX(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m10 = m[4];\n const m11 = m[5];\n const m12 = m[6];\n const m13 = m[7];\n const m20 = m[8];\n const m21 = m[9];\n const m22 = m[10];\n const m23 = m[11];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[4] = c * m10 + s * m20;\n dst[5] = c * m11 + s * m21;\n dst[6] = c * m12 + s * m22;\n dst[7] = c * m13 + s * m23;\n dst[8] = c * m20 - s * m10;\n dst[9] = c * m21 - s * m11;\n dst[10] = c * m22 - s * m12;\n dst[11] = c * m23 - s * m13;\n\n if (m !== dst) {\n dst[ 0] = m[ 0];\n dst[ 1] = m[ 1];\n dst[ 2] = m[ 2];\n dst[ 3] = m[ 3];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationY(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c;\n dst[ 1] = 0;\n dst[ 2] = -s;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = s;\n dst[ 9] = 0;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the y-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateY(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c * m00 - s * m20;\n dst[ 1] = c * m01 - s * m21;\n dst[ 2] = c * m02 - s * m22;\n dst[ 3] = c * m03 - s * m23;\n dst[ 8] = c * m20 + s * m00;\n dst[ 9] = c * m21 + s * m01;\n dst[10] = c * m22 + s * m02;\n dst[11] = c * m23 + s * m03;\n\n if (m !== dst) {\n dst[ 4] = m[ 4];\n dst[ 5] = m[ 5];\n dst[ 6] = m[ 6];\n dst[ 7] = m[ 7];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationZ(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c;\n dst[ 1] = s;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = -s;\n dst[ 5] = c;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the z-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateZ(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c * m00 + s * m10;\n dst[ 1] = c * m01 + s * m11;\n dst[ 2] = c * m02 + s * m12;\n dst[ 3] = c * m03 + s * m13;\n dst[ 4] = c * m10 - s * m00;\n dst[ 5] = c * m11 - s * m01;\n dst[ 6] = c * m12 - s * m02;\n dst[ 7] = c * m13 - s * m03;\n\n if (m !== dst) {\n dst[ 8] = m[ 8];\n dst[ 9] = m[ 9];\n dst[10] = m[10];\n dst[11] = m[11];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the given axis by the given\n * angle.\n * @param {module:twgl/v3.Vec3} axis The axis\n * about which to rotate.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} A matrix which rotates angle radians\n * around the axis.\n * @memberOf module:twgl/m4\n */\nfunction axisRotation(axis, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n const n = Math.sqrt(x * x + y * y + z * z);\n x /= n;\n y /= n;\n z /= n;\n const xx = x * x;\n const yy = y * y;\n const zz = z * z;\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n const oneMinusCosine = 1 - c;\n\n dst[ 0] = xx + (1 - xx) * c;\n dst[ 1] = x * y * oneMinusCosine + z * s;\n dst[ 2] = x * z * oneMinusCosine - y * s;\n dst[ 3] = 0;\n dst[ 4] = x * y * oneMinusCosine - z * s;\n dst[ 5] = yy + (1 - yy) * c;\n dst[ 6] = y * z * oneMinusCosine + x * s;\n dst[ 7] = 0;\n dst[ 8] = x * z * oneMinusCosine + y * s;\n dst[ 9] = y * z * oneMinusCosine - x * s;\n dst[10] = zz + (1 - zz) * c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the given axis by the\n * given angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} axis The axis\n * about which to rotate.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction axisRotate(m, axis, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n const n = Math.sqrt(x * x + y * y + z * z);\n x /= n;\n y /= n;\n z /= n;\n const xx = x * x;\n const yy = y * y;\n const zz = z * z;\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n const oneMinusCosine = 1 - c;\n\n const r00 = xx + (1 - xx) * c;\n const r01 = x * y * oneMinusCosine + z * s;\n const r02 = x * z * oneMinusCosine - y * s;\n const r10 = x * y * oneMinusCosine - z * s;\n const r11 = yy + (1 - yy) * c;\n const r12 = y * z * oneMinusCosine + x * s;\n const r20 = x * z * oneMinusCosine + y * s;\n const r21 = y * z * oneMinusCosine - x * s;\n const r22 = zz + (1 - zz) * c;\n\n const m00 = m[0];\n const m01 = m[1];\n const m02 = m[2];\n const m03 = m[3];\n const m10 = m[4];\n const m11 = m[5];\n const m12 = m[6];\n const m13 = m[7];\n const m20 = m[8];\n const m21 = m[9];\n const m22 = m[10];\n const m23 = m[11];\n\n dst[ 0] = r00 * m00 + r01 * m10 + r02 * m20;\n dst[ 1] = r00 * m01 + r01 * m11 + r02 * m21;\n dst[ 2] = r00 * m02 + r01 * m12 + r02 * m22;\n dst[ 3] = r00 * m03 + r01 * m13 + r02 * m23;\n dst[ 4] = r10 * m00 + r11 * m10 + r12 * m20;\n dst[ 5] = r10 * m01 + r11 * m11 + r12 * m21;\n dst[ 6] = r10 * m02 + r11 * m12 + r12 * m22;\n dst[ 7] = r10 * m03 + r11 * m13 + r12 * m23;\n dst[ 8] = r20 * m00 + r21 * m10 + r22 * m20;\n dst[ 9] = r20 * m01 + r21 * m11 + r22 * m21;\n dst[10] = r20 * m02 + r21 * m12 + r22 * m22;\n dst[11] = r20 * m03 + r21 * m13 + r22 * m23;\n\n if (m !== dst) {\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which scales in each dimension by an amount given by\n * the corresponding entry in the given vector; assumes the vector has three\n * entries.\n * @param {module:twgl/v3.Vec3} v A vector of\n * three entries specifying the factor by which to scale in each dimension.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The scaling matrix.\n * @memberOf module:twgl/m4\n */\nfunction scaling(v, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = v[0];\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = v[1];\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = v[2];\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Scales the given 4-by-4 matrix in each dimension by an amount\n * given by the corresponding entry in the given vector; assumes the vector has\n * three entries.\n * @param {module:twgl/m4.Mat4} m The matrix to be modified.\n * @param {module:twgl/v3.Vec3} v A vector of three entries specifying the\n * factor by which to scale in each dimension.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The scaled matrix.\n * @memberOf module:twgl/m4\n */\nfunction scale(m, v, dst) {\n dst = dst || new MatType(16);\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[ 0] = v0 * m[0 * 4 + 0];\n dst[ 1] = v0 * m[0 * 4 + 1];\n dst[ 2] = v0 * m[0 * 4 + 2];\n dst[ 3] = v0 * m[0 * 4 + 3];\n dst[ 4] = v1 * m[1 * 4 + 0];\n dst[ 5] = v1 * m[1 * 4 + 1];\n dst[ 6] = v1 * m[1 * 4 + 2];\n dst[ 7] = v1 * m[1 * 4 + 3];\n dst[ 8] = v2 * m[2 * 4 + 0];\n dst[ 9] = v2 * m[2 * 4 + 1];\n dst[10] = v2 * m[2 * 4 + 2];\n dst[11] = v2 * m[2 * 4 + 3];\n\n if (m !== dst) {\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix and a vector with 3 entries,\n * interprets the vector as a point, transforms that point by the matrix, and\n * returns the result as a vector with 3 entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The point.\n * @param {module:twgl/v3.Vec3} [dst] optional vec3 to store result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed point.\n * @memberOf module:twgl/m4\n */\nfunction transformPoint(m, v, dst) {\n dst = dst || create$1();\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n const d = v0 * m[0 * 4 + 3] + v1 * m[1 * 4 + 3] + v2 * m[2 * 4 + 3] + m[3 * 4 + 3];\n\n dst[0] = (v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0] + m[3 * 4 + 0]) / d;\n dst[1] = (v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1] + m[3 * 4 + 1]) / d;\n dst[2] = (v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2] + m[3 * 4 + 2]) / d;\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a\n * direction, transforms that direction by the matrix, and returns the result;\n * assumes the transformation of 3-dimensional space represented by the matrix\n * is parallel-preserving, i.e. any combination of rotation, scaling and\n * translation, but not a perspective distortion. Returns a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The direction.\n * @param {module:twgl/v3.Vec3} [dst] optional Vec3 to store result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed direction.\n * @memberOf module:twgl/m4\n */\nfunction transformDirection(m, v, dst) {\n dst = dst || create$1();\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0];\n dst[1] = v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1];\n dst[2] = v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2];\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector\n * as a normal to a surface, and computes a vector which is normal upon\n * transforming that surface by the matrix. The effect of this function is the\n * same as transforming v (as a direction) by the inverse-transpose of m. This\n * function assumes the transformation of 3-dimensional space represented by the\n * matrix is parallel-preserving, i.e. any combination of rotation, scaling and\n * translation, but not a perspective distortion. Returns a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The normal.\n * @param {module:twgl/v3.Vec3} [dst] The direction. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed normal.\n * @memberOf module:twgl/m4\n */\nfunction transformNormal$1(m, v, dst) {\n dst = dst || create$1();\n const mi = inverse(m);\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];\n dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];\n dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];\n\n return dst;\n}\n\nvar m4 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n axisRotate: axisRotate,\n axisRotation: axisRotation,\n copy: copy,\n create: create,\n frustum: frustum,\n getAxis: getAxis,\n getTranslation: getTranslation,\n identity: identity,\n inverse: inverse,\n lookAt: lookAt,\n multiply: multiply,\n negate: negate,\n ortho: ortho,\n perspective: perspective,\n rotateX: rotateX,\n rotateY: rotateY,\n rotateZ: rotateZ,\n rotationX: rotationX,\n rotationY: rotationY,\n rotationZ: rotationZ,\n scale: scale,\n scaling: scaling,\n setAxis: setAxis,\n setDefaultType: setDefaultType,\n setTranslation: setTranslation,\n transformDirection: transformDirection,\n transformNormal: transformNormal$1,\n transformPoint: transformPoint,\n translate: translate,\n translation: translation,\n transpose: transpose\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/* DataType */\nconst BYTE$2 = 0x1400;\nconst UNSIGNED_BYTE$3 = 0x1401;\nconst SHORT$2 = 0x1402;\nconst UNSIGNED_SHORT$3 = 0x1403;\nconst INT$3 = 0x1404;\nconst UNSIGNED_INT$3 = 0x1405;\nconst FLOAT$3 = 0x1406;\nconst UNSIGNED_SHORT_4_4_4_4$1 = 0x8033;\nconst UNSIGNED_SHORT_5_5_5_1$1 = 0x8034;\nconst UNSIGNED_SHORT_5_6_5$1 = 0x8363;\nconst HALF_FLOAT$1 = 0x140B;\nconst UNSIGNED_INT_2_10_10_10_REV$1 = 0x8368;\nconst UNSIGNED_INT_10F_11F_11F_REV$1 = 0x8C3B;\nconst UNSIGNED_INT_5_9_9_9_REV$1 = 0x8C3E;\nconst FLOAT_32_UNSIGNED_INT_24_8_REV$1 = 0x8DAD;\nconst UNSIGNED_INT_24_8$1 = 0x84FA;\n\nconst glTypeToTypedArray = {};\n{\n const tt = glTypeToTypedArray;\n tt[BYTE$2] = Int8Array;\n tt[UNSIGNED_BYTE$3] = Uint8Array;\n tt[SHORT$2] = Int16Array;\n tt[UNSIGNED_SHORT$3] = Uint16Array;\n tt[INT$3] = Int32Array;\n tt[UNSIGNED_INT$3] = Uint32Array;\n tt[FLOAT$3] = Float32Array;\n tt[UNSIGNED_SHORT_4_4_4_4$1] = Uint16Array;\n tt[UNSIGNED_SHORT_5_5_5_1$1] = Uint16Array;\n tt[UNSIGNED_SHORT_5_6_5$1] = Uint16Array;\n tt[HALF_FLOAT$1] = Uint16Array;\n tt[UNSIGNED_INT_2_10_10_10_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_10F_11F_11F_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_5_9_9_9_REV$1] = Uint32Array;\n tt[FLOAT_32_UNSIGNED_INT_24_8_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_24_8$1] = Uint32Array;\n}\n\n/**\n * Get the GL type for a typedArray\n * @param {ArrayBufferView} typedArray a typedArray\n * @return {number} the GL type for array. For example pass in an `Int8Array` and `gl.BYTE` will\n * be returned. Pass in a `Uint32Array` and `gl.UNSIGNED_INT` will be returned\n * @memberOf module:twgl/typedArray\n */\nfunction getGLTypeForTypedArray(typedArray) {\n if (typedArray instanceof Int8Array) { return BYTE$2; } // eslint-disable-line\n if (typedArray instanceof Uint8Array) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArray instanceof Uint8ClampedArray) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArray instanceof Int16Array) { return SHORT$2; } // eslint-disable-line\n if (typedArray instanceof Uint16Array) { return UNSIGNED_SHORT$3; } // eslint-disable-line\n if (typedArray instanceof Int32Array) { return INT$3; } // eslint-disable-line\n if (typedArray instanceof Uint32Array) { return UNSIGNED_INT$3; } // eslint-disable-line\n if (typedArray instanceof Float32Array) { return FLOAT$3; } // eslint-disable-line\n throw new Error('unsupported typed array type');\n}\n\n/**\n * Get the GL type for a typedArray type\n * @param {ArrayBufferView} typedArrayType a typedArray constructor\n * @return {number} the GL type for type. For example pass in `Int8Array` and `gl.BYTE` will\n * be returned. Pass in `Uint32Array` and `gl.UNSIGNED_INT` will be returned\n * @memberOf module:twgl/typedArray\n */\nfunction getGLTypeForTypedArrayType(typedArrayType) {\n if (typedArrayType === Int8Array) { return BYTE$2; } // eslint-disable-line\n if (typedArrayType === Uint8Array) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArrayType === Uint8ClampedArray) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArrayType === Int16Array) { return SHORT$2; } // eslint-disable-line\n if (typedArrayType === Uint16Array) { return UNSIGNED_SHORT$3; } // eslint-disable-line\n if (typedArrayType === Int32Array) { return INT$3; } // eslint-disable-line\n if (typedArrayType === Uint32Array) { return UNSIGNED_INT$3; } // eslint-disable-line\n if (typedArrayType === Float32Array) { return FLOAT$3; } // eslint-disable-line\n throw new Error('unsupported typed array type');\n}\n\n/**\n * Get the typed array constructor for a given GL type\n * @param {number} type the GL type. (eg: `gl.UNSIGNED_INT`)\n * @return {function} the constructor for a the corresponding typed array. (eg. `Uint32Array`).\n * @memberOf module:twgl/typedArray\n */\nfunction getTypedArrayTypeForGLType(type) {\n const CTOR = glTypeToTypedArray[type];\n if (!CTOR) {\n throw new Error('unknown gl type');\n }\n return CTOR;\n}\n\nconst isArrayBuffer$1 = typeof SharedArrayBuffer !== 'undefined'\n ? function isArrayBufferOrSharedArrayBuffer(a) {\n return a && a.buffer && (a.buffer instanceof ArrayBuffer || a.buffer instanceof SharedArrayBuffer);\n }\n : function isArrayBuffer(a) {\n return a && a.buffer && a.buffer instanceof ArrayBuffer;\n };\n\nvar typedarrays = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getGLTypeForTypedArray: getGLTypeForTypedArray,\n getGLTypeForTypedArrayType: getGLTypeForTypedArrayType,\n getTypedArrayTypeForGLType: getTypedArrayTypeForGLType,\n isArrayBuffer: isArrayBuffer$1\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/* eslint no-console: \"off\" */\n\n/**\n * Copy named properties\n *\n * @param {string[]} names names of properties to copy\n * @param {object} src object to copy properties from\n * @param {object} dst object to copy properties to\n * @private\n */\nfunction copyNamedProperties(names, src, dst) {\n names.forEach(function(name) {\n const value = src[name];\n if (value !== undefined) {\n dst[name] = value;\n }\n });\n}\n\n/**\n * Copies properties from source to dest only if a matching key is in dest\n *\n * @param {Object.} src the source\n * @param {Object.} dst the dest\n * @private\n */\nfunction copyExistingProperties(src, dst) {\n Object.keys(dst).forEach(function(key) {\n if (dst.hasOwnProperty(key) && src.hasOwnProperty(key)) { /* eslint no-prototype-builtins: 0 */\n dst[key] = src[key];\n }\n });\n}\n\nfunction error$1(...args) {\n console.error(...args);\n}\n\nfunction warn$1(...args) {\n console.warn(...args);\n}\n\nconst isTypeWeakMaps = new Map();\n\nfunction isType(object, type) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n let weakMap = isTypeWeakMaps.get(type);\n if (!weakMap) {\n weakMap = new WeakMap();\n isTypeWeakMaps.set(type, weakMap);\n }\n let isOfType = weakMap.get(object);\n if (isOfType === undefined) {\n const s = Object.prototype.toString.call(object);\n isOfType = s.substring(8, s.length - 1) === type;\n weakMap.set(object, isOfType);\n }\n return isOfType;\n}\n\nfunction isBuffer(gl, t) {\n return typeof WebGLBuffer !== 'undefined' && isType(t, 'WebGLBuffer');\n}\n\nfunction isRenderbuffer(gl, t) {\n return typeof WebGLRenderbuffer !== 'undefined' && isType(t, 'WebGLRenderbuffer');\n}\n\nfunction isTexture(gl, t) {\n return typeof WebGLTexture !== 'undefined' && isType(t, 'WebGLTexture');\n}\n\nfunction isSampler(gl, t) {\n return typeof WebGLSampler !== 'undefined' && isType(t, 'WebGLSampler');\n}\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst STATIC_DRAW = 0x88e4;\nconst ARRAY_BUFFER$1 = 0x8892;\nconst ELEMENT_ARRAY_BUFFER$2 = 0x8893;\nconst BUFFER_SIZE = 0x8764;\n\nconst BYTE$1 = 0x1400;\nconst UNSIGNED_BYTE$2 = 0x1401;\nconst SHORT$1 = 0x1402;\nconst UNSIGNED_SHORT$2 = 0x1403;\nconst INT$2 = 0x1404;\nconst UNSIGNED_INT$2 = 0x1405;\nconst FLOAT$2 = 0x1406;\nconst defaults$2 = {\n attribPrefix: \"\",\n};\n\n/**\n * Sets the default attrib prefix\n *\n * When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`\n * as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.\n *\n * In other words I'll create arrays of geometry like this\n *\n * var arrays = {\n * position: ...\n * normal: ...\n * texcoord: ...\n * };\n *\n * But need those mapped to attributes and my attributes start with `a_`.\n *\n * @deprecated see {@link module:twgl.setDefaults}\n * @param {string} prefix prefix for attribs\n * @memberOf module:twgl/attributes\n */\nfunction setAttributePrefix(prefix) {\n defaults$2.attribPrefix = prefix;\n}\n\nfunction setDefaults$2(newDefaults) {\n copyExistingProperties(newDefaults, defaults$2);\n}\n\nfunction setBufferFromTypedArray(gl, type, buffer, array, drawType) {\n gl.bindBuffer(type, buffer);\n gl.bufferData(type, array, drawType || STATIC_DRAW);\n}\n\n/**\n * Given typed array creates a WebGLBuffer and copies the typed array\n * into it.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|WebGLBuffer} typedArray the typed array. Note: If a WebGLBuffer is passed in it will just be returned. No action will be taken\n * @param {number} [type] the GL bind type for the buffer. Default = `gl.ARRAY_BUFFER`.\n * @param {number} [drawType] the GL draw type for the buffer. Default = 'gl.STATIC_DRAW`.\n * @return {WebGLBuffer} the created WebGLBuffer\n * @memberOf module:twgl/attributes\n */\nfunction createBufferFromTypedArray(gl, typedArray, type, drawType) {\n if (isBuffer(gl, typedArray)) {\n return typedArray;\n }\n type = type || ARRAY_BUFFER$1;\n const buffer = gl.createBuffer();\n setBufferFromTypedArray(gl, type, buffer, typedArray, drawType);\n return buffer;\n}\n\nfunction isIndices(name) {\n return name === \"indices\";\n}\n\n// This is really just a guess. Though I can't really imagine using\n// anything else? Maybe for some compression?\nfunction getNormalizationForTypedArrayType(typedArrayType) {\n if (typedArrayType === Int8Array) { return true; } // eslint-disable-line\n if (typedArrayType === Uint8Array) { return true; } // eslint-disable-line\n return false;\n}\n\nfunction getArray$1(array) {\n return array.length ? array : array.data;\n}\n\nconst texcoordRE = /coord|texture/i;\nconst colorRE = /color|colour/i;\n\nfunction guessNumComponentsFromName(name, length) {\n let numComponents;\n if (texcoordRE.test(name)) {\n numComponents = 2;\n } else if (colorRE.test(name)) {\n numComponents = 4;\n } else {\n numComponents = 3; // position, normals, indices ...\n }\n\n if (length % numComponents > 0) {\n throw new Error(`Can not guess numComponents for attribute '${name}'. Tried ${numComponents} but ${length} values is not evenly divisible by ${numComponents}. You should specify it.`);\n }\n\n return numComponents;\n}\n\nfunction getNumComponents$1(array, arrayName, numValues) {\n return array.numComponents || array.size || guessNumComponentsFromName(arrayName, numValues || getArray$1(array).length);\n}\n\nfunction makeTypedArray(array, name) {\n if (isArrayBuffer$1(array)) {\n return array;\n }\n\n if (isArrayBuffer$1(array.data)) {\n return array.data;\n }\n\n if (Array.isArray(array)) {\n array = {\n data: array,\n };\n }\n\n let Type = array.type ? typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type) : undefined;\n if (!Type) {\n if (isIndices(name)) {\n Type = Uint16Array;\n } else {\n Type = Float32Array;\n }\n }\n return new Type(array.data);\n}\n\nfunction glTypeFromGLTypeOrTypedArrayType(glTypeOrTypedArrayCtor) {\n return typeof glTypeOrTypedArrayCtor === 'number'\n ? glTypeOrTypedArrayCtor\n : glTypeOrTypedArrayCtor ? getGLTypeForTypedArrayType(glTypeOrTypedArrayCtor) : FLOAT$2;\n}\n\nfunction typedArrayTypeFromGLTypeOrTypedArrayCtor(glTypeOrTypedArrayCtor) {\n return typeof glTypeOrTypedArrayCtor === 'number'\n ? getTypedArrayTypeForGLType(glTypeOrTypedArrayCtor)\n : glTypeOrTypedArrayCtor || Float32Array;\n}\n\nfunction attribBufferFromBuffer(gl, array/*, arrayName */) {\n return {\n buffer: array.buffer,\n numValues: 2 * 3 * 4, // safely divided by 2, 3, 4\n type: glTypeFromGLTypeOrTypedArrayType(array.type),\n arrayType: typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type),\n };\n}\n\nfunction attribBufferFromSize(gl, array/*, arrayName*/) {\n const numValues = array.data || array;\n const arrayType = typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type);\n const numBytes = numValues * arrayType.BYTES_PER_ELEMENT;\n const buffer = gl.createBuffer();\n gl.bindBuffer(ARRAY_BUFFER$1, buffer);\n gl.bufferData(ARRAY_BUFFER$1, numBytes, array.drawType || STATIC_DRAW);\n return {\n buffer,\n numValues,\n type: getGLTypeForTypedArrayType(arrayType),\n arrayType,\n };\n}\n\nfunction attribBufferFromArrayLike(gl, array, arrayName) {\n const typedArray = makeTypedArray(array, arrayName);\n return {\n arrayType: typedArray.constructor,\n buffer: createBufferFromTypedArray(gl, typedArray, undefined, array.drawType),\n type: getGLTypeForTypedArray(typedArray),\n numValues: 0,\n };\n}\n\n/**\n * The info for an attribute. This is effectively just the arguments to `gl.vertexAttribPointer` plus the WebGLBuffer\n * for the attribute.\n *\n * @typedef {Object} AttribInfo\n * @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be\n * disabled and set to this constant value and all other values will be ignored.\n * @property {number} [numComponents] the number of components for this attribute.\n * @property {number} [size] synonym for `numComponents`.\n * @property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`\n * @property {boolean} [normalize] whether or not to normalize the data. Default = false\n * @property {number} [offset] offset into buffer in bytes. Default = 0\n * @property {number} [stride] the stride in bytes per element. Default = 0\n * @property {number} [divisor] the divisor in instances. Default = 0.\n * Requires WebGL2 or the ANGLE_instanced_arrays extension.\n * and, if you're using WebGL1 you must have called {@link module:twgl.addExtensionsToContext}\n * @property {WebGLBuffer} buffer the buffer that contains the data for this attribute\n * @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {(Int8ArrayConstructor|Uint8ArrayConstructor|Int16ArrayConstructor|Uint16ArrayConstructor|Int32ArrayConstructor|Uint32ArrayConstructor|Float32ArrayConstructor)} TypedArrayConstructor\n */\n\n/**\n * Use this type of array spec when TWGL can't guess the type or number of components of an array\n * @typedef {Object} FullArraySpec\n * @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be\n * disabled and set to this constant value and all other values will be ignored.\n * @property {(number|number[]|ArrayBufferView)} [data] The data of the array. A number alone becomes the number of elements of type.\n * @property {number} [numComponents] number of components for `vertexAttribPointer`. Default is based on the name of the array.\n * If `coord` is in the name assumes `numComponents = 2`.\n * If `color` is in the name assumes `numComponents = 4`.\n * otherwise assumes `numComponents = 3`\n * @property {number|TypedArrayConstructor} [type] type. This is used if `data` is a JavaScript array, or `buffer` is passed in, or `data` is a number.\n * It can either be the constructor for a typedarray. (eg. `Uint8Array`) OR a WebGL type, (eg `gl.UNSIGNED_BYTE`).\n * For example if you want colors in a `Uint8Array` you might have a `FullArraySpec` like `{ type: gl.UNSIGNED_BYTE, data: [255,0,255,255, ...], }`.\n * @property {number} [size] synonym for `numComponents`.\n * @property {boolean} [normalize] normalize for `vertexAttribPointer`. Default is true if type is `Int8Array` or `Uint8Array` otherwise false.\n * @property {number} [stride] stride for `vertexAttribPointer`. Default = 0\n * @property {number} [offset] offset for `vertexAttribPointer`. Default = 0\n * @property {number} [divisor] divisor for `vertexAttribDivisor`. Default = 0.\n * Requires WebGL2 or the ANGLE_instanced_arrays extension.\n * and, if you using WebGL1 you must have called {@link module:twgl.addExtensionsToContext}\n * @property {string} [attrib] name of attribute this array maps to. Defaults to same name as array prefixed by the default attribPrefix.\n * @property {string} [name] synonym for `attrib`.\n * @property {string} [attribName] synonym for `attrib`.\n * @property {WebGLBuffer} [buffer] Buffer to use for this attribute. This lets you use your own buffer\n * but you will need to supply `numComponents` and `type`. You can effectively pass an `AttribInfo`\n * to provide this. Example:\n *\n * const bufferInfo1 = twgl.createBufferInfoFromArrays(gl, {\n * position: [1, 2, 3, ... ],\n * });\n * const bufferInfo2 = twgl.createBufferInfoFromArrays(gl, {\n * position: bufferInfo1.attribs.position, // use the same buffer from bufferInfo1\n * });\n *\n * @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW\n * @memberOf module:twgl\n */\n\n/**\n * An individual array in {@link module:twgl.Arrays}\n *\n * When passed to {@link module:twgl.createBufferInfoFromArrays} if an ArraySpec is `number[]` or `ArrayBufferView`\n * the types will be guessed based on the name. `indices` will be `Uint16Array`, everything else will\n * be `Float32Array`. If an ArraySpec is a number it's the number of floats for an empty (zeroed) buffer.\n *\n * @typedef {(number|number[]|ArrayBufferView|module:twgl.FullArraySpec)} ArraySpec\n * @memberOf module:twgl\n */\n\n/**\n * This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your\n * attributes have a common prefix you can specify it by calling {@link module:twgl.setAttributePrefix}.\n *\n * Bare JavaScript Arrays\n *\n * var arrays = {\n * position: [-1, 1, 0],\n * normal: [0, 1, 0],\n * ...\n * }\n *\n * Bare TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([-1, 1, 0]),\n * color: new Uint8Array([255, 128, 64, 255]),\n * ...\n * }\n *\n * * Will guess at `numComponents` if not specified based on name.\n *\n * If `coord` is in the name assumes `numComponents = 2`\n *\n * If `color` is in the name assumes `numComponents = 4`\n *\n * otherwise assumes `numComponents = 3`\n *\n * Objects with various fields. See {@link module:twgl.FullArraySpec}.\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * @typedef {Object.} Arrays\n * @memberOf module:twgl\n */\n\n\n/**\n * Creates a set of attribute data and WebGLBuffers from set of arrays\n *\n * Given\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * color: { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * returns something like\n *\n * var attribs = {\n * position: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * texcoord: { numComponents: 2, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * normal: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * color: { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, buffer: WebGLBuffer, },\n * };\n *\n * notes:\n *\n * * Arrays can take various forms\n *\n * Bare JavaScript Arrays\n *\n * var arrays = {\n * position: [-1, 1, 0],\n * normal: [0, 1, 0],\n * ...\n * }\n *\n * Bare TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([-1, 1, 0]),\n * color: new Uint8Array([255, 128, 64, 255]),\n * ...\n * }\n *\n * * Will guess at `numComponents` if not specified based on name.\n *\n * If `coord` is in the name assumes `numComponents = 2`\n *\n * If `color` is in the name assumes `numComponents = 4`\n *\n * otherwise assumes `numComponents = 3`\n *\n * @param {WebGLRenderingContext} gl The webgl rendering context.\n * @param {module:twgl.Arrays} arrays The arrays\n * @param {module:twgl.BufferInfo} [srcBufferInfo] a BufferInfo to copy from\n * This lets you share buffers. Any arrays you supply will override\n * the buffers from srcBufferInfo.\n * @return {Object.} the attribs\n * @memberOf module:twgl/attributes\n */\nfunction createAttribsFromArrays(gl, arrays) {\n const attribs = {};\n Object.keys(arrays).forEach(function(arrayName) {\n if (!isIndices(arrayName)) {\n const array = arrays[arrayName];\n const attribName = array.attrib || array.name || array.attribName || (defaults$2.attribPrefix + arrayName);\n if (array.value) {\n if (!Array.isArray(array.value) && !isArrayBuffer$1(array.value)) {\n throw new Error('array.value is not array or typedarray');\n }\n attribs[attribName] = {\n value: array.value,\n };\n } else {\n let fn;\n if (array.buffer && array.buffer instanceof WebGLBuffer) {\n fn = attribBufferFromBuffer;\n } else if (typeof array === \"number\" || typeof array.data === \"number\") {\n fn = attribBufferFromSize;\n } else {\n fn = attribBufferFromArrayLike;\n }\n const {buffer, type, numValues, arrayType} = fn(gl, array, arrayName);\n const normalization = array.normalize !== undefined ? array.normalize : getNormalizationForTypedArrayType(arrayType);\n const numComponents = getNumComponents$1(array, arrayName, numValues);\n attribs[attribName] = {\n buffer: buffer,\n numComponents: numComponents,\n type: type,\n normalize: normalization,\n stride: array.stride || 0,\n offset: array.offset || 0,\n divisor: array.divisor === undefined ? undefined : array.divisor,\n drawType: array.drawType,\n };\n }\n }\n });\n gl.bindBuffer(ARRAY_BUFFER$1, null);\n return attribs;\n}\n\n/**\n * Sets the contents of a buffer attached to an attribInfo\n *\n * This is helper function to dynamically update a buffer.\n *\n * Let's say you make a bufferInfo\n *\n * var arrays = {\n * position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),\n * texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),\n * normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n * indices: new Uint16Array([0, 1, 2, 1, 2, 3]),\n * };\n * var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);\n *\n * And you want to dynamically update the positions. You could do this\n *\n * // assuming arrays.position has already been updated with new data.\n * twgl.setAttribInfoBufferFromArray(gl, bufferInfo.attribs.position, arrays.position);\n *\n * @param {WebGLRenderingContext} gl\n * @param {AttribInfo} attribInfo The attribInfo who's buffer contents to set. NOTE: If you have an attribute prefix\n * the name of the attribute will include the prefix.\n * @param {ArraySpec} array Note: it is arguably inefficient to pass in anything but a typed array because anything\n * else will have to be converted to a typed array before it can be used by WebGL. During init time that\n * inefficiency is usually not important but if you're updating data dynamically best to be efficient.\n * @param {number} [offset] an optional offset into the buffer. This is only an offset into the WebGL buffer\n * not the array. To pass in an offset into the array itself use a typed array and create an `ArrayBufferView`\n * for the portion of the array you want to use.\n *\n * var someArray = new Float32Array(1000); // an array with 1000 floats\n * var someSubArray = new Float32Array(someArray.buffer, offsetInBytes, sizeInUnits); // a view into someArray\n *\n * Now you can pass `someSubArray` into setAttribInfoBufferFromArray`\n * @memberOf module:twgl/attributes\n */\nfunction setAttribInfoBufferFromArray(gl, attribInfo, array, offset) {\n array = makeTypedArray(array);\n if (offset !== undefined) {\n gl.bindBuffer(ARRAY_BUFFER$1, attribInfo.buffer);\n gl.bufferSubData(ARRAY_BUFFER$1, offset, array);\n } else {\n setBufferFromTypedArray(gl, ARRAY_BUFFER$1, attribInfo.buffer, array, attribInfo.drawType);\n }\n}\n\nfunction getBytesPerValueForGLType(gl, type) {\n if (type === BYTE$1) return 1; // eslint-disable-line\n if (type === UNSIGNED_BYTE$2) return 1; // eslint-disable-line\n if (type === SHORT$1) return 2; // eslint-disable-line\n if (type === UNSIGNED_SHORT$2) return 2; // eslint-disable-line\n if (type === INT$2) return 4; // eslint-disable-line\n if (type === UNSIGNED_INT$2) return 4; // eslint-disable-line\n if (type === FLOAT$2) return 4; // eslint-disable-line\n return 0;\n}\n\n// Tries to get the number of elements from a set of arrays.\nconst positionKeys = ['position', 'positions', 'a_position'];\nfunction getNumElementsFromNonIndexedArrays(arrays) {\n let key;\n let ii;\n for (ii = 0; ii < positionKeys.length; ++ii) {\n key = positionKeys[ii];\n if (key in arrays) {\n break;\n }\n }\n if (ii === positionKeys.length) {\n key = Object.keys(arrays)[0];\n }\n const array = arrays[key];\n const length = getArray$1(array).length;\n if (length === undefined) {\n return 1; // There's no arrays\n }\n const numComponents = getNumComponents$1(array, key);\n const numElements = length / numComponents;\n if (length % numComponents > 0) {\n throw new Error(`numComponents ${numComponents} not correct for length ${length}`);\n }\n return numElements;\n}\n\nfunction getNumElementsFromAttributes(gl, attribs) {\n let key;\n let ii;\n for (ii = 0; ii < positionKeys.length; ++ii) {\n key = positionKeys[ii];\n if (key in attribs) {\n break;\n }\n key = defaults$2.attribPrefix + key;\n if (key in attribs) {\n break;\n }\n }\n if (ii === positionKeys.length) {\n key = Object.keys(attribs)[0];\n }\n const attrib = attribs[key];\n if (!attrib.buffer) {\n return 1; // There's no buffer\n }\n gl.bindBuffer(ARRAY_BUFFER$1, attrib.buffer);\n const numBytes = gl.getBufferParameter(ARRAY_BUFFER$1, BUFFER_SIZE);\n gl.bindBuffer(ARRAY_BUFFER$1, null);\n\n const bytesPerValue = getBytesPerValueForGLType(gl, attrib.type);\n const totalElements = numBytes / bytesPerValue;\n const numComponents = attrib.numComponents || attrib.size;\n // TODO: check stride\n const numElements = totalElements / numComponents;\n if (numElements % 1 !== 0) {\n throw new Error(`numComponents ${numComponents} not correct for length ${length}`);\n }\n return numElements;\n}\n\n/**\n * @typedef {Object} BufferInfo\n * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.\n * @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..\n * @property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.\n * @property {Object.} [attribs] The attribs appropriate to call `setAttributes`\n * @memberOf module:twgl\n */\n\n/**\n * Creates a BufferInfo from an object of arrays.\n *\n * This can be passed to {@link module:twgl.setBuffersAndAttributes} and to\n * {@link module:twgl:drawBufferInfo}.\n *\n * Given an object like\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * Creates an BufferInfo like this\n *\n * bufferInfo = {\n * numElements: 4, // or whatever the number of elements is\n * indices: WebGLBuffer, // this property will not exist if there are no indices\n * attribs: {\n * position: { buffer: WebGLBuffer, numComponents: 3, },\n * normal: { buffer: WebGLBuffer, numComponents: 3, },\n * texcoord: { buffer: WebGLBuffer, numComponents: 2, },\n * },\n * };\n *\n * The properties of arrays can be JavaScript arrays in which case the number of components\n * will be guessed.\n *\n * var arrays = {\n * position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],\n * texcoord: [0, 0, 0, 1, 1, 0, 1, 1],\n * normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],\n * indices: [0, 1, 2, 1, 2, 3],\n * };\n *\n * They can also be TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),\n * texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),\n * normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n * indices: new Uint16Array([0, 1, 2, 1, 2, 3]),\n * };\n *\n * Or AugmentedTypedArrays\n *\n * var positions = createAugmentedTypedArray(3, 4);\n * var texcoords = createAugmentedTypedArray(2, 4);\n * var normals = createAugmentedTypedArray(3, 4);\n * var indices = createAugmentedTypedArray(3, 2, Uint16Array);\n *\n * positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);\n * texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);\n * normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);\n * indices.push([0, 1, 2, 1, 2, 3]);\n *\n * var arrays = {\n * position: positions,\n * texcoord: texcoords,\n * normal: normals,\n * indices: indices,\n * };\n *\n * For the last example it is equivalent to\n *\n * var bufferInfo = {\n * attribs: {\n * position: { numComponents: 3, buffer: gl.createBuffer(), },\n * texcoord: { numComponents: 2, buffer: gl.createBuffer(), },\n * normal: { numComponents: 3, buffer: gl.createBuffer(), },\n * },\n * indices: gl.createBuffer(),\n * numElements: 6,\n * };\n *\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.position.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.texcoord.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.normal.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);\n * gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.Arrays} arrays Your data\n * @param {module:twgl.BufferInfo} [srcBufferInfo] An existing\n * buffer info to start from. WebGLBuffers etc specified\n * in the srcBufferInfo will be used in a new BufferInfo\n * with any arrays specified overriding the ones in\n * srcBufferInfo.\n * @return {module:twgl.BufferInfo} A BufferInfo\n * @memberOf module:twgl/attributes\n */\nfunction createBufferInfoFromArrays(gl, arrays, srcBufferInfo) {\n const newAttribs = createAttribsFromArrays(gl, arrays);\n const bufferInfo = Object.assign({}, srcBufferInfo ? srcBufferInfo : {});\n bufferInfo.attribs = Object.assign({}, srcBufferInfo ? srcBufferInfo.attribs : {}, newAttribs);\n const indices = arrays.indices;\n if (indices) {\n const newIndices = makeTypedArray(indices, \"indices\");\n bufferInfo.indices = createBufferFromTypedArray(gl, newIndices, ELEMENT_ARRAY_BUFFER$2);\n bufferInfo.numElements = newIndices.length;\n bufferInfo.elementType = getGLTypeForTypedArray(newIndices);\n } else if (!bufferInfo.numElements) {\n bufferInfo.numElements = getNumElementsFromAttributes(gl, bufferInfo.attribs);\n }\n\n return bufferInfo;\n}\n\n/**\n * Creates a buffer from an array, typed array, or array spec\n *\n * Given something like this\n *\n * [1, 2, 3],\n *\n * or\n *\n * new Uint16Array([1,2,3]);\n *\n * or\n *\n * {\n * data: [1, 2, 3],\n * type: Uint8Array,\n * }\n *\n * returns a WebGLBuffer that contains the given data.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {module:twgl.ArraySpec} array an array, typed array, or array spec.\n * @param {string} arrayName name of array. Used to guess the type if type can not be derived otherwise.\n * @return {WebGLBuffer} a WebGLBuffer containing the data in array.\n * @memberOf module:twgl/attributes\n */\nfunction createBufferFromArray(gl, array, arrayName) {\n const type = arrayName === \"indices\" ? ELEMENT_ARRAY_BUFFER$2 : ARRAY_BUFFER$1;\n const typedArray = makeTypedArray(array, arrayName);\n return createBufferFromTypedArray(gl, typedArray, type);\n}\n\n/**\n * Creates buffers from arrays or typed arrays\n *\n * Given something like this\n *\n * var arrays = {\n * positions: [1, 2, 3],\n * normals: [0, 0, 1],\n * }\n *\n * returns something like\n *\n * buffers = {\n * positions: WebGLBuffer,\n * normals: WebGLBuffer,\n * }\n *\n * If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {module:twgl.Arrays} arrays\n * @return {Object} returns an object with one WebGLBuffer per array\n * @memberOf module:twgl/attributes\n */\nfunction createBuffersFromArrays(gl, arrays) {\n const buffers = { };\n Object.keys(arrays).forEach(function(key) {\n buffers[key] = createBufferFromArray(gl, arrays[key], key);\n });\n\n // Ugh!\n if (arrays.indices) {\n buffers.numElements = arrays.indices.length;\n buffers.elementType = getGLTypeForTypedArray(makeTypedArray(arrays.indices));\n } else {\n buffers.numElements = getNumElementsFromNonIndexedArrays(arrays);\n }\n\n return buffers;\n}\n\nvar attributes = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createAttribsFromArrays: createAttribsFromArrays,\n createBuffersFromArrays: createBuffersFromArrays,\n createBufferFromArray: createBufferFromArray,\n createBufferFromTypedArray: createBufferFromTypedArray,\n createBufferInfoFromArrays: createBufferInfoFromArrays,\n setAttribInfoBufferFromArray: setAttribInfoBufferFromArray,\n setAttributePrefix: setAttributePrefix,\n setAttributeDefaults_: setDefaults$2,\n getNumComponents_: getNumComponents$1,\n getArray_: getArray$1\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst getArray = getArray$1; // eslint-disable-line\nconst getNumComponents = getNumComponents$1; // eslint-disable-line\n\n/**\n * @typedef {(Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array)} TypedArray\n */\n\n/**\n * Add `push` to a typed array. It just keeps a 'cursor'\n * and allows use to `push` values into the array so we\n * don't have to manually compute offsets\n * @param {TypedArray} typedArray TypedArray to augment\n * @param {number} numComponents number of components.\n * @private\n */\nfunction augmentTypedArray(typedArray, numComponents) {\n let cursor = 0;\n typedArray.push = function() {\n for (let ii = 0; ii < arguments.length; ++ii) {\n const value = arguments[ii];\n if (value instanceof Array || isArrayBuffer$1(value)) {\n for (let jj = 0; jj < value.length; ++jj) {\n typedArray[cursor++] = value[jj];\n }\n } else {\n typedArray[cursor++] = value;\n }\n }\n };\n typedArray.reset = function(opt_index) {\n cursor = opt_index || 0;\n };\n typedArray.numComponents = numComponents;\n Object.defineProperty(typedArray, 'numElements', {\n get: function() {\n return this.length / this.numComponents | 0;\n },\n });\n return typedArray;\n}\n\n/**\n * creates a typed array with a `push` function attached\n * so that you can easily *push* values.\n *\n * `push` can take multiple arguments. If an argument is an array each element\n * of the array will be added to the typed array.\n *\n * Example:\n *\n * const array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values\n * array.push(1, 2, 3);\n * array.push([4, 5, 6]);\n * // array now contains [1, 2, 3, 4, 5, 6]\n *\n * Also has `numComponents` and `numElements` properties.\n *\n * @param {number} numComponents number of components\n * @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`.\n * @param {constructor} opt_type A constructor for the type. Default = `Float32Array`.\n * @return {ArrayBufferView} A typed array.\n * @memberOf module:twgl/primitives\n */\nfunction createAugmentedTypedArray(numComponents, numElements, opt_type) {\n const Type = opt_type || Float32Array;\n return augmentTypedArray(new Type(numComponents * numElements), numComponents);\n}\n\nfunction allButIndices(name) {\n return name !== \"indices\";\n}\n\n/**\n * Given indexed vertices creates a new set of vertices un-indexed by expanding the indexed vertices.\n * @param {Object.} vertices The indexed vertices to deindex\n * @return {Object.} The deindexed vertices\n * @memberOf module:twgl/primitives\n */\nfunction deindexVertices(vertices) {\n const indices = vertices.indices;\n const newVertices = {};\n const numElements = indices.length;\n\n function expandToUnindexed(channel) {\n const srcBuffer = vertices[channel];\n const numComponents = srcBuffer.numComponents;\n const dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor);\n for (let ii = 0; ii < numElements; ++ii) {\n const ndx = indices[ii];\n const offset = ndx * numComponents;\n for (let jj = 0; jj < numComponents; ++jj) {\n dstBuffer.push(srcBuffer[offset + jj]);\n }\n }\n newVertices[channel] = dstBuffer;\n }\n\n Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed);\n\n return newVertices;\n}\n\n/**\n * flattens the normals of deindexed vertices in place.\n * @param {Object.} vertices The deindexed vertices who's normals to flatten\n * @return {Object.} The flattened vertices (same as was passed in)\n * @memberOf module:twgl/primitives\n */\nfunction flattenNormals(vertices) {\n if (vertices.indices) {\n throw new Error('can not flatten normals of indexed vertices. deindex them first');\n }\n\n const normals = vertices.normal;\n const numNormals = normals.length;\n for (let ii = 0; ii < numNormals; ii += 9) {\n // pull out the 3 normals for this triangle\n const nax = normals[ii + 0];\n const nay = normals[ii + 1];\n const naz = normals[ii + 2];\n\n const nbx = normals[ii + 3];\n const nby = normals[ii + 4];\n const nbz = normals[ii + 5];\n\n const ncx = normals[ii + 6];\n const ncy = normals[ii + 7];\n const ncz = normals[ii + 8];\n\n // add them\n let nx = nax + nbx + ncx;\n let ny = nay + nby + ncy;\n let nz = naz + nbz + ncz;\n\n // normalize them\n const length = Math.sqrt(nx * nx + ny * ny + nz * nz);\n\n nx /= length;\n ny /= length;\n nz /= length;\n\n // copy them back in\n normals[ii + 0] = nx;\n normals[ii + 1] = ny;\n normals[ii + 2] = nz;\n\n normals[ii + 3] = nx;\n normals[ii + 4] = ny;\n normals[ii + 5] = nz;\n\n normals[ii + 6] = nx;\n normals[ii + 7] = ny;\n normals[ii + 8] = nz;\n }\n\n return vertices;\n}\n\nfunction applyFuncToV3Array(array, matrix, fn) {\n const len = array.length;\n const tmp = new Float32Array(3);\n for (let ii = 0; ii < len; ii += 3) {\n fn(matrix, [array[ii], array[ii + 1], array[ii + 2]], tmp);\n array[ii ] = tmp[0];\n array[ii + 1] = tmp[1];\n array[ii + 2] = tmp[2];\n }\n}\n\nfunction transformNormal(mi, v, dst) {\n dst = dst || create$1();\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];\n dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];\n dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];\n\n return dst;\n}\n\n/**\n * Reorients directions by the given matrix..\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientDirections(array, matrix) {\n applyFuncToV3Array(array, matrix, transformDirection);\n return array;\n}\n\n/**\n * Reorients normals by the inverse-transpose of the given\n * matrix..\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientNormals(array, matrix) {\n applyFuncToV3Array(array, inverse(matrix), transformNormal);\n return array;\n}\n\n/**\n * Reorients positions by the given matrix. In other words, it\n * multiplies each vertex by the given matrix.\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientPositions(array, matrix) {\n applyFuncToV3Array(array, matrix, transformPoint);\n return array;\n}\n\n/**\n * @typedef {(number[]|TypedArray)} NativeArrayOrTypedArray\n */\n\n/**\n * Reorients arrays by the given matrix. Assumes arrays have\n * names that contains 'pos' could be reoriented as positions,\n * 'binorm' or 'tan' as directions, and 'norm' as normals.\n *\n * @param {Object.} arrays The vertices to reorient\n * @param {module:twgl/m4.Mat4} matrix matrix to reorient by.\n * @return {Object.} same arrays that were passed in.\n * @memberOf module:twgl/primitives\n */\nfunction reorientVertices(arrays, matrix) {\n Object.keys(arrays).forEach(function(name) {\n const array = arrays[name];\n if (name.indexOf(\"pos\") >= 0) {\n reorientPositions(array, matrix);\n } else if (name.indexOf(\"tan\") >= 0 || name.indexOf(\"binorm\") >= 0) {\n reorientDirections(array, matrix);\n } else if (name.indexOf(\"norm\") >= 0) {\n reorientNormals(array, matrix);\n }\n });\n return arrays;\n}\n\n/**\n * Creates XY quad BufferInfo\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {Object.} the created XY Quad BufferInfo\n * @memberOf module:twgl/primitives\n * @function createXYQuadBuffers\n */\n\n/**\n * Creates XY quad Buffers\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {module:twgl.BufferInfo} the created XY Quad buffers\n * @memberOf module:twgl/primitives\n * @function createXYQuadBufferInfo\n */\n\n/**\n * Creates XY quad vertices\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadVertices(1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadVertices(1, 0, 0.5);\n *\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {Object.} the created XY Quad vertices\n * @memberOf module:twgl/primitives\n */\nfunction createXYQuadVertices(size, xOffset, yOffset) {\n size = size || 2;\n xOffset = xOffset || 0;\n yOffset = yOffset || 0;\n size *= 0.5;\n return {\n position: {\n numComponents: 2,\n data: [\n xOffset + -1 * size, yOffset + -1 * size,\n xOffset + 1 * size, yOffset + -1 * size,\n xOffset + -1 * size, yOffset + 1 * size,\n xOffset + 1 * size, yOffset + 1 * size,\n ],\n },\n normal: [\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n ],\n texcoord: [\n 0, 0,\n 1, 0,\n 0, 1,\n 1, 1,\n ],\n indices: [ 0, 1, 2, 2, 1, 3 ],\n };\n}\n\n/**\n * Creates XZ plane BufferInfo.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {module:twgl.BufferInfo} The created plane BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createPlaneBufferInfo\n */\n\n/**\n * Creates XZ plane buffers.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {Object.} The created plane buffers.\n * @memberOf module:twgl/primitives\n * @function createPlaneBuffers\n */\n\n/**\n * Creates XZ plane vertices.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {Object.} The created plane vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createPlaneVertices(\n width,\n depth,\n subdivisionsWidth,\n subdivisionsDepth,\n matrix) {\n width = width || 1;\n depth = depth || 1;\n subdivisionsWidth = subdivisionsWidth || 1;\n subdivisionsDepth = subdivisionsDepth || 1;\n matrix = matrix || identity();\n\n const numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n for (let z = 0; z <= subdivisionsDepth; z++) {\n for (let x = 0; x <= subdivisionsWidth; x++) {\n const u = x / subdivisionsWidth;\n const v = z / subdivisionsDepth;\n positions.push(\n width * u - width * 0.5,\n 0,\n depth * v - depth * 0.5);\n normals.push(0, 1, 0);\n texcoords.push(u, v);\n }\n }\n\n const numVertsAcross = subdivisionsWidth + 1;\n const indices = createAugmentedTypedArray(\n 3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array);\n\n for (let z = 0; z < subdivisionsDepth; z++) { // eslint-disable-line\n for (let x = 0; x < subdivisionsWidth; x++) { // eslint-disable-line\n // Make triangle 1 of quad.\n indices.push(\n (z + 0) * numVertsAcross + x,\n (z + 1) * numVertsAcross + x,\n (z + 0) * numVertsAcross + x + 1);\n\n // Make triangle 2 of quad.\n indices.push(\n (z + 1) * numVertsAcross + x,\n (z + 1) * numVertsAcross + x + 1,\n (z + 0) * numVertsAcross + x + 1);\n }\n }\n\n const arrays = reorientVertices({\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n }, matrix);\n return arrays;\n}\n\n/**\n * Creates sphere BufferInfo.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {module:twgl.BufferInfo} The created sphere BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createSphereBufferInfo\n */\n\n/**\n * Creates sphere buffers.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {Object.} The created sphere buffers.\n * @memberOf module:twgl/primitives\n * @function createSphereBuffers\n */\n\n/**\n * Creates sphere vertices.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {Object.} The created sphere vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createSphereVertices(\n radius,\n subdivisionsAxis,\n subdivisionsHeight,\n opt_startLatitudeInRadians,\n opt_endLatitudeInRadians,\n opt_startLongitudeInRadians,\n opt_endLongitudeInRadians) {\n if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {\n throw new Error('subdivisionAxis and subdivisionHeight must be > 0');\n }\n\n opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0;\n opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI;\n opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0;\n opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2);\n\n const latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians;\n const longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians;\n\n // We are going to generate our sphere by iterating through its\n // spherical coordinates and generating 2 triangles for each quad on a\n // ring of the sphere.\n const numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n // Generate the individual vertices in our vertex buffer.\n for (let y = 0; y <= subdivisionsHeight; y++) {\n for (let x = 0; x <= subdivisionsAxis; x++) {\n // Generate a vertex based on its spherical coordinates\n const u = x / subdivisionsAxis;\n const v = y / subdivisionsHeight;\n const theta = longRange * u + opt_startLongitudeInRadians;\n const phi = latRange * v + opt_startLatitudeInRadians;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n const ux = cosTheta * sinPhi;\n const uy = cosPhi;\n const uz = sinTheta * sinPhi;\n positions.push(radius * ux, radius * uy, radius * uz);\n normals.push(ux, uy, uz);\n texcoords.push(1 - u, v);\n }\n }\n\n const numVertsAround = subdivisionsAxis + 1;\n const indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array);\n for (let x = 0; x < subdivisionsAxis; x++) { // eslint-disable-line\n for (let y = 0; y < subdivisionsHeight; y++) { // eslint-disable-line\n // Make triangle 1 of quad.\n indices.push(\n (y + 0) * numVertsAround + x,\n (y + 0) * numVertsAround + x + 1,\n (y + 1) * numVertsAround + x);\n\n // Make triangle 2 of quad.\n indices.push(\n (y + 1) * numVertsAround + x,\n (y + 0) * numVertsAround + x + 1,\n (y + 1) * numVertsAround + x + 1);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Array of the indices of corners of each face of a cube.\n * @type {Array.}\n * @private\n */\nconst CUBE_FACE_INDICES = [\n [3, 7, 5, 1], // right\n [6, 2, 0, 4], // left\n [6, 7, 3, 2], // ??\n [0, 1, 5, 4], // ??\n [7, 6, 4, 5], // front\n [2, 3, 1, 0], // back\n];\n\n/**\n * Creates a BufferInfo for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] width, height and depth of the cube.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCubeBufferInfo\n */\n\n/**\n * Creates the buffers and indices for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] width, height and depth of the cube.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCubeBuffers\n */\n\n/**\n * Creates the vertices and indices for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {number} [size] width, height and depth of the cube.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createCubeVertices(size) {\n size = size || 1;\n const k = size / 2;\n\n const cornerVertices = [\n [-k, -k, -k],\n [+k, -k, -k],\n [-k, +k, -k],\n [+k, +k, -k],\n [-k, -k, +k],\n [+k, -k, +k],\n [-k, +k, +k],\n [+k, +k, +k],\n ];\n\n const faceNormals = [\n [+1, +0, +0],\n [-1, +0, +0],\n [+0, +1, +0],\n [+0, -1, +0],\n [+0, +0, +1],\n [+0, +0, -1],\n ];\n\n const uvCoords = [\n [1, 0],\n [0, 0],\n [0, 1],\n [1, 1],\n ];\n\n const numVertices = 6 * 4;\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2 , numVertices);\n const indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array);\n\n for (let f = 0; f < 6; ++f) {\n const faceIndices = CUBE_FACE_INDICES[f];\n for (let v = 0; v < 4; ++v) {\n const position = cornerVertices[faceIndices[v]];\n const normal = faceNormals[f];\n const uv = uvCoords[v];\n\n // Each face needs all four vertices because the normals and texture\n // coordinates are not all the same.\n positions.push(position);\n normals.push(normal);\n texcoords.push(uv);\n\n }\n // Two triangles make a square face.\n const offset = 4 * f;\n indices.push(offset + 0, offset + 1, offset + 2);\n indices.push(offset + 0, offset + 2, offset + 3);\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Creates a BufferInfo for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {module:twgl.BufferInfo} The created cone BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createTruncatedConeBufferInfo\n */\n\n/**\n * Creates buffers for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created cone buffers.\n * @memberOf module:twgl/primitives\n * @function createTruncatedConeBuffers\n */\n\n/**\n * Creates vertices for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis. .\n *\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created cone vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createTruncatedConeVertices(\n bottomRadius,\n topRadius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n opt_topCap,\n opt_bottomCap) {\n if (radialSubdivisions < 3) {\n throw new Error('radialSubdivisions must be 3 or greater');\n }\n\n if (verticalSubdivisions < 1) {\n throw new Error('verticalSubdivisions must be 1 or greater');\n }\n\n const topCap = (opt_topCap === undefined) ? true : opt_topCap;\n const bottomCap = (opt_bottomCap === undefined) ? true : opt_bottomCap;\n\n const extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0);\n\n const numVertices = (radialSubdivisions + 1) * (verticalSubdivisions + 1 + extra);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, radialSubdivisions * (verticalSubdivisions + extra / 2) * 2, Uint16Array);\n\n const vertsAroundEdge = radialSubdivisions + 1;\n\n // The slant of the cone is constant across its surface\n const slant = Math.atan2(bottomRadius - topRadius, height);\n const cosSlant = Math.cos(slant);\n const sinSlant = Math.sin(slant);\n\n const start = topCap ? -2 : 0;\n const end = verticalSubdivisions + (bottomCap ? 2 : 0);\n\n for (let yy = start; yy <= end; ++yy) {\n let v = yy / verticalSubdivisions;\n let y = height * v;\n let ringRadius;\n if (yy < 0) {\n y = 0;\n v = 1;\n ringRadius = bottomRadius;\n } else if (yy > verticalSubdivisions) {\n y = height;\n v = 1;\n ringRadius = topRadius;\n } else {\n ringRadius = bottomRadius +\n (topRadius - bottomRadius) * (yy / verticalSubdivisions);\n }\n if (yy === -2 || yy === verticalSubdivisions + 2) {\n ringRadius = 0;\n v = 0;\n }\n y -= height / 2;\n for (let ii = 0; ii < vertsAroundEdge; ++ii) {\n const sin = Math.sin(ii * Math.PI * 2 / radialSubdivisions);\n const cos = Math.cos(ii * Math.PI * 2 / radialSubdivisions);\n positions.push(sin * ringRadius, y, cos * ringRadius);\n if (yy < 0) {\n normals.push(0, -1, 0);\n } else if (yy > verticalSubdivisions) {\n normals.push(0, 1, 0);\n } else if (ringRadius === 0.0) {\n normals.push(0, 0, 0);\n } else {\n normals.push(sin * cosSlant, sinSlant, cos * cosSlant);\n }\n texcoords.push((ii / radialSubdivisions), 1 - v);\n }\n }\n\n for (let yy = 0; yy < verticalSubdivisions + extra; ++yy) { // eslint-disable-line\n if (yy === 1 && topCap || yy === verticalSubdivisions + extra - 2 && bottomCap) {\n continue;\n }\n for (let ii = 0; ii < radialSubdivisions; ++ii) { // eslint-disable-line\n indices.push(vertsAroundEdge * (yy + 0) + 0 + ii,\n vertsAroundEdge * (yy + 0) + 1 + ii,\n vertsAroundEdge * (yy + 1) + 1 + ii);\n indices.push(vertsAroundEdge * (yy + 0) + 0 + ii,\n vertsAroundEdge * (yy + 1) + 1 + ii,\n vertsAroundEdge * (yy + 1) + 0 + ii);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Expands RLE data\n * @param {number[]} rleData data in format of run-length, x, y, z, run-length, x, y, z\n * @param {number[]} [padding] value to add each entry with.\n * @return {number[]} the expanded rleData\n * @private\n */\nfunction expandRLEData(rleData, padding) {\n padding = padding || [];\n const data = [];\n for (let ii = 0; ii < rleData.length; ii += 4) {\n const runLength = rleData[ii];\n const element = rleData.slice(ii + 1, ii + 4);\n element.push.apply(element, padding);\n for (let jj = 0; jj < runLength; ++jj) {\n data.push.apply(data, element);\n }\n }\n return data;\n}\n\n/**\n * Creates 3D 'F' BufferInfo.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function create3DFBufferInfo\n */\n\n/**\n * Creates 3D 'F' buffers.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function create3DFBuffers\n */\n\n/**\n * Creates 3D 'F' vertices.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color arrays.\n *\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction create3DFVertices() {\n\n const positions = [\n // left column front\n 0, 0, 0,\n 0, 150, 0,\n 30, 0, 0,\n 0, 150, 0,\n 30, 150, 0,\n 30, 0, 0,\n\n // top rung front\n 30, 0, 0,\n 30, 30, 0,\n 100, 0, 0,\n 30, 30, 0,\n 100, 30, 0,\n 100, 0, 0,\n\n // middle rung front\n 30, 60, 0,\n 30, 90, 0,\n 67, 60, 0,\n 30, 90, 0,\n 67, 90, 0,\n 67, 60, 0,\n\n // left column back\n 0, 0, 30,\n 30, 0, 30,\n 0, 150, 30,\n 0, 150, 30,\n 30, 0, 30,\n 30, 150, 30,\n\n // top rung back\n 30, 0, 30,\n 100, 0, 30,\n 30, 30, 30,\n 30, 30, 30,\n 100, 0, 30,\n 100, 30, 30,\n\n // middle rung back\n 30, 60, 30,\n 67, 60, 30,\n 30, 90, 30,\n 30, 90, 30,\n 67, 60, 30,\n 67, 90, 30,\n\n // top\n 0, 0, 0,\n 100, 0, 0,\n 100, 0, 30,\n 0, 0, 0,\n 100, 0, 30,\n 0, 0, 30,\n\n // top rung front\n 100, 0, 0,\n 100, 30, 0,\n 100, 30, 30,\n 100, 0, 0,\n 100, 30, 30,\n 100, 0, 30,\n\n // under top rung\n 30, 30, 0,\n 30, 30, 30,\n 100, 30, 30,\n 30, 30, 0,\n 100, 30, 30,\n 100, 30, 0,\n\n // between top rung and middle\n 30, 30, 0,\n 30, 60, 30,\n 30, 30, 30,\n 30, 30, 0,\n 30, 60, 0,\n 30, 60, 30,\n\n // top of middle rung\n 30, 60, 0,\n 67, 60, 30,\n 30, 60, 30,\n 30, 60, 0,\n 67, 60, 0,\n 67, 60, 30,\n\n // front of middle rung\n 67, 60, 0,\n 67, 90, 30,\n 67, 60, 30,\n 67, 60, 0,\n 67, 90, 0,\n 67, 90, 30,\n\n // bottom of middle rung.\n 30, 90, 0,\n 30, 90, 30,\n 67, 90, 30,\n 30, 90, 0,\n 67, 90, 30,\n 67, 90, 0,\n\n // front of bottom\n 30, 90, 0,\n 30, 150, 30,\n 30, 90, 30,\n 30, 90, 0,\n 30, 150, 0,\n 30, 150, 30,\n\n // bottom\n 0, 150, 0,\n 0, 150, 30,\n 30, 150, 30,\n 0, 150, 0,\n 30, 150, 30,\n 30, 150, 0,\n\n // left side\n 0, 0, 0,\n 0, 0, 30,\n 0, 150, 30,\n 0, 0, 0,\n 0, 150, 30,\n 0, 150, 0,\n ];\n\n const texcoords = [\n // left column front\n 0.22, 0.19,\n 0.22, 0.79,\n 0.34, 0.19,\n 0.22, 0.79,\n 0.34, 0.79,\n 0.34, 0.19,\n\n // top rung front\n 0.34, 0.19,\n 0.34, 0.31,\n 0.62, 0.19,\n 0.34, 0.31,\n 0.62, 0.31,\n 0.62, 0.19,\n\n // middle rung front\n 0.34, 0.43,\n 0.34, 0.55,\n 0.49, 0.43,\n 0.34, 0.55,\n 0.49, 0.55,\n 0.49, 0.43,\n\n // left column back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // top rung back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // middle rung back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // top\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n 1, 1,\n 0, 1,\n\n // top rung front\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n 1, 1,\n 0, 1,\n\n // under top rung\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // between top rung and middle\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // top of middle rung\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // front of middle rung\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // bottom of middle rung.\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // front of bottom\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // bottom\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // left side\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n ];\n\n const normals = expandRLEData([\n // left column front\n // top rung front\n // middle rung front\n 18, 0, 0, 1,\n\n // left column back\n // top rung back\n // middle rung back\n 18, 0, 0, -1,\n\n // top\n 6, 0, 1, 0,\n\n // top rung front\n 6, 1, 0, 0,\n\n // under top rung\n 6, 0, -1, 0,\n\n // between top rung and middle\n 6, 1, 0, 0,\n\n // top of middle rung\n 6, 0, 1, 0,\n\n // front of middle rung\n 6, 1, 0, 0,\n\n // bottom of middle rung.\n 6, 0, -1, 0,\n\n // front of bottom\n 6, 1, 0, 0,\n\n // bottom\n 6, 0, -1, 0,\n\n // left side\n 6, -1, 0, 0,\n ]);\n\n const colors = expandRLEData([\n // left column front\n // top rung front\n // middle rung front\n 18, 200, 70, 120,\n\n // left column back\n // top rung back\n // middle rung back\n 18, 80, 70, 200,\n\n // top\n 6, 70, 200, 210,\n\n // top rung front\n 6, 200, 200, 70,\n\n // under top rung\n 6, 210, 100, 70,\n\n // between top rung and middle\n 6, 210, 160, 70,\n\n // top of middle rung\n 6, 70, 180, 210,\n\n // front of middle rung\n 6, 100, 70, 210,\n\n // bottom of middle rung.\n 6, 76, 210, 100,\n\n // front of bottom\n 6, 140, 210, 80,\n\n // bottom\n 6, 90, 130, 110,\n\n // left side\n 6, 160, 160, 220,\n ], [255]);\n\n const numVerts = positions.length / 3;\n\n const arrays = {\n position: createAugmentedTypedArray(3, numVerts),\n texcoord: createAugmentedTypedArray(2, numVerts),\n normal: createAugmentedTypedArray(3, numVerts),\n color: createAugmentedTypedArray(4, numVerts, Uint8Array),\n indices: createAugmentedTypedArray(3, numVerts / 3, Uint16Array),\n };\n\n arrays.position.push(positions);\n arrays.texcoord.push(texcoords);\n arrays.normal.push(normals);\n arrays.color.push(colors);\n\n for (let ii = 0; ii < numVerts; ++ii) {\n arrays.indices.push(ii);\n }\n\n return arrays;\n}\n\n/**\n * Creates crescent BufferInfo.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCresentBufferInfo\n */\n\n/**\n * Creates crescent buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCresentBuffers\n */\n\n/**\n * Creates crescent vertices.\n *\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n * @function createCresentBuffers\n */\n\n/**\n * Creates crescent BufferInfo.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCrescentBufferInfo\n */\n\n/**\n * Creates crescent buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCrescentBuffers\n */\n\n/**\n * Creates crescent vertices.\n *\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\n function createCrescentVertices(\n verticalRadius,\n outerRadius,\n innerRadius,\n thickness,\n subdivisionsDown,\n startOffset,\n endOffset) {\n if (subdivisionsDown <= 0) {\n throw new Error('subdivisionDown must be > 0');\n }\n\n startOffset = startOffset || 0;\n endOffset = endOffset || 1;\n\n const subdivisionsThick = 2;\n\n const offsetRange = endOffset - startOffset;\n const numVertices = (subdivisionsDown + 1) * 2 * (2 + subdivisionsThick);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n function lerp(a, b, s) {\n return a + (b - a) * s;\n }\n\n function createArc(arcRadius, x, normalMult, normalAdd, uMult, uAdd) {\n for (let z = 0; z <= subdivisionsDown; z++) {\n const uBack = x / (subdivisionsThick - 1);\n const v = z / subdivisionsDown;\n const xBack = (uBack - 0.5) * 2;\n const angle = (startOffset + (v * offsetRange)) * Math.PI;\n const s = Math.sin(angle);\n const c = Math.cos(angle);\n const radius = lerp(verticalRadius, arcRadius, s);\n const px = xBack * thickness;\n const py = c * verticalRadius;\n const pz = s * radius;\n positions.push(px, py, pz);\n const n = add(multiply$1([0, s, c], normalMult), normalAdd);\n normals.push(n);\n texcoords.push(uBack * uMult + uAdd, v);\n }\n }\n\n // Generate the individual vertices in our vertex buffer.\n for (let x = 0; x < subdivisionsThick; x++) {\n const uBack = (x / (subdivisionsThick - 1) - 0.5) * 2;\n createArc(outerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);\n createArc(outerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 0);\n createArc(innerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);\n createArc(innerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 1);\n }\n\n // Do outer surface.\n const indices = createAugmentedTypedArray(3, (subdivisionsDown * 2) * (2 + subdivisionsThick), Uint16Array);\n\n function createSurface(leftArcOffset, rightArcOffset) {\n for (let z = 0; z < subdivisionsDown; ++z) {\n // Make triangle 1 of quad.\n indices.push(\n leftArcOffset + z + 0,\n leftArcOffset + z + 1,\n rightArcOffset + z + 0);\n\n // Make triangle 2 of quad.\n indices.push(\n leftArcOffset + z + 1,\n rightArcOffset + z + 1,\n rightArcOffset + z + 0);\n }\n }\n\n const numVerticesDown = subdivisionsDown + 1;\n // front\n createSurface(numVerticesDown * 0, numVerticesDown * 4);\n // right\n createSurface(numVerticesDown * 5, numVerticesDown * 7);\n // back\n createSurface(numVerticesDown * 6, numVerticesDown * 2);\n // left\n createSurface(numVerticesDown * 3, numVerticesDown * 1);\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Creates cylinder BufferInfo. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCylinderBufferInfo\n */\n\n /**\n * Creates cylinder buffers. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCylinderBuffers\n */\n\n /**\n * Creates cylinder vertices. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createCylinderVertices(\n radius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n topCap,\n bottomCap) {\n return createTruncatedConeVertices(\n radius,\n radius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n topCap,\n bottomCap);\n}\n\n/**\n * Creates BufferInfo for a torus\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createTorusBufferInfo\n */\n\n/**\n * Creates buffers for a torus\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createTorusBuffers\n */\n\n/**\n * Creates vertices for a torus\n *\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createTorusVertices(\n radius,\n thickness,\n radialSubdivisions,\n bodySubdivisions,\n startAngle,\n endAngle) {\n if (radialSubdivisions < 3) {\n throw new Error('radialSubdivisions must be 3 or greater');\n }\n\n if (bodySubdivisions < 3) {\n throw new Error('verticalSubdivisions must be 3 or greater');\n }\n\n startAngle = startAngle || 0;\n endAngle = endAngle || Math.PI * 2;\n const range = endAngle - startAngle;\n\n const radialParts = radialSubdivisions + 1;\n const bodyParts = bodySubdivisions + 1;\n const numVertices = radialParts * bodyParts;\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, (radialSubdivisions) * (bodySubdivisions) * 2, Uint16Array);\n\n for (let slice = 0; slice < bodyParts; ++slice) {\n const v = slice / bodySubdivisions;\n const sliceAngle = v * Math.PI * 2;\n const sliceSin = Math.sin(sliceAngle);\n const ringRadius = radius + sliceSin * thickness;\n const ny = Math.cos(sliceAngle);\n const y = ny * thickness;\n for (let ring = 0; ring < radialParts; ++ring) {\n const u = ring / radialSubdivisions;\n const ringAngle = startAngle + u * range;\n const xSin = Math.sin(ringAngle);\n const zCos = Math.cos(ringAngle);\n const x = xSin * ringRadius;\n const z = zCos * ringRadius;\n const nx = xSin * sliceSin;\n const nz = zCos * sliceSin;\n positions.push(x, y, z);\n normals.push(nx, ny, nz);\n texcoords.push(u, 1 - v);\n }\n }\n\n for (let slice = 0; slice < bodySubdivisions; ++slice) { // eslint-disable-line\n for (let ring = 0; ring < radialSubdivisions; ++ring) { // eslint-disable-line\n const nextRingIndex = 1 + ring;\n const nextSliceIndex = 1 + slice;\n indices.push(radialParts * slice + ring,\n radialParts * nextSliceIndex + ring,\n radialParts * slice + nextRingIndex);\n indices.push(radialParts * nextSliceIndex + ring,\n radialParts * nextSliceIndex + nextRingIndex,\n radialParts * slice + nextRingIndex);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n\n/**\n * Creates a disc BufferInfo. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createDiscBufferInfo\n */\n\n/**\n * Creates disc buffers. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createDiscBuffers\n */\n\n/**\n * Creates disc vertices. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createDiscVertices(\n radius,\n divisions,\n stacks,\n innerRadius,\n stackPower) {\n if (divisions < 3) {\n throw new Error('divisions must be at least 3');\n }\n\n stacks = stacks ? stacks : 1;\n stackPower = stackPower ? stackPower : 1;\n innerRadius = innerRadius ? innerRadius : 0;\n\n // Note: We don't share the center vertex because that would\n // mess up texture coordinates.\n const numVertices = (divisions + 1) * (stacks + 1);\n\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array);\n\n let firstIndex = 0;\n const radiusSpan = radius - innerRadius;\n const pointsPerStack = divisions + 1;\n\n // Build the disk one stack at a time.\n for (let stack = 0; stack <= stacks; ++stack) {\n const stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower);\n\n for (let i = 0; i <= divisions; ++i) {\n const theta = 2.0 * Math.PI * i / divisions;\n const x = stackRadius * Math.cos(theta);\n const z = stackRadius * Math.sin(theta);\n\n positions.push(x, 0, z);\n normals.push(0, 1, 0);\n texcoords.push(1 - (i / divisions), stack / stacks);\n if (stack > 0 && i !== divisions) {\n // a, b, c and d are the indices of the vertices of a quad. unless\n // the current stack is the one closest to the center, in which case\n // the vertices a and b connect to the center vertex.\n const a = firstIndex + (i + 1);\n const b = firstIndex + i;\n const c = firstIndex + i - pointsPerStack;\n const d = firstIndex + (i + 1) - pointsPerStack;\n\n // Make a quad of the vertices a, b, c, d.\n indices.push(a, b, c);\n indices.push(a, c, d);\n }\n }\n\n firstIndex += divisions + 1;\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * creates a random integer between 0 and range - 1 inclusive.\n * @param {number} range\n * @return {number} random value between 0 and range - 1 inclusive.\n * @private\n */\nfunction randInt(range) {\n return Math.random() * range | 0;\n}\n\n/**\n * Used to supply random colors\n * @callback RandomColorFunc\n * @param {number} ndx index of triangle/quad if unindexed or index of vertex if indexed\n * @param {number} channel 0 = red, 1 = green, 2 = blue, 3 = alpha\n * @return {number} a number from 0 to 255\n * @memberOf module:twgl/primitives\n */\n\n/**\n * @typedef {Object} RandomVerticesOptions\n * @property {number} [vertsPerColor] Defaults to 3 for non-indexed vertices\n * @property {module:twgl/primitives.RandomColorFunc} [rand] A function to generate random numbers\n * @memberOf module:twgl/primitives\n */\n\n/**\n * Creates an augmentedTypedArray of random vertex colors.\n * If the vertices are indexed (have an indices array) then will\n * just make random colors. Otherwise assumes they are triangles\n * and makes one random color for every 3 vertices.\n * @param {Object.} vertices Vertices as returned from one of the createXXXVertices functions.\n * @param {module:twgl/primitives.RandomVerticesOptions} [options] options.\n * @return {Object.} same vertices as passed in with `color` added.\n * @memberOf module:twgl/primitives\n */\nfunction makeRandomVertexColors(vertices, options) {\n options = options || {};\n const numElements = vertices.position.numElements;\n const vColors = createAugmentedTypedArray(4, numElements, Uint8Array);\n const rand = options.rand || function(ndx, channel) {\n return channel < 3 ? randInt(256) : 255;\n };\n vertices.color = vColors;\n if (vertices.indices) {\n // just make random colors if index\n for (let ii = 0; ii < numElements; ++ii) {\n vColors.push(rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3));\n }\n } else {\n // make random colors per triangle\n const numVertsPerColor = options.vertsPerColor || 3;\n const numSets = numElements / numVertsPerColor;\n for (let ii = 0; ii < numSets; ++ii) { // eslint-disable-line\n const color = [rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3)];\n for (let jj = 0; jj < numVertsPerColor; ++jj) {\n vColors.push(color);\n }\n }\n }\n return vertices;\n}\n\n/**\n * creates a function that calls fn to create vertices and then\n * creates a buffers for them\n * @private\n */\nfunction createBufferFunc(fn) {\n return function(gl) {\n const arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1));\n return createBuffersFromArrays(gl, arrays);\n };\n}\n\n/**\n * creates a function that calls fn to create vertices and then\n * creates a bufferInfo object for them\n * @private\n */\nfunction createBufferInfoFunc(fn) {\n return function(gl) {\n const arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1));\n return createBufferInfoFromArrays(gl, arrays);\n };\n}\n\nconst arraySpecPropertyNames = [\n \"numComponents\",\n \"size\",\n \"type\",\n \"normalize\",\n \"stride\",\n \"offset\",\n \"attrib\",\n \"name\",\n \"attribName\",\n];\n\n/**\n * Copy elements from one array to another\n *\n * @param {Array|TypedArray} src source array\n * @param {Array|TypedArray} dst dest array\n * @param {number} dstNdx index in dest to copy src\n * @param {number} [offset] offset to add to copied values\n * @private\n */\nfunction copyElements(src, dst, dstNdx, offset) {\n offset = offset || 0;\n const length = src.length;\n for (let ii = 0; ii < length; ++ii) {\n dst[dstNdx + ii] = src[ii] + offset;\n }\n}\n\n/**\n * Creates an array of the same time\n *\n * @param {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} srcArray array who's type to copy\n * @param {number} length size of new array\n * @return {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} array with same type as srcArray\n * @private\n */\nfunction createArrayOfSameType(srcArray, length) {\n const arraySrc = getArray(srcArray);\n const newArray = new arraySrc.constructor(length);\n let newArraySpec = newArray;\n // If it appears to have been augmented make new one augmented\n if (arraySrc.numComponents && arraySrc.numElements) {\n augmentTypedArray(newArray, arraySrc.numComponents);\n }\n // If it was a full spec make new one a full spec\n if (srcArray.data) {\n newArraySpec = {\n data: newArray,\n };\n copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec);\n }\n return newArraySpec;\n}\n\n/**\n * Concatenates sets of vertices\n *\n * Assumes the vertices match in composition. For example\n * if one set of vertices has positions, normals, and indices\n * all sets of vertices must have positions, normals, and indices\n * and of the same type.\n *\n * Example:\n *\n * const cubeVertices = twgl.primitives.createCubeVertices(2);\n * const sphereVertices = twgl.primitives.createSphereVertices(1, 10, 10);\n * // move the sphere 2 units up\n * twgl.primitives.reorientVertices(\n * sphereVertices, twgl.m4.translation([0, 2, 0]));\n * // merge the sphere with the cube\n * const cubeSphereVertices = twgl.primitives.concatVertices(\n * [cubeVertices, sphereVertices]);\n * // turn them into WebGL buffers and attrib data\n * const bufferInfo = twgl.createBufferInfoFromArrays(gl, cubeSphereVertices);\n *\n * @param {module:twgl.Arrays[]} arrays Array of arrays of vertices\n * @return {module:twgl.Arrays} The concatenated vertices.\n * @memberOf module:twgl/primitives\n */\nfunction concatVertices(arrayOfArrays) {\n const names = {};\n let baseName;\n // get names of all arrays.\n // and numElements for each set of vertices\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n Object.keys(arrays).forEach(function(name) { // eslint-disable-line\n if (!names[name]) {\n names[name] = [];\n }\n if (!baseName && name !== 'indices') {\n baseName = name;\n }\n const arrayInfo = arrays[name];\n const numComponents = getNumComponents(arrayInfo, name);\n const array = getArray(arrayInfo);\n const numElements = array.length / numComponents;\n names[name].push(numElements);\n });\n }\n\n // compute length of combined array\n // and return one for reference\n function getLengthOfCombinedArrays(name) {\n let length = 0;\n let arraySpec;\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n const arrayInfo = arrays[name];\n const array = getArray(arrayInfo);\n length += array.length;\n if (!arraySpec || arrayInfo.data) {\n arraySpec = arrayInfo;\n }\n }\n return {\n length: length,\n spec: arraySpec,\n };\n }\n\n function copyArraysToNewArray(name, base, newArray) {\n let baseIndex = 0;\n let offset = 0;\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n const arrayInfo = arrays[name];\n const array = getArray(arrayInfo);\n if (name === 'indices') {\n copyElements(array, newArray, offset, baseIndex);\n baseIndex += base[ii];\n } else {\n copyElements(array, newArray, offset);\n }\n offset += array.length;\n }\n }\n\n const base = names[baseName];\n\n const newArrays = {};\n Object.keys(names).forEach(function(name) {\n const info = getLengthOfCombinedArrays(name);\n const newArraySpec = createArrayOfSameType(info.spec, info.length);\n copyArraysToNewArray(name, base, getArray(newArraySpec));\n newArrays[name] = newArraySpec;\n });\n return newArrays;\n}\n\n/**\n * Creates a duplicate set of vertices\n *\n * This is useful for calling reorientVertices when you\n * also want to keep the original available\n *\n * @param {module:twgl.Arrays} arrays of vertices\n * @return {module:twgl.Arrays} The duplicated vertices.\n * @memberOf module:twgl/primitives\n */\nfunction duplicateVertices(arrays) {\n const newArrays = {};\n Object.keys(arrays).forEach(function(name) {\n const arraySpec = arrays[name];\n const srcArray = getArray(arraySpec);\n const newArraySpec = createArrayOfSameType(arraySpec, srcArray.length);\n copyElements(srcArray, getArray(newArraySpec), 0);\n newArrays[name] = newArraySpec;\n });\n return newArrays;\n}\n\nconst create3DFBufferInfo = createBufferInfoFunc(create3DFVertices);\nconst create3DFBuffers = createBufferFunc(create3DFVertices);\nconst createCubeBufferInfo = createBufferInfoFunc(createCubeVertices);\nconst createCubeBuffers = createBufferFunc(createCubeVertices);\nconst createPlaneBufferInfo = createBufferInfoFunc(createPlaneVertices);\nconst createPlaneBuffers = createBufferFunc(createPlaneVertices);\nconst createSphereBufferInfo = createBufferInfoFunc(createSphereVertices);\nconst createSphereBuffers = createBufferFunc(createSphereVertices);\nconst createTruncatedConeBufferInfo = createBufferInfoFunc(createTruncatedConeVertices);\nconst createTruncatedConeBuffers = createBufferFunc(createTruncatedConeVertices);\nconst createXYQuadBufferInfo = createBufferInfoFunc(createXYQuadVertices);\nconst createXYQuadBuffers = createBufferFunc(createXYQuadVertices);\nconst createCrescentBufferInfo = createBufferInfoFunc(createCrescentVertices);\nconst createCrescentBuffers = createBufferFunc(createCrescentVertices);\nconst createCylinderBufferInfo = createBufferInfoFunc(createCylinderVertices);\nconst createCylinderBuffers = createBufferFunc(createCylinderVertices);\nconst createTorusBufferInfo = createBufferInfoFunc(createTorusVertices);\nconst createTorusBuffers = createBufferFunc(createTorusVertices);\nconst createDiscBufferInfo = createBufferInfoFunc(createDiscVertices);\nconst createDiscBuffers = createBufferFunc(createDiscVertices);\n\n// these were mis-spelled until 4.12\nconst createCresentBufferInfo = createCrescentBufferInfo;\nconst createCresentBuffers = createCrescentBuffers;\nconst createCresentVertices = createCrescentVertices;\n\nvar primitives = /*#__PURE__*/Object.freeze({\n __proto__: null,\n create3DFBufferInfo: create3DFBufferInfo,\n create3DFBuffers: create3DFBuffers,\n create3DFVertices: create3DFVertices,\n createAugmentedTypedArray: createAugmentedTypedArray,\n createCubeBufferInfo: createCubeBufferInfo,\n createCubeBuffers: createCubeBuffers,\n createCubeVertices: createCubeVertices,\n createPlaneBufferInfo: createPlaneBufferInfo,\n createPlaneBuffers: createPlaneBuffers,\n createPlaneVertices: createPlaneVertices,\n createSphereBufferInfo: createSphereBufferInfo,\n createSphereBuffers: createSphereBuffers,\n createSphereVertices: createSphereVertices,\n createTruncatedConeBufferInfo: createTruncatedConeBufferInfo,\n createTruncatedConeBuffers: createTruncatedConeBuffers,\n createTruncatedConeVertices: createTruncatedConeVertices,\n createXYQuadBufferInfo: createXYQuadBufferInfo,\n createXYQuadBuffers: createXYQuadBuffers,\n createXYQuadVertices: createXYQuadVertices,\n createCresentBufferInfo: createCresentBufferInfo,\n createCresentBuffers: createCresentBuffers,\n createCresentVertices: createCresentVertices,\n createCrescentBufferInfo: createCrescentBufferInfo,\n createCrescentBuffers: createCrescentBuffers,\n createCrescentVertices: createCrescentVertices,\n createCylinderBufferInfo: createCylinderBufferInfo,\n createCylinderBuffers: createCylinderBuffers,\n createCylinderVertices: createCylinderVertices,\n createTorusBufferInfo: createTorusBufferInfo,\n createTorusBuffers: createTorusBuffers,\n createTorusVertices: createTorusVertices,\n createDiscBufferInfo: createDiscBufferInfo,\n createDiscBuffers: createDiscBuffers,\n createDiscVertices: createDiscVertices,\n deindexVertices: deindexVertices,\n flattenNormals: flattenNormals,\n makeRandomVertexColors: makeRandomVertexColors,\n reorientDirections: reorientDirections,\n reorientNormals: reorientNormals,\n reorientPositions: reorientPositions,\n reorientVertices: reorientVertices,\n concatVertices: concatVertices,\n duplicateVertices: duplicateVertices\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Gets the gl version as a number\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {number} version of gl\n * @private\n */\n//function getVersionAsNumber(gl) {\n// return parseFloat(gl.getParameter(gl.VERSION).substr(6));\n//}\n\n/**\n * Check if context is WebGL 2.0\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {bool} true if it's WebGL 2.0\n * @memberOf module:twgl\n */\nfunction isWebGL2(gl) {\n // This is the correct check but it's slow\n // return gl.getParameter(gl.VERSION).indexOf(\"WebGL 2.0\") === 0;\n // This might also be the correct check but I'm assuming it's slow-ish\n // return gl instanceof WebGL2RenderingContext;\n return !!gl.texStorage2D;\n}\n\n/**\n * Check if context is WebGL 1.0\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {bool} true if it's WebGL 1.0\n * @memberOf module:twgl\n */\nfunction isWebGL1(gl) {\n // This is the correct check but it's slow\n // const version = getVersionAsNumber(gl);\n // return version <= 1.0 && version > 0.0; // because as of 2016/5 Edge returns 0.96\n // This might also be the correct check but I'm assuming it's slow-ish\n // return gl instanceof WebGLRenderingContext;\n return !gl.texStorage2D;\n}\n\n/**\n * Gets a string for WebGL enum\n *\n * Note: Several enums are the same. Without more\n * context (which function) it's impossible to always\n * give the correct enum. As it is, for matching values\n * it gives all enums. Checking the WebGL2RenderingContext\n * that means\n *\n * 0 = ZERO | POINT | NONE | NO_ERROR\n * 1 = ONE | LINES | SYNC_FLUSH_COMMANDS_BIT\n * 32777 = BLEND_EQUATION_RGB | BLEND_EQUATION_RGB\n * 36662 = COPY_READ_BUFFER | COPY_READ_BUFFER_BINDING\n * 36663 = COPY_WRITE_BUFFER | COPY_WRITE_BUFFER_BINDING\n * 36006 = FRAMEBUFFER_BINDING | DRAW_FRAMEBUFFER_BINDING\n *\n * It's also not useful for bits really unless you pass in individual bits.\n * In other words\n *\n * const bits = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;\n * twgl.glEnumToString(gl, bits); // not going to work\n *\n * Note that some enums only exist on extensions. If you\n * want them to show up you need to pass the extension at least\n * once. For example\n *\n * const ext = gl.getExtension('WEBGL_compressed_texture_s3tc');\n * if (ext) {\n * twgl.glEnumToString(ext, 0); // just prime the function\n *\n * ..later..\n *\n * const internalFormat = ext.COMPRESSED_RGB_S3TC_DXT1_EXT;\n * console.log(twgl.glEnumToString(gl, internalFormat));\n *\n * Notice I didn't have to pass the extension the second time. This means\n * you can have place that generically gets an enum for texture formats for example.\n * and as long as you primed the function with the extensions\n *\n * If you're using `twgl.addExtensionsToContext` to enable your extensions\n * then twgl will automatically get the extension's enums.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext or any extension object\n * @param {number} value the value of the enum you want to look up.\n * @return {string} enum string or hex value\n * @memberOf module:twgl\n * @function glEnumToString\n */\nconst glEnumToString = (function() {\n const haveEnumsForType = {};\n const enums = {};\n\n function addEnums(gl) {\n const type = gl.constructor.name;\n if (!haveEnumsForType[type]) {\n for (const key in gl) {\n if (typeof gl[key] === 'number') {\n const existing = enums[gl[key]];\n enums[gl[key]] = existing ? `${existing} | ${key}` : key;\n }\n }\n haveEnumsForType[type] = true;\n }\n }\n\n return function glEnumToString(gl, value) {\n addEnums(gl);\n return enums[value] || (typeof value === 'number' ? `0x${value.toString(16)}` : value);\n };\n}());\n\nvar utils = /*#__PURE__*/Object.freeze({\n __proto__: null,\n glEnumToString: glEnumToString,\n isWebGL1: isWebGL1,\n isWebGL2: isWebGL2\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nconst defaults$1 = {\n textureColor: new Uint8Array([128, 192, 255, 255]),\n textureOptions: {},\n crossOrigin: undefined,\n};\nconst isArrayBuffer = isArrayBuffer$1;\n\n// Should we make this on demand?\nconst getShared2DContext = function() {\n let s_ctx;\n return function getShared2DContext() {\n s_ctx = s_ctx ||\n ((typeof document !== 'undefined' && document.createElement)\n ? document.createElement(\"canvas\").getContext(\"2d\")\n : null);\n return s_ctx;\n };\n}();\n\n// NOTE: Chrome supports 2D canvas in a Worker (behind flag as of v64 but\n// not only does Firefox NOT support it but Firefox freezes immediately\n// if you try to create one instead of just returning null and continuing.\n// : (global.OffscreenCanvas && (new global.OffscreenCanvas(1, 1)).getContext(\"2d\")); // OffscreenCanvas may not support 2d\n\n// NOTE: We can maybe remove some of the need for the 2d canvas. In WebGL2\n// we can use the various unpack settings. Otherwise we could try using\n// the ability of an ImageBitmap to be cut. Unfortunately cutting an ImageBitmap\n// is async and the current TWGL code expects a non-Async result though that\n// might not be a problem. ImageBitmap though is not available in Edge or Safari\n// as of 2018-01-02\n\n/* PixelFormat */\nconst ALPHA = 0x1906;\nconst RGB = 0x1907;\nconst RGBA$1 = 0x1908;\nconst LUMINANCE = 0x1909;\nconst LUMINANCE_ALPHA = 0x190A;\nconst DEPTH_COMPONENT$1 = 0x1902;\nconst DEPTH_STENCIL$1 = 0x84F9;\n\n/* TextureWrapMode */\n// const REPEAT = 0x2901;\n// const MIRRORED_REPEAT = 0x8370;\nconst CLAMP_TO_EDGE$1 = 0x812f;\n\n/* TextureMagFilter */\nconst NEAREST = 0x2600;\nconst LINEAR$1 = 0x2601;\n\n/* TextureMinFilter */\n// const NEAREST_MIPMAP_NEAREST = 0x2700;\n// const LINEAR_MIPMAP_NEAREST = 0x2701;\n// const NEAREST_MIPMAP_LINEAR = 0x2702;\n// const LINEAR_MIPMAP_LINEAR = 0x2703;\n\n/* Texture Target */\nconst TEXTURE_2D$2 = 0x0de1;\nconst TEXTURE_CUBE_MAP$1 = 0x8513;\nconst TEXTURE_3D$1 = 0x806f;\nconst TEXTURE_2D_ARRAY$1 = 0x8c1a;\n\n/* Cubemap Targets */\nconst TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;\nconst TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;\nconst TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;\nconst TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;\nconst TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;\nconst TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a;\n\n/* Texture Parameters */\nconst TEXTURE_MIN_FILTER = 0x2801;\nconst TEXTURE_MAG_FILTER = 0x2800;\nconst TEXTURE_WRAP_S = 0x2802;\nconst TEXTURE_WRAP_T = 0x2803;\nconst TEXTURE_WRAP_R = 0x8072;\nconst TEXTURE_MIN_LOD = 0x813a;\nconst TEXTURE_MAX_LOD = 0x813b;\nconst TEXTURE_BASE_LEVEL = 0x813c;\nconst TEXTURE_MAX_LEVEL = 0x813d;\nconst TEXTURE_COMPARE_MODE = 0x884C;\nconst TEXTURE_COMPARE_FUNC = 0x884D;\n\n/* Pixel store */\nconst UNPACK_ALIGNMENT = 0x0cf5;\nconst UNPACK_ROW_LENGTH = 0x0cf2;\nconst UNPACK_IMAGE_HEIGHT = 0x806e;\nconst UNPACK_SKIP_PIXELS = 0x0cf4;\nconst UNPACK_SKIP_ROWS = 0x0cf3;\nconst UNPACK_SKIP_IMAGES = 0x806d;\nconst UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;\nconst UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;\nconst UNPACK_FLIP_Y_WEBGL = 0x9240;\n\nconst R8 = 0x8229;\nconst R8_SNORM = 0x8F94;\nconst R16F = 0x822D;\nconst R32F = 0x822E;\nconst R8UI = 0x8232;\nconst R8I = 0x8231;\nconst RG16UI = 0x823A;\nconst RG16I = 0x8239;\nconst RG32UI = 0x823C;\nconst RG32I = 0x823B;\nconst RG8 = 0x822B;\nconst RG8_SNORM = 0x8F95;\nconst RG16F = 0x822F;\nconst RG32F = 0x8230;\nconst RG8UI = 0x8238;\nconst RG8I = 0x8237;\nconst R16UI = 0x8234;\nconst R16I = 0x8233;\nconst R32UI = 0x8236;\nconst R32I = 0x8235;\nconst RGB8 = 0x8051;\nconst SRGB8 = 0x8C41;\nconst RGB565$1 = 0x8D62;\nconst RGB8_SNORM = 0x8F96;\nconst R11F_G11F_B10F = 0x8C3A;\nconst RGB9_E5 = 0x8C3D;\nconst RGB16F = 0x881B;\nconst RGB32F = 0x8815;\nconst RGB8UI = 0x8D7D;\nconst RGB8I = 0x8D8F;\nconst RGB16UI = 0x8D77;\nconst RGB16I = 0x8D89;\nconst RGB32UI = 0x8D71;\nconst RGB32I = 0x8D83;\nconst RGBA8 = 0x8058;\nconst SRGB8_ALPHA8 = 0x8C43;\nconst RGBA8_SNORM = 0x8F97;\nconst RGB5_A1$1 = 0x8057;\nconst RGBA4$1 = 0x8056;\nconst RGB10_A2 = 0x8059;\nconst RGBA16F = 0x881A;\nconst RGBA32F = 0x8814;\nconst RGBA8UI = 0x8D7C;\nconst RGBA8I = 0x8D8E;\nconst RGB10_A2UI = 0x906F;\nconst RGBA16UI = 0x8D76;\nconst RGBA16I = 0x8D88;\nconst RGBA32I = 0x8D82;\nconst RGBA32UI = 0x8D70;\n\nconst DEPTH_COMPONENT16$1 = 0x81A5;\nconst DEPTH_COMPONENT24$1 = 0x81A6;\nconst DEPTH_COMPONENT32F$1 = 0x8CAC;\nconst DEPTH32F_STENCIL8$1 = 0x8CAD;\nconst DEPTH24_STENCIL8$1 = 0x88F0;\n\n/* DataType */\nconst BYTE = 0x1400;\nconst UNSIGNED_BYTE$1 = 0x1401;\nconst SHORT = 0x1402;\nconst UNSIGNED_SHORT$1 = 0x1403;\nconst INT$1 = 0x1404;\nconst UNSIGNED_INT$1 = 0x1405;\nconst FLOAT$1 = 0x1406;\nconst UNSIGNED_SHORT_4_4_4_4 = 0x8033;\nconst UNSIGNED_SHORT_5_5_5_1 = 0x8034;\nconst UNSIGNED_SHORT_5_6_5 = 0x8363;\nconst HALF_FLOAT = 0x140B;\nconst HALF_FLOAT_OES = 0x8D61; // Thanks Khronos for making this different >:(\nconst UNSIGNED_INT_2_10_10_10_REV = 0x8368;\nconst UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;\nconst UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;\nconst FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;\nconst UNSIGNED_INT_24_8 = 0x84FA;\n\nconst RG = 0x8227;\nconst RG_INTEGER = 0x8228;\nconst RED = 0x1903;\nconst RED_INTEGER = 0x8D94;\nconst RGB_INTEGER = 0x8D98;\nconst RGBA_INTEGER = 0x8D99;\n\nconst formatInfo = {};\n{\n // NOTE: this is named `numColorComponents` vs `numComponents` so we can let Uglify mangle\n // the name.\n const f = formatInfo;\n f[ALPHA] = { numColorComponents: 1, };\n f[LUMINANCE] = { numColorComponents: 1, };\n f[LUMINANCE_ALPHA] = { numColorComponents: 2, };\n f[RGB] = { numColorComponents: 3, };\n f[RGBA$1] = { numColorComponents: 4, };\n f[RED] = { numColorComponents: 1, };\n f[RED_INTEGER] = { numColorComponents: 1, };\n f[RG] = { numColorComponents: 2, };\n f[RG_INTEGER] = { numColorComponents: 2, };\n f[RGB] = { numColorComponents: 3, };\n f[RGB_INTEGER] = { numColorComponents: 3, };\n f[RGBA$1] = { numColorComponents: 4, };\n f[RGBA_INTEGER] = { numColorComponents: 4, };\n f[DEPTH_COMPONENT$1] = { numColorComponents: 1, };\n f[DEPTH_STENCIL$1] = { numColorComponents: 2, };\n}\n\n/**\n * @typedef {Object} TextureFormatDetails\n * @property {number} textureFormat format to pass texImage2D and similar functions.\n * @property {boolean} colorRenderable true if you can render to this format of texture.\n * @property {boolean} textureFilterable true if you can filter the texture, false if you can ony use `NEAREST`.\n * @property {number[]} type Array of possible types you can pass to texImage2D and similar function\n * @property {Object.} bytesPerElementMap A map of types to bytes per element\n * @private\n */\n\nlet s_textureInternalFormatInfo;\nfunction getTextureInternalFormatInfo(internalFormat) {\n if (!s_textureInternalFormatInfo) {\n // NOTE: these properties need unique names so we can let Uglify mangle the name.\n const t = {};\n // unsized formats\n t[ALPHA] = { textureFormat: ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 2, 4], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[LUMINANCE] = { textureFormat: LUMINANCE, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 2, 4], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[LUMINANCE_ALPHA] = { textureFormat: LUMINANCE_ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [2, 4, 4, 8], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[RGB] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 6, 6, 12, 2], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1, UNSIGNED_SHORT_5_6_5], };\n t[RGBA$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 8, 8, 16, 2, 2], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1], };\n t[DEPTH_COMPONENT$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_INT$1, UNSIGNED_SHORT$1], };\n\n // sized formats\n t[R8] = { textureFormat: RED, colorRenderable: true, textureFilterable: true, bytesPerElement: [1], type: [UNSIGNED_BYTE$1], };\n t[R8_SNORM] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [1], type: [BYTE], };\n t[R16F] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [4, 2], type: [FLOAT$1, HALF_FLOAT], };\n t[R32F] = { textureFormat: RED, colorRenderable: false, textureFilterable: false, bytesPerElement: [4], type: [FLOAT$1], };\n t[R8UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [1], type: [UNSIGNED_BYTE$1], };\n t[R8I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [1], type: [BYTE], };\n t[R16UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [UNSIGNED_SHORT$1], };\n t[R16I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [SHORT], };\n t[R32UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT$1], };\n t[R32I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [INT$1], };\n t[RG8] = { textureFormat: RG, colorRenderable: true, textureFilterable: true, bytesPerElement: [2], type: [UNSIGNED_BYTE$1], };\n t[RG8_SNORM] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [2], type: [BYTE], };\n t[RG16F] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [8, 4], type: [FLOAT$1, HALF_FLOAT], };\n t[RG32F] = { textureFormat: RG, colorRenderable: false, textureFilterable: false, bytesPerElement: [8], type: [FLOAT$1], };\n t[RG8UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [UNSIGNED_BYTE$1], };\n t[RG8I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [BYTE], };\n t[RG16UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_SHORT$1], };\n t[RG16I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [SHORT], };\n t[RG32UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [UNSIGNED_INT$1], };\n t[RG32I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [INT$1], };\n t[RGB8] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[SRGB8] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[RGB565$1] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 2], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_5_6_5], };\n t[RGB8_SNORM] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [3], type: [BYTE], };\n t[R11F_G11F_B10F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT$1, HALF_FLOAT, UNSIGNED_INT_10F_11F_11F_REV], };\n t[RGB9_E5] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT$1, HALF_FLOAT, UNSIGNED_INT_5_9_9_9_REV], };\n t[RGB16F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6], type: [FLOAT$1, HALF_FLOAT], };\n t[RGB32F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [FLOAT$1], };\n t[RGB8UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[RGB8I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [3], type: [BYTE], };\n t[RGB16UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [6], type: [UNSIGNED_SHORT$1], };\n t[RGB16I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [6], type: [SHORT], };\n t[RGB32UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [UNSIGNED_INT$1], };\n t[RGB32I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [INT$1], };\n t[RGBA8] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[SRGB8_ALPHA8] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[RGBA8_SNORM] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: true, bytesPerElement: [4], type: [BYTE], };\n t[RGB5_A1$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2, 4], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA4$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_4_4_4_4], };\n t[RGB10_A2] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA16F] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: true, bytesPerElement: [16, 8], type: [FLOAT$1, HALF_FLOAT], };\n t[RGBA32F] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: false, bytesPerElement: [16], type: [FLOAT$1], };\n t[RGBA8UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[RGBA8I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [BYTE], };\n t[RGB10_A2UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA16UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [UNSIGNED_SHORT$1], };\n t[RGBA16I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [SHORT], };\n t[RGBA32I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [16], type: [INT$1], };\n t[RGBA32UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [16], type: [UNSIGNED_INT$1], };\n // Sized Internal\n t[DEPTH_COMPONENT16$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_SHORT$1, UNSIGNED_INT$1], };\n t[DEPTH_COMPONENT24$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT$1], };\n t[DEPTH_COMPONENT32F$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [FLOAT$1], };\n t[DEPTH24_STENCIL8$1] = { textureFormat: DEPTH_STENCIL$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT_24_8], };\n t[DEPTH32F_STENCIL8$1] = { textureFormat: DEPTH_STENCIL$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [FLOAT_32_UNSIGNED_INT_24_8_REV], };\n\n Object.keys(t).forEach(function(internalFormat) {\n const info = t[internalFormat];\n info.bytesPerElementMap = {};\n info.bytesPerElement.forEach(function(bytesPerElement, ndx) {\n const type = info.type[ndx];\n info.bytesPerElementMap[type] = bytesPerElement;\n });\n });\n s_textureInternalFormatInfo = t;\n }\n return s_textureInternalFormatInfo[internalFormat];\n}\n\n/**\n * Gets the number of bytes per element for a given internalFormat / type\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @param {number} type The type parameter for texImage2D etc..\n * @return {number} the number of bytes per element for the given internalFormat, type combo\n * @memberOf module:twgl/textures\n */\nfunction getBytesPerElementForInternalFormat(internalFormat, type) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n const bytesPerElement = info.bytesPerElementMap[type];\n if (bytesPerElement === undefined) {\n throw \"unknown internal format\";\n }\n return bytesPerElement;\n}\n\n/**\n * Info related to a specific texture internalFormat as returned\n * from {@link module:twgl/textures.getFormatAndTypeForInternalFormat}.\n *\n * @typedef {Object} TextureFormatInfo\n * @property {number} format Format to pass to texImage2D and related functions\n * @property {number} type Type to pass to texImage2D and related functions\n * @memberOf module:twgl/textures\n */\n\n/**\n * Gets the format and type for a given internalFormat\n *\n * @param {number} internalFormat The internal format\n * @return {module:twgl/textures.TextureFormatInfo} the corresponding format and type,\n * @memberOf module:twgl/textures\n */\nfunction getFormatAndTypeForInternalFormat(internalFormat) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return {\n format: info.textureFormat,\n type: info.type[0],\n };\n}\n\n/**\n * Returns true if value is power of 2\n * @param {number} value number to check.\n * @return true if value is power of 2\n * @private\n */\nfunction isPowerOf2(value) {\n return (value & (value - 1)) === 0;\n}\n\n/**\n * Gets whether or not we can generate mips for the given\n * internal format.\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {number} width The width parameter from texImage2D etc..\n * @param {number} height The height parameter from texImage2D etc..\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @return {boolean} true if we can generate mips\n * @memberOf module:twgl/textures\n */\nfunction canGenerateMipmap(gl, width, height, internalFormat) {\n if (!isWebGL2(gl)) {\n return isPowerOf2(width) && isPowerOf2(height);\n }\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return info.colorRenderable && info.textureFilterable;\n}\n\n/**\n * Gets whether or not we can generate mips for the given format\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @return {boolean} true if we can generate mips\n * @memberOf module:twgl/textures\n */\nfunction canFilter(internalFormat) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return info.textureFilterable;\n}\n\n/**\n * Gets the number of components for a given image format.\n * @param {number} format the format.\n * @return {number} the number of components for the format.\n * @memberOf module:twgl/textures\n */\nfunction getNumComponentsForFormat(format) {\n const info = formatInfo[format];\n if (!info) {\n throw \"unknown format: \" + format;\n }\n return info.numColorComponents;\n}\n\n/**\n * Gets the texture type for a given array type.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @return {number} the gl texture type\n * @private\n */\nfunction getTextureTypeForArrayType(gl, src, defaultType) {\n if (isArrayBuffer(src)) {\n return getGLTypeForTypedArray(src);\n }\n return defaultType || UNSIGNED_BYTE$1;\n}\n\nfunction guessDimensions(gl, target, width, height, numElements) {\n if (numElements % 1 !== 0) {\n throw \"can't guess dimensions\";\n }\n if (!width && !height) {\n const size = Math.sqrt(numElements / (target === TEXTURE_CUBE_MAP$1 ? 6 : 1));\n if (size % 1 === 0) {\n width = size;\n height = size;\n } else {\n width = numElements;\n height = 1;\n }\n } else if (!height) {\n height = numElements / width;\n if (height % 1) {\n throw \"can't guess dimensions\";\n }\n } else if (!width) {\n width = numElements / height;\n if (width % 1) {\n throw \"can't guess dimensions\";\n }\n }\n return {\n width: width,\n height: height,\n };\n}\n\n/**\n * Sets the default texture color.\n *\n * The default texture color is used when loading textures from\n * urls. Because the URL will be loaded async we'd like to be\n * able to use the texture immediately. By putting a 1x1 pixel\n * color in the texture we can start using the texture before\n * the URL has loaded.\n *\n * @param {number[]} color Array of 4 values in the range 0 to 1\n * @deprecated see {@link module:twgl.setDefaults}\n * @memberOf module:twgl/textures\n */\nfunction setDefaultTextureColor(color) {\n defaults$1.textureColor = new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);\n}\n\nfunction setDefaults$1(newDefaults) {\n copyExistingProperties(newDefaults, defaults$1);\n if (newDefaults.textureColor) {\n setDefaultTextureColor(newDefaults.textureColor);\n }\n}\n\n/**\n * A function to generate the source for a texture.\n * @callback TextureFunc\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options the texture options\n * @return {*} Returns any of the things documented for `src` for {@link module:twgl.TextureOptions}.\n * @memberOf module:twgl\n */\n\n/**\n * Texture options passed to most texture functions. Each function will use whatever options\n * are appropriate for its needs. This lets you pass the same options to all functions.\n *\n * Note: A `TexImageSource` is defined in the WebGL spec as a `HTMLImageElement`, `HTMLVideoElement`,\n * `HTMLCanvasElement`, `ImageBitmap`, or `ImageData`.\n *\n * @typedef {Object} TextureOptions\n * @property {number} [target] the type of texture `gl.TEXTURE_2D` or `gl.TEXTURE_CUBE_MAP`. Defaults to `gl.TEXTURE_2D`.\n * @property {number} [level] the mip level to affect. Defaults to 0. Note, if set auto will be considered false unless explicitly set to true.\n * @property {number} [width] the width of the texture. Only used if src is an array or typed array or null.\n * @property {number} [height] the height of a texture. Only used if src is an array or typed array or null.\n * @property {number} [depth] the depth of a texture. Only used if src is an array or type array or null and target is `TEXTURE_3D` .\n * @property {number} [min] the min filter setting (eg. `gl.LINEAR`). Defaults to `gl.NEAREST_MIPMAP_LINEAR`\n * or if texture is not a power of 2 on both dimensions then defaults to `gl.LINEAR`.\n * @property {number} [mag] the mag filter setting (eg. `gl.LINEAR`). Defaults to `gl.LINEAR`\n * @property {number} [minMag] both the min and mag filter settings.\n * @property {number} [internalFormat] internal format for texture. Defaults to `gl.RGBA`\n * @property {number} [format] format for texture. Defaults to `gl.RGBA`.\n * @property {number} [type] type for texture. Defaults to `gl.UNSIGNED_BYTE` unless `src` is ArrayBufferView. If `src`\n * is ArrayBufferView defaults to type that matches ArrayBufferView type.\n * @property {number} [wrap] Texture wrapping for both S and T (and R if TEXTURE_3D or WebGLSampler). Defaults to `gl.REPEAT` for 2D unless src is WebGL1 and src not npot and `gl.CLAMP_TO_EDGE` for cube\n * @property {number} [wrapS] Texture wrapping for S. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [wrapT] Texture wrapping for T. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [wrapR] Texture wrapping for R. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [minLod] TEXTURE_MIN_LOD setting\n * @property {number} [maxLod] TEXTURE_MAX_LOD setting\n * @property {number} [baseLevel] TEXTURE_BASE_LEVEL setting\n * @property {number} [maxLevel] TEXTURE_MAX_LEVEL setting\n * @property {number} [compareFunc] TEXTURE_COMPARE_FUNC setting\n * @property {number} [compareMode] TEXTURE_COMPARE_MODE setting\n * @property {number} [unpackAlignment] The `gl.UNPACK_ALIGNMENT` used when uploading an array. Defaults to 1.\n * @property {number[]|ArrayBufferView} [color] Color to initialize this texture with if loading an image asynchronously.\n * The default use a blue 1x1 pixel texture. You can set another default by calling `twgl.setDefaults`\n * or you can set an individual texture's initial color by setting this property. Example: `[1, .5, .5, 1]` = pink\n * @property {number} [premultiplyAlpha] Whether or not to premultiply alpha. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {number} [flipY] Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {number} [colorspaceConversion] Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {boolean} [auto] If `undefined` or `true`, in WebGL1, texture filtering is set automatically for non-power of 2 images and\n * mips are generated for power of 2 images. In WebGL2 mips are generated if they can be. Note: if `level` is set above\n * then then `auto` is assumed to be `false` unless explicity set to `true`.\n * @property {number[]} [cubeFaceOrder] The order that cube faces are pulled out of an img or set of images. The default is\n *\n * [gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n * gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n * gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]\n *\n * @property {(number[]|ArrayBufferView|TexImageSource|TexImageSource[]|string|string[]|module:twgl.TextureFunc)} [src] source for texture\n *\n * If `string` then it's assumed to be a URL to an image. The image will be downloaded async. A usable\n * 1x1 pixel texture will be returned immediately. The texture will be updated once the image has downloaded.\n * If `target` is `gl.TEXTURE_CUBE_MAP` will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3.\n * The pieces will be uploaded in `cubeFaceOrder`\n *\n * If `string[]` or `TexImageSource[]` and target is `gl.TEXTURE_CUBE_MAP` then it must have 6 entries, one for each face of a cube map.\n *\n * If `string[]` or `TexImageSource[]` and target is `gl.TEXTURE_2D_ARRAY` then each entry is a slice of the a 2d array texture\n * and will be scaled to the specified width and height OR to the size of the first image that loads.\n *\n * If `TexImageSource` then it wil be used immediately to create the contents of the texture. Examples `HTMLImageElement`,\n * `HTMLCanvasElement`, `HTMLVideoElement`.\n *\n * If `number[]` or `ArrayBufferView` it's assumed to be data for a texture. If `width` or `height` is\n * not specified it is guessed as follows. First the number of elements is computed by `src.length / numComponents`\n * where `numComponents` is derived from `format`. If `target` is `gl.TEXTURE_CUBE_MAP` then `numElements` is divided\n * by 6. Then\n *\n * * If neither `width` nor `height` are specified and `sqrt(numElements)` is an integer then width and height\n * are set to `sqrt(numElements)`. Otherwise `width = numElements` and `height = 1`.\n *\n * * If only one of `width` or `height` is specified then the other equals `numElements / specifiedDimension`.\n *\n * If `number[]` will be converted to `type`.\n *\n * If `src` is a function it will be called with a `WebGLRenderingContext` and these options.\n * Whatever it returns is subject to these rules. So it can return a string url, an `HTMLElement`\n * an array etc...\n *\n * If `src` is undefined then an empty texture will be created of size `width` by `height`.\n *\n * @property {string} [crossOrigin] What to set the crossOrigin property of images when they are downloaded.\n * default: undefined. Also see {@link module:twgl.setDefaults}.\n *\n * @memberOf module:twgl\n */\n\n/**\n * Sets any packing state that will be set based on the options.\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @private\n */\nfunction setPackState(gl, options) {\n if (options.colorspaceConversion !== undefined) {\n gl.pixelStorei(UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion);\n }\n if (options.premultiplyAlpha !== undefined) {\n gl.pixelStorei(UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha);\n }\n if (options.flipY !== undefined) {\n gl.pixelStorei(UNPACK_FLIP_Y_WEBGL, options.flipY);\n }\n}\n\n/**\n * Set skip state to defaults\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @private\n */\nfunction setSkipStateToDefault(gl) {\n gl.pixelStorei(UNPACK_ALIGNMENT, 4);\n if (isWebGL2(gl)) {\n gl.pixelStorei(UNPACK_ROW_LENGTH, 0);\n gl.pixelStorei(UNPACK_IMAGE_HEIGHT, 0);\n gl.pixelStorei(UNPACK_SKIP_PIXELS, 0);\n gl.pixelStorei(UNPACK_SKIP_ROWS, 0);\n gl.pixelStorei(UNPACK_SKIP_IMAGES, 0);\n }\n}\n\n/**\n * Sets the parameters of a texture or sampler\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {number|WebGLSampler} target texture target or sampler\n * @param {function()} parameteriFn texParameteri or samplerParameteri fn\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @private\n */\nfunction setTextureSamplerParameters(gl, target, parameteriFn, options) {\n if (options.minMag) {\n parameteriFn.call(gl, target, TEXTURE_MIN_FILTER, options.minMag);\n parameteriFn.call(gl, target, TEXTURE_MAG_FILTER, options.minMag);\n }\n if (options.min) {\n parameteriFn.call(gl, target, TEXTURE_MIN_FILTER, options.min);\n }\n if (options.mag) {\n parameteriFn.call(gl, target, TEXTURE_MAG_FILTER, options.mag);\n }\n if (options.wrap) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_S, options.wrap);\n parameteriFn.call(gl, target, TEXTURE_WRAP_T, options.wrap);\n if (target === TEXTURE_3D$1 || isSampler(gl, target)) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_R, options.wrap);\n }\n }\n if (options.wrapR) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_R, options.wrapR);\n }\n if (options.wrapS) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_S, options.wrapS);\n }\n if (options.wrapT) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_T, options.wrapT);\n }\n if (options.minLod !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MIN_LOD, options.minLod);\n }\n if (options.maxLod !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MAX_LOD, options.maxLod);\n }\n if (options.baseLevel !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_BASE_LEVEL, options.baseLevel);\n }\n if (options.maxLevel !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MAX_LEVEL, options.maxLevel);\n }\n if (options.compareFunc !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_COMPARE_FUNC, options.compareFunc);\n }\n if (options.compareMode !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_COMPARE_MODE, options.compareMode);\n }\n}\n\n/**\n * Sets the texture parameters of a texture.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n */\nfunction setTextureParameters(gl, tex, options) {\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n setTextureSamplerParameters(gl, target, gl.texParameteri, options);\n}\n\n/**\n * Sets the sampler parameters of a sampler.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLSampler} sampler the WebGLSampler to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @memberOf module:twgl/textures\n */\nfunction setSamplerParameters(gl, sampler, options) {\n setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options);\n}\n\n/**\n * Creates a new sampler object and sets parameters.\n *\n * Example:\n *\n * const sampler = twgl.createSampler(gl, {\n * minMag: gl.NEAREST, // sets both TEXTURE_MIN_FILTER and TEXTURE_MAG_FILTER\n * wrap: gl.CLAMP_TO_NEAREST, // sets both TEXTURE_WRAP_S and TEXTURE_WRAP_T and TEXTURE_WRAP_R\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} options A object of TextureOptions one per sampler.\n * @return {Object.} the created samplers by name\n * @private\n */\nfunction createSampler(gl, options) {\n const sampler = gl.createSampler();\n setSamplerParameters(gl, sampler, options);\n return sampler;\n}\n\n/**\n * Creates a multiple sampler objects and sets parameters on each.\n *\n * Example:\n *\n * const samplers = twgl.createSamplers(gl, {\n * nearest: {\n * minMag: gl.NEAREST,\n * },\n * nearestClampS: {\n * minMag: gl.NEAREST,\n * wrapS: gl.CLAMP_TO_NEAREST,\n * },\n * linear: {\n * minMag: gl.LINEAR,\n * },\n * nearestClamp: {\n * minMag: gl.NEAREST,\n * wrap: gl.CLAMP_TO_EDGE,\n * },\n * linearClamp: {\n * minMag: gl.LINEAR,\n * wrap: gl.CLAMP_TO_EDGE,\n * },\n * linearClampT: {\n * minMag: gl.LINEAR,\n * wrapT: gl.CLAMP_TO_EDGE,\n * },\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set on the sampler\n * @private\n */\nfunction createSamplers(gl, samplerOptions) {\n const samplers = {};\n Object.keys(samplerOptions).forEach(function(name) {\n samplers[name] = createSampler(gl, samplerOptions[name]);\n });\n return samplers;\n}\n\n/**\n * Makes a 1x1 pixel\n * If no color is passed in uses the default color which can be set by calling `setDefaultTextureColor`.\n * @param {(number[]|ArrayBufferView)} [color] The color using 0-1 values\n * @return {Uint8Array} Unit8Array with color.\n * @private\n */\nfunction make1Pixel(color) {\n color = color || defaults$1.textureColor;\n if (isArrayBuffer(color)) {\n return color;\n }\n return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);\n}\n\n/**\n * Sets filtering or generates mips for texture based on width or height\n * If width or height is not passed in uses `options.width` and//or `options.height`\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @param {number} [width] width of texture\n * @param {number} [height] height of texture\n * @param {number} [internalFormat] The internalFormat parameter from texImage2D etc..\n * @memberOf module:twgl/textures\n */\nfunction setTextureFilteringForSize(gl, tex, options, width, height, internalFormat) {\n options = options || defaults$1.textureOptions;\n internalFormat = internalFormat || RGBA$1;\n const target = options.target || TEXTURE_2D$2;\n width = width || options.width;\n height = height || options.height;\n gl.bindTexture(target, tex);\n if (canGenerateMipmap(gl, width, height, internalFormat)) {\n gl.generateMipmap(target);\n } else {\n const filtering = canFilter(internalFormat) ? LINEAR$1 : NEAREST;\n gl.texParameteri(target, TEXTURE_MIN_FILTER, filtering);\n gl.texParameteri(target, TEXTURE_MAG_FILTER, filtering);\n gl.texParameteri(target, TEXTURE_WRAP_S, CLAMP_TO_EDGE$1);\n gl.texParameteri(target, TEXTURE_WRAP_T, CLAMP_TO_EDGE$1);\n }\n}\n\nfunction shouldAutomaticallySetTextureFilteringForSize(options) {\n return options.auto === true || (options.auto === undefined && options.level === undefined);\n}\n\n/**\n * Gets an array of cubemap face enums\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @return {number[]} cubemap face enums\n * @private\n */\nfunction getCubeFaceOrder(gl, options) {\n options = options || {};\n return options.cubeFaceOrder || [\n TEXTURE_CUBE_MAP_POSITIVE_X,\n TEXTURE_CUBE_MAP_NEGATIVE_X,\n TEXTURE_CUBE_MAP_POSITIVE_Y,\n TEXTURE_CUBE_MAP_NEGATIVE_Y,\n TEXTURE_CUBE_MAP_POSITIVE_Z,\n TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ];\n}\n\n/**\n * @typedef {Object} FaceInfo\n * @property {number} face gl enum for texImage2D\n * @property {number} ndx face index (0 - 5) into source data\n * @ignore\n */\n\n/**\n * Gets an array of FaceInfos\n * There's a bug in some NVidia drivers that will crash the driver if\n * `gl.TEXTURE_CUBE_MAP_POSITIVE_X` is not uploaded first. So, we take\n * the user's desired order from his faces to WebGL and make sure we\n * do the faces in WebGL order\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @return {FaceInfo[]} cubemap face infos. Arguably the `face` property of each element is redundant but\n * it's needed internally to sort the array of `ndx` properties by `face`.\n * @private\n */\nfunction getCubeFacesWithNdx(gl, options) {\n const faces = getCubeFaceOrder(gl, options);\n // work around bug in NVidia drivers. We have to upload the first face first else the driver crashes :(\n const facesWithNdx = faces.map(function(face, ndx) {\n return { face: face, ndx: ndx };\n });\n facesWithNdx.sort(function(a, b) {\n return a.face - b.face;\n });\n return facesWithNdx;\n}\n\n/**\n * Set a texture from the contents of an element. Will also set\n * texture filtering or generate mips based on the dimensions of the element\n * unless `options.auto === false`. If `target === gl.TEXTURE_CUBE_MAP` will\n * attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {HTMLElement} element a canvas, img, or video element.\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n * @kind function\n */\nfunction setTextureFromElement(gl, tex, element, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n const level = options.level || 0;\n let width = element.width;\n let height = element.height;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || formatType.type;\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n if (target === TEXTURE_CUBE_MAP$1) {\n // guess the parts\n const imgWidth = element.width;\n const imgHeight = element.height;\n let size;\n let slices;\n if (imgWidth / 6 === imgHeight) {\n // It's 6x1\n size = imgHeight;\n slices = [0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0];\n } else if (imgHeight / 6 === imgWidth) {\n // It's 1x6\n size = imgWidth;\n slices = [0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];\n } else if (imgWidth / 3 === imgHeight / 2) {\n // It's 3x2\n size = imgWidth / 3;\n slices = [0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1];\n } else if (imgWidth / 2 === imgHeight / 3) {\n // It's 2x3\n size = imgWidth / 2;\n slices = [0, 0, 1, 0, 0, 1, 1, 1, 0, 2, 1, 2];\n } else {\n throw \"can't figure out cube map from element: \" + (element.src ? element.src : element.nodeName);\n }\n const ctx = getShared2DContext();\n if (ctx) {\n ctx.canvas.width = size;\n ctx.canvas.height = size;\n width = size;\n height = size;\n getCubeFacesWithNdx(gl, options).forEach(function(f) {\n const xOffset = slices[f.ndx * 2 + 0] * size;\n const yOffset = slices[f.ndx * 2 + 1] * size;\n ctx.drawImage(element, xOffset, yOffset, size, size, 0, 0, size, size);\n gl.texImage2D(f.face, level, internalFormat, format, type, ctx.canvas);\n });\n // Free up the canvas memory\n ctx.canvas.width = 1;\n ctx.canvas.height = 1;\n } else if (typeof createImageBitmap !== 'undefined') {\n // NOTE: It seems like we should prefer ImageBitmap because unlike canvas it's\n // note lossy? (alpha is not premultiplied? although I'm not sure what\n width = size;\n height = size;\n getCubeFacesWithNdx(gl, options).forEach(function(f) {\n const xOffset = slices[f.ndx * 2 + 0] * size;\n const yOffset = slices[f.ndx * 2 + 1] * size;\n // We can't easily use a default texture color here as it would have to match\n // the type across all faces where as with a 2D one there's only one face\n // so we're replacing everything all at once. It also has to be the correct size.\n // On the other hand we need all faces to be the same size so as one face loads\n // the rest match else the texture will be un-renderable.\n gl.texImage2D(f.face, level, internalFormat, size, size, 0, format, type, null);\n createImageBitmap(element, xOffset, yOffset, size, size, {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n })\n .then(function(imageBitmap) {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n gl.texImage2D(f.face, level, internalFormat, format, type, imageBitmap);\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n });\n });\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n const smallest = Math.min(element.width, element.height);\n const largest = Math.max(element.width, element.height);\n const depth = largest / smallest;\n if (depth % 1 !== 0) {\n throw \"can not compute 3D dimensions of element\";\n }\n const xMult = element.width === largest ? 1 : 0;\n const yMult = element.height === largest ? 1 : 0;\n gl.pixelStorei(UNPACK_ALIGNMENT, 1);\n gl.pixelStorei(UNPACK_ROW_LENGTH, element.width);\n gl.pixelStorei(UNPACK_IMAGE_HEIGHT, 0);\n gl.pixelStorei(UNPACK_SKIP_IMAGES, 0);\n gl.texImage3D(target, level, internalFormat, smallest, smallest, smallest, 0, format, type, null);\n for (let d = 0; d < depth; ++d) {\n const srcX = d * smallest * xMult;\n const srcY = d * smallest * yMult;\n gl.pixelStorei(UNPACK_SKIP_PIXELS, srcX);\n gl.pixelStorei(UNPACK_SKIP_ROWS, srcY);\n gl.texSubImage3D(target, level, 0, 0, d, smallest, smallest, 1, format, type, element);\n }\n setSkipStateToDefault(gl);\n } else {\n gl.texImage2D(target, level, internalFormat, format, type, element);\n }\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n setTextureParameters(gl, tex, options);\n}\n\nfunction noop() {\n}\n\n/**\n * Checks whether the url's origin is the same so that we can set the `crossOrigin`\n * @param {string} url url to image\n * @returns {boolean} true if the window's origin is the same as image's url\n * @private\n */\nfunction urlIsSameOrigin(url) {\n if (typeof document !== 'undefined') {\n // for IE really\n const a = document.createElement('a');\n a.href = url;\n return a.hostname === location.hostname &&\n a.port === location.port &&\n a.protocol === location.protocol;\n } else {\n const localOrigin = (new URL(location.href)).origin;\n const urlOrigin = (new URL(url, location.href)).origin;\n return urlOrigin === localOrigin;\n }\n}\n\nfunction setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin) {\n return crossOrigin === undefined && !urlIsSameOrigin(url)\n ? 'anonymous'\n : crossOrigin;\n}\n\n/**\n * Loads an image\n * @param {string} url url to image\n * @param {string} crossOrigin\n * @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null\n * if there was an error\n * @return {HTMLImageElement} the image being loaded.\n * @private\n */\nfunction loadImage(url, crossOrigin, callback) {\n callback = callback || noop;\n let img;\n crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults$1.crossOrigin;\n crossOrigin = setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin);\n if (typeof Image !== 'undefined') {\n img = new Image();\n if (crossOrigin !== undefined) {\n img.crossOrigin = crossOrigin;\n }\n\n const clearEventHandlers = function clearEventHandlers() {\n img.removeEventListener('error', onError); // eslint-disable-line\n img.removeEventListener('load', onLoad); // eslint-disable-line\n img = null;\n };\n\n const onError = function onError() {\n const msg = \"couldn't load image: \" + url;\n error$1(msg);\n callback(msg, img);\n clearEventHandlers();\n };\n\n const onLoad = function onLoad() {\n callback(null, img);\n clearEventHandlers();\n };\n\n img.addEventListener('error', onError);\n img.addEventListener('load', onLoad);\n img.src = url;\n return img;\n } else if (typeof ImageBitmap !== 'undefined') {\n let err;\n let bm;\n const cb = function cb() {\n callback(err, bm);\n };\n\n const options = {};\n if (crossOrigin) {\n options.mode = 'cors'; // TODO: not sure how to translate image.crossOrigin\n }\n fetch(url, options).then(function(response) {\n if (!response.ok) {\n throw response;\n }\n return response.blob();\n }).then(function(blob) {\n return createImageBitmap(blob, {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n });\n }).then(function(bitmap) {\n // not sure if this works. We don't want\n // to catch the user's error. So, call\n // the callback in a timeout so we're\n // not in this scope inside the promise.\n bm = bitmap;\n setTimeout(cb);\n }).catch(function(e) {\n err = e;\n setTimeout(cb);\n });\n img = null;\n }\n return img;\n}\n\n/**\n * check if object is a TexImageSource\n *\n * @param {Object} obj Object to test\n * @return {boolean} true if object is a TexImageSource\n * @private\n */\nfunction isTexImageSource(obj) {\n return (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap) ||\n (typeof ImageData !== 'undefined' && obj instanceof ImageData) ||\n (typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement);\n}\n\n/**\n * if obj is an TexImageSource then just\n * uses it otherwise if obj is a string\n * then load it first.\n *\n * @param {string|TexImageSource} obj\n * @param {string} crossOrigin\n * @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null\n * if there was an error\n * @private\n */\nfunction loadAndUseImage(obj, crossOrigin, callback) {\n if (isTexImageSource(obj)) {\n setTimeout(function() {\n callback(null, obj);\n });\n return obj;\n }\n\n return loadImage(obj, crossOrigin, callback);\n}\n\n/**\n * Sets a texture to a 1x1 pixel color. If `options.color === false` is nothing happens. If it's not set\n * the default texture color is used which can be set by calling `setDefaultTextureColor`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction setTextureTo1PixelColor(gl, tex, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n if (options.color === false) {\n return;\n }\n // Assume it's a URL\n // Put 1x1 pixels in texture. That makes it renderable immediately regardless of filtering.\n const color = make1Pixel(options.color);\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, RGBA$1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, 0, RGBA$1, 1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n } else {\n gl.texImage2D(target, 0, RGBA$1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n }\n}\n\n/**\n * The src image(s) used to create a texture.\n *\n * When you call {@link module:twgl.createTexture} or {@link module:twgl.createTextures}\n * you can pass in urls for images to load into the textures. If it's a single url\n * then this will be a single HTMLImageElement. If it's an array of urls used for a cubemap\n * this will be a corresponding array of images for the cubemap.\n *\n * @typedef {HTMLImageElement|HTMLImageElement[]} TextureSrc\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback TextureReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} texture the texture.\n * @param {module:twgl.TextureSrc} source image(s) used to as the src for the texture\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when all images have finished downloading and been uploaded into their respective textures\n * @callback TexturesReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {Object.} textures the created textures by name. Same as returned by {@link module:twgl.createTextures}.\n * @param {Object.} sources the image(s) used for the texture by name.\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback CubemapReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} tex the texture.\n * @param {HTMLImageElement[]} imgs the images for each face.\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback ThreeDReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} tex the texture.\n * @param {HTMLImageElement[]} imgs the images for each slice.\n * @memberOf module:twgl\n */\n\n/**\n * Loads a texture from an image from a Url as specified in `options.src`\n * If `options.color !== false` will set the texture to a 1x1 pixel color so that the texture is\n * immediately useable. It will be updated with the contents of the image once the image has finished\n * downloading. Filtering options will be set as appropriate for image unless `options.auto === false`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.TextureReadyCallback} [callback] A function to be called when the image has finished loading. err will\n * be non null if there was an error.\n * @return {HTMLImageElement} the image being downloaded.\n * @memberOf module:twgl/textures\n */\nfunction loadTextureFromUrl(gl, tex, options, callback) {\n callback = callback || noop;\n options = options || defaults$1.textureOptions;\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n const img = loadAndUseImage(options.src, options.crossOrigin, function(err, img) {\n if (err) {\n callback(err, tex, img);\n } else {\n setTextureFromElement(gl, tex, img, options);\n callback(null, tex, img);\n }\n });\n return img;\n}\n\n/**\n * Loads a cubemap from 6 urls or TexImageSources as specified in `options.src`. Will set the cubemap to a 1x1 pixel color\n * so that it is usable immediately unless `option.color === false`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.CubemapReadyCallback} [callback] A function to be called when all the images have finished loading. err will\n * be non null if there was an error.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction loadCubemapFromUrls(gl, tex, options, callback) {\n callback = callback || noop;\n const urls = options.src;\n if (urls.length !== 6) {\n throw \"there must be 6 urls for a cubemap\";\n }\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || UNSIGNED_BYTE$1;\n const target = options.target || TEXTURE_2D$2;\n if (target !== TEXTURE_CUBE_MAP$1) {\n throw \"target must be TEXTURE_CUBE_MAP\";\n }\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n let numToLoad = 6;\n const errors = [];\n const faces = getCubeFaceOrder(gl, options);\n let imgs; // eslint-disable-line\n\n function uploadImg(faceTarget) {\n return function(err, img) {\n --numToLoad;\n if (err) {\n errors.push(err);\n } else {\n if (img.width !== img.height) {\n errors.push(\"cubemap face img is not a square: \" + img.src);\n } else {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n\n // So assuming this is the first image we now have one face that's img sized\n // and 5 faces that are 1x1 pixel so size the other faces\n if (numToLoad === 5) {\n // use the default order\n getCubeFaceOrder().forEach(function(otherTarget) {\n // Should we re-use the same face or a color?\n gl.texImage2D(otherTarget, level, internalFormat, format, type, img);\n });\n } else {\n gl.texImage2D(faceTarget, level, internalFormat, format, type, img);\n }\n\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n gl.generateMipmap(target);\n }\n }\n }\n\n if (numToLoad === 0) {\n callback(errors.length ? errors : undefined, tex, imgs);\n }\n };\n }\n\n imgs = urls.map(function(url, ndx) {\n return loadAndUseImage(url, options.crossOrigin, uploadImg(faces[ndx]));\n });\n}\n\n/**\n * Loads a 2d array or 3d texture from urls OR TexImageSources as specified in `options.src`.\n * Will set the texture to a 1x1 pixel color\n * so that it is usable immediately unless `option.color === false`.\n *\n * If the width and height is not specified the width and height of the first\n * image loaded will be used. Note that since images are loaded async\n * which image downloads first is unknown.\n *\n * If an image is not the same size as the width and height it will be scaled\n * to that width and height.\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.ThreeDReadyCallback} [callback] A function to be called when all the images have finished loading. err will\n * be non null if there was an error.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction loadSlicesFromUrls(gl, tex, options, callback) {\n callback = callback || noop;\n const urls = options.src;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || UNSIGNED_BYTE$1;\n const target = options.target || TEXTURE_2D_ARRAY$1;\n if (target !== TEXTURE_3D$1 && target !== TEXTURE_2D_ARRAY$1) {\n throw \"target must be TEXTURE_3D or TEXTURE_2D_ARRAY\";\n }\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n let numToLoad = urls.length;\n const errors = [];\n let imgs; // eslint-disable-line\n const level = options.level || 0;\n let width = options.width;\n let height = options.height;\n const depth = urls.length;\n let firstImage = true;\n\n function uploadImg(slice) {\n return function(err, img) {\n --numToLoad;\n if (err) {\n errors.push(err);\n } else {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n\n if (firstImage) {\n firstImage = false;\n width = options.width || img.width;\n height = options.height || img.height;\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, null);\n\n // put it in every slice otherwise some slices will be 0,0,0,0\n for (let s = 0; s < depth; ++s) {\n gl.texSubImage3D(target, level, 0, 0, s, width, height, 1, format, type, img);\n }\n } else {\n let src = img;\n let ctx;\n if (img.width !== width || img.height !== height) {\n // Size the image to fix\n ctx = getShared2DContext();\n src = ctx.canvas;\n ctx.canvas.width = width;\n ctx.canvas.height = height;\n ctx.drawImage(img, 0, 0, width, height);\n }\n\n gl.texSubImage3D(target, level, 0, 0, slice, width, height, 1, format, type, src);\n\n // free the canvas memory\n if (ctx && src === ctx.canvas) {\n ctx.canvas.width = 0;\n ctx.canvas.height = 0;\n }\n }\n\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n gl.generateMipmap(target);\n }\n }\n\n if (numToLoad === 0) {\n callback(errors.length ? errors : undefined, tex, imgs);\n }\n };\n }\n\n imgs = urls.map(function(url, ndx) {\n return loadAndUseImage(url, options.crossOrigin, uploadImg(ndx));\n });\n}\n\n/**\n * Sets a texture from an array or typed array. If the width or height is not provided will attempt to\n * guess the size. See {@link module:twgl.TextureOptions}.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {(number[]|ArrayBufferView)} src An array or typed arry with texture data.\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n */\nfunction setTextureFromArray(gl, tex, src, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n let width = options.width;\n let height = options.height;\n let depth = options.depth;\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);\n if (!isArrayBuffer(src)) {\n const Type = getTypedArrayTypeForGLType(type);\n src = new Type(src);\n } else if (src instanceof Uint8ClampedArray) {\n src = new Uint8Array(src.buffer);\n }\n\n const bytesPerElement = getBytesPerElementForInternalFormat(internalFormat, type);\n const numElements = src.byteLength / bytesPerElement; // TODO: check UNPACK_ALIGNMENT?\n if (numElements % 1) {\n throw \"length wrong size for format: \" + glEnumToString(gl, format);\n }\n let dimensions;\n if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n if (!width && !height && !depth) {\n const size = Math.cbrt(numElements);\n if (size % 1 !== 0) {\n throw \"can't guess cube size of array of numElements: \" + numElements;\n }\n width = size;\n height = size;\n depth = size;\n } else if (width && (!height || !depth)) {\n dimensions = guessDimensions(gl, target, height, depth, numElements / width);\n height = dimensions.width;\n depth = dimensions.height;\n } else if (height && (!width || !depth)) {\n dimensions = guessDimensions(gl, target, width, depth, numElements / height);\n width = dimensions.width;\n depth = dimensions.height;\n } else {\n dimensions = guessDimensions(gl, target, width, height, numElements / depth);\n width = dimensions.width;\n height = dimensions.height;\n }\n } else {\n dimensions = guessDimensions(gl, target, width, height, numElements);\n width = dimensions.width;\n height = dimensions.height;\n }\n setSkipStateToDefault(gl);\n gl.pixelStorei(UNPACK_ALIGNMENT, options.unpackAlignment || 1);\n setPackState(gl, options);\n if (target === TEXTURE_CUBE_MAP$1) {\n const elementsPerElement = bytesPerElement / src.BYTES_PER_ELEMENT;\n const faceSize = numElements / 6 * elementsPerElement;\n\n getCubeFacesWithNdx(gl, options).forEach(f => {\n const offset = faceSize * f.ndx;\n const data = src.subarray(offset, offset + faceSize);\n gl.texImage2D(f.face, level, internalFormat, width, height, 0, format, type, data);\n });\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, src);\n } else {\n gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, src);\n }\n return {\n width: width,\n height: height,\n depth: depth,\n type: type,\n };\n}\n\n/**\n * Sets a texture with no contents of a certain size. In other words calls `gl.texImage2D` with `null`.\n * You must set `options.width` and `options.height`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @memberOf module:twgl/textures\n */\nfunction setEmptyTexture(gl, tex, options) {\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || formatType.type;\n setPackState(gl, options);\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, options.width, options.height, 0, format, type, null);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, options.width, options.height, options.depth, 0, format, type, null);\n } else {\n gl.texImage2D(target, level, internalFormat, options.width, options.height, 0, format, type, null);\n }\n}\n\n/**\n * Creates a texture based on the options passed in.\n *\n * Note: may reset UNPACK_ALIGNMENT, UNPACK_ROW_LENGTH, UNPACK_IMAGE_HEIGHT, UNPACK_SKIP_IMAGES\n * UNPACK_SKIP_PIXELS, and UNPACK_SKIP_ROWS\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.TextureReadyCallback} [callback] A callback called when an image has been downloaded and uploaded to the texture.\n * @return {WebGLTexture} the created texture.\n * @memberOf module:twgl/textures\n */\nfunction createTexture(gl, options, callback) {\n callback = callback || noop;\n options = options || defaults$1.textureOptions;\n const tex = gl.createTexture();\n const target = options.target || TEXTURE_2D$2;\n let width = options.width || 1;\n let height = options.height || 1;\n const internalFormat = options.internalFormat || RGBA$1;\n gl.bindTexture(target, tex);\n if (target === TEXTURE_CUBE_MAP$1) {\n // this should have been the default for cubemaps :(\n gl.texParameteri(target, TEXTURE_WRAP_S, CLAMP_TO_EDGE$1);\n gl.texParameteri(target, TEXTURE_WRAP_T, CLAMP_TO_EDGE$1);\n }\n let src = options.src;\n if (src) {\n if (typeof src === \"function\") {\n src = src(gl, options);\n }\n if (typeof (src) === \"string\") {\n loadTextureFromUrl(gl, tex, options, callback);\n } else if (isArrayBuffer(src) ||\n (Array.isArray(src) && (\n typeof src[0] === 'number' ||\n Array.isArray(src[0]) ||\n isArrayBuffer(src[0]))\n )\n ) {\n const dimensions = setTextureFromArray(gl, tex, src, options);\n width = dimensions.width;\n height = dimensions.height;\n } else if (Array.isArray(src) && (typeof (src[0]) === 'string' || isTexImageSource(src[0]))) {\n if (target === TEXTURE_CUBE_MAP$1) {\n loadCubemapFromUrls(gl, tex, options, callback);\n } else {\n loadSlicesFromUrls(gl, tex, options, callback);\n }\n } else { // if (isTexImageSource(src))\n setTextureFromElement(gl, tex, src, options);\n width = src.width;\n height = src.height;\n }\n } else {\n setEmptyTexture(gl, tex, options);\n }\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n setTextureParameters(gl, tex, options);\n return tex;\n}\n\n/**\n * Resizes a texture based on the options passed in.\n *\n * Note: This is not a generic resize anything function.\n * It's mostly used by {@link module:twgl.resizeFramebufferInfo}\n * It will use `options.src` if it exists to try to determine a `type`\n * otherwise it will assume `gl.UNSIGNED_BYTE`. No data is provided\n * for the texture. Texture parameters will be set accordingly\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the texture to resize\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {number} [width] the new width. If not passed in will use `options.width`\n * @param {number} [height] the new height. If not passed in will use `options.height`\n * @param {number} [depth] the new depth. If not passed in will use `options.depth`\n * @memberOf module:twgl/textures\n */\nfunction resizeTexture(gl, tex, options, width, height, depth) {\n width = width || options.width;\n height = height || options.height;\n depth = depth || options.depth;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n let type;\n const src = options.src;\n if (!src) {\n type = options.type || formatType.type;\n } else if (isArrayBuffer(src) || (Array.isArray(src) && typeof (src[0]) === 'number')) {\n type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);\n } else {\n type = options.type || formatType.type;\n }\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, width, height, 0, format, type, null);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, null);\n } else {\n gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null);\n }\n}\n\n/**\n * Check if a src is an async request.\n * if src is a string we're going to download an image\n * if src is an array of strings we're going to download cubemap images\n * @param {*} src The src from a TextureOptions\n * @returns {bool} true if src is async.\n * @private\n */\nfunction isAsyncSrc(src) {\n return typeof src === 'string' ||\n (Array.isArray(src) && typeof src[0] === 'string');\n}\n\n/**\n * Creates a bunch of textures based on the passed in options.\n *\n * Example:\n *\n * const textures = twgl.createTextures(gl, {\n * // a power of 2 image\n * hftIcon: { src: \"images/hft-icon-16.png\", mag: gl.NEAREST },\n * // a non-power of 2 image\n * clover: { src: \"images/clover.jpg\" },\n * // From a canvas\n * fromCanvas: { src: ctx.canvas },\n * // A cubemap from 6 images\n * yokohama: {\n * target: gl.TEXTURE_CUBE_MAP,\n * src: [\n * 'images/yokohama/posx.jpg',\n * 'images/yokohama/negx.jpg',\n * 'images/yokohama/posy.jpg',\n * 'images/yokohama/negy.jpg',\n * 'images/yokohama/posz.jpg',\n * 'images/yokohama/negz.jpg',\n * ],\n * },\n * // A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1)\n * goldengate: {\n * target: gl.TEXTURE_CUBE_MAP,\n * src: 'images/goldengate.jpg',\n * },\n * // A 2x2 pixel texture from a JavaScript array\n * checker: {\n * mag: gl.NEAREST,\n * min: gl.LINEAR,\n * src: [\n * 255,255,255,255,\n * 192,192,192,255,\n * 192,192,192,255,\n * 255,255,255,255,\n * ],\n * },\n * // a 1x2 pixel texture from a typed array.\n * stripe: {\n * mag: gl.NEAREST,\n * min: gl.LINEAR,\n * format: gl.LUMINANCE,\n * src: new Uint8Array([\n * 255,\n * 128,\n * 255,\n * 128,\n * 255,\n * 128,\n * 255,\n * 128,\n * ]),\n * width: 1,\n * },\n * });\n *\n * Now\n *\n * * `textures.hftIcon` will be a 2d texture\n * * `textures.clover` will be a 2d texture\n * * `textures.fromCanvas` will be a 2d texture\n * * `textures.yohohama` will be a cubemap texture\n * * `textures.goldengate` will be a cubemap texture\n * * `textures.checker` will be a 2d texture\n * * `textures.stripe` will be a 2d texture\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} options A object of TextureOptions one per texture.\n * @param {module:twgl.TexturesReadyCallback} [callback] A callback called when all textures have been downloaded.\n * @return {Object.} the created textures by name\n * @memberOf module:twgl/textures\n */\nfunction createTextures(gl, textureOptions, callback) {\n callback = callback || noop;\n let numDownloading = 0;\n const errors = [];\n const textures = {};\n const images = {};\n\n function callCallbackIfReady() {\n if (numDownloading === 0) {\n setTimeout(function() {\n callback(errors.length ? errors : undefined, textures, images);\n }, 0);\n }\n }\n\n Object.keys(textureOptions).forEach(function(name) {\n const options = textureOptions[name];\n let onLoadFn;\n if (isAsyncSrc(options.src)) {\n onLoadFn = function(err, tex, img) {\n images[name] = img;\n --numDownloading;\n if (err) {\n errors.push(err);\n }\n callCallbackIfReady();\n };\n ++numDownloading;\n }\n textures[name] = createTexture(gl, options, onLoadFn);\n });\n\n // queue the callback if there are no images to download.\n // We do this because if your code is structured to wait for\n // images to download but then you comment out all the async\n // images your code would break.\n callCallbackIfReady();\n\n return textures;\n}\n\nvar textures = /*#__PURE__*/Object.freeze({\n __proto__: null,\n setTextureDefaults_: setDefaults$1,\n createSampler: createSampler,\n createSamplers: createSamplers,\n setSamplerParameters: setSamplerParameters,\n createTexture: createTexture,\n setEmptyTexture: setEmptyTexture,\n setTextureFromArray: setTextureFromArray,\n loadTextureFromUrl: loadTextureFromUrl,\n setTextureFromElement: setTextureFromElement,\n setTextureFilteringForSize: setTextureFilteringForSize,\n setTextureParameters: setTextureParameters,\n setDefaultTextureColor: setDefaultTextureColor,\n createTextures: createTextures,\n resizeTexture: resizeTexture,\n canGenerateMipmap: canGenerateMipmap,\n canFilter: canFilter,\n getNumComponentsForFormat: getNumComponentsForFormat,\n getBytesPerElementForInternalFormat: getBytesPerElementForInternalFormat,\n getFormatAndTypeForInternalFormat: getFormatAndTypeForInternalFormat\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Low level shader program related functions\n *\n * You should generally not need to use these functions. They are provided\n * for those cases where you're doing something out of the ordinary\n * and you need lower level access.\n *\n * For backward compatibility they are available at both `twgl.programs` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/programs\n */\n\nconst error = error$1;\nconst warn = warn$1;\nfunction getElementById(id) {\n return (typeof document !== 'undefined' && document.getElementById)\n ? document.getElementById(id)\n : null;\n}\n\nconst TEXTURE0 = 0x84c0;\nconst DYNAMIC_DRAW = 0x88e8;\n\nconst ARRAY_BUFFER = 0x8892;\nconst ELEMENT_ARRAY_BUFFER$1 = 0x8893;\nconst UNIFORM_BUFFER = 0x8a11;\nconst TRANSFORM_FEEDBACK_BUFFER = 0x8c8e;\n\nconst TRANSFORM_FEEDBACK = 0x8e22;\n\nconst COMPILE_STATUS = 0x8b81;\nconst LINK_STATUS = 0x8b82;\nconst FRAGMENT_SHADER = 0x8b30;\nconst VERTEX_SHADER = 0x8b31;\nconst SEPARATE_ATTRIBS = 0x8c8d;\n\nconst ACTIVE_UNIFORMS = 0x8b86;\nconst ACTIVE_ATTRIBUTES = 0x8b89;\nconst TRANSFORM_FEEDBACK_VARYINGS = 0x8c83;\nconst ACTIVE_UNIFORM_BLOCKS = 0x8a36;\nconst UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8a44;\nconst UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8a46;\nconst UNIFORM_BLOCK_DATA_SIZE = 0x8a40;\nconst UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8a43;\n\nconst FLOAT = 0x1406;\nconst FLOAT_VEC2 = 0x8B50;\nconst FLOAT_VEC3 = 0x8B51;\nconst FLOAT_VEC4 = 0x8B52;\nconst INT = 0x1404;\nconst INT_VEC2 = 0x8B53;\nconst INT_VEC3 = 0x8B54;\nconst INT_VEC4 = 0x8B55;\nconst BOOL = 0x8B56;\nconst BOOL_VEC2 = 0x8B57;\nconst BOOL_VEC3 = 0x8B58;\nconst BOOL_VEC4 = 0x8B59;\nconst FLOAT_MAT2 = 0x8B5A;\nconst FLOAT_MAT3 = 0x8B5B;\nconst FLOAT_MAT4 = 0x8B5C;\nconst SAMPLER_2D = 0x8B5E;\nconst SAMPLER_CUBE = 0x8B60;\nconst SAMPLER_3D = 0x8B5F;\nconst SAMPLER_2D_SHADOW = 0x8B62;\nconst FLOAT_MAT2x3 = 0x8B65;\nconst FLOAT_MAT2x4 = 0x8B66;\nconst FLOAT_MAT3x2 = 0x8B67;\nconst FLOAT_MAT3x4 = 0x8B68;\nconst FLOAT_MAT4x2 = 0x8B69;\nconst FLOAT_MAT4x3 = 0x8B6A;\nconst SAMPLER_2D_ARRAY = 0x8DC1;\nconst SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;\nconst SAMPLER_CUBE_SHADOW = 0x8DC5;\nconst UNSIGNED_INT = 0x1405;\nconst UNSIGNED_INT_VEC2 = 0x8DC6;\nconst UNSIGNED_INT_VEC3 = 0x8DC7;\nconst UNSIGNED_INT_VEC4 = 0x8DC8;\nconst INT_SAMPLER_2D = 0x8DCA;\nconst INT_SAMPLER_3D = 0x8DCB;\nconst INT_SAMPLER_CUBE = 0x8DCC;\nconst INT_SAMPLER_2D_ARRAY = 0x8DCF;\nconst UNSIGNED_INT_SAMPLER_2D = 0x8DD2;\nconst UNSIGNED_INT_SAMPLER_3D = 0x8DD3;\nconst UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;\nconst UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;\n\nconst TEXTURE_2D$1 = 0x0DE1;\nconst TEXTURE_CUBE_MAP = 0x8513;\nconst TEXTURE_3D = 0x806F;\nconst TEXTURE_2D_ARRAY = 0x8C1A;\n\nconst typeMap = {};\n\n/**\n * Returns the corresponding bind point for a given sampler type\n * @private\n */\nfunction getBindPointForSamplerType(gl, type) {\n return typeMap[type].bindPoint;\n}\n\n// This kind of sucks! If you could compose functions as in `var fn = gl[name];`\n// this code could be a lot smaller but that is sadly really slow (T_T)\n\nfunction floatSetter(gl, location) {\n return function(v) {\n gl.uniform1f(location, v);\n };\n}\n\nfunction floatArraySetter(gl, location) {\n return function(v) {\n gl.uniform1fv(location, v);\n };\n}\n\nfunction floatVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2fv(location, v);\n };\n}\n\nfunction floatVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3fv(location, v);\n };\n}\n\nfunction floatVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4fv(location, v);\n };\n}\n\nfunction intSetter(gl, location) {\n return function(v) {\n gl.uniform1i(location, v);\n };\n}\n\nfunction intArraySetter(gl, location) {\n return function(v) {\n gl.uniform1iv(location, v);\n };\n}\n\nfunction intVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2iv(location, v);\n };\n}\n\nfunction intVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3iv(location, v);\n };\n}\n\nfunction intVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4iv(location, v);\n };\n}\n\nfunction uintSetter(gl, location) {\n return function(v) {\n gl.uniform1ui(location, v);\n };\n}\n\nfunction uintArraySetter(gl, location) {\n return function(v) {\n gl.uniform1uiv(location, v);\n };\n}\n\nfunction uintVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2uiv(location, v);\n };\n}\n\nfunction uintVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3uiv(location, v);\n };\n}\n\nfunction uintVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4uiv(location, v);\n };\n}\n\nfunction floatMat2Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2fv(location, false, v);\n };\n}\n\nfunction floatMat3Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3fv(location, false, v);\n };\n}\n\nfunction floatMat4Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4fv(location, false, v);\n };\n}\n\nfunction floatMat23Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2x3fv(location, false, v);\n };\n}\n\nfunction floatMat32Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3x2fv(location, false, v);\n };\n}\n\nfunction floatMat24Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2x4fv(location, false, v);\n };\n}\n\nfunction floatMat42Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4x2fv(location, false, v);\n };\n}\n\nfunction floatMat34Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3x4fv(location, false, v);\n };\n}\n\nfunction floatMat43Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4x3fv(location, false, v);\n };\n}\n\nfunction samplerSetter(gl, type, unit, location) {\n const bindPoint = getBindPointForSamplerType(gl, type);\n return isWebGL2(gl) ? function(textureOrPair) {\n let texture;\n let sampler;\n if (!textureOrPair || isTexture(gl, textureOrPair)) {\n texture = textureOrPair;\n sampler = null;\n } else {\n texture = textureOrPair.texture;\n sampler = textureOrPair.sampler;\n }\n gl.uniform1i(location, unit);\n gl.activeTexture(TEXTURE0 + unit);\n gl.bindTexture(bindPoint, texture);\n gl.bindSampler(unit, sampler);\n } : function(texture) {\n gl.uniform1i(location, unit);\n gl.activeTexture(TEXTURE0 + unit);\n gl.bindTexture(bindPoint, texture);\n };\n}\n\nfunction samplerArraySetter(gl, type, unit, location, size) {\n const bindPoint = getBindPointForSamplerType(gl, type);\n const units = new Int32Array(size);\n for (let ii = 0; ii < size; ++ii) {\n units[ii] = unit + ii;\n }\n\n return isWebGL2(gl) ? function(textures) {\n gl.uniform1iv(location, units);\n textures.forEach(function(textureOrPair, index) {\n gl.activeTexture(TEXTURE0 + units[index]);\n let texture;\n let sampler;\n if (!textureOrPair || isTexture(gl, textureOrPair)) {\n texture = textureOrPair;\n sampler = null;\n } else {\n texture = textureOrPair.texture;\n sampler = textureOrPair.sampler;\n }\n gl.bindSampler(unit, sampler);\n gl.bindTexture(bindPoint, texture);\n });\n } : function(textures) {\n gl.uniform1iv(location, units);\n textures.forEach(function(texture, index) {\n gl.activeTexture(TEXTURE0 + units[index]);\n gl.bindTexture(bindPoint, texture);\n });\n };\n}\n\ntypeMap[FLOAT] = { Type: Float32Array, size: 4, setter: floatSetter, arraySetter: floatArraySetter, };\ntypeMap[FLOAT_VEC2] = { Type: Float32Array, size: 8, setter: floatVec2Setter, cols: 2, };\ntypeMap[FLOAT_VEC3] = { Type: Float32Array, size: 12, setter: floatVec3Setter, cols: 3, };\ntypeMap[FLOAT_VEC4] = { Type: Float32Array, size: 16, setter: floatVec4Setter, cols: 4, };\ntypeMap[INT] = { Type: Int32Array, size: 4, setter: intSetter, arraySetter: intArraySetter, };\ntypeMap[INT_VEC2] = { Type: Int32Array, size: 8, setter: intVec2Setter, cols: 2, };\ntypeMap[INT_VEC3] = { Type: Int32Array, size: 12, setter: intVec3Setter, cols: 3, };\ntypeMap[INT_VEC4] = { Type: Int32Array, size: 16, setter: intVec4Setter, cols: 4, };\ntypeMap[UNSIGNED_INT] = { Type: Uint32Array, size: 4, setter: uintSetter, arraySetter: uintArraySetter, };\ntypeMap[UNSIGNED_INT_VEC2] = { Type: Uint32Array, size: 8, setter: uintVec2Setter, cols: 2, };\ntypeMap[UNSIGNED_INT_VEC3] = { Type: Uint32Array, size: 12, setter: uintVec3Setter, cols: 3, };\ntypeMap[UNSIGNED_INT_VEC4] = { Type: Uint32Array, size: 16, setter: uintVec4Setter, cols: 4, };\ntypeMap[BOOL] = { Type: Uint32Array, size: 4, setter: intSetter, arraySetter: intArraySetter, };\ntypeMap[BOOL_VEC2] = { Type: Uint32Array, size: 8, setter: intVec2Setter, cols: 2, };\ntypeMap[BOOL_VEC3] = { Type: Uint32Array, size: 12, setter: intVec3Setter, cols: 3, };\ntypeMap[BOOL_VEC4] = { Type: Uint32Array, size: 16, setter: intVec4Setter, cols: 4, };\ntypeMap[FLOAT_MAT2] = { Type: Float32Array, size: 32, setter: floatMat2Setter, rows: 2, cols: 2, };\ntypeMap[FLOAT_MAT3] = { Type: Float32Array, size: 48, setter: floatMat3Setter, rows: 3, cols: 3, };\ntypeMap[FLOAT_MAT4] = { Type: Float32Array, size: 64, setter: floatMat4Setter, rows: 4, cols: 4, };\ntypeMap[FLOAT_MAT2x3] = { Type: Float32Array, size: 32, setter: floatMat23Setter, rows: 2, cols: 3, };\ntypeMap[FLOAT_MAT2x4] = { Type: Float32Array, size: 32, setter: floatMat24Setter, rows: 2, cols: 4, };\ntypeMap[FLOAT_MAT3x2] = { Type: Float32Array, size: 48, setter: floatMat32Setter, rows: 3, cols: 2, };\ntypeMap[FLOAT_MAT3x4] = { Type: Float32Array, size: 48, setter: floatMat34Setter, rows: 3, cols: 4, };\ntypeMap[FLOAT_MAT4x2] = { Type: Float32Array, size: 64, setter: floatMat42Setter, rows: 4, cols: 2, };\ntypeMap[FLOAT_MAT4x3] = { Type: Float32Array, size: 64, setter: floatMat43Setter, rows: 4, cols: 3, };\ntypeMap[SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[SAMPLER_2D_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[SAMPLER_2D_ARRAY_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[SAMPLER_CUBE_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[UNSIGNED_INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[UNSIGNED_INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[UNSIGNED_INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[UNSIGNED_INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\n\nfunction floatAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n switch (b.value.length) {\n case 4:\n gl.vertexAttrib4fv(index, b.value);\n break;\n case 3:\n gl.vertexAttrib3fv(index, b.value);\n break;\n case 2:\n gl.vertexAttrib2fv(index, b.value);\n break;\n case 1:\n gl.vertexAttrib1fv(index, b.value);\n break;\n default:\n throw new Error('the length of a float constant value must be between 1 and 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribPointer(\n index, b.numComponents || b.size, b.type || FLOAT, b.normalize || false, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction intAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n if (b.value.length === 4) {\n gl.vertexAttrib4iv(index, b.value);\n } else {\n throw new Error('The length of an integer constant value must be 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribIPointer(\n index, b.numComponents || b.size, b.type || INT, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction uintAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n if (b.value.length === 4) {\n gl.vertexAttrib4uiv(index, b.value);\n } else {\n throw new Error('The length of an unsigned integer constant value must be 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribIPointer(\n index, b.numComponents || b.size, b.type || UNSIGNED_INT, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction matAttribSetter(gl, index, typeInfo) {\n const defaultSize = typeInfo.size;\n const count = typeInfo.count;\n\n return function(b) {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n const numComponents = b.size || b.numComponents || defaultSize;\n const size = numComponents / count;\n const type = b.type || FLOAT;\n const typeInfo = typeMap[type];\n const stride = typeInfo.size * numComponents;\n const normalize = b.normalize || false;\n const offset = b.offset || 0;\n const rowOffset = stride / count;\n for (let i = 0; i < count; ++i) {\n gl.enableVertexAttribArray(index + i);\n gl.vertexAttribPointer(\n index + i, size, type, normalize, stride, offset + rowOffset * i);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index + i, b.divisor || 0);\n }\n }\n };\n}\n\n\n\nconst attrTypeMap = {};\nattrTypeMap[FLOAT] = { size: 4, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC2] = { size: 8, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC3] = { size: 12, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC4] = { size: 16, setter: floatAttribSetter, };\nattrTypeMap[INT] = { size: 4, setter: intAttribSetter, };\nattrTypeMap[INT_VEC2] = { size: 8, setter: intAttribSetter, };\nattrTypeMap[INT_VEC3] = { size: 12, setter: intAttribSetter, };\nattrTypeMap[INT_VEC4] = { size: 16, setter: intAttribSetter, };\nattrTypeMap[UNSIGNED_INT] = { size: 4, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC2] = { size: 8, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC3] = { size: 12, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC4] = { size: 16, setter: uintAttribSetter, };\nattrTypeMap[BOOL] = { size: 4, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC2] = { size: 8, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC3] = { size: 12, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC4] = { size: 16, setter: intAttribSetter, };\nattrTypeMap[FLOAT_MAT2] = { size: 4, setter: matAttribSetter, count: 2, };\nattrTypeMap[FLOAT_MAT3] = { size: 9, setter: matAttribSetter, count: 3, };\nattrTypeMap[FLOAT_MAT4] = { size: 16, setter: matAttribSetter, count: 4, };\n\nconst errorRE = /ERROR:\\s*\\d+:(\\d+)/gi;\nfunction addLineNumbersWithError(src, log = '', lineOffset = 0) {\n // Note: Error message formats are not defined by any spec so this may or may not work.\n const matches = [...log.matchAll(errorRE)];\n const lineNoToErrorMap = new Map(matches.map((m, ndx) => {\n const lineNo = parseInt(m[1]);\n const next = matches[ndx + 1];\n const end = next ? next.index : log.length;\n const msg = log.substring(m.index, end);\n return [lineNo - 1, msg];\n }));\n return src.split('\\n').map((line, lineNo) => {\n const err = lineNoToErrorMap.get(lineNo);\n return `${lineNo + 1 + lineOffset}: ${line}${err ? `\\n\\n^^^ ${err}` : ''}`;\n }).join('\\n');\n}\n\n/**\n * Error Callback\n * @callback ErrorCallback\n * @param {string} msg error message.\n * @param {number} [lineOffset] amount to add to line number\n * @memberOf module:twgl\n */\n\n/**\n * Program Callback\n * @callback ProgramCallback\n * @param {string} [err] error message, falsy if no error\n * @param {WebGLProgram|module:twgl.ProgramInfo} [result] the program or programInfo\n */\n\nconst spaceRE = /^[ \\t]*\\n/;\n\n/**\n * Remove the first end of line because WebGL 2.0 requires\n * #version 300 es\n * as the first line. No whitespace allowed before that line\n * so\n *\n * \n *\n * Has one line before it which is invalid according to GLSL ES 3.00\n *\n * @param {string} shaderSource The source of the shader\n * @returns {{shaderSource: string, lineOffset: number}}\n * @private\n */\nfunction prepShaderSource(shaderSource) {\n let lineOffset = 0;\n if (spaceRE.test(shaderSource)) {\n lineOffset = 1;\n shaderSource = shaderSource.replace(spaceRE, '');\n }\n return {lineOffset, shaderSource};\n}\n\n/**\n * @param {module:twgl.ProgramOptions} progOptions\n * @param {string} msg\n * @return null\n * @private\n */\nfunction reportError(progOptions, msg) {\n progOptions.errorCallback(msg);\n if (progOptions.callback) {\n setTimeout(() => {\n progOptions.callback(`${msg}\\n${progOptions.errors.join('\\n')}`);\n });\n }\n return null;\n}\n\n/**\n * Check Shader status\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {number} shaderType The shader type\n * @param {WebGLShader} shader The shader\n * @param {ErrorCallback} [errFn] function to receive error message.\n * @return {string} errors or empty string\n * @private\n */\nfunction checkShaderStatus(gl, shaderType, shader, errFn) {\n errFn = errFn || error;\n // Check the compile status\n const compiled = gl.getShaderParameter(shader, COMPILE_STATUS);\n if (!compiled) {\n // Something went wrong during compilation; get the error\n const lastError = gl.getShaderInfoLog(shader);\n const {lineOffset, shaderSource} = prepShaderSource(gl.getShaderSource(shader));\n const error = `${addLineNumbersWithError(shaderSource, lastError, lineOffset)}\\nError compiling ${glEnumToString(gl, shaderType)}: ${lastError}`;\n errFn(error);\n return error;\n }\n return '';\n}\n\n/**\n * @typedef {Object} FullProgramSpec\n * @property {string[]} shaders the shader source or element ids.\n * @property {function(string)} [errorCallback] callback for errors\n * @property {Object.|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.\n * @property {(module:twgl.BufferInfo|Object.|string[])} [transformFeedbackVaryings] If passed\n * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise\n * you can pass an array of names.\n * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.\n * @property {ProgramCallback} [callback] callback for async program compilation.\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {string[]|module:twgl.FullProgramSpec} ProgramSpec\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {Object} ProgramOptions\n * @property {function(string)} [errorCallback] callback for errors\n * @property {Object.|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.\n * @property {(module:twgl.BufferInfo|Object.|string[])} [transformFeedbackVaryings] If passed\n * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise\n * you can pass an array of names.\n * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.\n * @property {ProgramCallback} [callback] callback for async program compilation.\n * @memberOf module:twgl\n */\n\n/**\n * Gets the program options based on all these optional arguments\n * @param {module:twgl.ProgramOptions|string[]} [opt_attribs] Options for the program or an array of attribs names. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {module:twgl.ProgramOptions} an instance of ProgramOptions based on the arguments passed in\n * @private\n */\nfunction getProgramOptions(opt_attribs, opt_locations, opt_errorCallback) {\n let transformFeedbackVaryings;\n let transformFeedbackMode;\n let callback;\n if (typeof opt_locations === 'function') {\n opt_errorCallback = opt_locations;\n opt_locations = undefined;\n }\n if (typeof opt_attribs === 'function') {\n opt_errorCallback = opt_attribs;\n opt_attribs = undefined;\n } else if (opt_attribs && !Array.isArray(opt_attribs)) {\n const opt = opt_attribs;\n opt_errorCallback = opt.errorCallback;\n opt_attribs = opt.attribLocations;\n transformFeedbackVaryings = opt.transformFeedbackVaryings;\n transformFeedbackMode = opt.transformFeedbackMode;\n callback = opt.callback;\n }\n\n const errorCallback = opt_errorCallback || error;\n const errors = [];\n const options = {\n errorCallback(msg, ...args) {\n errors.push(msg);\n errorCallback(msg, ...args);\n },\n transformFeedbackVaryings,\n transformFeedbackMode,\n callback,\n errors,\n };\n\n {\n let attribLocations = {};\n if (Array.isArray(opt_attribs)) {\n opt_attribs.forEach(function(attrib, ndx) {\n attribLocations[attrib] = opt_locations ? opt_locations[ndx] : ndx;\n });\n } else {\n attribLocations = opt_attribs || {};\n }\n options.attribLocations = attribLocations;\n }\n\n return options;\n}\n\nconst defaultShaderType = [\n \"VERTEX_SHADER\",\n \"FRAGMENT_SHADER\",\n];\n\nfunction getShaderTypeFromScriptType(gl, scriptType) {\n if (scriptType.indexOf(\"frag\") >= 0) {\n return FRAGMENT_SHADER;\n } else if (scriptType.indexOf(\"vert\") >= 0) {\n return VERTEX_SHADER;\n }\n return undefined;\n}\n\nfunction deleteProgramAndShaders(gl, program, notThese) {\n const shaders = gl.getAttachedShaders(program);\n for (const shader of shaders) {\n if (notThese.has(shader)) {\n gl.deleteShader(shader);\n }\n }\n gl.deleteProgram(program);\n}\n\nconst wait = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));\n\nfunction createProgramNoCheck(gl, shaders, programOptions) {\n const program = gl.createProgram();\n const {\n attribLocations,\n transformFeedbackVaryings,\n transformFeedbackMode,\n } = getProgramOptions(programOptions);\n\n for (let ndx = 0; ndx < shaders.length; ++ndx) {\n let shader = shaders[ndx];\n if (typeof shader === 'string') {\n const elem = getElementById(shader);\n const src = elem ? elem.text : shader;\n let type = gl[defaultShaderType[ndx]];\n if (elem && elem.type) {\n type = getShaderTypeFromScriptType(gl, elem.type) || type;\n }\n shader = gl.createShader(type);\n gl.shaderSource(shader, prepShaderSource(src).shaderSource);\n gl.compileShader(shader);\n gl.attachShader(program, shader);\n }\n }\n\n Object.entries(attribLocations).forEach(([attrib, loc]) => gl.bindAttribLocation(program, loc, attrib));\n\n {\n let varyings = transformFeedbackVaryings;\n if (varyings) {\n if (varyings.attribs) {\n varyings = varyings.attribs;\n }\n if (!Array.isArray(varyings)) {\n varyings = Object.keys(varyings);\n }\n gl.transformFeedbackVaryings(program, varyings, transformFeedbackMode || SEPARATE_ATTRIBS);\n }\n }\n\n gl.linkProgram(program);\n return program;\n}\n\n/**\n * Creates a program, attaches (and/or compiles) shaders, binds attrib locations, links the\n * program.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgram(gl, [vs, fs], options);\n * twgl.createProgram(gl, [vs, fs], opt_errFunc);\n * twgl.createProgram(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgram(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]|module:twgl.ErrorCallback} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error of a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgram(\n gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {\n // This code is really convoluted, because it may or may not be async\n // Maybe it would be better to have a separate function\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const shaderSet = new Set(shaders);\n const program = createProgramNoCheck(gl, shaders, progOptions);\n\n function hasErrors(gl, program) {\n const errors = getProgramErrors(gl, program, progOptions.errorCallback);\n if (errors) {\n deleteProgramAndShaders(gl, program, shaderSet);\n }\n return errors;\n }\n\n if (progOptions.callback) {\n waitForProgramLinkCompletionAsync(gl, program).then(() => {\n const errors = hasErrors(gl, program);\n progOptions.callback(errors, errors ? undefined : program);\n });\n return undefined;\n }\n\n return hasErrors(gl, program) ? undefined : program;\n}\n\n/**\n * This only works because the functions it wraps the first 2 arguments\n * are gl and any, followed by things that become programOptions\n * @private\n */\nfunction wrapCallbackFnToAsyncFn(fn) {\n return function(gl, arg1, ...args) {\n return new Promise((resolve, reject) => {\n const programOptions = getProgramOptions(...args);\n programOptions.callback = (err, program) => {\n if (err) {\n reject(err);\n } else {\n resolve(program);\n }\n };\n fn(gl, arg1, programOptions);\n });\n };\n}\n\n/**\n * Same as createProgram but returns a promise\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramAsync(gl, [vs, fs], options);\n * twgl.createProgramAsync(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @function\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]|module:twgl.ErrorCallback} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {Promise} The created program\n * @memberOf module:twgl/programs\n */\nconst createProgramAsync = wrapCallbackFnToAsyncFn(createProgram);\n\n/**\n * Same as createProgramInfo but returns a promise\n * @function\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders or ids. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]|module:twgl.ErrorCallback} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {Promise} The created ProgramInfo\n * @memberOf module:twgl/programs\n */\nconst createProgramInfoAsync = wrapCallbackFnToAsyncFn(createProgramInfo);\n\nasync function waitForProgramLinkCompletionAsync(gl, program) {\n const ext = gl.getExtension('KHR_parallel_shader_compile');\n const checkFn = ext\n ? (gl, program) => gl.getProgramParameter(program, ext.COMPLETION_STATUS_KHR)\n : () => true;\n\n let waitTime = 0;\n do {\n await wait(waitTime); // must wait at least once\n waitTime = 1000 / 60;\n } while (!checkFn(gl, program));\n}\n\nasync function waitForAllProgramsLinkCompletionAsync(gl, programs) {\n for (const program of Object.values(programs)) {\n await waitForProgramLinkCompletionAsync(gl, program);\n }\n}\n\n/**\n * Check a program's link status\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program Program to check\n * @param {ErrorCallback} [errFn] func for errors\n * @return {string?} errors if program is failed, else undefined\n * @private\n */\nfunction getProgramErrors(gl, program, errFn) {\n errFn = errFn || error;\n // Check the link status\n const linked = gl.getProgramParameter(program, LINK_STATUS);\n if (!linked) {\n // something went wrong with the link\n const lastError = gl.getProgramInfoLog(program);\n errFn(`Error in program linking: ${lastError}`);\n // print any errors from these shaders\n const shaders = gl.getAttachedShaders(program);\n const errors = shaders.map(shader => checkShaderStatus(gl, gl.getShaderParameter(shader, gl.SHADER_TYPE), shader, errFn));\n return `${lastError}\\n${errors.filter(_ => _).join('\\n')}`;\n }\n return undefined;\n}\n\n/**\n * Creates a program from 2 script tags.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_options);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderScriptIds Array of ids of the script\n * tags for the shaders. The first is assumed to be the\n * vertex shader, the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]|module:twgl.ErrorCallback} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error or a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgramFromScripts(\n gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const shaders = [];\n for (const scriptId of shaderScriptIds) {\n const shaderScript = getElementById(scriptId);\n if (!shaderScript) {\n return reportError(progOptions, `unknown script element: ${scriptId}`);\n }\n shaders.push(shaderScript.text);\n }\n return createProgram(gl, shaders, progOptions);\n}\n\n/**\n * Creates a program from 2 sources.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramFromSource(gl, [vs, fs], opt_options);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]|module:twgl.ErrorCallback} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error or a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgramFromSources(\n gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {\n return createProgram(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);\n}\n\n/**\n * Returns true if attribute/uniform is a reserved/built in\n *\n * It makes no sense to me why GL returns these because it's\n * illegal to call `gl.getUniformLocation` and `gl.getAttribLocation`\n * with names that start with `gl_` (and `webgl_` in WebGL)\n *\n * I can only assume they are there because they might count\n * when computing the number of uniforms/attributes used when you want to\n * know if you are near the limit. That doesn't really make sense\n * to me but the fact that these get returned are in the spec.\n *\n * @param {WebGLActiveInfo} info As returned from `gl.getActiveUniform` or\n * `gl.getActiveAttrib`.\n * @return {bool} true if it's reserved\n * @private\n */\nfunction isBuiltIn(info) {\n const name = info.name;\n return name.startsWith(\"gl_\") || name.startsWith(\"webgl_\");\n}\n\nconst tokenRE = /(\\.|\\[|]|\\w+)/g;\nconst isDigit = s => s >= '0' && s <= '9';\nfunction addSetterToUniformTree(fullPath, setter, node, uniformSetters) {\n const tokens = fullPath.split(tokenRE).filter(s => s !== '');\n let tokenNdx = 0;\n let path = '';\n\n for (;;) {\n const token = tokens[tokenNdx++]; // has to be name or number\n path += token;\n const isArrayIndex = isDigit(token[0]);\n const accessor = isArrayIndex\n ? parseInt(token)\n : token;\n if (isArrayIndex) {\n path += tokens[tokenNdx++]; // skip ']'\n }\n const isLastToken = tokenNdx === tokens.length;\n if (isLastToken) {\n node[accessor] = setter;\n break;\n } else {\n const token = tokens[tokenNdx++]; // has to be . or [\n const isArray = token === '[';\n const child = node[accessor] || (isArray ? [] : {});\n node[accessor] = child;\n node = child;\n uniformSetters[path] = uniformSetters[path] || function(node) {\n return function(value) {\n setUniformTree(node, value);\n };\n }(child);\n path += token;\n }\n }\n}\n\n/**\n * Creates setter functions for all uniforms of a shader\n * program.\n *\n * @see {@link module:twgl.setUniforms}\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program the program to create setters for.\n * @returns {Object.} an object with a setter by name for each uniform\n * @memberOf module:twgl/programs\n */\nfunction createUniformSetters(gl, program) {\n let textureUnit = 0;\n\n /**\n * Creates a setter for a uniform of the given program with it's\n * location embedded in the setter.\n * @param {WebGLProgram} program\n * @param {WebGLUniformInfo} uniformInfo\n * @returns {function} the created setter.\n */\n function createUniformSetter(program, uniformInfo, location) {\n const isArray = uniformInfo.name.endsWith(\"[0]\");\n const type = uniformInfo.type;\n const typeInfo = typeMap[type];\n if (!typeInfo) {\n throw new Error(`unknown type: 0x${type.toString(16)}`); // we should never get here.\n }\n let setter;\n if (typeInfo.bindPoint) {\n // it's a sampler\n const unit = textureUnit;\n textureUnit += uniformInfo.size;\n if (isArray) {\n setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size);\n } else {\n setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size);\n }\n } else {\n if (typeInfo.arraySetter && isArray) {\n setter = typeInfo.arraySetter(gl, location);\n } else {\n setter = typeInfo.setter(gl, location);\n }\n }\n setter.location = location;\n return setter;\n }\n\n const uniformSetters = {};\n const uniformTree = {};\n const numUniforms = gl.getProgramParameter(program, ACTIVE_UNIFORMS);\n\n for (let ii = 0; ii < numUniforms; ++ii) {\n const uniformInfo = gl.getActiveUniform(program, ii);\n if (isBuiltIn(uniformInfo)) {\n continue;\n }\n let name = uniformInfo.name;\n // remove the array suffix.\n if (name.endsWith(\"[0]\")) {\n name = name.substr(0, name.length - 3);\n }\n const location = gl.getUniformLocation(program, uniformInfo.name);\n // the uniform will have no location if it's in a uniform block\n if (location) {\n const setter = createUniformSetter(program, uniformInfo, location);\n uniformSetters[name] = setter;\n addSetterToUniformTree(name, setter, uniformTree, uniformSetters);\n }\n }\n\n return uniformSetters;\n}\n\n/**\n * @typedef {Object} TransformFeedbackInfo\n * @property {number} index index of transform feedback\n * @property {number} type GL type\n * @property {number} size 1 - 4\n * @memberOf module:twgl\n */\n\n/**\n * Create TransformFeedbackInfo for passing to bindTransformFeedbackInfo.\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program an existing WebGLProgram.\n * @return {Object}\n * @memberOf module:twgl\n */\nfunction createTransformFeedbackInfo(gl, program) {\n const info = {};\n const numVaryings = gl.getProgramParameter(program, TRANSFORM_FEEDBACK_VARYINGS);\n for (let ii = 0; ii < numVaryings; ++ii) {\n const varying = gl.getTransformFeedbackVarying(program, ii);\n info[varying.name] = {\n index: ii,\n type: varying.type,\n size: varying.size,\n };\n }\n return info;\n}\n\n/**\n * Binds buffers for transform feedback.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {(module:twgl.ProgramInfo|Object)} transformFeedbackInfo A ProgramInfo or TransformFeedbackInfo.\n * @param {(module:twgl.BufferInfo|Object)} [bufferInfo] A BufferInfo or set of AttribInfos.\n * @memberOf module:twgl\n */\nfunction bindTransformFeedbackInfo(gl, transformFeedbackInfo, bufferInfo) {\n if (transformFeedbackInfo.transformFeedbackInfo) {\n transformFeedbackInfo = transformFeedbackInfo.transformFeedbackInfo;\n }\n if (bufferInfo.attribs) {\n bufferInfo = bufferInfo.attribs;\n }\n for (const name in bufferInfo) {\n const varying = transformFeedbackInfo[name];\n if (varying) {\n const buf = bufferInfo[name];\n if (buf.offset) {\n gl.bindBufferRange(TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer, buf.offset, buf.size);\n } else {\n gl.bindBufferBase(TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer);\n }\n }\n }\n}\n\n/**\n * Creates a transform feedback and sets the buffers\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}\n * @param {(module:twgl.BufferInfo|Object)} [bufferInfo] A BufferInfo or set of AttribInfos.\n * @return {WebGLTransformFeedback} the created transform feedback\n * @memberOf module:twgl\n */\nfunction createTransformFeedback(gl, programInfo, bufferInfo) {\n const tf = gl.createTransformFeedback();\n gl.bindTransformFeedback(TRANSFORM_FEEDBACK, tf);\n gl.useProgram(programInfo.program);\n bindTransformFeedbackInfo(gl, programInfo, bufferInfo);\n gl.bindTransformFeedback(TRANSFORM_FEEDBACK, null);\n return tf;\n}\n\n/**\n * @typedef {Object} UniformData\n * @property {string} name The name of the uniform\n * @property {number} type The WebGL type enum for this uniform\n * @property {number} size The number of elements for this uniform\n * @property {number} blockNdx The block index this uniform appears in\n * @property {number} offset The byte offset in the block for this uniform's value\n * @memberOf module:twgl\n */\n\n/**\n * The specification for one UniformBlockObject\n *\n * @typedef {Object} BlockSpec\n * @property {number} index The index of the block.\n * @property {number} size The size in bytes needed for the block\n * @property {number[]} uniformIndices The indices of the uniforms used by the block. These indices\n * correspond to entries in a UniformData array in the {@link module:twgl.UniformBlockSpec}.\n * @property {bool} usedByVertexShader Self explanatory\n * @property {bool} usedByFragmentShader Self explanatory\n * @property {bool} used Self explanatory\n * @memberOf module:twgl\n */\n\n/**\n * A `UniformBlockSpec` represents the data needed to create and bind\n * UniformBlockObjects for a given program\n *\n * @typedef {Object} UniformBlockSpec\n * @property {Object.} blockSpecs The BlockSpec for each block by block name\n * @property {UniformData[]} uniformData An array of data for each uniform by uniform index.\n * @memberOf module:twgl\n */\n\n/**\n * Creates a UniformBlockSpec for the given program.\n *\n * A UniformBlockSpec represents the data needed to create and bind\n * UniformBlockObjects\n *\n * @param {WebGL2RenderingContext} gl A WebGL2 Rendering Context\n * @param {WebGLProgram} program A WebGLProgram for a successfully linked program\n * @return {module:twgl.UniformBlockSpec} The created UniformBlockSpec\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockSpecFromProgram(gl, program) {\n const numUniforms = gl.getProgramParameter(program, ACTIVE_UNIFORMS);\n const uniformData = [];\n const uniformIndices = [];\n\n for (let ii = 0; ii < numUniforms; ++ii) {\n uniformIndices.push(ii);\n uniformData.push({});\n const uniformInfo = gl.getActiveUniform(program, ii);\n uniformData[ii].name = uniformInfo.name;\n }\n\n [\n [ \"UNIFORM_TYPE\", \"type\" ],\n [ \"UNIFORM_SIZE\", \"size\" ], // num elements\n [ \"UNIFORM_BLOCK_INDEX\", \"blockNdx\" ],\n [ \"UNIFORM_OFFSET\", \"offset\", ],\n ].forEach(function(pair) {\n const pname = pair[0];\n const key = pair[1];\n gl.getActiveUniforms(program, uniformIndices, gl[pname]).forEach(function(value, ndx) {\n uniformData[ndx][key] = value;\n });\n });\n\n const blockSpecs = {};\n\n const numUniformBlocks = gl.getProgramParameter(program, ACTIVE_UNIFORM_BLOCKS);\n for (let ii = 0; ii < numUniformBlocks; ++ii) {\n const name = gl.getActiveUniformBlockName(program, ii);\n const blockSpec = {\n index: gl.getUniformBlockIndex(program, name),\n usedByVertexShader: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n usedByFragmentShader: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n size: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_DATA_SIZE),\n uniformIndices: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),\n };\n blockSpec.used = blockSpec.usedByVertexShader || blockSpec.usedByFragmentShader;\n blockSpecs[name] = blockSpec;\n }\n\n return {\n blockSpecs: blockSpecs,\n uniformData: uniformData,\n };\n}\n\nconst arraySuffixRE = /\\[\\d+\\]\\.$/; // better way to check?\n\nconst pad = (v, padding) => ((v + (padding - 1)) / padding | 0) * padding;\n\nfunction createUniformBlockUniformSetter(view, isArray, rows, cols) {\n if (isArray || rows) {\n cols = cols || 1;\n const numElements = view.length;\n const totalRows = numElements / 4;\n return function(value) {\n let dst = 0;\n let src = 0;\n for (let row = 0; row < totalRows; ++row) {\n for (let col = 0; col < cols; ++col) {\n view[dst++] = value[src++];\n }\n dst += 4 - cols;\n }\n };\n } else {\n return function(value) {\n if (value.length) {\n view.set(value);\n } else {\n view[0] = value;\n }\n };\n }\n}\n\n/**\n * Represents a UniformBlockObject including an ArrayBuffer with all the uniform values\n * and a corresponding WebGLBuffer to hold those values on the GPU\n *\n * @typedef {Object} UniformBlockInfo\n * @property {string} name The name of the block\n * @property {ArrayBuffer} array The array buffer that contains the uniform values\n * @property {Float32Array} asFloat A float view on the array buffer. This is useful\n * inspecting the contents of the buffer in the debugger.\n * @property {WebGLBuffer} buffer A WebGL buffer that will hold a copy of the uniform values for rendering.\n * @property {number} [offset] offset into buffer\n * @property {Object} uniforms A uniform name to ArrayBufferView map.\n * each Uniform has a correctly typed `ArrayBufferView` into array at the correct offset\n * and length of that uniform. So for example a float uniform would have a 1 float `Float32Array`\n * view. A single mat4 would have a 16 element `Float32Array` view. An ivec2 would have an\n * `Int32Array` view, etc.\n * @property {Object} setters A setter for this uniform.\n * The reason to use setters is elements of arrays are padded to vec4 sizes which\n * means if you want to set an array of 4 floats you'd need to set 16 values\n * (or set elements 0, 4, 8, 12). In other words\n * `someBlockInfo.uniforms.some4FloatArrayUniform.set([0, , , , 1, , , , 2, , , , 3])`\n * where as the setter handles just passing in [0, 1, 2, 3] either directly as in\n * `someBlockInfo.setter.some4FloatArrayUniform.set([0, 1, 2, 3])` (not recommended)\n * or via {@link module:twgl.setBlockUniforms}\n * @memberOf module:twgl\n */\n\n/**\n * Creates a `UniformBlockInfo` for the specified block\n *\n * Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy\n * `UniformBlockInfo` is returned**. This is because when debugging GLSL\n * it is common to comment out large portions of a shader or for example set\n * the final output to a constant. When that happens blocks get optimized out.\n * If this function did not create dummy blocks your code would crash when debugging.\n *\n * @param {WebGL2RenderingContext} gl A WebGL2RenderingContext\n * @param {WebGLProgram} program A WebGLProgram\n * @param {module:twgl.UniformBlockSpec} uniformBlockSpec. A UniformBlockSpec as returned\n * from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {string} blockName The name of the block.\n * @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockInfoFromProgram(gl, program, uniformBlockSpec, blockName) {\n const blockSpecs = uniformBlockSpec.blockSpecs;\n const uniformData = uniformBlockSpec.uniformData;\n const blockSpec = blockSpecs[blockName];\n if (!blockSpec) {\n warn(\"no uniform block object named:\", blockName);\n return {\n name: blockName,\n uniforms: {},\n };\n }\n const array = new ArrayBuffer(blockSpec.size);\n const buffer = gl.createBuffer();\n const uniformBufferIndex = blockSpec.index;\n gl.bindBuffer(UNIFORM_BUFFER, buffer);\n gl.uniformBlockBinding(program, blockSpec.index, uniformBufferIndex);\n\n let prefix = blockName + \".\";\n if (arraySuffixRE.test(prefix)) {\n prefix = prefix.replace(arraySuffixRE, \".\");\n }\n const uniforms = {};\n const setters = {};\n const setterTree = {};\n blockSpec.uniformIndices.forEach(function(uniformNdx) {\n const data = uniformData[uniformNdx];\n let name = data.name;\n if (name.startsWith(prefix)) {\n name = name.substr(prefix.length);\n }\n const isArray = name.endsWith('[0]');\n if (isArray) {\n name = name.substr(0, name.length - 3);\n }\n const typeInfo = typeMap[data.type];\n const Type = typeInfo.Type;\n const byteLength = isArray\n ? pad(typeInfo.size, 16) * data.size\n : typeInfo.size * data.size;\n const uniformView = new Type(array, data.offset, byteLength / Type.BYTES_PER_ELEMENT);\n uniforms[name] = uniformView;\n // Note: I'm not sure what to do here. The original\n // idea was to create TypedArray views into each part\n // of the block. This is useful, for example if you have\n // a block with { mat4: model; mat4 view; mat4 projection; }\n // you'll get a Float32Array for each one suitable for\n // passing to most JS math libraries including twgl's and glMatrix.js.\n //\n // But, if you have a an array of structures, especially if that\n // array is large, you get a whole bunch of TypedArray views.\n // Every one of them has overhead and switching between them all\n // is probably a cache miss. In that case it would really be better\n // to just have one view (asFloat) and have all the setters\n // just reference the correct portion. But, then you can't easily\n // treat a matrix, or a vec4, as a standalone thing like you can\n // with all the views.\n //\n // Another problem with the views is they are not shared. With\n // uniforms you have one set of setters. With UniformBlockInfo\n // you have a set of setters *pre block instance*. That's because\n // TypedArray views can't be mapped to different buffers.\n //\n // My gut right now is if you really want the speed and compactness\n // then you should probably roll your own solution. TWGL's goal\n // here is ease of use as AFAICT there is no simple generic efficient\n // solution.\n const setter = createUniformBlockUniformSetter(uniformView, isArray, typeInfo.rows, typeInfo.cols);\n setters[name] = setter;\n addSetterToUniformTree(name, setter, setterTree, setters);\n });\n return {\n name: blockName,\n array,\n asFloat: new Float32Array(array), // for debugging\n buffer,\n uniforms,\n setters,\n };\n}\n\n/**\n * Creates a `UniformBlockInfo` for the specified block\n *\n * Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy\n * `UniformBlockInfo` is returned**. This is because when debugging GLSL\n * it is common to comment out large portions of a shader or for example set\n * the final output to a constant. When that happens blocks get optimized out.\n * If this function did not create dummy blocks your code would crash when debugging.\n *\n * @param {WebGL2RenderingContext} gl A WebGL2RenderingContext\n * @param {module:twgl.ProgramInfo} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo}\n * @param {string} blockName The name of the block.\n * @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockInfo(gl, programInfo, blockName) {\n return createUniformBlockInfoFromProgram(gl, programInfo.program, programInfo.uniformBlockSpec, blockName);\n}\n\n/**\n * Binds a uniform block to the matching uniform block point.\n * Matches by blocks by name so blocks must have the same name not just the same\n * structure.\n *\n * If you have changed any values and you upload the values into the corresponding WebGLBuffer\n * call {@link module:twgl.setUniformBlock} instead.\n *\n * @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.\n * @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as\n * returned from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from\n * {@link module:twgl.createUniformBlockInfo}.\n * @return {bool} true if buffer was bound. If the programInfo has no block with the same block name\n * no buffer is bound.\n * @memberOf module:twgl/programs\n */\nfunction bindUniformBlock(gl, programInfo, uniformBlockInfo) {\n const uniformBlockSpec = programInfo.uniformBlockSpec || programInfo;\n const blockSpec = uniformBlockSpec.blockSpecs[uniformBlockInfo.name];\n if (blockSpec) {\n const bufferBindIndex = blockSpec.index;\n gl.bindBufferRange(UNIFORM_BUFFER, bufferBindIndex, uniformBlockInfo.buffer, uniformBlockInfo.offset || 0, uniformBlockInfo.array.byteLength);\n return true;\n }\n return false;\n}\n\n/**\n * Uploads the current uniform values to the corresponding WebGLBuffer\n * and binds that buffer to the program's corresponding bind point for the uniform block object.\n *\n * If you haven't changed any values and you only need to bind the uniform block object\n * call {@link module:twgl.bindUniformBlock} instead.\n *\n * @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.\n * @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as\n * returned from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from\n * {@link module:twgl.createUniformBlockInfo}.\n * @memberOf module:twgl/programs\n */\nfunction setUniformBlock(gl, programInfo, uniformBlockInfo) {\n if (bindUniformBlock(gl, programInfo, uniformBlockInfo)) {\n gl.bufferData(UNIFORM_BUFFER, uniformBlockInfo.array, DYNAMIC_DRAW);\n }\n}\n\n/**\n * Sets values of a uniform block object\n *\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo A UniformBlockInfo as returned by {@link module:twgl.createUniformBlockInfo}.\n * @param {Object.} values A uniform name to value map where the value is correct for the given\n * type of uniform. So for example given a block like\n *\n * uniform SomeBlock {\n * float someFloat;\n * vec2 someVec2;\n * vec3 someVec3Array[2];\n * int someInt;\n * }\n *\n * You can set the values of the uniform block with\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * someFloat: 12.3,\n * someVec2: [1, 2],\n * someVec3Array: [1, 2, 3, 4, 5, 6],\n * someInt: 5,\n * }\n *\n * Arrays can be JavaScript arrays or typed arrays\n *\n * You can also fill out structure and array values either via\n * shortcut. Example\n *\n * // -- in shader --\n * struct Light {\n * float intensity;\n * vec4 color;\n * float nearFar[2];\n * };\n * uniform Lights {\n * Light lights[2];\n * };\n *\n * // in JavaScript\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * lights: [\n * { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },\n * { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },\n * ],\n * });\n *\n * or the more traditional way\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * \"lights[0].intensity\": 5.0,\n * \"lights[0].color\": [1, 0, 0, 1],\n * \"lights[0].nearFar\": [0.1, 10],\n * \"lights[1].intensity\": 2.0,\n * \"lights[1].color\": [0, 0, 1, 1],\n * \"lights[1].nearFar\": [0.2, 15],\n * });\n *\n * You can also specify partial paths\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * 'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },\n * });\n *\n * But you can not specify leaf array indices.\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * 'lights[1].nearFar[1]': 15, // BAD! nearFar is a leaf\n * 'lights[1].nearFar': [0.2, 15], // GOOD\n * });\n *\n * **IMPORTANT!**, packing in a UniformBlock is unintuitive.\n * For example the actual layout of `someVec3Array` above in memory\n * is `1, 2, 3, unused, 4, 5, 6, unused`. twgl takes in 6 values\n * as shown about and copies them, skipping the padding. This might\n * be confusing if you're already familiar with Uniform blocks.\n *\n * If you want to deal with the padding yourself you can access the array\n * buffer views directly. eg:\n *\n * someBlockInfo.someVec3Array.set([1, 2, 3, 0, 4, 5, 6, 0]);\n *\n * Any name that doesn't match will be ignored\n * @memberOf module:twgl/programs\n */\nfunction setBlockUniforms(uniformBlockInfo, values) {\n const setters = uniformBlockInfo.setters;\n for (const name in values) {\n const setter = setters[name];\n if (setter) {\n const value = values[name];\n setter(value);\n }\n }\n}\n\nfunction setUniformTree(tree, values) {\n for (const name in values) {\n const prop = tree[name];\n if (typeof prop === 'function') {\n prop(values[name]);\n } else {\n setUniformTree(tree[name], values[name]);\n }\n }\n}\n\n/**\n * Set uniforms and binds related textures.\n *\n * example:\n *\n * const programInfo = createProgramInfo(\n * gl, [\"some-vs\", \"some-fs\"]);\n *\n * const tex1 = gl.createTexture();\n * const tex2 = gl.createTexture();\n *\n * ... assume we setup the textures with data ...\n *\n * const uniforms = {\n * u_someSampler: tex1,\n * u_someOtherSampler: tex2,\n * u_someColor: [1,0,0,1],\n * u_somePosition: [0,1,1],\n * u_someMatrix: [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ],\n * };\n *\n * gl.useProgram(programInfo.program);\n *\n * This will automatically bind the textures AND set the\n * uniforms.\n *\n * twgl.setUniforms(programInfo, uniforms);\n *\n * For the example above it is equivalent to\n *\n * let texUnit = 0;\n * gl.activeTexture(gl.TEXTURE0 + texUnit);\n * gl.bindTexture(gl.TEXTURE_2D, tex1);\n * gl.uniform1i(u_someSamplerLocation, texUnit++);\n * gl.activeTexture(gl.TEXTURE0 + texUnit);\n * gl.bindTexture(gl.TEXTURE_2D, tex2);\n * gl.uniform1i(u_someSamplerLocation, texUnit++);\n * gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);\n * gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);\n * gl.uniformMatrix4fv(u_someMatrix, false, [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ]);\n *\n * Note it is perfectly reasonable to call `setUniforms` multiple times. For example\n *\n * const uniforms = {\n * u_someSampler: tex1,\n * u_someOtherSampler: tex2,\n * };\n *\n * const moreUniforms {\n * u_someColor: [1,0,0,1],\n * u_somePosition: [0,1,1],\n * u_someMatrix: [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ],\n * };\n *\n * twgl.setUniforms(programInfo, uniforms);\n * twgl.setUniforms(programInfo, moreUniforms);\n *\n * You can also add WebGLSamplers to uniform samplers as in\n *\n * const uniforms = {\n * u_someSampler: {\n * texture: someWebGLTexture,\n * sampler: someWebGLSampler,\n * },\n * };\n *\n * In which case both the sampler and texture will be bound to the\n * same unit.\n *\n * @param {(module:twgl.ProgramInfo|Object.)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from\n * `createUniformSetters`.\n * @param {Object.} values an object with values for the\n * uniforms.\n * You can pass multiple objects by putting them in an array or by calling with more arguments.For example\n *\n * const sharedUniforms = {\n * u_fogNear: 10,\n * u_projection: ...\n * ...\n * };\n *\n * const localUniforms = {\n * u_world: ...\n * u_diffuseColor: ...\n * };\n *\n * twgl.setUniforms(programInfo, sharedUniforms, localUniforms);\n *\n * // is the same as\n *\n * twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]);\n *\n * // is the same as\n *\n * twgl.setUniforms(programInfo, sharedUniforms);\n * twgl.setUniforms(programInfo, localUniforms};\n *\n * You can also fill out structure and array values either via\n * shortcut. Example\n *\n * // -- in shader --\n * struct Light {\n * float intensity;\n * vec4 color;\n * float nearFar[2];\n * };\n * uniform Light lights[2];\n *\n * // in JavaScript\n *\n * twgl.setUniforms(programInfo, {\n * lights: [\n * { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },\n * { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },\n * ],\n * });\n *\n * or the more traditional way\n *\n * twgl.setUniforms(programInfo, {\n * \"lights[0].intensity\": 5.0,\n * \"lights[0].color\": [1, 0, 0, 1],\n * \"lights[0].nearFar\": [0.1, 10],\n * \"lights[1].intensity\": 2.0,\n * \"lights[1].color\": [0, 0, 1, 1],\n * \"lights[1].nearFar\": [0.2, 15],\n * });\n *\n * You can also specify partial paths\n *\n * twgl.setUniforms(programInfo, {\n * 'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },\n * });\n *\n * But you can not specify leaf array indices\n *\n * twgl.setUniforms(programInfo, {\n * 'lights[1].nearFar[1]': 15, // BAD! nearFar is a leaf\n * 'lights[1].nearFar': [0.2, 15], // GOOD\n * });\n *\n * @memberOf module:twgl/programs\n */\nfunction setUniforms(setters, ...args) { // eslint-disable-line\n const actualSetters = setters.uniformSetters || setters;\n const numArgs = args.length;\n for (let aNdx = 0; aNdx < numArgs; ++aNdx) {\n const values = args[aNdx];\n if (Array.isArray(values)) {\n const numValues = values.length;\n for (let ii = 0; ii < numValues; ++ii) {\n setUniforms(actualSetters, values[ii]);\n }\n } else {\n for (const name in values) {\n const setter = actualSetters[name];\n if (setter) {\n setter(values[name]);\n }\n }\n }\n }\n}\n\n/**\n * Alias for `setUniforms`\n * @function\n * @param {(module:twgl.ProgramInfo|Object.)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from\n * `createUniformSetters`.\n * @param {Object.} values an object with values for the\n * @memberOf module:twgl/programs\n */\nconst setUniformsAndBindTextures = setUniforms;\n\n/**\n * Creates setter functions for all attributes of a shader\n * program. You can pass this to {@link module:twgl.setBuffersAndAttributes} to set all your buffers and attributes.\n *\n * @see {@link module:twgl.setAttributes} for example\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program the program to create setters for.\n * @return {Object.} an object with a setter for each attribute by name.\n * @memberOf module:twgl/programs\n */\nfunction createAttributeSetters(gl, program) {\n const attribSetters = {\n };\n\n const numAttribs = gl.getProgramParameter(program, ACTIVE_ATTRIBUTES);\n for (let ii = 0; ii < numAttribs; ++ii) {\n const attribInfo = gl.getActiveAttrib(program, ii);\n if (isBuiltIn(attribInfo)) {\n continue;\n }\n const index = gl.getAttribLocation(program, attribInfo.name);\n const typeInfo = attrTypeMap[attribInfo.type];\n const setter = typeInfo.setter(gl, index, typeInfo);\n setter.location = index;\n attribSetters[attribInfo.name] = setter;\n }\n\n return attribSetters;\n}\n\n/**\n * Sets attributes and binds buffers (deprecated... use {@link module:twgl.setBuffersAndAttributes})\n *\n * Example:\n *\n * const program = createProgramFromScripts(\n * gl, [\"some-vs\", \"some-fs\");\n *\n * const attribSetters = createAttributeSetters(program);\n *\n * const positionBuffer = gl.createBuffer();\n * const texcoordBuffer = gl.createBuffer();\n *\n * const attribs = {\n * a_position: {buffer: positionBuffer, numComponents: 3},\n * a_texcoord: {buffer: texcoordBuffer, numComponents: 2},\n * };\n *\n * gl.useProgram(program);\n *\n * This will automatically bind the buffers AND set the\n * attributes.\n *\n * setAttributes(attribSetters, attribs);\n *\n * Properties of attribs. For each attrib you can add\n * properties:\n *\n * * type: the type of data in the buffer. Default = gl.FLOAT\n * * normalize: whether or not to normalize the data. Default = false\n * * stride: the stride. Default = 0\n * * offset: offset into the buffer. Default = 0\n * * divisor: the divisor for instances. Default = undefined\n *\n * For example if you had 3 value float positions, 2 value\n * float texcoord and 4 value uint8 colors you'd setup your\n * attribs like this\n *\n * const attribs = {\n * a_position: {buffer: positionBuffer, numComponents: 3},\n * a_texcoord: {buffer: texcoordBuffer, numComponents: 2},\n * a_color: {\n * buffer: colorBuffer,\n * numComponents: 4,\n * type: gl.UNSIGNED_BYTE,\n * normalize: true,\n * },\n * };\n *\n * @param {Object.} setters Attribute setters as returned from createAttributeSetters\n * @param {Object.} buffers AttribInfos mapped by attribute name.\n * @memberOf module:twgl/programs\n * @deprecated use {@link module:twgl.setBuffersAndAttributes}\n * @private\n */\nfunction setAttributes(setters, buffers) {\n for (const name in buffers) {\n const setter = setters[name];\n if (setter) {\n setter(buffers[name]);\n }\n }\n}\n\n/**\n * Sets attributes and buffers including the `ELEMENT_ARRAY_BUFFER` if appropriate\n *\n * Example:\n *\n * const programInfo = createProgramInfo(\n * gl, [\"some-vs\", \"some-fs\");\n *\n * const arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * };\n *\n * const bufferInfo = createBufferInfoFromArrays(gl, arrays);\n *\n * gl.useProgram(programInfo.program);\n *\n * This will automatically bind the buffers AND set the\n * attributes.\n *\n * setBuffersAndAttributes(gl, programInfo, bufferInfo);\n *\n * For the example above it is equivalent to\n *\n * gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n * gl.enableVertexAttribArray(a_positionLocation);\n * gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);\n * gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);\n * gl.enableVertexAttribArray(a_texcoordLocation);\n * gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {(module:twgl.ProgramInfo|Object.)} setters A `ProgramInfo` as returned from {@link module:twgl.createProgramInfo} or Attribute setters as returned from {@link module:twgl.createAttributeSetters}\n * @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} buffers a `BufferInfo` as returned from {@link module:twgl.createBufferInfoFromArrays}.\n * or a `VertexArrayInfo` as returned from {@link module:twgl.createVertexArrayInfo}\n * @memberOf module:twgl/programs\n */\nfunction setBuffersAndAttributes(gl, programInfo, buffers) {\n if (buffers.vertexArrayObject) {\n gl.bindVertexArray(buffers.vertexArrayObject);\n } else {\n setAttributes(programInfo.attribSetters || programInfo, buffers.attribs);\n if (buffers.indices) {\n gl.bindBuffer(ELEMENT_ARRAY_BUFFER$1, buffers.indices);\n }\n }\n}\n\n/**\n * @typedef {Object} ProgramInfo\n * @property {WebGLProgram} program A shader program\n * @property {Object} uniformSetters object of setters as returned from createUniformSetters,\n * @property {Object} attribSetters object of setters as returned from createAttribSetters,\n * @property {module:twgl.UniformBlockSpec} [uniformBlockSpec] a uniform block spec for making UniformBlockInfos with createUniformBlockInfo etc..\n * @property {Object} [transformFeedbackInfo] info for transform feedbacks\n * @memberOf module:twgl\n */\n\n/**\n * Creates a ProgramInfo from an existing program.\n *\n * A ProgramInfo contains\n *\n * programInfo = {\n * program: WebGLProgram,\n * uniformSetters: object of setters as returned from createUniformSetters,\n * attribSetters: object of setters as returned from createAttribSetters,\n * }\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {WebGLProgram} program an existing WebGLProgram.\n * @return {module:twgl.ProgramInfo} The created ProgramInfo.\n * @memberOf module:twgl/programs\n */\nfunction createProgramInfoFromProgram(gl, program) {\n const uniformSetters = createUniformSetters(gl, program);\n const attribSetters = createAttributeSetters(gl, program);\n const programInfo = {\n program,\n uniformSetters,\n attribSetters,\n };\n\n if (isWebGL2(gl)) {\n programInfo.uniformBlockSpec = createUniformBlockSpecFromProgram(gl, program);\n programInfo.transformFeedbackInfo = createTransformFeedbackInfo(gl, program);\n }\n\n return programInfo;\n}\n\nconst notIdRE = /\\s|{|}|;/;\n\n/**\n * Creates a ProgramInfo from 2 sources.\n *\n * A ProgramInfo contains\n *\n * programInfo = {\n * program: WebGLProgram,\n * uniformSetters: object of setters as returned from createUniformSetters,\n * attribSetters: object of setters as returned from createAttribSetters,\n * }\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramInfo(gl, [vs, fs], options);\n * twgl.createProgramInfo(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders or ids. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]|module:twgl.ErrorCallback} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {module:twgl.ProgramInfo?} The created ProgramInfo or null if it failed to link or compile\n * @memberOf module:twgl/programs\n */\nfunction createProgramInfo(\n gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const errors = [];\n shaderSources = shaderSources.map(function(source) {\n // Lets assume if there is no \\n it's an id\n if (!notIdRE.test(source)) {\n const script = getElementById(source);\n if (!script) {\n const err = `no element with id: ${source}`;\n progOptions.errorCallback(err);\n errors.push(err);\n } else {\n source = script.text;\n }\n }\n return source;\n });\n\n if (errors.length) {\n return reportError(progOptions, '');\n }\n\n const origCallback = progOptions.callback;\n if (origCallback) {\n progOptions.callback = (err, program) => {\n origCallback(err, err ? undefined : createProgramInfoFromProgram(gl, program));\n };\n }\n\n const program = createProgramFromSources(gl, shaderSources, progOptions);\n if (!program) {\n return null;\n }\n\n return createProgramInfoFromProgram(gl, program);\n}\n\nfunction checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions) {\n // check errors for everything.\n for (const [name, program] of Object.entries(programs)) {\n const options = {...programOptions};\n const spec = programSpecs[name];\n if (!Array.isArray(spec)) {\n Object.assign(options, spec);\n }\n const errors = getProgramErrors(gl, program, options.errorCallback);\n if (errors) {\n // delete everything we created\n for (const program of Object.values(programs)) {\n const shaders = gl.getAttachedShaders(program);\n gl.deleteProgram(program);\n for (const shader of shaders) {\n // Don't delete it if we didn't create it.\n if (!noDeleteShadersSet.has(shader)) {\n gl.deleteShader(shader);\n }\n }\n }\n return errors;\n }\n }\n\n return undefined;\n}\n\n/**\n * Creates multiple programs\n *\n * Note: the reason this function exists is because the fastest way to create multiple\n * programs in WebGL is to create and compile all shaders and link all programs and only\n * afterwards check if they succeeded. In that way, giving all your shaders\n *\n * @see {@link module:twgl.createProgram}\n *\n * Example:\n *\n * const programs = twgl.createPrograms(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nfunction createPrograms(gl, programSpecs, programOptions = {}) {\n // Remember existing shaders so that if there is an error we don't delete them\n const noDeleteShadersSet = new Set();\n\n // compile and link everything\n const programs = Object.fromEntries(Object.entries(programSpecs).map(([name, spec]) => {\n const options = {...programOptions};\n const shaders = Array.isArray(spec) ? spec : spec.shaders;\n if (!Array.isArray(spec)) {\n Object.assign(options, spec);\n }\n shaders.forEach(noDeleteShadersSet.add, noDeleteShadersSet);\n return [name, createProgramNoCheck(gl, shaders, options)];\n }));\n\n if (programOptions.callback) {\n waitForAllProgramsLinkCompletionAsync(gl, programs).then(() => {\n const errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);\n programOptions.callback(errors, errors ? undefined : programs);\n });\n return undefined;\n }\n\n const errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);\n return errors ? undefined : programs;\n}\n\n/**\n * Creates multiple programInfos\n *\n * Note: the reason this function exists is because the fastest way to create multiple\n * programs in WebGL is to create and compile all shaders and link all programs and only\n * afterwards check if they succeeded. In that way, giving all your shaders\n *\n * @see {@link module:twgl.createProgramInfo}\n *\n * Examples:\n *\n * const programInfos = twgl.createProgramInfos(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * or\n *\n * const {lambert, phong, particles} = twgl.createProgramInfos(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nfunction createProgramInfos(gl, programSpecs, programOptions) {\n programOptions = getProgramOptions(programOptions);\n\n function createProgramInfosForPrograms(gl, programs) {\n return Object.fromEntries(Object.entries(programs).map(([name, program]) =>\n [name, createProgramInfoFromProgram(gl, program)]\n ));\n }\n\n const origCallback = programOptions.callback;\n if (origCallback) {\n programOptions.callback = (err, programs) => {\n origCallback(err, err ? undefined : createProgramInfosForPrograms(gl, programs));\n };\n }\n\n const programs = createPrograms(gl, programSpecs, programOptions);\n if (origCallback || !programs) {\n return undefined;\n }\n\n return createProgramInfosForPrograms(gl, programs);\n}\n\n/**\n * Creates multiple programs asynchronously\n *\n * @see {@link module:twgl.createProgramAsync}\n *\n * Example:\n *\n * const programs = await twgl.createProgramsAsync(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @function\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nconst createProgramsAsync = wrapCallbackFnToAsyncFn(createPrograms);\n\n/**\n * Creates multiple programInfos asynchronously\n *\n * @see {@link module:twgl.createProgramInfoAsync}\n *\n * Example:\n *\n * const programInfos = await twgl.createProgramInfosAsync(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @function\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Promise>} the created programInfos by name\n */\nconst createProgramInfosAsync = wrapCallbackFnToAsyncFn(createProgramInfos);\n\nvar programs = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createAttributeSetters: createAttributeSetters,\n createProgram: createProgram,\n createProgramAsync: createProgramAsync,\n createPrograms: createPrograms,\n createProgramsAsync: createProgramsAsync,\n createProgramFromScripts: createProgramFromScripts,\n createProgramFromSources: createProgramFromSources,\n createProgramInfo: createProgramInfo,\n createProgramInfoAsync: createProgramInfoAsync,\n createProgramInfos: createProgramInfos,\n createProgramInfosAsync: createProgramInfosAsync,\n createProgramInfoFromProgram: createProgramInfoFromProgram,\n createUniformSetters: createUniformSetters,\n createUniformBlockSpecFromProgram: createUniformBlockSpecFromProgram,\n createUniformBlockInfoFromProgram: createUniformBlockInfoFromProgram,\n createUniformBlockInfo: createUniformBlockInfo,\n createTransformFeedback: createTransformFeedback,\n createTransformFeedbackInfo: createTransformFeedbackInfo,\n bindTransformFeedbackInfo: bindTransformFeedbackInfo,\n setAttributes: setAttributes,\n setBuffersAndAttributes: setBuffersAndAttributes,\n setUniforms: setUniforms,\n setUniformsAndBindTextures: setUniformsAndBindTextures,\n setUniformBlock: setUniformBlock,\n setBlockUniforms: setBlockUniforms,\n bindUniformBlock: bindUniformBlock\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst TRIANGLES = 0x0004;\nconst UNSIGNED_SHORT = 0x1403;\n\n/**\n * Drawing related functions\n *\n * For backward compatibility they are available at both `twgl.draw` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/draw\n */\n\n/**\n * Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate\n *\n * normally you'd call `gl.drawElements` or `gl.drawArrays` yourself\n * but calling this means if you switch from indexed data to non-indexed\n * data you don't have to remember to update your draw call.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} bufferInfo A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays} or\n * a VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}\n * @param {number} [type] eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...). Defaults to `gl.TRIANGLES`\n * @param {number} [count] An optional count. Defaults to bufferInfo.numElements\n * @param {number} [offset] An optional offset. Defaults to 0.\n * @param {number} [instanceCount] An optional instanceCount. if set then `drawArraysInstanced` or `drawElementsInstanced` will be called\n * @memberOf module:twgl/draw\n */\nfunction drawBufferInfo(gl, bufferInfo, type, count, offset, instanceCount) {\n type = type === undefined ? TRIANGLES : type;\n const indices = bufferInfo.indices;\n const elementType = bufferInfo.elementType;\n const numElements = count === undefined ? bufferInfo.numElements : count;\n offset = offset === undefined ? 0 : offset;\n if (elementType || indices) {\n if (instanceCount !== undefined) {\n gl.drawElementsInstanced(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset, instanceCount);\n } else {\n gl.drawElements(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset);\n }\n } else {\n if (instanceCount !== undefined) {\n gl.drawArraysInstanced(type, offset, numElements, instanceCount);\n } else {\n gl.drawArrays(type, offset, numElements);\n }\n }\n}\n\n/**\n * A DrawObject is useful for putting objects in to an array and passing them to {@link module:twgl.drawObjectList}.\n *\n * You need either a `BufferInfo` or a `VertexArrayInfo`.\n *\n * @typedef {Object} DrawObject\n * @property {boolean} [active] whether or not to draw. Default = `true` (must be `false` to be not true). In other words `undefined` = `true`\n * @property {number} [type] type to draw eg. `gl.TRIANGLES`, `gl.LINES`, etc...\n * @property {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}\n * @property {module:twgl.BufferInfo} [bufferInfo] A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays}\n * @property {module:twgl.VertexArrayInfo} [vertexArrayInfo] A VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}\n * @property {Object} uniforms The values for the uniforms.\n * You can pass multiple objects by putting them in an array. For example\n *\n * var sharedUniforms = {\n * u_fogNear: 10,\n * u_projection: ...\n * ...\n * };\n *\n * var localUniforms = {\n * u_world: ...\n * u_diffuseColor: ...\n * };\n *\n * var drawObj = {\n * ...\n * uniforms: [sharedUniforms, localUniforms],\n * };\n *\n * @property {number} [offset] the offset to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to 0.\n * @property {number} [count] the count to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to bufferInfo.numElements.\n * @property {number} [instanceCount] the number of instances. Defaults to undefined.\n * @memberOf module:twgl\n */\n\n/**\n * Draws a list of objects\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {DrawObject[]} objectsToDraw an array of objects to draw.\n * @memberOf module:twgl/draw\n */\nfunction drawObjectList(gl, objectsToDraw) {\n let lastUsedProgramInfo = null;\n let lastUsedBufferInfo = null;\n\n objectsToDraw.forEach(function(object) {\n if (object.active === false) {\n return;\n }\n\n const programInfo = object.programInfo;\n const bufferInfo = object.vertexArrayInfo || object.bufferInfo;\n let bindBuffers = false;\n const type = object.type === undefined ? TRIANGLES : object.type;\n\n if (programInfo !== lastUsedProgramInfo) {\n lastUsedProgramInfo = programInfo;\n gl.useProgram(programInfo.program);\n\n // We have to rebind buffers when changing programs because we\n // only bind buffers the program uses. So if 2 programs use the same\n // bufferInfo but the 1st one uses only positions the when the\n // we switch to the 2nd one some of the attributes will not be on.\n bindBuffers = true;\n }\n\n // Setup all the needed attributes.\n if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {\n if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject && !bufferInfo.vertexArrayObject) {\n gl.bindVertexArray(null);\n }\n lastUsedBufferInfo = bufferInfo;\n setBuffersAndAttributes(gl, programInfo, bufferInfo);\n }\n\n // Set the uniforms.\n setUniforms(programInfo, object.uniforms);\n\n // Draw\n drawBufferInfo(gl, bufferInfo, type, object.count, object.offset, object.instanceCount);\n });\n\n if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject) {\n gl.bindVertexArray(null);\n }\n}\n\nvar draw = /*#__PURE__*/Object.freeze({\n __proto__: null,\n drawBufferInfo: drawBufferInfo,\n drawObjectList: drawObjectList\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst FRAMEBUFFER = 0x8d40;\nconst RENDERBUFFER = 0x8d41;\nconst TEXTURE_2D = 0x0de1;\n\nconst UNSIGNED_BYTE = 0x1401;\n\n/* PixelFormat */\nconst DEPTH_COMPONENT = 0x1902;\nconst RGBA = 0x1908;\nconst DEPTH_COMPONENT24 = 0x81a6;\nconst DEPTH_COMPONENT32F = 0x8cac;\nconst DEPTH24_STENCIL8 = 0x88f0;\nconst DEPTH32F_STENCIL8 = 0x8cad;\n\n/* Framebuffer Object. */\nconst RGBA4 = 0x8056;\nconst RGB5_A1 = 0x8057;\nconst RGB565 = 0x8D62;\nconst DEPTH_COMPONENT16 = 0x81A5;\nconst STENCIL_INDEX = 0x1901;\nconst STENCIL_INDEX8 = 0x8D48;\nconst DEPTH_STENCIL = 0x84F9;\nconst COLOR_ATTACHMENT0 = 0x8CE0;\nconst DEPTH_ATTACHMENT = 0x8D00;\nconst STENCIL_ATTACHMENT = 0x8D20;\nconst DEPTH_STENCIL_ATTACHMENT = 0x821A;\n\n/* TextureWrapMode */\nconst CLAMP_TO_EDGE = 0x812F;\n\n/* TextureMagFilter */\nconst LINEAR = 0x2601;\n\n/**\n * The options for a framebuffer attachment.\n *\n * Note: For a `format` that is a texture include all the texture\n * options from {@link module:twgl.TextureOptions} for example\n * `min`, `mag`, `clamp`, etc... Note that unlike {@link module:twgl.TextureOptions}\n * `auto` defaults to `false` for attachment textures but `min` and `mag` default\n * to `gl.LINEAR` and `wrap` defaults to `CLAMP_TO_EDGE`\n *\n * @typedef {Object} AttachmentOptions\n * @property {number} [attachmentPoint] The attachment point. Defaults\n * to `gl.COLOR_ATTACHMENT0 + ndx` unless type is a depth or stencil type\n * then it's gl.DEPTH_ATTACHMENT or `gl.DEPTH_STENCIL_ATTACHMENT` depending\n * on the format or attachment type.\n * @property {number} [format] The format. If one of `gl.RGBA4`,\n * `gl.RGB565`, `gl.RGB5_A1`, `gl.DEPTH_COMPONENT16`,\n * `gl.STENCIL_INDEX8` or `gl.DEPTH_STENCIL` then will create a\n * renderbuffer. Otherwise will create a texture. Default = `gl.RGBA`\n * @property {number} [type] The type. Used for texture. Default = `gl.UNSIGNED_BYTE`.\n * @property {number} [target] The texture target for `gl.framebufferTexture2D`.\n * Defaults to `gl.TEXTURE_2D`. Set to appropriate face for cube maps.\n * @property {number} [samples] The number of samples. Default = 1\n * @property {number} [level] level for `gl.framebufferTexture2D`. Defaults to 0.\n * @property {number} [layer] layer for `gl.framebufferTextureLayer`. Defaults to undefined.\n * If set then `gl.framebufferTextureLayer` is called, if not then `gl.framebufferTexture2D`\n * @property {(WebGLRenderbuffer | WebGLTexture)} [attachment] An existing renderbuffer or texture.\n * If provided will attach this Object. This allows you to share\n * attachments across framebuffers.\n * @memberOf module:twgl\n * @mixes module:twgl.TextureOptions\n */\n\nconst defaultAttachments = [\n { format: RGBA, type: UNSIGNED_BYTE, min: LINEAR, wrap: CLAMP_TO_EDGE, },\n { format: DEPTH_STENCIL, },\n];\n\nconst attachmentsByFormat = {};\nattachmentsByFormat[DEPTH_STENCIL] = DEPTH_STENCIL_ATTACHMENT;\nattachmentsByFormat[STENCIL_INDEX] = STENCIL_ATTACHMENT;\nattachmentsByFormat[STENCIL_INDEX8] = STENCIL_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT16] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT24] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT32F] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH24_STENCIL8] = DEPTH_STENCIL_ATTACHMENT;\nattachmentsByFormat[DEPTH32F_STENCIL8] = DEPTH_STENCIL_ATTACHMENT;\n\nfunction getAttachmentPointForFormat(format, internalFormat) {\n return attachmentsByFormat[format] || attachmentsByFormat[internalFormat];\n}\n\nconst renderbufferFormats = {};\nrenderbufferFormats[RGBA4] = true;\nrenderbufferFormats[RGB5_A1] = true;\nrenderbufferFormats[RGB565] = true;\nrenderbufferFormats[DEPTH_STENCIL] = true;\nrenderbufferFormats[DEPTH_COMPONENT16] = true;\nrenderbufferFormats[STENCIL_INDEX] = true;\nrenderbufferFormats[STENCIL_INDEX8] = true;\n\nfunction isRenderbufferFormat(format) {\n return renderbufferFormats[format];\n}\n\nconst MAX_COLOR_ATTACHMENT_POINTS = 32; // even an 3090 only supports 8 but WebGL/OpenGL ES define constants for 32\n\nfunction isColorAttachmentPoint(attachmentPoint) {\n return attachmentPoint >= COLOR_ATTACHMENT0 && attachmentPoint < COLOR_ATTACHMENT0 + MAX_COLOR_ATTACHMENT_POINTS;\n}\n\n/**\n * @typedef {Object} FramebufferInfo\n * @property {WebGLFramebuffer} framebuffer The WebGLFramebuffer for this framebufferInfo\n * @property {Array.<(WebGLRenderbuffer | WebGLTexture)>} attachments The created attachments in the same order as passed in to {@link module:twgl.createFramebufferInfo}.\n * @property {number} width The width of the framebuffer and its attachments\n * @property {number} height The width of the framebuffer and its attachments\n * @memberOf module:twgl\n */\n\n/**\n * Creates a framebuffer and attachments.\n *\n * This returns a {@link module:twgl.FramebufferInfo} because it needs to return the attachments as well as the framebuffer.\n * It also leaves the framebuffer it just created as the currently bound `FRAMEBUFFER`.\n * Note: If this is WebGL2 or if you called {@link module:twgl.addExtensionsToContext} then it will set the drawBuffers\n * to `[COLOR_ATTACHMENT0, COLOR_ATTACHMENT1, ...]` for how ever many color attachments were created.\n *\n * The simplest usage\n *\n * // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer\n * const fbi = twgl.createFramebufferInfo(gl);\n *\n * More complex usage\n *\n * // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer\n * const attachments = [\n * { format: RGB565, mag: NEAREST },\n * { format: STENCIL_INDEX8 },\n * ]\n * const fbi = twgl.createFramebufferInfo(gl, attachments);\n *\n * Passing in a specific size\n *\n * const width = 256;\n * const height = 256;\n * const fbi = twgl.createFramebufferInfo(gl, attachments, width, height);\n *\n * **Note!!** It is up to you to check if the framebuffer is renderable by calling `gl.checkFramebufferStatus`.\n * [WebGL1 only guarantees 3 combinations of attachments work](https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.6).\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.AttachmentOptions[]} [attachments] which attachments to create. If not provided the default is a framebuffer with an\n * `RGBA`, `UNSIGNED_BYTE` texture `COLOR_ATTACHMENT0` and a `DEPTH_STENCIL` renderbuffer `DEPTH_STENCIL_ATTACHMENT`.\n * @param {number} [width] the width for the attachments. Default = size of drawingBuffer\n * @param {number} [height] the height for the attachments. Default = size of drawingBuffer\n * @return {module:twgl.FramebufferInfo} the framebuffer and attachments.\n * @memberOf module:twgl/framebuffers\n */\nfunction createFramebufferInfo(gl, attachments, width, height) {\n const target = FRAMEBUFFER;\n const fb = gl.createFramebuffer();\n gl.bindFramebuffer(target, fb);\n width = width || gl.drawingBufferWidth;\n height = height || gl.drawingBufferHeight;\n attachments = attachments || defaultAttachments;\n const usedColorAttachmentsPoints = [];\n const framebufferInfo = {\n framebuffer: fb,\n attachments: [],\n width: width,\n height: height,\n };\n\n attachments.forEach(function(attachmentOptions, i) {\n let attachment = attachmentOptions.attachment;\n const samples = attachmentOptions.samples;\n const format = attachmentOptions.format;\n let attachmentPoint = attachmentOptions.attachmentPoint || getAttachmentPointForFormat(format, attachmentOptions.internalFormat);\n if (!attachmentPoint) {\n attachmentPoint = COLOR_ATTACHMENT0 + i;\n }\n if (isColorAttachmentPoint(attachmentPoint)) {\n usedColorAttachmentsPoints.push(attachmentPoint);\n }\n if (!attachment) {\n if (samples !== undefined || isRenderbufferFormat(format)) {\n attachment = gl.createRenderbuffer();\n gl.bindRenderbuffer(RENDERBUFFER, attachment);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(RENDERBUFFER, samples, format, width, height);\n } else {\n gl.renderbufferStorage(RENDERBUFFER, format, width, height);\n }\n } else {\n const textureOptions = Object.assign({}, attachmentOptions);\n textureOptions.width = width;\n textureOptions.height = height;\n if (textureOptions.auto === undefined) {\n textureOptions.auto = false;\n textureOptions.min = textureOptions.min || textureOptions.minMag || LINEAR;\n textureOptions.mag = textureOptions.mag || textureOptions.minMag || LINEAR;\n textureOptions.wrapS = textureOptions.wrapS || textureOptions.wrap || CLAMP_TO_EDGE;\n textureOptions.wrapT = textureOptions.wrapT || textureOptions.wrap || CLAMP_TO_EDGE;\n }\n attachment = createTexture(gl, textureOptions);\n }\n }\n if (isRenderbuffer(gl, attachment)) {\n gl.framebufferRenderbuffer(target, attachmentPoint, RENDERBUFFER, attachment);\n } else if (isTexture(gl, attachment)) {\n if (attachmentOptions.layer !== undefined) {\n gl.framebufferTextureLayer(\n target,\n attachmentPoint,\n attachment,\n attachmentOptions.level || 0,\n attachmentOptions.layer);\n } else {\n gl.framebufferTexture2D(\n target,\n attachmentPoint,\n attachmentOptions.target || TEXTURE_2D,\n attachment,\n attachmentOptions.level || 0);\n }\n } else {\n throw new Error('unknown attachment type');\n }\n framebufferInfo.attachments.push(attachment);\n });\n if (gl.drawBuffers) {\n gl.drawBuffers(usedColorAttachmentsPoints);\n }\n return framebufferInfo;\n}\n\n/**\n * Resizes the attachments of a framebuffer.\n *\n * You need to pass in the same `attachments` as you passed in {@link module:twgl.createFramebufferInfo}\n * because TWGL has no idea the format/type of each attachment.\n *\n * The simplest usage\n *\n * // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer\n * const fbi = twgl.createFramebufferInfo(gl);\n *\n * ...\n *\n * function render() {\n * if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {\n * // resize the attachments\n * twgl.resizeFramebufferInfo(gl, fbi);\n * }\n *\n * More complex usage\n *\n * // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer\n * const attachments = [\n * { format: RGB565, mag: NEAREST },\n * { format: STENCIL_INDEX8 },\n * ]\n * const fbi = twgl.createFramebufferInfo(gl, attachments);\n *\n * ...\n *\n * function render() {\n * if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {\n * // resize the attachments to match\n * twgl.resizeFramebufferInfo(gl, fbi, attachments);\n * }\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.FramebufferInfo} framebufferInfo a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.\n * @param {module:twgl.AttachmentOptions[]} [attachments] the same attachments options as passed to {@link module:twgl.createFramebufferInfo}.\n * @param {number} [width] the width for the attachments. Default = size of drawingBuffer\n * @param {number} [height] the height for the attachments. Default = size of drawingBuffer\n * @memberOf module:twgl/framebuffers\n */\nfunction resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) {\n width = width || gl.drawingBufferWidth;\n height = height || gl.drawingBufferHeight;\n framebufferInfo.width = width;\n framebufferInfo.height = height;\n attachments = attachments || defaultAttachments;\n attachments.forEach(function(attachmentOptions, ndx) {\n const attachment = framebufferInfo.attachments[ndx];\n const format = attachmentOptions.format;\n const samples = attachmentOptions.samples;\n if (samples !== undefined || isRenderbuffer(gl, attachment)) {\n gl.bindRenderbuffer(RENDERBUFFER, attachment);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(RENDERBUFFER, samples, format, width, height);\n } else {\n gl.renderbufferStorage(RENDERBUFFER, format, width, height);\n }\n } else if (isTexture(gl, attachment)) {\n resizeTexture(gl, attachment, attachmentOptions, width, height);\n } else {\n throw new Error('unknown attachment type');\n }\n });\n}\n\n/**\n * Binds a framebuffer\n *\n * This function pretty much solely exists because I spent hours\n * trying to figure out why something I wrote wasn't working only\n * to realize I forget to set the viewport dimensions.\n * My hope is this function will fix that.\n *\n * It is effectively the same as\n *\n * gl.bindFramebuffer(gl.FRAMEBUFFER, someFramebufferInfo.framebuffer);\n * gl.viewport(0, 0, someFramebufferInfo.width, someFramebufferInfo.height);\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.FramebufferInfo|null} [framebufferInfo] a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.\n * If falsy will bind the canvas.\n * @param {number} [target] The target. If not passed `gl.FRAMEBUFFER` will be used.\n * @memberOf module:twgl/framebuffers\n */\n\nfunction bindFramebufferInfo(gl, framebufferInfo, target) {\n target = target || FRAMEBUFFER;\n if (framebufferInfo) {\n gl.bindFramebuffer(target, framebufferInfo.framebuffer);\n gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height);\n } else {\n gl.bindFramebuffer(target, null);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n }\n}\n\nvar framebuffers = /*#__PURE__*/Object.freeze({\n __proto__: null,\n bindFramebufferInfo: bindFramebufferInfo,\n createFramebufferInfo: createFramebufferInfo,\n resizeFramebufferInfo: resizeFramebufferInfo\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * vertex array object related functions\n *\n * You should generally not need to use these functions. They are provided\n * for those cases where you're doing something out of the ordinary\n * and you need lower level access.\n *\n * For backward compatibility they are available at both `twgl.attributes` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/vertexArrays\n */\n\nconst ELEMENT_ARRAY_BUFFER = 0x8893;\n\n/**\n * @typedef {Object} VertexArrayInfo\n * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.\n * @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..\n * @property {WebGLVertexArrayObject} [vertexArrayObject] a vertex array object\n * @memberOf module:twgl\n */\n\n/**\n * Creates a VertexArrayInfo from a BufferInfo and one or more ProgramInfos\n *\n * This can be passed to {@link module:twgl.setBuffersAndAttributes} and to\n * {@link module:twgl:drawBufferInfo}.\n *\n * > **IMPORTANT:** Vertex Array Objects are **not** a direct analog for a BufferInfo. Vertex Array Objects\n * assign buffers to specific attributes at creation time. That means they can only be used with programs\n * who's attributes use the same attribute locations for the same purposes.\n *\n * > Bind your attribute locations by passing an array of attribute names to {@link module:twgl.createProgramInfo}\n * or use WebGL 2's GLSL ES 3's `layout(location = )` to make sure locations match.\n *\n * also\n *\n * > **IMPORTANT:** After calling twgl.setBuffersAndAttribute with a BufferInfo that uses a Vertex Array Object\n * that Vertex Array Object will be bound. That means **ANY MANIPULATION OF ELEMENT_ARRAY_BUFFER or ATTRIBUTES**\n * will affect the Vertex Array Object state.\n *\n * > Call `gl.bindVertexArray(null)` to get back manipulating the global attributes and ELEMENT_ARRAY_BUFFER.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.ProgramInfo|module:twgl.ProgramInfo[]} programInfo a programInfo or array of programInfos\n * @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...\n *\n * You need to make sure every attribute that will be used is bound. So for example assume shader 1\n * uses attributes A, B, C and shader 2 uses attributes A, B, D. If you only pass in the programInfo\n * for shader 1 then only attributes A, B, and C will have their attributes set because TWGL doesn't\n * now attribute D's location.\n *\n * So, you can pass in both shader 1 and shader 2's programInfo\n *\n * @return {module:twgl.VertexArrayInfo} The created VertexArrayInfo\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVertexArrayInfo(gl, programInfos, bufferInfo) {\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n if (!programInfos.length) {\n programInfos = [programInfos];\n }\n programInfos.forEach(function(programInfo) {\n setBuffersAndAttributes(gl, programInfo, bufferInfo);\n });\n gl.bindVertexArray(null);\n return {\n numElements: bufferInfo.numElements,\n elementType: bufferInfo.elementType,\n vertexArrayObject: vao,\n };\n}\n\n/**\n * Creates a vertex array object and then sets the attributes on it\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {Object.} setters Attribute setters as returned from createAttributeSetters\n * @param {Object.} attribs AttribInfos mapped by attribute name.\n * @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices\n *\n * @return {WebGLVertexArrayObject|null} The created WebGLVertexArrayObject\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVAOAndSetAttributes(gl, setters, attribs, indices) {\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n setAttributes(setters, attribs);\n if (indices) {\n gl.bindBuffer(ELEMENT_ARRAY_BUFFER, indices);\n }\n // We unbind this because otherwise any change to ELEMENT_ARRAY_BUFFER\n // like when creating buffers for other stuff will mess up this VAO's binding\n gl.bindVertexArray(null);\n return vao;\n}\n\n/**\n * Creates a vertex array object and then sets the attributes\n * on it\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {Object.| module:twgl.ProgramInfo} programInfo as returned from createProgramInfo or Attribute setters as returned from createAttributeSetters\n * @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...\n * @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices\n *\n * @return {WebGLVertexArrayObject|null} The created WebGLVertexArrayObject\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVAOFromBufferInfo(gl, programInfo, bufferInfo) {\n return createVAOAndSetAttributes(gl, programInfo.attribSetters || programInfo, bufferInfo.attribs, bufferInfo.indices);\n}\n\nvar vertexArrays = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createVertexArrayInfo: createVertexArrayInfo,\n createVAOAndSetAttributes: createVAOAndSetAttributes,\n createVAOFromBufferInfo: createVAOFromBufferInfo\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nconst defaults = {\n addExtensionsToContext: true,\n};\n\n/**\n * Various default settings for twgl.\n *\n * Note: You can call this any number of times. Example:\n *\n * twgl.setDefaults({ textureColor: [1, 0, 0, 1] });\n * twgl.setDefaults({ attribPrefix: 'a_' });\n *\n * is equivalent to\n *\n * twgl.setDefaults({\n * textureColor: [1, 0, 0, 1],\n * attribPrefix: 'a_',\n * });\n *\n * @typedef {Object} Defaults\n * @property {string} [attribPrefix] The prefix to stick on attributes\n *\n * When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`\n * as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.\n *\n * In other words I'll create arrays of geometry like this\n *\n * const arrays = {\n * position: ...\n * normal: ...\n * texcoord: ...\n * };\n *\n * But need those mapped to attributes and my attributes start with `a_`.\n *\n * Default: `\"\"`\n *\n * @property {number[]} [textureColor] Array of 4 values in the range 0 to 1\n *\n * The default texture color is used when loading textures from\n * urls. Because the URL will be loaded async we'd like to be\n * able to use the texture immediately. By putting a 1x1 pixel\n * color in the texture we can start using the texture before\n * the URL has loaded.\n *\n * Default: `[0.5, 0.75, 1, 1]`\n *\n * @property {string} [crossOrigin]\n *\n * If not undefined sets the crossOrigin attribute on images\n * that twgl creates when downloading images for textures.\n *\n * Also see {@link module:twgl.TextureOptions}.\n *\n * @property {bool} [addExtensionsToContext]\n *\n * If true, then, when twgl will try to add any supported WebGL extensions\n * directly to the context under their normal GL names. For example\n * if ANGLE_instances_arrays exists then twgl would enable it,\n * add the functions `vertexAttribDivisor`, `drawArraysInstanced`,\n * `drawElementsInstanced`, and the constant `VERTEX_ATTRIB_ARRAY_DIVISOR`\n * to the `WebGLRenderingContext`.\n *\n * @memberOf module:twgl\n */\n\n/**\n * Sets various defaults for twgl.\n *\n * In the interest of terseness which is kind of the point\n * of twgl I've integrated a few of the older functions here\n *\n * @param {module:twgl.Defaults} newDefaults The default settings.\n * @memberOf module:twgl\n */\nfunction setDefaults(newDefaults) {\n copyExistingProperties(newDefaults, defaults);\n setDefaults$2(newDefaults); // eslint-disable-line\n setDefaults$1(newDefaults); // eslint-disable-line\n}\n\nconst prefixRE = /^(.*?)_/;\nfunction addExtensionToContext(gl, extensionName) {\n glEnumToString(gl, 0);\n const ext = gl.getExtension(extensionName);\n if (ext) {\n const enums = {};\n const fnSuffix = prefixRE.exec(extensionName)[1];\n const enumSuffix = '_' + fnSuffix;\n for (const key in ext) {\n const value = ext[key];\n const isFunc = typeof (value) === 'function';\n const suffix = isFunc ? fnSuffix : enumSuffix;\n let name = key;\n // examples of where this is not true are WEBGL_compressed_texture_s3tc\n // and WEBGL_compressed_texture_pvrtc\n if (key.endsWith(suffix)) {\n name = key.substring(0, key.length - suffix.length);\n }\n if (gl[name] !== undefined) {\n if (!isFunc && gl[name] !== value) {\n warn$1(name, gl[name], value, key);\n }\n } else {\n if (isFunc) {\n gl[name] = function(origFn) {\n return function() {\n return origFn.apply(ext, arguments);\n };\n }(value);\n } else {\n gl[name] = value;\n enums[name] = value;\n }\n }\n }\n // pass the modified enums to glEnumToString\n enums.constructor = {\n name: ext.constructor.name,\n };\n glEnumToString(enums, 0);\n }\n return ext;\n}\n\n/*\n * If you're wondering why the code doesn't just iterate\n * over all extensions using `gl.getExtensions` is that it's possible\n * some future extension is incompatible with this code. Rather than\n * have thing suddenly break it seems better to manually add to this\n * list.\n *\n */\nconst supportedExtensions = [\n 'ANGLE_instanced_arrays',\n 'EXT_blend_minmax',\n 'EXT_color_buffer_float',\n 'EXT_color_buffer_half_float',\n 'EXT_disjoint_timer_query',\n 'EXT_disjoint_timer_query_webgl2',\n 'EXT_frag_depth',\n 'EXT_sRGB',\n 'EXT_shader_texture_lod',\n 'EXT_texture_filter_anisotropic',\n 'OES_element_index_uint',\n 'OES_standard_derivatives',\n 'OES_texture_float',\n 'OES_texture_float_linear',\n 'OES_texture_half_float',\n 'OES_texture_half_float_linear',\n 'OES_vertex_array_object',\n 'WEBGL_color_buffer_float',\n 'WEBGL_compressed_texture_atc',\n 'WEBGL_compressed_texture_etc1',\n 'WEBGL_compressed_texture_pvrtc',\n 'WEBGL_compressed_texture_s3tc',\n 'WEBGL_compressed_texture_s3tc_srgb',\n 'WEBGL_depth_texture',\n 'WEBGL_draw_buffers',\n];\n\n/**\n * Attempts to enable all of the following extensions\n * and add their functions and constants to the\n * `WebGLRenderingContext` using their normal non-extension like names.\n *\n * ANGLE_instanced_arrays\n * EXT_blend_minmax\n * EXT_color_buffer_float\n * EXT_color_buffer_half_float\n * EXT_disjoint_timer_query\n * EXT_disjoint_timer_query_webgl2\n * EXT_frag_depth\n * EXT_sRGB\n * EXT_shader_texture_lod\n * EXT_texture_filter_anisotropic\n * OES_element_index_uint\n * OES_standard_derivatives\n * OES_texture_float\n * OES_texture_float_linear\n * OES_texture_half_float\n * OES_texture_half_float_linear\n * OES_vertex_array_object\n * WEBGL_color_buffer_float\n * WEBGL_compressed_texture_atc\n * WEBGL_compressed_texture_etc1\n * WEBGL_compressed_texture_pvrtc\n * WEBGL_compressed_texture_s3tc\n * WEBGL_compressed_texture_s3tc_srgb\n * WEBGL_depth_texture\n * WEBGL_draw_buffers\n *\n * For example if `ANGLE_instanced_arrays` exists then the functions\n * `drawArraysInstanced`, `drawElementsInstanced`, `vertexAttribDivisor`\n * and the constant `VERTEX_ATTRIB_ARRAY_DIVISOR` are added to the\n * `WebGLRenderingContext`.\n *\n * Note that if you want to know if the extension exists you should\n * probably call `gl.getExtension` for each extension. Alternatively\n * you can check for the existence of the functions or constants that\n * are expected to be added. For example\n *\n * if (gl.drawBuffers) {\n * // Either WEBGL_draw_buffers was enabled OR you're running in WebGL2\n * ....\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @memberOf module:twgl\n */\nfunction addExtensionsToContext(gl) {\n for (let ii = 0; ii < supportedExtensions.length; ++ii) {\n addExtensionToContext(gl, supportedExtensions[ii]);\n }\n}\n\n/**\n * Creates a webgl context.\n * @param {HTMLCanvasElement} canvas The canvas tag to get\n * context from. If one is not passed in one will be\n * created.\n * @return {WebGLRenderingContext} The created context.\n * @private\n */\nfunction create3DContext(canvas, opt_attribs) {\n const names = [\"webgl\", \"experimental-webgl\"];\n let context = null;\n for (let ii = 0; ii < names.length; ++ii) {\n context = canvas.getContext(names[ii], opt_attribs);\n if (context) {\n if (defaults.addExtensionsToContext) {\n addExtensionsToContext(context);\n }\n break;\n }\n }\n return context;\n}\n\n/**\n * Gets a WebGL1 context.\n *\n * Note: Will attempt to enable Vertex Array Objects\n * and add WebGL2 entry points. (unless you first set defaults with\n * `twgl.setDefaults({enableVertexArrayObjects: false})`;\n *\n * @param {HTMLCanvasElement} canvas a canvas element.\n * @param {WebGLContextAttributes} [opt_attribs] optional webgl context creation attributes\n * @return {WebGLRenderingContext} The created context.\n * @memberOf module:twgl\n * @deprecated\n * @private\n */\nfunction getWebGLContext(canvas, opt_attribs) {\n const gl = create3DContext(canvas, opt_attribs);\n return gl;\n}\n\n/**\n * Creates a webgl context.\n *\n * Will return a WebGL2 context if possible.\n *\n * You can check if it's WebGL2 with\n *\n * twgl.isWebGL2(gl);\n *\n * @param {HTMLCanvasElement} canvas The canvas tag to get\n * context from. If one is not passed in one will be\n * created.\n * @return {WebGLRenderingContext} The created context.\n */\nfunction createContext(canvas, opt_attribs) {\n const names = [\"webgl2\", \"webgl\", \"experimental-webgl\"];\n let context = null;\n for (let ii = 0; ii < names.length; ++ii) {\n context = canvas.getContext(names[ii], opt_attribs);\n if (context) {\n if (defaults.addExtensionsToContext) {\n addExtensionsToContext(context);\n }\n break;\n }\n }\n return context;\n}\n\n/**\n * Gets a WebGL context. Will create a WebGL2 context if possible.\n *\n * You can check if it's WebGL2 with\n *\n * function isWebGL2(gl) {\n * return gl.getParameter(gl.VERSION).indexOf(\"WebGL 2.0 \") == 0;\n * }\n *\n * Note: For a WebGL1 context will attempt to enable Vertex Array Objects\n * and add WebGL2 entry points. (unless you first set defaults with\n * `twgl.setDefaults({enableVertexArrayObjects: false})`;\n *\n * @param {HTMLCanvasElement} canvas a canvas element.\n * @param {WebGLContextAttributes} [opt_attribs] optional webgl context creation attributes\n * @return {WebGLRenderingContext} The created context.\n * @memberOf module:twgl\n */\nfunction getContext(canvas, opt_attribs) {\n const gl = createContext(canvas, opt_attribs);\n return gl;\n}\n\n/**\n * Resize a canvas to match the size it's displayed.\n * @param {HTMLCanvasElement} canvas The canvas to resize.\n * @param {number} [multiplier] So you can pass in `window.devicePixelRatio` or other scale value if you want to.\n * @return {boolean} true if the canvas was resized.\n * @memberOf module:twgl\n */\nfunction resizeCanvasToDisplaySize(canvas, multiplier) {\n multiplier = multiplier || 1;\n multiplier = Math.max(0, multiplier);\n const width = canvas.clientWidth * multiplier | 0;\n const height = canvas.clientHeight * multiplier | 0;\n if (canvas.width !== width || canvas.height !== height) {\n canvas.width = width;\n canvas.height = height;\n return true;\n }\n return false;\n}\n\nexport { addExtensionsToContext, attributes, bindFramebufferInfo, bindTransformFeedbackInfo, bindUniformBlock, canFilter, canGenerateMipmap, createAttribsFromArrays, createAttributeSetters, createBufferFromArray, createBufferFromTypedArray, createBufferInfoFromArrays, createBuffersFromArrays, createFramebufferInfo, createProgram, createProgramAsync, createProgramFromScripts, createProgramFromSources, createProgramInfo, createProgramInfoAsync, createProgramInfoFromProgram, createProgramInfos, createProgramInfosAsync, createPrograms, createProgramsAsync, createSampler, createSamplers, createTexture, createTextures, createTransformFeedback, createTransformFeedbackInfo, createUniformBlockInfo, createUniformBlockInfoFromProgram, createUniformBlockSpecFromProgram, createUniformSetters, createVAOAndSetAttributes, createVAOFromBufferInfo, createVertexArrayInfo, draw, drawBufferInfo, drawObjectList, framebuffers, getArray$1 as getArray_, getBytesPerElementForInternalFormat, getContext, getFormatAndTypeForInternalFormat, getGLTypeForTypedArray, getGLTypeForTypedArrayType, getNumComponentsForFormat, getNumComponents$1 as getNumComponents_, getTypedArrayTypeForGLType, getWebGLContext, glEnumToString, isArrayBuffer$1 as isArrayBuffer, isWebGL1, isWebGL2, loadTextureFromUrl, m4, primitives, programs, resizeCanvasToDisplaySize, resizeFramebufferInfo, resizeTexture, setAttribInfoBufferFromArray, setDefaults$2 as setAttributeDefaults_, setAttributePrefix, setAttributes, setBlockUniforms, setBuffersAndAttributes, setDefaultTextureColor, setDefaults, setEmptyTexture, setSamplerParameters, setDefaults$1 as setTextureDefaults_, setTextureFilteringForSize, setTextureFromArray, setTextureFromElement, setTextureParameters, setUniformBlock, setUniforms, setUniformsAndBindTextures, textures, typedarrays, utils, v3, vertexArrays };\n","/**\n * This is the vertex shader for the \"raster\" program.\n * \n * It takes in positions and transforms them using a matrix supplied by mapbox.\n * It also passes through the texture coordinates for the fragment shader.\n */\n\nattribute vec2 aPos; // We use this to pass in the positions of the vertices.\nuniform mat4 uMatrix; // We use this to pass in the matrix that will be used to transform the vertices\n\nvarying vec2 vTexCoord; // We use this to pass the texture coordinates to the fragment shader\n\n/**\n * This is the scaling factor of mapbox tiles. For reference, see the following:\n * - https://github.com/mapbox/mapbox-gl-js/blob/acc665f77fa6852c11c3755f69afcb781c15b7cd/src/shaders/_prelude.vertex.glsl#L3\n * - https://github.com/mapbox/mapbox-gl-js/blob/acc665f77fa6852c11c3755f69afcb781c15b7cd/src/shaders/globe_raster.vertex.glsl#L49\n * - https://github.com/mapbox/mapbox-gl-js/blob/f2117b4ef501bbab298898e4f6c34083178d519a/src/data/extent.js\n */\nfloat Extent = 8192.0;\n\nvoid main() {\n // Transform the vertex position via the matrix & extent:\n gl_Position = uMatrix * vec4(aPos * Extent, 0, 1);\n\n // Pass the texture coords through for the fragment shader:\n vTexCoord = aPos;\n}\n","/**\n * This is the fragment shader for the \"mask\" program.\n * \n * It determines the color for each pixel, pulling the color from the texture\n * and then adjusting the hue and saturation as needed.\n *\n * We pass in parameters via the \"uniforms\", including the opacity of the mask,\n * the target hue, and thresholds for hue and saturation). We also pass the\n * texture itself via a uniform.\n */\n\nprecision highp float; // Use high precision for floats\n\nvarying vec2 vTexCoord; // The texture coordinates, passed in from the vertex shader.\nuniform sampler2D uTexture; // The texture we're pulling from (a raster tile image).\n\nuniform float uOpacity; // 0 to 1 (how opaque the mask is)\nuniform float uHueTarget; // -1 to disable, 0 to 1 (we adjust hue to be closer to this target)\nuniform float uHueThreshold; // 0 to 1 (we fade out colors that have hue below this threshold)\nuniform float uSaturationThreshold; // 0 to 1 (we fade out colors that have saturation below this threshold)\nuniform float uFadeFactor; // 0 to 1 (how much to fade colors we're excluding)\n\nconst float hueAdjustmentFactor = 0.35; // 0 to 1 (how much to adjust hue towards target)\n\n// Function to convert RGB to HSV (so we can adjust hue and saturation)\nvec3 rgb2hsv(vec3 c) {\n vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n\n float d = q.x - min(q.w, q.y);\n float e = 1.0e-10;\n return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);\n}\n\n// Function to convert HSV to RGB (so we can convert back after adjusting hue and saturation)\nvec3 hsv2rgb(vec3 c) {\n vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n}\n\nvoid main() {\n // Pull the color from the texture:\n vec4 color = texture2D(uTexture, vTexCoord);\n\n // Adjust opacity, using the value passed in via `uOpacity`\n color.a *= uOpacity;\n\n // Convert RGB to HSV\n vec3 hsv = rgb2hsv(color.rgb);\n\n // Adjust hue and saturation as needed\n if(hsv.s < uSaturationThreshold) {\n color.a *= (1.0 - uFadeFactor); // (fade out colors w/ low saturation)\n } else if(hsv.x < uHueThreshold) {\n color.a *= (1.0 - uFadeFactor); // (fade out colors w/ low hue)\n } else if(uHueTarget != -1.0) {\n hsv.x = hsv.x + (uHueTarget - hsv.x) * hueAdjustmentFactor; // (if uHueTarget is set, adjust hue to be closer to uHueTarget)\n }\n\n // Convert HSV back to RGB\n vec3 rgb = hsv2rgb(hsv);\n\n // Apply alpha (we're using `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)` i.e. premultiplied alpha form)\n gl_FragColor = vec4(rgb.rgb * color.a, color.a);\n}\n","/**\n * This is the vertex shader for the \"mask\" program.\n * \n * It takes in positions and transforms them using a matrix supplied by mapbox.\n */\n\nattribute vec2 aPos; // We use this to pass in the positions of the vertices.\nuniform mat4 uMatrix; // We use this to pass in the matrix that will be used to transform the vertices\n\nvoid main() {\n // Transform the vertex position via the matrix:\n gl_Position = uMatrix * vec4(aPos, 0, 1);\n}\n","/**\n * This is the fragment shader for the \"mask\" program.\n * \n * It just colors the pixels in the mask black, and then we use the WebGL\n * stencil buffer to mask the output of the \"raster\" program.\n */\n\nprecision highp float; // Use high precision for floats\n\nvoid main() {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); // Color = black\n}\n","import earcut from 'earcut';\nimport mapboxgl from 'mapbox-gl';\nimport * as twgl from 'twgl.js';\n\n// These are the coordinates for two triangles that make up a unit square (with its lower left vertex at the origin)\nconst UNIT_QUAD = [0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1];\n\n/**\n * Returns a twgl.BufferInfo object for the main program\n */\nexport const getBufferInfo = (\n gl, // WebGLRenderingContext\n) =>\n twgl.createBufferInfoFromArrays(gl, {\n aPos: { numComponents: 2, data: UNIT_QUAD },\n });\n\n/**\n * Returns a twgl.BufferInfo object for the mask program\n */\nexport const getMaskBufferInfo = (\n gl, // WebGLRenderingContext\n maskPolygons, // Array of geojson polygon features\n) => {\n const positions = [];\n const triangles = [];\n let triangleStartIndex = 0;\n\n maskPolygons.forEach((data) => {\n if (!data.geometry || data.geometry.type !== 'Polygon') {\n throw new Error('Clipping mask must be a polygon feature.');\n }\n\n // Convert geographic coordinates to Mercator\n const { coordinates } = data.geometry;\n const converted = coordinates.map((coordArr) =>\n coordArr.map((coord) => {\n const mercator = mapboxgl.MercatorCoordinate.fromLngLat(coord);\n return [mercator.x, mercator.y];\n }),\n );\n\n // Flatten the polygon into triangles\n const flatten = earcut.flatten(converted);\n const { vertices, holes, dimensions } = flatten;\n const triangle = earcut(vertices, holes, dimensions);\n const triangleNew = triangle.map((item) => item + triangleStartIndex);\n\n triangleStartIndex += vertices.length / 2;\n positions.push(...vertices);\n triangles.push(...triangleNew);\n });\n\n return twgl.createBufferInfoFromArrays(gl, {\n aPos: { numComponents: 2, data: positions },\n indices: new Uint32Array(triangles),\n });\n};\n","/**\n * For reference:\n * - https://github.com/maeneak/mapbox-texture-layer\n * - https://github.com/naivemap/mapbox-gl-layers/tree/main/packages/mapbox-gl-image-layer\n */\nimport * as twgl from 'twgl.js';\n\nimport rasterVertexSource from './shaders/raster.vert';\nimport rasterFragmentSource from './shaders/raster.frag';\nimport maskVertexSource from './shaders/mask.vert';\nimport maskFragmentSource from './shaders/mask.frag';\nimport { getBufferInfo, getMaskBufferInfo } from './helpers';\nimport { MAPBOX_SOURCECACHE_LAYER_PREFIX } from '../../../constants/map';\nimport { multipolygonToPolygons } from '../../geojson';\n\nexport default class RasterLayerWithClipping {\n constructor({\n id,\n spec,\n opacity = 1,\n resampling = 'linear',\n maskPolygons = null, // maskPolygons = array of geojson polygon features\n hueTarget = -1,\n hueThreshold = 0,\n saturationThreshold = 0,\n fadeFactor = 0.75,\n }) {\n this.map = null;\n this.gl = null;\n this.type = 'custom';\n this.tileSource = null;\n this.programInfo = null;\n\n this.id = id;\n this.source = `${this.id}Source`;\n this.tileJson = spec;\n this.opacity = opacity;\n this.maskPolygons = maskPolygons;\n this.resampling = resampling;\n this.hueTarget = hueTarget;\n this.hueThreshold = hueThreshold;\n this.saturationThreshold = saturationThreshold;\n this.fadeFactor = fadeFactor;\n }\n\n onAdd(map, gl) {\n this.map = map;\n this.gl = gl;\n\n this.programInfo = twgl.createProgramInfo(gl, [\n rasterVertexSource,\n rasterFragmentSource,\n ]);\n\n this.maskProgramInfo = twgl.createProgramInfo(gl, [\n maskVertexSource,\n maskFragmentSource,\n ]);\n map.addSource(this.source, this.tileJson);\n\n this.tileSource = this.map.getSource(this.source);\n\n // eslint-disable-next-line no-underscore-dangle\n this.sourceCache = this.map.painter.style._sourceCaches[\n `${MAPBOX_SOURCECACHE_LAYER_PREFIX}${this.source}`\n ];\n\n // This is a hack to make mapbox mark the sourceCache as 'used' so it will initialise tiles.\n this.map.style._layers[this.id].source = this.source; // eslint-disable-line no-underscore-dangle\n\n this.setupLayer();\n }\n\n setupLayer() {\n try {\n this.bufferInfo = getBufferInfo(this.gl);\n this.setupMask();\n } catch (err) {\n console.error(err);\n }\n }\n\n setupMask() {\n this.maskBufferInfo = getMaskBufferInfo(this.gl, this.maskPolygons ?? []);\n }\n\n onRemove(map, gl) {\n map.removeSource(this.source);\n\n if (this.programInfo) gl.deleteProgram(this.programInfo.program);\n }\n\n updateOpacity(opacity) {\n this.opacity = opacity;\n }\n\n updateHueTarget(hueTarget) {\n this.hueTarget = hueTarget;\n }\n\n updateHueThreshold(hueThreshold) {\n this.hueThreshold = hueThreshold;\n }\n\n updateSaturationThreshold(saturationThreshold) {\n this.saturationThreshold = saturationThreshold;\n }\n\n updateFadeFactor(fadeFactor) {\n this.fadeFactor = fadeFactor;\n }\n\n updateMask(features) {\n if (!this.gl || !this.map) return;\n\n // Convert MultiPolygon features into multiple Polygon features\n const polygons = features.flatMap((feature) => {\n if (feature.geometry.type === 'MultiPolygon') {\n return multipolygonToPolygons(feature);\n }\n return feature;\n });\n\n this.maskPolygons = polygons;\n\n this.setupMask();\n }\n\n render(gl, matrix) {\n if (!this.programInfo) return;\n\n // blend\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n const tiles = this.sourceCache\n .getVisibleCoordinates()\n .map((tileid) => this.sourceCache.getTile(tileid));\n\n tiles.forEach((tile) => {\n if (!tile.texture) return;\n\n if (this.maskProgramInfo && this.maskBufferInfo) {\n // MASK\n gl.useProgram(this.maskProgramInfo.program);\n\n // stencil\n gl.enable(gl.STENCIL_TEST);\n gl.stencilFunc(gl.ALWAYS, 1, 0xff);\n gl.stencilOp(gl.REPLACE, gl.REPLACE, gl.REPLACE);\n gl.stencilMask(0xff);\n gl.clear(gl.STENCIL_BUFFER_BIT);\n\n // matrix\n twgl.setUniforms(this.maskProgramInfo, { uMatrix: matrix });\n\n // pos & indices\n twgl.setBuffersAndAttributes(\n gl,\n this.maskProgramInfo,\n this.maskBufferInfo,\n );\n\n // draw\n twgl.drawBufferInfo(gl, this.maskBufferInfo, gl.TRIANGLES);\n }\n\n // RASTER\n gl.useProgram(this.programInfo.program);\n\n // stencil\n if (this.maskProgramInfo?.program) {\n gl.stencilFunc(gl.EQUAL, 1, 0xff);\n gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);\n }\n\n // texture\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tile.texture.texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n // texture sampling (linear or nearest)\n const textureFilter =\n this.resampling === 'linear' ? gl.LINEAR : gl.NEAREST;\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, textureFilter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, textureFilter);\n\n // draw\n twgl.setUniforms(this.programInfo, {\n uMatrix: tile.tileID.projMatrix,\n uTexture: tile.texture.texture,\n uOpacity: this.opacity,\n uHueTarget: this.hueTarget,\n uHueThreshold: this.hueThreshold,\n uSaturationThreshold: this.saturationThreshold,\n uFadeFactor: this.fadeFactor,\n });\n twgl.setBuffersAndAttributes(gl, this.programInfo, this.bufferInfo);\n twgl.drawBufferInfo(gl, this.bufferInfo, gl.TRIANGLES);\n\n // cleanup\n gl.clear(gl.STENCIL_BUFFER_BIT);\n gl.disable(gl.STENCIL_TEST);\n });\n }\n}\n","export const RGBA_LENGTH = 4; // 4 components per pixel (RGBA)\nexport const MAX_POINTS_TO_SAMPLE = 2000; // For performance reasons, do not sample more than 2000 points when calculating suitability within one or more polygons\n","import _ from 'lodash';\nimport * as turf from '@turf/turf';\n\nimport RasterLayerWithClipping from '../RasterLayerWithClipping';\nimport { acresPerSqMeter } from '../../../constants/units';\nimport { MAX_POINTS_TO_SAMPLE, RGBA_LENGTH } from './constants';\n\nexport const clearBuffer = (gl) => {\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // eslint-disable-line no-bitwise\n};\n\n/**\n * Takes `{ x, y }` coordinates and the `gl` object and translates\n * them to `{ x, y }` pixel coordinates that are adjusted for pixel ratio.\n *\n * This helps avoid floating point issues.\n */\nexport const translateXY = (point, gl) => {\n const ratio = window.devicePixelRatio;\n\n const w = gl.drawingBufferWidth;\n const h = gl.drawingBufferHeight;\n\n const pixelX = Math.floor(point.x * ratio);\n const pixelY = Math.floor(h - point.y * ratio);\n\n const x = _.clamp(pixelX, 0, w);\n const y = _.clamp(pixelY, 0, h);\n\n return { x, y };\n};\n\n/**\n * Gets the layers corresponding to `layerIds` from `map` and ensures that they\n * are `RasterLayerWithClipping` instances.\n */\nexport const getClippableTilesetLayers = (map, layerIds) =>\n layerIds.map((layerId) => {\n const layer = map.getLayer(layerId);\n if (!layer) {\n throw new Error(`Layer ${layerId} not found`);\n }\n if (!(layer.implementation instanceof RasterLayerWithClipping)) {\n throw new Error('Layer is not a RasterLayerWithClipping');\n }\n return layer;\n });\n\n/**\n * Just moving the map isn't enough to get the tiles for those map bounds to\n * load immediately. To make sure the tiles load, this function calls the\n * `mapbox-gl-js` code responsible for loading in the tiles correctly, and this\n * approach is a bit faster than calling `map._render()`.\n *\n * We then also await a 0-tick promise, which gives up control of the main\n * thread and allows the browser to finish loading the tiles before we continue.\n *\n * FIXME: awaiting a 0-tick promise is a hacky way to ensure the tiles are\n * loaded, but I haven't been able to find a better solution.\n * - Mark (2024-05-24)\n */\nexport const ensureTilesLoad = async (map, transform) => {\n if (!map) throw new Error('Map not loaded');\n if (!transform) throw new Error('Transform is required');\n\n map.style.updateSources(transform);\n map.style._updatePlacement(transform); // eslint-disable-line no-underscore-dangle\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n};\n\n/**\n * Hides all layers except the ones we care about. Returns a cleanup function to\n * restore the layer visibility settings.\n */\nexport const hideLayersExcept = (layerIds, map) => {\n const original = {};\n\n // Hide the other layers\n const except = layerIds.concat(['background']); // keep bg layer visible too\n map\n .getStyle()\n .layers.map((l) => l.id)\n .filter((id) => !except.includes(id))\n .forEach((id) => {\n original[id] = map.getLayoutProperty(id, 'visibility');\n map.setLayoutProperty(id, 'visibility', 'none');\n });\n\n // Store the initial background color\n const initBackgroundColor = map.getPaintProperty(\n 'background',\n 'background-color',\n );\n\n // Set background color to black\n map.setPaintProperty('background', 'background-color', 'black');\n\n // cleanup function to restore\n const restoreLayersVisibility = () => {\n Object.entries(original).forEach(([id, visibility]) => {\n map.setLayoutProperty(id, 'visibility', visibility);\n });\n map.setPaintProperty('background', 'background-color', initBackgroundColor);\n };\n\n return { restoreLayersVisibility };\n};\n\n/**\n * Returns the `mapbox-gl-js` `Tile` class.\n *\n * This is sooooooo hacky. mapbox-gl-js doesn't export the Tile class so we're\n * looking for an existing instance of it and using it to create new instances\n * via a proxy of the contructor. Apologies to future Mark for when we update\n * mapbox-gl-js and this breaks.\n * - Mark (2024-05-17)\n */\nexport const getMapboxTileClass = (map) => {\n /* eslint-disable no-underscore-dangle */\n const existingTile = Object.values(map.style._mergedSourceCaches)\n .filter((x) => x._tiles && Object.keys(x._tiles).length > 0)\n .flatMap((t) => Object.values(t._tiles))[0];\n /* eslint-enable no-underscore-dangle */\n\n if (!existingTile) throw new Error('No tiles loaded yet.');\n\n const TileConstructor = existingTile.constructor;\n return new Proxy(TileConstructor, {\n construct(Target, args) {\n return new Target(...args);\n },\n });\n};\n\n/**\n * Generates a grid of points within the features of `featureCollection`.\n * Exported for testing\n */\nexport const generatePointsInFeatures = ({\n map,\n featureCollection,\n maxPoints = MAX_POINTS_TO_SAMPLE, // reasonable default for performance\n}) => {\n const { features } = featureCollection;\n const bounds = turf.bbox(featureCollection);\n\n // Convert featureCollection to a single MultiPolygon mask:\n const mask =\n features.length <= 1\n ? features[0] || turf.featureCollection([])\n : turf.union(featureCollection);\n\n /**\n * Here, we generate a grid of pixels within the mask, using 10 meters as\n * the resolution (the suitability data resolution is ~30 meters). If this would\n * result in more than `maxPoints` points, we reduce the resolution\n * until we have fewer points than that limit.\n *\n * We then project these points from map coordinates to pixel coordinates.\n */\n const pointGridSize = Math.max(10, Math.sqrt(turf.area(mask) / maxPoints));\n return turf\n .pointGrid(bounds, pointGridSize, { units: 'meters', mask })\n .features.map((point) => map.project(point.geometry.coordinates));\n};\n\n/**\n * Returns a function that will sample the color data from the `map` canvas from\n * a grid of points within a `featureCollection` and return the number of\n * suitable acres.\n *\n * Call this one time once the map is positioned, and then call the returned function\n * once per layer. This way, you can calculate suitability across multiple layers\n * but only call `generatePointsInFeatures` once.\n *\n * `maxPoints` is the maximum number of points we'll sample.\n *\n * NOTE: the returned function uses `gl.readPixels()`, which is synchronous and\n * relatively slow.\n */\nexport const getCalculateSuitabilityFromMap = ({\n map,\n featureCollection,\n maxPoints,\n}) => {\n // Generate the points to sample\n const points = generatePointsInFeatures({\n map,\n featureCollection,\n maxPoints,\n });\n\n // Calculate the total area of the featureCollection in acres\n const area = turf.area(featureCollection) * acresPerSqMeter;\n\n // Get the WebGL context\n const { gl } = map.painter.context;\n\n // Return a function that calculates the suitability\n const calculateSuitabilityFromMap = () => {\n // Pull the color data for the whole canvas\n const w = gl.drawingBufferWidth;\n const h = gl.drawingBufferHeight;\n const pixels = new Uint8Array(w * h * RGBA_LENGTH);\n gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);\n\n // Then, sample the color at each point in our array\n const suitablePoints = points.filter((point) => {\n const { x, y } = translateXY(point, gl);\n const index = (x + w * y) * RGBA_LENGTH;\n\n const [r, g, b, a] = pixels.slice(index, index + RGBA_LENGTH);\n\n // Return true if the pixel is not fully black or fully transparent\n // NOTE: we're using a threshold of 0.001 to account for floating point errors\n return (r > 0.001 || g > 0.001 || b > 0.001) && a > 0.001;\n });\n\n // Calculate the proportion of suitable points\n const suitabilityProportion = suitablePoints.length / points.length;\n\n // Return the number of suitable acres\n return suitabilityProportion * area;\n };\n\n return calculateSuitabilityFromMap;\n};\n","export const TILESET_LAYER_PREFIX = 'tileset-layer';\n\n// NOTE: this should probably eventually be stored in the tilesets table\nexport const SUITABILITY_THRESHOLD = 0.58;\nexport const SUITABILITY_THRESHOLD_FOR_CHESTNUTS = 0.48;\n\n// NOTE: these have to match what's in the database (tilesets table, name column)\nexport const CHINESE_CHESTNUT_TILESET_NAME = 'chinese-chestnut-v2';\nexport const BLACK_LOCUST_TILESET_NAME = 'black-locust-v2';\nexport const HYBRID_POPLAR_TILESET_NAME = 'hybrid-poplar-v2';\nexport const BLACKCURRANT_TILESET_NAME = 'blackcurrant-v2';\nexport const AMERICAN_ELDERBERRY_TILESET_NAME = 'american-elderberry-v2';\nexport const AMERICAN_HAZELNUT_TILESET_NAME = 'american-hazelnut-v2';\n\nexport const TILESET_MIN_ZOOM = 8;\nexport const TILESET_MAX_ZOOM = 16;\n","import _ from 'lodash';\n\nimport { getColorDifference, isGrayscale } from './colors';\nimport { TILESET_LAYER_PREFIX } from '../constants/tilesets';\n\n/**\n * Some tricky logic here.\n *\n * There are two kinds of tilesets:\n * 1. Tilesets with a continuous key that is not grayscale that also have discrete keys that *are* grayscale.\n * 2. Tilesets with just a discrete key (that is not grayscale).\n *\n * - For type 1, if the hovered color is greyscale, we need to highlight it in the discrete section. If it's not greyscale, we'll highlight the hovered color on the gradient.\n * - For type 2, we always highlight the hovered color in the discrete section.\n *\n * And, when we're highlighting a color in the discrete section, we need to pick\n * the closest color. Ideally, the set of discrete colors the tileset uses would\n * be the same as the set of colors our discrete key uses, but that's not\n * actually the case.\n *\n * @returns {{\n * continuousColortoHighlight?: string;\n * discreteColortoHighlight?: string;\n * }}\n */\nexport const getHighlightColors = ({ tileset, hoveredColor }) => {\n // If there's no hovered color, there's nothing to highlight.\n if (!hoveredColor || hoveredColor.length === 0) return {};\n\n const discreteKeyColors = tileset.discreteKey.map(({ hexCode }) => hexCode);\n const closestDiscreteColor = _.minBy(discreteKeyColors, (color) =>\n getColorDifference(color, hoveredColor),\n );\n\n const hoveredColorIsGrayscale = isGrayscale(hoveredColor);\n const hasDiscreteExactMatch = discreteKeyColors.includes(hoveredColor);\n const tilesetHasContinuousKey = tileset.continuousKey;\n\n /* Type 1️ */\n if (tilesetHasContinuousKey) {\n // For grayscale color, return the closest discrete key color:\n if (hoveredColorIsGrayscale) {\n return { discreteColortoHighlight: closestDiscreteColor };\n }\n\n // For non-grayscale color, highlight it on the gradient:\n return { continuousColortoHighlight: hoveredColor };\n }\n\n /* Type 2 */\n // If the color is grayscale, we shouldn't highlight any color, since the discrete key is not grayscale.\n if (hoveredColorIsGrayscale) {\n // One exception is if the discrete key contains this exact color, which sometimes happens (non-grayscale keys sometimes contain black or white).\n if (hasDiscreteExactMatch) {\n return { discreteColortoHighlight: hoveredColor };\n }\n\n return {};\n }\n\n // Return the nearest color in the discrete key colors:\n return { discreteColortoHighlight: closestDiscreteColor };\n};\n\nexport const layerIdForTileset = (tilesetId) =>\n `${TILESET_LAYER_PREFIX}|${tilesetId}`;\n\n/**\n * Converts lat/lng info to a tile URL as well as providing offsets for where\n * the point is within the tile.\n *\n * The offsets are both in the range 0.0 to 1.0 and have the origin in the bottom left.\n *\n * NOTE: this is specifically for TMS tiles (the kind we use), not XYZ tiles.\n * The two are very similar but differ in the y axis (TMS y axis is flipped\n * relative to XYZ). For reference:\n * - https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames\n * - https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification\n * - https://gist.github.com/tmcw/4954720\n */\nexport const latLngToTileInfo = ({ lat, lng, zoom, tilesetId }) => {\n const { floor, log, cos, tan, PI } = Math;\n\n const zoomExp = 2 ** zoom;\n const latRad = (lat * PI) / 180;\n\n const xFull = ((lng + 180) / 360) * zoomExp;\n const yFull = ((1 - log(tan(latRad) + 1 / cos(latRad)) / PI) / 2) * zoomExp;\n const zFull = zoom;\n\n // Edge case!\n // If yFull is already an integer, we subtract one here so we can use the next\n // tile w/ a yOffset of 0.0 instead of this tile with a yOffset of 1.0.\n // This ensures we get the behavior we'd expect for edge cases (like coords\n // 0,0 using tile 512/512 with 0,0 offset instead of tile 512/511 with 0,1\n // offset).\n const yFloor = yFull === floor(yFull) ? yFull - 1 : floor(yFull);\n\n const x = floor(xFull);\n const y = zoomExp - 1 - yFloor; // since we're using TMS tiles, y is inverted\n const z = floor(zFull);\n\n const url = `${window.location.origin}/tileset/${tilesetId}/${z}/${x}/${y}.png`;\n\n const xOffset = xFull - x;\n const yOffset = 1 - (yFull - yFloor); // (y is inverted so we need to subtract the offset from 1)\n\n return { url, xOffset, yOffset };\n};\n","import { useEffect, useState } from 'react';\nimport tinycolor from 'tinycolor2';\n\nimport {\n CHINESE_CHESTNUT_TILESET_NAME,\n SUITABILITY_THRESHOLD,\n SUITABILITY_THRESHOLD_FOR_CHESTNUTS,\n TILESET_MAX_ZOOM,\n TILESET_MIN_ZOOM,\n} from '../constants/tilesets';\nimport { getGradientHueAtPosition } from '../utils/colors';\nimport { layerIdForTileset } from '../utils/tilesets';\nimport RasterLayerWithClipping from '../utils/webgl/RasterLayerWithClipping';\n\nconst SATURATION_THRESHOLD = 0.15; // Filter out grey & grey-ish colors\n\n/**\n * When the map is loaded and the tileset data has loaded, add a\n * RasterLayerWithClipping layer to the map for each tileset.\n */\nconst useAddClippableTilesetLayers = (map, tilesets) => {\n // Keep track of the RasterLayerWithClipping instances\n const [tilesetLayers, setTilesetLayers] = useState([]);\n\n // Ensure we always have a raster layer for each tileset:\n useEffect(() => {\n if (!map) return null;\n\n // Create a raster layer for each tileset\n const newTilesetLayers = tilesets.map(\n ({ id, name, zoomLevels, continuousKey }) => {\n const maxSuitabilityColor = continuousKey.slice(-1)[0]?.hexCode;\n const maxSuitabilityHue =\n tinycolor(maxSuitabilityColor).toHsl().h / 360;\n\n let hueTarget = -1;\n if (name === CHINESE_CHESTNUT_TILESET_NAME && maxSuitabilityColor) {\n // hacky fix for the fact that chestnuts always have worse suitability than other crops:\n hueTarget = maxSuitabilityHue;\n }\n\n let hueThreshold = 0;\n if (maxSuitabilityHue) {\n const gradientColors = continuousKey.map(({ hexCode }) => hexCode);\n\n const suitabilityThreshold =\n // hacky fix for the fact that chestnuts always have worse suitability than other crops:\n name === CHINESE_CHESTNUT_TILESET_NAME\n ? SUITABILITY_THRESHOLD_FOR_CHESTNUTS\n : SUITABILITY_THRESHOLD;\n\n hueThreshold = getGradientHueAtPosition(\n suitabilityThreshold,\n gradientColors,\n );\n\n hueThreshold *= 1.0001; // Bump it up verrrry slightly to fix a floating point issue\n }\n\n return new RasterLayerWithClipping({\n id: layerIdForTileset(id),\n spec: {\n type: 'raster',\n tiles: [\n `${window.location.origin}/api/public/tileset/${id}/{z}/{x}/{y}.png`,\n ],\n tileSize: 256, // This matches TilesetLayer.jsx — if our tile size changes, this will need to be updated\n minzoom: zoomLevels ? Math.min(...zoomLevels) : TILESET_MIN_ZOOM,\n maxzoom: zoomLevels ? Math.max(...zoomLevels) : TILESET_MAX_ZOOM,\n scheme: 'tms',\n },\n opacity: 0, // initially render w/ no visibility, we set the selectedCrop layer to be visible later\n resampling: 'nearest',\n saturationThreshold: SATURATION_THRESHOLD, // Don't show grey areas on the map\n hueTarget,\n hueThreshold,\n });\n },\n );\n\n // add each layer to the map\n newTilesetLayers.forEach((layer) => {\n map.addLayer(layer);\n });\n\n // update state\n setTilesetLayers(newTilesetLayers);\n\n // cleanup function: remove all tileset layers\n return () => {\n if (!map || map._removed) return; // eslint-disable-line no-underscore-dangle\n\n newTilesetLayers.forEach((layer) => {\n map.removeLayer(layer.id);\n });\n setTilesetLayers([]);\n };\n }, [map, tilesets]);\n\n return tilesetLayers;\n};\n\nexport default useAddClippableTilesetLayers;\n","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/*!\n Copyright (c) 2017 Jed Watson.\n Licensed under the MIT License (MIT), see\n http://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tvar hasOwn = {}.hasOwnProperty;\n\n\tfunction classNames () {\n\t\tvar classes = [];\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (!arg) continue;\n\n\t\t\tvar argType = typeof arg;\n\n\t\t\tif (argType === 'string' || argType === 'number') {\n\t\t\t\tclasses.push(arg);\n\t\t\t} else if (Array.isArray(arg) && arg.length) {\n\t\t\t\tvar inner = classNames.apply(null, arg);\n\t\t\t\tif (inner) {\n\t\t\t\t\tclasses.push(inner);\n\t\t\t\t}\n\t\t\t} else if (argType === 'object') {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\t\t\tclasses.push(key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn classes.join(' ');\n\t}\n\n\tif (typeof module !== 'undefined' && module.exports) {\n\t\tclassNames.default = classNames;\n\t\tmodule.exports = classNames;\n\t} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\t\t// register as 'classnames', consistent with npm package name\n\t\tdefine('classnames', [], function () {\n\t\t\treturn classNames;\n\t\t});\n\t} else {\n\t\twindow.classNames = classNames;\n\t}\n}());\n","import PropTypes from 'prop-types'; // https://github.com/twbs/bootstrap/blob/v4.0.0-alpha.4/js/src/modal.js#L436-L443\n\nexport function getScrollbarWidth() {\n var scrollDiv = document.createElement('div'); // .modal-scrollbar-measure styles // https://github.com/twbs/bootstrap/blob/v4.0.0-alpha.4/scss/_modal.scss#L106-L113\n\n scrollDiv.style.position = 'absolute';\n scrollDiv.style.top = '-9999px';\n scrollDiv.style.width = '50px';\n scrollDiv.style.height = '50px';\n scrollDiv.style.overflow = 'scroll';\n document.body.appendChild(scrollDiv);\n var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n document.body.removeChild(scrollDiv);\n return scrollbarWidth;\n}\nexport function setScrollbarWidth(padding) {\n document.body.style.paddingRight = padding > 0 ? padding + \"px\" : null;\n}\nexport function isBodyOverflowing() {\n return document.body.clientWidth < window.innerWidth;\n}\nexport function getOriginalBodyPadding() {\n var style = window.getComputedStyle(document.body, null);\n return parseInt(style && style.getPropertyValue('padding-right') || 0, 10);\n}\nexport function conditionallyUpdateScrollbar() {\n var scrollbarWidth = getScrollbarWidth(); // https://github.com/twbs/bootstrap/blob/v4.0.0-alpha.6/js/src/modal.js#L433\n\n var fixedContent = document.querySelectorAll('.fixed-top, .fixed-bottom, .is-fixed, .sticky-top')[0];\n var bodyPadding = fixedContent ? parseInt(fixedContent.style.paddingRight || 0, 10) : 0;\n\n if (isBodyOverflowing()) {\n setScrollbarWidth(bodyPadding + scrollbarWidth);\n }\n}\nvar globalCssModule;\nexport function setGlobalCssModule(cssModule) {\n globalCssModule = cssModule;\n}\nexport function mapToCssModules(className, cssModule) {\n if (className === void 0) {\n className = '';\n }\n\n if (cssModule === void 0) {\n cssModule = globalCssModule;\n }\n\n if (!cssModule) return className;\n return className.split(' ').map(function (c) {\n return cssModule[c] || c;\n }).join(' ');\n}\n/**\n * Returns a new object with the key/value pairs from `obj` that are not in the array `omitKeys`.\n */\n\nexport function omit(obj, omitKeys) {\n var result = {};\n Object.keys(obj).forEach(function (key) {\n if (omitKeys.indexOf(key) === -1) {\n result[key] = obj[key];\n }\n });\n return result;\n}\n/**\n * Returns a filtered copy of an object with only the specified keys.\n */\n\nexport function pick(obj, keys) {\n var pickKeys = Array.isArray(keys) ? keys : [keys];\n var length = pickKeys.length;\n var key;\n var result = {};\n\n while (length > 0) {\n length -= 1;\n key = pickKeys[length];\n result[key] = obj[key];\n }\n\n return result;\n}\nvar warned = {};\nexport function warnOnce(message) {\n if (!warned[message]) {\n /* istanbul ignore else */\n if (typeof console !== 'undefined') {\n console.error(message); // eslint-disable-line no-console\n }\n\n warned[message] = true;\n }\n}\nexport function deprecated(propType, explanation) {\n return function validate(props, propName, componentName) {\n if (props[propName] !== null && typeof props[propName] !== 'undefined') {\n warnOnce(\"\\\"\" + propName + \"\\\" property of \\\"\" + componentName + \"\\\" has been deprecated.\\n\" + explanation);\n }\n\n for (var _len = arguments.length, rest = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {\n rest[_key - 3] = arguments[_key];\n }\n\n return propType.apply(void 0, [props, propName, componentName].concat(rest));\n };\n} // Shim Element if needed (e.g. in Node environment)\n\nvar Element = typeof window === 'object' && window.Element || function () {};\n\nexport function DOMElement(props, propName, componentName) {\n if (!(props[propName] instanceof Element)) {\n return new Error('Invalid prop `' + propName + '` supplied to `' + componentName + '`. Expected prop to be an instance of Element. Validation failed.');\n }\n}\nexport var targetPropType = PropTypes.oneOfType([PropTypes.string, PropTypes.func, DOMElement, PropTypes.shape({\n current: PropTypes.any\n})]);\nexport var tagPropType = PropTypes.oneOfType([PropTypes.func, PropTypes.string, PropTypes.shape({\n $$typeof: PropTypes.symbol,\n render: PropTypes.func\n}), PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.string, PropTypes.shape({\n $$typeof: PropTypes.symbol,\n render: PropTypes.func\n})]))]);\n/* eslint key-spacing: [\"error\", { afterColon: true, align: \"value\" }] */\n// These are all setup to match what is in the bootstrap _variables.scss\n// https://github.com/twbs/bootstrap/blob/v4-dev/scss/_variables.scss\n\nexport var TransitionTimeouts = {\n Fade: 150,\n // $transition-fade\n Collapse: 350,\n // $transition-collapse\n Modal: 300,\n // $modal-transition\n Carousel: 600 // $carousel-transition\n\n}; // Duplicated Transition.propType keys to ensure that Reactstrap builds\n// for distribution properly exclude these keys for nested child HTML attributes\n// since `react-transition-group` removes propTypes in production builds.\n\nexport var TransitionPropTypeKeys = ['in', 'mountOnEnter', 'unmountOnExit', 'appear', 'enter', 'exit', 'timeout', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited'];\nexport var TransitionStatuses = {\n ENTERING: 'entering',\n ENTERED: 'entered',\n EXITING: 'exiting',\n EXITED: 'exited'\n};\nexport var keyCodes = {\n esc: 27,\n space: 32,\n enter: 13,\n tab: 9,\n up: 38,\n down: 40,\n home: 36,\n end: 35,\n n: 78,\n p: 80\n};\nexport var PopperPlacements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];\nexport var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nexport function isReactRefObj(target) {\n if (target && typeof target === 'object') {\n return 'current' in target;\n }\n\n return false;\n}\n\nfunction getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n\n return Object.prototype.toString.call(value);\n}\n\nexport function toNumber(value) {\n var type = typeof value;\n var NAN = 0 / 0;\n\n if (type === 'number') {\n return value;\n }\n\n if (type === 'symbol' || type === 'object' && getTag(value) === '[object Symbol]') {\n return NAN;\n }\n\n if (isObject(value)) {\n var other = typeof value.valueOf === 'function' ? value.valueOf() : value;\n value = isObject(other) ? \"\" + other : other;\n }\n\n if (type !== 'string') {\n return value === 0 ? value : +value;\n }\n\n value = value.replace(/^\\s+|\\s+$/g, '');\n var isBinary = /^0b[01]+$/i.test(value);\n return isBinary || /^0o[0-7]+$/i.test(value) ? parseInt(value.slice(2), isBinary ? 2 : 8) : /^[-+]0x[0-9a-f]+$/i.test(value) ? NAN : +value;\n}\nexport function isObject(value) {\n var type = typeof value;\n return value != null && (type === 'object' || type === 'function');\n}\nexport function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n\n var tag = getTag(value);\n return tag === '[object Function]' || tag === '[object AsyncFunction]' || tag === '[object GeneratorFunction]' || tag === '[object Proxy]';\n}\nexport function findDOMElements(target) {\n if (isReactRefObj(target)) {\n return target.current;\n }\n\n if (isFunction(target)) {\n return target();\n }\n\n if (typeof target === 'string' && canUseDOM) {\n var selection = document.querySelectorAll(target);\n\n if (!selection.length) {\n selection = document.querySelectorAll(\"#\" + target);\n }\n\n if (!selection.length) {\n throw new Error(\"The target '\" + target + \"' could not be identified in the dom, tip: check spelling\");\n }\n\n return selection;\n }\n\n return target;\n}\nexport function isArrayOrNodeList(els) {\n if (els === null) {\n return false;\n }\n\n return Array.isArray(els) || canUseDOM && typeof els.length === 'number';\n}\nexport function getTarget(target, allElements) {\n var els = findDOMElements(target);\n\n if (allElements) {\n if (isArrayOrNodeList(els)) {\n return els;\n }\n\n if (els === null) {\n return [];\n }\n\n return [els];\n } else {\n if (isArrayOrNodeList(els)) {\n return els[0];\n }\n\n return els;\n }\n}\nexport var defaultToggleEvents = ['touchstart', 'click'];\nexport function addMultipleEventListeners(_els, handler, _events, useCapture) {\n var els = _els;\n\n if (!isArrayOrNodeList(els)) {\n els = [els];\n }\n\n var events = _events;\n\n if (typeof events === 'string') {\n events = events.split(/\\s+/);\n }\n\n if (!isArrayOrNodeList(els) || typeof handler !== 'function' || !Array.isArray(events)) {\n throw new Error(\"\\n The first argument of this function must be DOM node or an array on DOM nodes or NodeList.\\n The second must be a function.\\n The third is a string or an array of strings that represents DOM events\\n \");\n }\n\n Array.prototype.forEach.call(events, function (event) {\n Array.prototype.forEach.call(els, function (el) {\n el.addEventListener(event, handler, useCapture);\n });\n });\n return function removeEvents() {\n Array.prototype.forEach.call(events, function (event) {\n Array.prototype.forEach.call(els, function (el) {\n el.removeEventListener(event, handler, useCapture);\n });\n });\n };\n}\nexport var focusableElements = ['a[href]', 'area[href]', 'input:not([disabled]):not([type=hidden])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'object', 'embed', '[tabindex]:not(.modal)', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable=\"false\"])'];","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport { mapToCssModules, tagPropType } from './utils';\nvar propTypes = {\n active: PropTypes.bool,\n 'aria-label': PropTypes.string,\n block: PropTypes.bool,\n color: PropTypes.string,\n disabled: PropTypes.bool,\n outline: PropTypes.bool,\n tag: tagPropType,\n innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]),\n onClick: PropTypes.func,\n size: PropTypes.string,\n children: PropTypes.node,\n className: PropTypes.string,\n cssModule: PropTypes.object,\n close: PropTypes.bool\n};\nvar defaultProps = {\n color: 'secondary',\n tag: 'button'\n};\n\nvar Button = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Button, _React$Component);\n\n function Button(props) {\n var _this;\n\n _this = _React$Component.call(this, props) || this;\n _this.onClick = _this.onClick.bind(_assertThisInitialized(_this));\n return _this;\n }\n\n var _proto = Button.prototype;\n\n _proto.onClick = function onClick(e) {\n if (this.props.disabled) {\n e.preventDefault();\n return;\n }\n\n if (this.props.onClick) {\n return this.props.onClick(e);\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n active = _this$props.active,\n ariaLabel = _this$props['aria-label'],\n block = _this$props.block,\n className = _this$props.className,\n close = _this$props.close,\n cssModule = _this$props.cssModule,\n color = _this$props.color,\n outline = _this$props.outline,\n size = _this$props.size,\n Tag = _this$props.tag,\n innerRef = _this$props.innerRef,\n attributes = _objectWithoutPropertiesLoose(_this$props, [\"active\", \"aria-label\", \"block\", \"className\", \"close\", \"cssModule\", \"color\", \"outline\", \"size\", \"tag\", \"innerRef\"]);\n\n if (close && typeof attributes.children === 'undefined') {\n attributes.children = /*#__PURE__*/React.createElement(\"span\", {\n \"aria-hidden\": true\n }, \"\\xD7\");\n }\n\n var btnOutlineColor = \"btn\" + (outline ? '-outline' : '') + \"-\" + color;\n var classes = mapToCssModules(classNames(className, {\n close: close\n }, close || 'btn', close || btnOutlineColor, size ? \"btn-\" + size : false, block ? 'btn-block' : false, {\n active: active,\n disabled: this.props.disabled\n }), cssModule);\n\n if (attributes.href && Tag === 'button') {\n Tag = 'a';\n }\n\n var defaultAriaLabel = close ? 'Close' : null;\n return /*#__PURE__*/React.createElement(Tag, _extends({\n type: Tag === 'button' && attributes.onClick ? 'button' : undefined\n }, attributes, {\n className: classes,\n ref: innerRef,\n onClick: this.onClick,\n \"aria-label\": ariaLabel || defaultAriaLabel\n }));\n };\n\n return Button;\n}(React.Component);\n\nButton.propTypes = propTypes;\nButton.defaultProps = defaultProps;\nexport default Button;","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport { Transition } from 'react-transition-group';\nimport { mapToCssModules, omit, pick, TransitionPropTypeKeys, TransitionTimeouts, tagPropType } from './utils';\n\nvar propTypes = _objectSpread(_objectSpread({}, Transition.propTypes), {}, {\n children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),\n tag: tagPropType,\n baseClass: PropTypes.string,\n baseClassActive: PropTypes.string,\n className: PropTypes.string,\n cssModule: PropTypes.object,\n innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.string, PropTypes.func])\n});\n\nvar defaultProps = _objectSpread(_objectSpread({}, Transition.defaultProps), {}, {\n tag: 'div',\n baseClass: 'fade',\n baseClassActive: 'show',\n timeout: TransitionTimeouts.Fade,\n appear: true,\n enter: true,\n exit: true,\n in: true\n});\n\nfunction Fade(props) {\n var Tag = props.tag,\n baseClass = props.baseClass,\n baseClassActive = props.baseClassActive,\n className = props.className,\n cssModule = props.cssModule,\n children = props.children,\n innerRef = props.innerRef,\n otherProps = _objectWithoutPropertiesLoose(props, [\"tag\", \"baseClass\", \"baseClassActive\", \"className\", \"cssModule\", \"children\", \"innerRef\"]);\n\n var transitionProps = pick(otherProps, TransitionPropTypeKeys);\n var childProps = omit(otherProps, TransitionPropTypeKeys);\n return /*#__PURE__*/React.createElement(Transition, transitionProps, function (status) {\n var isActive = status === 'entered';\n var classes = mapToCssModules(classNames(className, baseClass, isActive && baseClassActive), cssModule);\n return /*#__PURE__*/React.createElement(Tag, _extends({\n className: classes\n }, childProps, {\n ref: innerRef\n }), children);\n });\n}\n\nFade.propTypes = propTypes;\nFade.defaultProps = defaultProps;\nexport default Fade;","import _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport { canUseDOM } from './utils';\nvar propTypes = {\n children: PropTypes.node.isRequired,\n node: PropTypes.any\n};\n\nvar Portal = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Portal, _React$Component);\n\n function Portal() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Portal.prototype;\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n if (this.defaultNode) {\n document.body.removeChild(this.defaultNode);\n }\n\n this.defaultNode = null;\n };\n\n _proto.render = function render() {\n if (!canUseDOM) {\n return null;\n }\n\n if (!this.props.node && !this.defaultNode) {\n this.defaultNode = document.createElement('div');\n document.body.appendChild(this.defaultNode);\n }\n\n return /*#__PURE__*/ReactDOM.createPortal(this.props.children, this.props.node || this.defaultNode);\n };\n\n return Portal;\n}(React.Component);\n\nPortal.propTypes = propTypes;\nexport default Portal;","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport Portal from './Portal';\nimport Fade from './Fade';\nimport { getOriginalBodyPadding, conditionallyUpdateScrollbar, setScrollbarWidth, mapToCssModules, omit, focusableElements, TransitionTimeouts, keyCodes, targetPropType, getTarget } from './utils';\n\nfunction noop() {}\n\nvar FadePropTypes = PropTypes.shape(Fade.propTypes);\nvar propTypes = {\n isOpen: PropTypes.bool,\n autoFocus: PropTypes.bool,\n centered: PropTypes.bool,\n scrollable: PropTypes.bool,\n size: PropTypes.string,\n toggle: PropTypes.func,\n keyboard: PropTypes.bool,\n role: PropTypes.string,\n labelledBy: PropTypes.string,\n backdrop: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['static'])]),\n onEnter: PropTypes.func,\n onExit: PropTypes.func,\n onOpened: PropTypes.func,\n onClosed: PropTypes.func,\n children: PropTypes.node,\n className: PropTypes.string,\n wrapClassName: PropTypes.string,\n modalClassName: PropTypes.string,\n backdropClassName: PropTypes.string,\n contentClassName: PropTypes.string,\n external: PropTypes.node,\n fade: PropTypes.bool,\n cssModule: PropTypes.object,\n zIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n backdropTransition: FadePropTypes,\n modalTransition: FadePropTypes,\n innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.string, PropTypes.func]),\n unmountOnClose: PropTypes.bool,\n returnFocusAfterClose: PropTypes.bool,\n container: targetPropType,\n trapFocus: PropTypes.bool\n};\nvar propsToOmit = Object.keys(propTypes);\nvar defaultProps = {\n isOpen: false,\n autoFocus: true,\n centered: false,\n scrollable: false,\n role: 'dialog',\n backdrop: true,\n keyboard: true,\n zIndex: 1050,\n fade: true,\n onOpened: noop,\n onClosed: noop,\n modalTransition: {\n timeout: TransitionTimeouts.Modal\n },\n backdropTransition: {\n mountOnEnter: true,\n timeout: TransitionTimeouts.Fade // uses standard fade transition\n\n },\n unmountOnClose: true,\n returnFocusAfterClose: true,\n container: 'body',\n trapFocus: false\n};\n\nvar Modal = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Modal, _React$Component);\n\n function Modal(props) {\n var _this;\n\n _this = _React$Component.call(this, props) || this;\n _this._element = null;\n _this._originalBodyPadding = null;\n _this.getFocusableChildren = _this.getFocusableChildren.bind(_assertThisInitialized(_this));\n _this.handleBackdropClick = _this.handleBackdropClick.bind(_assertThisInitialized(_this));\n _this.handleBackdropMouseDown = _this.handleBackdropMouseDown.bind(_assertThisInitialized(_this));\n _this.handleEscape = _this.handleEscape.bind(_assertThisInitialized(_this));\n _this.handleStaticBackdropAnimation = _this.handleStaticBackdropAnimation.bind(_assertThisInitialized(_this));\n _this.handleTab = _this.handleTab.bind(_assertThisInitialized(_this));\n _this.onOpened = _this.onOpened.bind(_assertThisInitialized(_this));\n _this.onClosed = _this.onClosed.bind(_assertThisInitialized(_this));\n _this.manageFocusAfterClose = _this.manageFocusAfterClose.bind(_assertThisInitialized(_this));\n _this.clearBackdropAnimationTimeout = _this.clearBackdropAnimationTimeout.bind(_assertThisInitialized(_this));\n _this.trapFocus = _this.trapFocus.bind(_assertThisInitialized(_this));\n _this.state = {\n isOpen: false,\n showStaticBackdropAnimation: false\n };\n return _this;\n }\n\n var _proto = Modal.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n var _this$props = this.props,\n isOpen = _this$props.isOpen,\n autoFocus = _this$props.autoFocus,\n onEnter = _this$props.onEnter;\n\n if (isOpen) {\n this.init();\n this.setState({\n isOpen: true\n });\n\n if (autoFocus) {\n this.setFocus();\n }\n }\n\n if (onEnter) {\n onEnter();\n } // traps focus inside the Modal, even if the browser address bar is focused\n\n\n document.addEventListener('focus', this.trapFocus, true);\n this._isMounted = true;\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {\n if (this.props.isOpen && !prevProps.isOpen) {\n this.init();\n this.setState({\n isOpen: true\n }); // let render() renders Modal Dialog first\n\n return;\n } // now Modal Dialog is rendered and we can refer this._element and this._dialog\n\n\n if (this.props.autoFocus && this.state.isOpen && !prevState.isOpen) {\n this.setFocus();\n }\n\n if (this._element && prevProps.zIndex !== this.props.zIndex) {\n this._element.style.zIndex = this.props.zIndex;\n }\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.clearBackdropAnimationTimeout();\n\n if (this.props.onExit) {\n this.props.onExit();\n }\n\n if (this._element) {\n this.destroy();\n\n if (this.props.isOpen || this.state.isOpen) {\n this.close();\n }\n }\n\n document.removeEventListener('focus', this.trapFocus, true);\n this._isMounted = false;\n };\n\n _proto.trapFocus = function trapFocus(ev) {\n if (!this.props.trapFocus) {\n return;\n }\n\n if (!this._element) //element is not attached\n return;\n if (this._dialog && this._dialog.parentNode === ev.target) // initial focus when the Modal is opened\n return;\n if (this.modalIndex < Modal.openCount - 1) // last opened modal\n return;\n var children = this.getFocusableChildren();\n\n for (var i = 0; i < children.length; i++) {\n // focus is already inside the Modal\n if (children[i] === ev.target) return;\n }\n\n if (children.length > 0) {\n // otherwise focus the first focusable element in the Modal\n ev.preventDefault();\n ev.stopPropagation();\n children[0].focus();\n }\n };\n\n _proto.onOpened = function onOpened(node, isAppearing) {\n this.props.onOpened();\n (this.props.modalTransition.onEntered || noop)(node, isAppearing);\n };\n\n _proto.onClosed = function onClosed(node) {\n var unmountOnClose = this.props.unmountOnClose; // so all methods get called before it is unmounted\n\n this.props.onClosed();\n (this.props.modalTransition.onExited || noop)(node);\n\n if (unmountOnClose) {\n this.destroy();\n }\n\n this.close();\n\n if (this._isMounted) {\n this.setState({\n isOpen: false\n });\n }\n };\n\n _proto.setFocus = function setFocus() {\n if (this._dialog && this._dialog.parentNode && typeof this._dialog.parentNode.focus === 'function') {\n this._dialog.parentNode.focus();\n }\n };\n\n _proto.getFocusableChildren = function getFocusableChildren() {\n return this._element.querySelectorAll(focusableElements.join(', '));\n };\n\n _proto.getFocusedChild = function getFocusedChild() {\n var currentFocus;\n var focusableChildren = this.getFocusableChildren();\n\n try {\n currentFocus = document.activeElement;\n } catch (err) {\n currentFocus = focusableChildren[0];\n }\n\n return currentFocus;\n } // not mouseUp because scrollbar fires it, shouldn't close when user scrolls\n ;\n\n _proto.handleBackdropClick = function handleBackdropClick(e) {\n if (e.target === this._mouseDownElement) {\n e.stopPropagation();\n var backdrop = this._dialog ? this._dialog.parentNode : null;\n\n if (backdrop && e.target === backdrop && this.props.backdrop === 'static') {\n this.handleStaticBackdropAnimation();\n }\n\n if (!this.props.isOpen || this.props.backdrop !== true) return;\n\n if (backdrop && e.target === backdrop && this.props.toggle) {\n this.props.toggle(e);\n }\n }\n };\n\n _proto.handleTab = function handleTab(e) {\n if (e.which !== 9) return;\n if (this.modalIndex < Modal.openCount - 1) return; // last opened modal\n\n var focusableChildren = this.getFocusableChildren();\n var totalFocusable = focusableChildren.length;\n if (totalFocusable === 0) return;\n var currentFocus = this.getFocusedChild();\n var focusedIndex = 0;\n\n for (var i = 0; i < totalFocusable; i += 1) {\n if (focusableChildren[i] === currentFocus) {\n focusedIndex = i;\n break;\n }\n }\n\n if (e.shiftKey && focusedIndex === 0) {\n e.preventDefault();\n focusableChildren[totalFocusable - 1].focus();\n } else if (!e.shiftKey && focusedIndex === totalFocusable - 1) {\n e.preventDefault();\n focusableChildren[0].focus();\n }\n };\n\n _proto.handleBackdropMouseDown = function handleBackdropMouseDown(e) {\n this._mouseDownElement = e.target;\n };\n\n _proto.handleEscape = function handleEscape(e) {\n if (this.props.isOpen && e.keyCode === keyCodes.esc && this.props.toggle) {\n if (this.props.keyboard) {\n e.preventDefault();\n e.stopPropagation();\n this.props.toggle(e);\n } else if (this.props.backdrop === 'static') {\n e.preventDefault();\n e.stopPropagation();\n this.handleStaticBackdropAnimation();\n }\n }\n };\n\n _proto.handleStaticBackdropAnimation = function handleStaticBackdropAnimation() {\n var _this2 = this;\n\n this.clearBackdropAnimationTimeout();\n this.setState({\n showStaticBackdropAnimation: true\n });\n this._backdropAnimationTimeout = setTimeout(function () {\n _this2.setState({\n showStaticBackdropAnimation: false\n });\n }, 100);\n };\n\n _proto.init = function init() {\n try {\n this._triggeringElement = document.activeElement;\n } catch (err) {\n this._triggeringElement = null;\n }\n\n if (!this._element) {\n this._element = document.createElement('div');\n\n this._element.setAttribute('tabindex', '-1');\n\n this._element.style.position = 'relative';\n this._element.style.zIndex = this.props.zIndex;\n this._mountContainer = getTarget(this.props.container);\n\n this._mountContainer.appendChild(this._element);\n }\n\n this._originalBodyPadding = getOriginalBodyPadding();\n conditionallyUpdateScrollbar();\n\n if (Modal.openCount === 0) {\n document.body.className = classNames(document.body.className, mapToCssModules('modal-open', this.props.cssModule));\n }\n\n this.modalIndex = Modal.openCount;\n Modal.openCount += 1;\n };\n\n _proto.destroy = function destroy() {\n if (this._element) {\n this._mountContainer.removeChild(this._element);\n\n this._element = null;\n }\n\n this.manageFocusAfterClose();\n };\n\n _proto.manageFocusAfterClose = function manageFocusAfterClose() {\n if (this._triggeringElement) {\n var returnFocusAfterClose = this.props.returnFocusAfterClose;\n if (this._triggeringElement.focus && returnFocusAfterClose) this._triggeringElement.focus();\n this._triggeringElement = null;\n }\n };\n\n _proto.close = function close() {\n if (Modal.openCount <= 1) {\n var modalOpenClassName = mapToCssModules('modal-open', this.props.cssModule); // Use regex to prevent matching `modal-open` as part of a different class, e.g. `my-modal-opened`\n\n var modalOpenClassNameRegex = new RegExp(\"(^| )\" + modalOpenClassName + \"( |$)\");\n document.body.className = document.body.className.replace(modalOpenClassNameRegex, ' ').trim();\n }\n\n this.manageFocusAfterClose();\n Modal.openCount = Math.max(0, Modal.openCount - 1);\n setScrollbarWidth(this._originalBodyPadding);\n };\n\n _proto.renderModalDialog = function renderModalDialog() {\n var _classNames,\n _this3 = this;\n\n var attributes = omit(this.props, propsToOmit);\n var dialogBaseClass = 'modal-dialog';\n return /*#__PURE__*/React.createElement(\"div\", _extends({}, attributes, {\n className: mapToCssModules(classNames(dialogBaseClass, this.props.className, (_classNames = {}, _classNames[\"modal-\" + this.props.size] = this.props.size, _classNames[dialogBaseClass + \"-centered\"] = this.props.centered, _classNames[dialogBaseClass + \"-scrollable\"] = this.props.scrollable, _classNames)), this.props.cssModule),\n role: \"document\",\n ref: function ref(c) {\n _this3._dialog = c;\n }\n }), /*#__PURE__*/React.createElement(\"div\", {\n className: mapToCssModules(classNames('modal-content', this.props.contentClassName), this.props.cssModule)\n }, this.props.children));\n };\n\n _proto.render = function render() {\n var unmountOnClose = this.props.unmountOnClose;\n\n if (!!this._element && (this.state.isOpen || !unmountOnClose)) {\n var isModalHidden = !!this._element && !this.state.isOpen && !unmountOnClose;\n this._element.style.display = isModalHidden ? 'none' : 'block';\n var _this$props2 = this.props,\n wrapClassName = _this$props2.wrapClassName,\n modalClassName = _this$props2.modalClassName,\n backdropClassName = _this$props2.backdropClassName,\n cssModule = _this$props2.cssModule,\n isOpen = _this$props2.isOpen,\n backdrop = _this$props2.backdrop,\n role = _this$props2.role,\n labelledBy = _this$props2.labelledBy,\n external = _this$props2.external,\n innerRef = _this$props2.innerRef;\n var modalAttributes = {\n onClick: this.handleBackdropClick,\n onMouseDown: this.handleBackdropMouseDown,\n onKeyUp: this.handleEscape,\n onKeyDown: this.handleTab,\n style: {\n display: 'block'\n },\n 'aria-labelledby': labelledBy,\n role: role,\n tabIndex: '-1'\n };\n var hasTransition = this.props.fade;\n\n var modalTransition = _objectSpread(_objectSpread(_objectSpread({}, Fade.defaultProps), this.props.modalTransition), {}, {\n baseClass: hasTransition ? this.props.modalTransition.baseClass : '',\n timeout: hasTransition ? this.props.modalTransition.timeout : 0\n });\n\n var backdropTransition = _objectSpread(_objectSpread(_objectSpread({}, Fade.defaultProps), this.props.backdropTransition), {}, {\n baseClass: hasTransition ? this.props.backdropTransition.baseClass : '',\n timeout: hasTransition ? this.props.backdropTransition.timeout : 0\n });\n\n var Backdrop = backdrop && (hasTransition ? /*#__PURE__*/React.createElement(Fade, _extends({}, backdropTransition, {\n in: isOpen && !!backdrop,\n cssModule: cssModule,\n className: mapToCssModules(classNames('modal-backdrop', backdropClassName), cssModule)\n })) : /*#__PURE__*/React.createElement(\"div\", {\n className: mapToCssModules(classNames('modal-backdrop', 'show', backdropClassName), cssModule)\n }));\n return /*#__PURE__*/React.createElement(Portal, {\n node: this._element\n }, /*#__PURE__*/React.createElement(\"div\", {\n className: mapToCssModules(wrapClassName)\n }, /*#__PURE__*/React.createElement(Fade, _extends({}, modalAttributes, modalTransition, {\n in: isOpen,\n onEntered: this.onOpened,\n onExited: this.onClosed,\n cssModule: cssModule,\n className: mapToCssModules(classNames('modal', modalClassName, this.state.showStaticBackdropAnimation && 'modal-static'), cssModule),\n innerRef: innerRef\n }), external, this.renderModalDialog()), Backdrop));\n }\n\n return null;\n };\n\n _proto.clearBackdropAnimationTimeout = function clearBackdropAnimationTimeout() {\n if (this._backdropAnimationTimeout) {\n clearTimeout(this._backdropAnimationTimeout);\n this._backdropAnimationTimeout = undefined;\n }\n };\n\n return Modal;\n}(React.Component);\n\nModal.propTypes = propTypes;\nModal.defaultProps = defaultProps;\nModal.openCount = 0;\nexport default Modal;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport { mapToCssModules, tagPropType } from './utils';\nvar propTypes = {\n tag: tagPropType,\n className: PropTypes.string,\n cssModule: PropTypes.object\n};\nvar defaultProps = {\n tag: 'div'\n};\n\nvar ModalBody = function ModalBody(props) {\n var className = props.className,\n cssModule = props.cssModule,\n Tag = props.tag,\n attributes = _objectWithoutPropertiesLoose(props, [\"className\", \"cssModule\", \"tag\"]);\n\n var classes = mapToCssModules(classNames(className, 'modal-body'), cssModule);\n return /*#__PURE__*/React.createElement(Tag, _extends({}, attributes, {\n className: classes\n }));\n};\n\nModalBody.propTypes = propTypes;\nModalBody.defaultProps = defaultProps;\nexport default ModalBody;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\n\n/* eslint react/prefer-stateless-function: 0 */\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport { mapToCssModules, warnOnce, tagPropType } from './utils';\nvar propTypes = {\n children: PropTypes.node,\n type: PropTypes.string,\n size: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n bsSize: PropTypes.string,\n valid: PropTypes.bool,\n invalid: PropTypes.bool,\n tag: tagPropType,\n innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]),\n plaintext: PropTypes.bool,\n addon: PropTypes.bool,\n className: PropTypes.string,\n cssModule: PropTypes.object\n};\nvar defaultProps = {\n type: 'text'\n};\n\nvar Input = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Input, _React$Component);\n\n function Input(props) {\n var _this;\n\n _this = _React$Component.call(this, props) || this;\n _this.getRef = _this.getRef.bind(_assertThisInitialized(_this));\n _this.focus = _this.focus.bind(_assertThisInitialized(_this));\n return _this;\n }\n\n var _proto = Input.prototype;\n\n _proto.getRef = function getRef(ref) {\n if (this.props.innerRef) {\n this.props.innerRef(ref);\n }\n\n this.ref = ref;\n };\n\n _proto.focus = function focus() {\n if (this.ref) {\n this.ref.focus();\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n className = _this$props.className,\n cssModule = _this$props.cssModule,\n type = _this$props.type,\n bsSize = _this$props.bsSize,\n valid = _this$props.valid,\n invalid = _this$props.invalid,\n tag = _this$props.tag,\n addon = _this$props.addon,\n plaintext = _this$props.plaintext,\n innerRef = _this$props.innerRef,\n attributes = _objectWithoutPropertiesLoose(_this$props, [\"className\", \"cssModule\", \"type\", \"bsSize\", \"valid\", \"invalid\", \"tag\", \"addon\", \"plaintext\", \"innerRef\"]);\n\n var checkInput = ['radio', 'checkbox'].indexOf(type) > -1;\n var isNotaNumber = new RegExp('\\\\D', 'g');\n var fileInput = type === 'file';\n var textareaInput = type === 'textarea';\n var selectInput = type === 'select';\n var rangeInput = type === 'range';\n var Tag = tag || (selectInput || textareaInput ? type : 'input');\n var formControlClass = 'form-control';\n\n if (plaintext) {\n formControlClass = formControlClass + \"-plaintext\";\n Tag = tag || 'input';\n } else if (fileInput) {\n formControlClass = formControlClass + \"-file\";\n } else if (rangeInput) {\n formControlClass = formControlClass + \"-range\";\n } else if (checkInput) {\n if (addon) {\n formControlClass = null;\n } else {\n formControlClass = 'form-check-input';\n }\n }\n\n if (attributes.size && isNotaNumber.test(attributes.size)) {\n warnOnce('Please use the prop \"bsSize\" instead of the \"size\" to bootstrap\\'s input sizing.');\n bsSize = attributes.size;\n delete attributes.size;\n }\n\n var classes = mapToCssModules(classNames(className, invalid && 'is-invalid', valid && 'is-valid', bsSize ? \"form-control-\" + bsSize : false, formControlClass), cssModule);\n\n if (Tag === 'input' || tag && typeof tag === 'function') {\n attributes.type = type;\n }\n\n if (attributes.children && !(plaintext || type === 'select' || typeof Tag !== 'string' || Tag === 'select')) {\n warnOnce(\"Input with a type of \\\"\" + type + \"\\\" cannot have children. Please use \\\"value\\\"/\\\"defaultValue\\\" instead.\");\n delete attributes.children;\n }\n\n return /*#__PURE__*/React.createElement(Tag, _extends({}, attributes, {\n ref: innerRef,\n className: classes,\n \"aria-invalid\": invalid\n }));\n };\n\n return Input;\n}(React.Component);\n\nInput.propTypes = propTypes;\nInput.defaultProps = defaultProps;\nexport default Input;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport { mapToCssModules, tagPropType } from './utils';\nvar propTypes = {\n tag: tagPropType,\n type: PropTypes.string,\n size: PropTypes.string,\n color: PropTypes.string,\n className: PropTypes.string,\n cssModule: PropTypes.object,\n children: PropTypes.string\n};\nvar defaultProps = {\n tag: 'div',\n type: 'border',\n children: 'Loading...'\n};\n\nvar Spinner = function Spinner(props) {\n var className = props.className,\n cssModule = props.cssModule,\n type = props.type,\n size = props.size,\n color = props.color,\n children = props.children,\n Tag = props.tag,\n attributes = _objectWithoutPropertiesLoose(props, [\"className\", \"cssModule\", \"type\", \"size\", \"color\", \"children\", \"tag\"]);\n\n var classes = mapToCssModules(classNames(className, size ? \"spinner-\" + type + \"-\" + size : false, \"spinner-\" + type, color ? \"text-\" + color : false), cssModule);\n return /*#__PURE__*/React.createElement(Tag, _extends({\n role: \"status\"\n }, attributes, {\n className: classes\n }), children && /*#__PURE__*/React.createElement(\"span\", {\n className: mapToCssModules('sr-only', cssModule)\n }, children));\n};\n\nSpinner.propTypes = propTypes;\nSpinner.defaultProps = defaultProps;\nexport default Spinner;","import { IconComponent } from './types';\n\nconst Logo: IconComponent = (props) => (\n \n \n \n \n \n \n \n \n \n \n);\n\nexport default Logo;\n","'use strict';\n\nvar isArray = Array.isArray;\nvar keyList = Object.keys;\nvar hasProp = Object.prototype.hasOwnProperty;\nvar hasElementType = typeof Element !== 'undefined';\n\nfunction equal(a, b) {\n // fast-deep-equal index.js 2.0.1\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = isArray(a)\n , arrB = isArray(b)\n , i\n , length\n , key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var dateA = a instanceof Date\n , dateB = b instanceof Date;\n if (dateA != dateB) return false;\n if (dateA && dateB) return a.getTime() == b.getTime();\n\n var regexpA = a instanceof RegExp\n , regexpB = b instanceof RegExp;\n if (regexpA != regexpB) return false;\n if (regexpA && regexpB) return a.toString() == b.toString();\n\n var keys = keyList(a);\n length = keys.length;\n\n if (length !== keyList(b).length)\n return false;\n\n for (i = length; i-- !== 0;)\n if (!hasProp.call(b, keys[i])) return false;\n // end fast-deep-equal\n\n // start react-fast-compare\n // custom handling for DOM elements\n if (hasElementType && a instanceof Element && b instanceof Element)\n return a === b;\n\n // custom handling for React\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (key === '_owner' && a.$$typeof) {\n // React-specific: avoid traversing React elements' _owner.\n // _owner contains circular references\n // and is not needed when comparing the actual elements (and not their owners)\n // .$$typeof and ._store on just reasonable markers of a react element\n continue;\n } else {\n // all other properties should be traversed as usual\n if (!equal(a[key], b[key])) return false;\n }\n }\n // end react-fast-compare\n\n // fast-deep-equal index.js 2.0.1\n return true;\n }\n\n return a !== a && b !== b;\n}\n// end fast-deep-equal\n\nmodule.exports = function exportedEqual(a, b) {\n try {\n return equal(a, b);\n } catch (error) {\n if ((error.message && error.message.match(/stack|recursion/i)) || (error.number === -2146828260)) {\n // warn on circular references, don't crash\n // browsers give this different errors name and messages:\n // chrome/safari: \"RangeError\", \"Maximum call stack size exceeded\"\n // firefox: \"InternalError\", too much recursion\"\n // edge: \"Error\", \"Out of stack space\"\n console.warn('Warning: react-fast-compare does not handle circular references.', error.name, error.message);\n return false;\n }\n // some other error. we should definitely know about these\n throw error;\n }\n};\n","var isMergeableObject = function isMergeableObject(value) {\n\treturn isNonNullObject(value)\n\t\t&& !isSpecial(value)\n};\n\nfunction isNonNullObject(value) {\n\treturn !!value && typeof value === 'object'\n}\n\nfunction isSpecial(value) {\n\tvar stringValue = Object.prototype.toString.call(value);\n\n\treturn stringValue === '[object RegExp]'\n\t\t|| stringValue === '[object Date]'\n\t\t|| isReactElement(value)\n}\n\n// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25\nvar canUseSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;\n\nfunction isReactElement(value) {\n\treturn value.$$typeof === REACT_ELEMENT_TYPE\n}\n\nfunction emptyTarget(val) {\n\treturn Array.isArray(val) ? [] : {}\n}\n\nfunction cloneUnlessOtherwiseSpecified(value, options) {\n\treturn (options.clone !== false && options.isMergeableObject(value))\n\t\t? deepmerge(emptyTarget(value), value, options)\n\t\t: value\n}\n\nfunction defaultArrayMerge(target, source, options) {\n\treturn target.concat(source).map(function(element) {\n\t\treturn cloneUnlessOtherwiseSpecified(element, options)\n\t})\n}\n\nfunction mergeObject(target, source, options) {\n\tvar destination = {};\n\tif (options.isMergeableObject(target)) {\n\t\tObject.keys(target).forEach(function(key) {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(target[key], options);\n\t\t});\n\t}\n\tObject.keys(source).forEach(function(key) {\n\t\tif (!options.isMergeableObject(source[key]) || !target[key]) {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(source[key], options);\n\t\t} else {\n\t\t\tdestination[key] = deepmerge(target[key], source[key], options);\n\t\t}\n\t});\n\treturn destination\n}\n\nfunction deepmerge(target, source, options) {\n\toptions = options || {};\n\toptions.arrayMerge = options.arrayMerge || defaultArrayMerge;\n\toptions.isMergeableObject = options.isMergeableObject || isMergeableObject;\n\n\tvar sourceIsArray = Array.isArray(source);\n\tvar targetIsArray = Array.isArray(target);\n\tvar sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;\n\n\tif (!sourceAndTargetTypesMatch) {\n\t\treturn cloneUnlessOtherwiseSpecified(source, options)\n\t} else if (sourceIsArray) {\n\t\treturn options.arrayMerge(target, source, options)\n\t} else {\n\t\treturn mergeObject(target, source, options)\n\t}\n}\n\ndeepmerge.all = function deepmergeAll(array, options) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new Error('first argument should be an array')\n\t}\n\n\treturn array.reduce(function(prev, next) {\n\t\treturn deepmerge(prev, next, options)\n\t}, {})\n};\n\nvar deepmerge_1 = deepmerge;\n\nexport default deepmerge_1;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n","import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n","import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n","import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n","import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n","import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n","import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n","import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n","import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n","import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n","import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n","import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n","import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n","import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n","import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n","import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n","import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n","import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n","import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n","import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n","import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n","import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n","import copyObject from './_copyObject.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n","import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\n","import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n","import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n","import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n","import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n","import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n","import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n","import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nexport default initCloneArray;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n","import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n","/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n","import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n","import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nexport default initCloneByTag;\n","import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n","import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n","import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n","import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n","import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n","import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n","import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nexport default baseClone;\n","import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\nfunction clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n}\n\nexport default clone;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n","import MapCache from './_MapCache.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nexport default memoize;\n","import memoize from './memoize.js';\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nexport default memoizeCapped;\n","import memoizeCapped from './_memoizeCapped.js';\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nexport default stringToPath;\n","import isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default toKey;\n","import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default baseToString;\n","import baseToString from './_baseToString.js';\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n","import arrayMap from './_arrayMap.js';\nimport copyArray from './_copyArray.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\nimport stringToPath from './_stringToPath.js';\nimport toKey from './_toKey.js';\nimport toString from './toString.js';\n\n/**\n * Converts `value` to a property path array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Util\n * @param {*} value The value to convert.\n * @returns {Array} Returns the new property path array.\n * @example\n *\n * _.toPath('a.b.c');\n * // => ['a', 'b', 'c']\n *\n * _.toPath('a[0].b.c');\n * // => ['a', '0', 'b', 'c']\n */\nfunction toPath(value) {\n if (isArray(value)) {\n return arrayMap(value, toKey);\n }\n return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));\n}\n\nexport default toPath;\n","import{createContext as e,useContext as r,useReducer as t,createElement as n,useEffect as o,useLayoutEffect as c,useRef as u,useState as s}from\"react\";import{unstable_runWithPriority as i,unstable_NormalPriority as p}from\"scheduler\";import{unstable_batchedUpdates as l}from\"react-dom\";const d=Symbol(),f=Symbol(),v=\"undefined\"==typeof window||/ServerSideRendering/.test(window.navigator&&window.navigator.userAgent)?o:c,a=i?e=>i(p,e):e=>e(),w=e=>e;function E(r){const t=e({[d]:{v:{current:r},n:{current:-1},l:new Set,u:e=>e()}});var o;return t[f]=t.Provider,t.Provider=(o=t.Provider,({value:e,children:r})=>{const t=u(e),c=u(0),[i,p]=s(null);i&&(i(e),p(null));const f=u();if(!f.current){const e=new Set,r=(r,t)=>{l(()=>{c.current+=1;const n={n:c.current};null!=t&&t.suspense&&(n.n*=-1,n.p=new Promise(e=>{p(()=>r=>{n.v=r,delete n.p,e(r)})})),e.forEach(e=>e(n)),r()})};f.current={[d]:{v:t,n:c,l:e,u:r}}}return v(()=>{t.current=e,c.current+=1,a(()=>{f.current[d].l.forEach(r=>{r({n:c.current,v:e})})})},[e]),n(o,{value:f.current},r)}),delete t.Consumer,t}function h(e,n){const o=r(e)[d];if(\"object\"==typeof process&&\"production\"!==process.env.NODE_ENV&&!o)throw new Error(\"useContextSelector requires special context\");const{v:{current:c},n:{current:u},l:s}=o,i=n(c),[p,l]=t((e,r)=>{if(!r)return[c,i];if(\"p\"in r)throw r.p;if(r.n===u)return Object.is(e[1],i)?e:[c,i];try{if(\"v\"in r){if(Object.is(e[0],r.v))return e;const t=n(r.v);return Object.is(e[1],t)?e:[r.v,t]}}catch(e){}return[...e]},[c,i]);return Object.is(p[1],i)||l(),v(()=>(s.add(l),()=>{s.delete(l)}),[s]),p[1]}function m(e){return h(e,w)}function b(e){const t=r(e)[d];if(\"object\"==typeof process&&\"production\"!==process.env.NODE_ENV&&!t)throw new Error(\"useContextUpdate requires special context\");const{u:n}=t;return n}const x=({context:e,value:r,children:t})=>{const{[f]:o}=e;if(\"object\"==typeof process&&\"production\"!==process.env.NODE_ENV&&!o)throw new Error(\"BridgeProvider requires special context\");return n(o,{value:r},t)},j=e=>{const t=r(e);if(\"object\"==typeof process&&\"production\"!==process.env.NODE_ENV&&!t[d])throw new Error(\"useBridgeValue requires special context\");return t};export{x as BridgeProvider,E as createContext,j as useBridgeValue,m as useContext,h as useContextSelector,b as useContextUpdate};\n//# sourceMappingURL=index.modern.js.map\n","import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nexport default cloneDeep;\n","import { Children, createElement, Fragment, useRef, useEffect, useReducer, useCallback, useMemo, useImperativeHandle, useLayoutEffect, forwardRef, Component } from 'react';\nimport isEqual from 'react-fast-compare';\nimport deepmerge from 'deepmerge';\nimport isPlainObject from 'lodash-es/isPlainObject';\nimport clone from 'lodash-es/clone';\nimport toPath from 'lodash-es/toPath';\nimport { createContext, useContext, useContextSelector } from 'use-context-selector';\nimport invariant from 'tiny-warning';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport cloneDeep from 'lodash-es/cloneDeep';\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\n/** @private is the value an empty array? */\n\nvar isEmptyArray = function isEmptyArray(value) {\n return Array.isArray(value) && value.length === 0;\n};\n/** @private is the given object a Function? */\n\nvar isFunction = function isFunction(obj) {\n return typeof obj === 'function';\n};\n/** @private is the given object an Object? */\n\nvar isObject = function isObject(obj) {\n return obj !== null && typeof obj === 'object';\n};\n/** @private is the given object an integer? */\n\nvar isInteger = function isInteger(obj) {\n return String(Math.floor(Number(obj))) === obj;\n};\n/** @private is the given object a string? */\n\nvar isString = function isString(obj) {\n return Object.prototype.toString.call(obj) === '[object String]';\n};\n/** @private is the given object a NaN? */\n// eslint-disable-next-line no-self-compare\n\nvar isNaN$1 = function isNaN(obj) {\n return obj !== obj;\n};\n/** @private Does a React component have exactly 0 children? */\n\nvar isEmptyChildren = function isEmptyChildren(children) {\n return Children.count(children) === 0;\n};\n/** @private is the given object/value a promise? */\n\nvar isPromise = function isPromise(value) {\n return isObject(value) && isFunction(value.then);\n};\n/** @private is the given object/value a type of synthetic event? */\n\nvar isInputEvent = function isInputEvent(value) {\n return value && isObject(value) && isObject(value.target);\n};\n/** @private Are we in RN? */\n\nvar isReactNative = typeof window !== 'undefined' && window.navigator && window.navigator.product && window.navigator.product === 'ReactNative';\n/**\r\n * Same as document.activeElement but wraps in a try-catch block. In IE it is\r\n * not safe to call document.activeElement if there is nothing focused.\r\n *\r\n * The activeElement will be null only if the document or document body is not\r\n * yet defined.\r\n *\r\n * @param {?Document} doc Defaults to current document.\r\n * @return {Element | null}\r\n * @see https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/dom/getActiveElement.js\r\n */\n\nfunction getActiveElement(doc) {\n doc = doc || (typeof document !== 'undefined' ? document : undefined);\n\n if (typeof doc === 'undefined') {\n return null;\n }\n\n try {\n return doc.activeElement || doc.body;\n } catch (e) {\n return doc.body;\n }\n}\n/**\r\n * Deeply get a value from an object via its path.\r\n */\n\nfunction getIn(obj, key, def, p) {\n if (p === void 0) {\n p = 0;\n }\n\n var path = toPath(key);\n\n while (obj && p < path.length) {\n obj = obj[path[p++]];\n }\n\n return obj === undefined ? def : obj;\n}\n/**\r\n * Deeply set a value from in object via it's path. If the value at `path`\r\n * has changed, return a shallow copy of obj with `value` set at `path`.\r\n * If `value` has not changed, return the original `obj`.\r\n *\r\n * Existing objects / arrays along `path` are also shallow copied. Sibling\r\n * objects along path retain the same internal js reference. Since new\r\n * objects / arrays are only created along `path`, we can test if anything\r\n * changed in a nested structure by comparing the object's reference in\r\n * the old and new object, similar to how russian doll cache invalidation\r\n * works.\r\n *\r\n * In earlier versions of this function, which used cloneDeep, there were\r\n * issues whereby settings a nested value would mutate the parent\r\n * instead of creating a new object. `clone` avoids that bug making a\r\n * shallow copy of the objects along the update path\r\n * so no object is mutated in place.\r\n *\r\n * Before changing this function, please read through the following\r\n * discussions.\r\n *\r\n * @see https://github.com/developit/linkstate\r\n * @see https://github.com/jaredpalmer/formik/pull/123\r\n */\n\nfunction setIn(obj, path, value) {\n var res = clone(obj); // this keeps inheritance when obj is a class\n\n var resVal = res;\n var i = 0;\n var pathArray = toPath(path);\n\n for (; i < pathArray.length - 1; i++) {\n var currentPath = pathArray[i];\n var currentObj = getIn(obj, pathArray.slice(0, i + 1));\n\n if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {\n resVal = resVal[currentPath] = clone(currentObj);\n } else {\n var nextPath = pathArray[i + 1];\n resVal = resVal[currentPath] = isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {};\n }\n } // Return original object if new value is the same as current\n\n\n if ((i === 0 ? obj : resVal)[pathArray[i]] === value) {\n return obj;\n }\n\n if (value === undefined) {\n delete resVal[pathArray[i]];\n } else {\n resVal[pathArray[i]] = value;\n } // If the path array has a single element, the loop did not run.\n // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.\n\n\n if (i === 0 && value === undefined) {\n delete res[pathArray[i]];\n }\n\n return res;\n}\n/**\r\n * Recursively a set the same value for all keys and arrays nested object, cloning\r\n * @param object\r\n * @param value\r\n * @param visited\r\n * @param response\r\n */\n\nfunction setNestedObjectValues(object, value, visited, response) {\n if (visited === void 0) {\n visited = new WeakMap();\n }\n\n if (response === void 0) {\n response = {};\n }\n\n for (var _i = 0, _Object$keys = Object.keys(object); _i < _Object$keys.length; _i++) {\n var k = _Object$keys[_i];\n var val = object[k];\n\n if (isObject(val)) {\n if (!visited.get(val)) {\n visited.set(val, true); // In order to keep array values consistent for both dot path and\n // bracket syntax, we need to check if this is an array so that\n // this will output { friends: [true] } and not { friends: { \"0\": true } }\n\n response[k] = Array.isArray(val) ? [] : {};\n setNestedObjectValues(val, value, visited, response[k]);\n }\n } else {\n response[k] = value;\n }\n }\n\n return response;\n}\n/** Return multi select values based on an array of options */\n\nfunction getSelectedValues(options) {\n var result = [];\n\n if (options) {\n for (var index = 0; index < options.length; index++) {\n var option = options[index];\n\n if (option.selected) {\n result.push(option.value);\n }\n }\n }\n\n return result;\n}\n/** Return the next value for a checkbox */\n\nfunction getValueForCheckbox(currentValue, checked, valueProp) {\n // If the current value was a boolean, return a boolean\n if (typeof currentValue === 'boolean') {\n return Boolean(checked);\n } // If the currentValue was not a boolean we want to return an array\n\n\n var currentArrayOfValues = [];\n var isValueInArray = false;\n var index = -1;\n\n if (!Array.isArray(currentValue)) {\n // eslint-disable-next-line eqeqeq\n if (!valueProp || valueProp == 'true' || valueProp == 'false') {\n return Boolean(checked);\n }\n } else {\n // If the current value is already an array, use it\n currentArrayOfValues = currentValue;\n index = currentValue.indexOf(valueProp);\n isValueInArray = index >= 0;\n } // If the checkbox was checked and the value is not already present in the aray we want to add the new value to the array of values\n\n\n if (checked && valueProp && !isValueInArray) {\n return currentArrayOfValues.concat(valueProp);\n } // If the checkbox was unchecked and the value is not in the array, simply return the already existing array of values\n\n\n if (!isValueInArray) {\n return currentArrayOfValues;\n } // If the checkbox was unchecked and the value is in the array, remove the value and return the array\n\n\n return currentArrayOfValues.slice(0, index).concat(currentArrayOfValues.slice(index + 1));\n}\nvar defaultParseFn = function defaultParseFn(value, _name) {\n return value;\n};\nvar numberParseFn = function numberParseFn(value, _name) {\n var parsed = parseFloat(value);\n return isNaN$1(parsed) ? '' : parsed;\n};\nvar defaultFormatFn = function defaultFormatFn(value, _name) {\n return value === undefined ? '' : value;\n};\n/** Get the value out of a React Synthetic event given some form state. Works cross-platform. */\n\nvar getValueFromEvent = function getValueFromEvent(event, valueState) {\n // React Native/Expo Web/maybe other render envs\n if (!isReactNative && event.nativeEvent && event.nativeEvent.text !== undefined) {\n return event.nativeEvent.text;\n } // React Native\n\n\n if (isReactNative && event.nativeEvent) {\n return event.nativeEvent.text;\n }\n\n var target = event.target ? event.target : event.currentTarget;\n var type = target.type,\n value = target.value,\n checked = target.checked,\n options = target.options,\n multiple = target.multiple;\n return /checkbox/.test(type) // checkboxes\n ? getValueForCheckbox(valueState, checked, value) : !!multiple // \n ? getSelectedValues(options) : value;\n }\n\n if (field) {\n // Set form fields by name\n setFieldValue(field, val);\n }\n }, [setFieldValue, state.values]);\n var handleChange = useEventCallback(function (eventOrPath) {\n if (isString(eventOrPath)) {\n return function (event) {\n return executeChange(event, eventOrPath);\n };\n } else {\n executeChange(eventOrPath);\n }\n });\n var setFieldTouched = useEventCallback(function (field, touched, shouldValidate) {\n if (touched === void 0) {\n touched = true;\n }\n\n dispatch({\n type: 'SET_FIELD_TOUCHED',\n payload: {\n field: field,\n value: touched\n }\n });\n var willValidate = shouldValidate === undefined ? validateOnBlur : shouldValidate;\n return willValidate ? validateFormWithHighPriority(state.values) : Promise.resolve();\n });\n var executeBlur = useCallback(function (e, path) {\n if (e.persist) {\n e.persist();\n }\n\n var _e$target = e.target,\n name = _e$target.name,\n id = _e$target.id,\n outerHTML = _e$target.outerHTML;\n var field = path ? path : name ? name : id;\n\n if (!field && process.env.NODE_ENV !== \"production\") {\n warnAboutMissingIdentifier({\n htmlContent: outerHTML,\n documentationAnchorLink: 'handleblur-e-any--void',\n handlerName: 'handleBlur'\n });\n }\n\n setFieldTouched(field, true);\n }, [setFieldTouched]);\n var handleBlur = useEventCallback(function (eventOrString) {\n if (isString(eventOrString)) {\n return function (event) {\n return executeBlur(event, eventOrString);\n };\n } else {\n executeBlur(eventOrString);\n }\n });\n var setFormikState = useCallback(function (stateOrCb) {\n if (isFunction(stateOrCb)) {\n dispatch({\n type: 'SET_FORMIK_STATE',\n payload: stateOrCb\n });\n } else {\n dispatch({\n type: 'SET_FORMIK_STATE',\n payload: function payload() {\n return stateOrCb;\n }\n });\n }\n }, []);\n var setStatus = useCallback(function (status) {\n dispatch({\n type: 'SET_STATUS',\n payload: status\n });\n }, []);\n var setSubmitting = useCallback(function (isSubmitting) {\n dispatch({\n type: 'SET_ISSUBMITTING',\n payload: isSubmitting\n });\n }, []);\n var submitForm = useEventCallback(function () {\n dispatch({\n type: 'SUBMIT_ATTEMPT'\n });\n return validateFormWithHighPriority().then(function (combinedErrors) {\n // In case an error was thrown and passed to the resolved Promise,\n // `combinedErrors` can be an instance of an Error. We need to check\n // that and abort the submit.\n // If we don't do that, calling `Object.keys(new Error())` yields an\n // empty array, which causes the validation to pass and the form\n // to be submitted.\n var isInstanceOfError = combinedErrors instanceof Error;\n var isActuallyValid = !isInstanceOfError && Object.keys(combinedErrors).length === 0;\n\n if (isActuallyValid) {\n // Proceed with submit...\n //\n // To respect sync submit fns, we can't simply wrap executeSubmit in a promise and\n // _always_ dispatch SUBMIT_SUCCESS because isSubmitting would then always be false.\n // This would be fine in simple cases, but make it impossible to disable submit\n // buttons where people use callbacks or promises as side effects (which is basically\n // all of v1 Formik code). Instead, recall that we are inside of a promise chain already,\n // so we can try/catch executeSubmit(), if it returns undefined, then just bail.\n // If there are errors, throw em. Otherwise, wrap executeSubmit in a promise and handle\n // cleanup of isSubmitting on behalf of the consumer.\n var promiseOrUndefined;\n\n try {\n promiseOrUndefined = executeSubmit(); // Bail if it's sync, consumer is responsible for cleaning up\n // via setSubmitting(false)\n\n if (promiseOrUndefined === undefined) {\n return;\n }\n } catch (error) {\n throw error;\n }\n\n return Promise.resolve(promiseOrUndefined).then(function (result) {\n if (!!isMounted.current) {\n dispatch({\n type: 'SUBMIT_SUCCESS'\n });\n }\n\n return result;\n })[\"catch\"](function (_errors) {\n if (!!isMounted.current) {\n dispatch({\n type: 'SUBMIT_FAILURE'\n }); // This is a legit error rejected by the onSubmit fn\n // so we don't want to break the promise chain\n\n throw _errors;\n }\n });\n } else if (!!isMounted.current) {\n // ^^^ Make sure Formik is still mounted before updating state\n dispatch({\n type: 'SUBMIT_FAILURE'\n }); // throw combinedErrors;\n\n if (isInstanceOfError) {\n throw combinedErrors;\n }\n }\n\n return;\n });\n });\n var handleSubmit = useEventCallback(function (e) {\n if (e && e.preventDefault && isFunction(e.preventDefault)) {\n e.preventDefault();\n }\n\n if (e && e.stopPropagation && isFunction(e.stopPropagation)) {\n e.stopPropagation();\n } // Warn if form submission is triggered by a